libminijail.c revision 1563b5b904547ab89dc3193f463c57002b7a28f2
1/*
2 * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7#define _BSD_SOURCE
8#define _GNU_SOURCE
9
10#include <asm/unistd.h>
11#include <ctype.h>
12#include <errno.h>
13#include <fcntl.h>
14#include <grp.h>
15#include <inttypes.h>
16#include <limits.h>
17#include <linux/capability.h>
18#include <pwd.h>
19#include <sched.h>
20#include <signal.h>
21#include <stdarg.h>
22#include <stddef.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <syscall.h>
27#include <sys/capability.h>
28#include <sys/mount.h>
29#include <sys/param.h>
30#include <sys/prctl.h>
31#include <sys/stat.h>
32#include <sys/types.h>
33#include <sys/user.h>
34#include <sys/wait.h>
35#include <unistd.h>
36
37#include "libminijail.h"
38#include "libminijail-private.h"
39
40#include "signal.h"
41#include "syscall_filter.h"
42#include "util.h"
43
44#ifdef HAVE_SECUREBITS_H
45#include <linux/securebits.h>
46#else
47#define SECURE_ALL_BITS         0x15
48#define SECURE_ALL_LOCKS        (SECURE_ALL_BITS << 1)
49#endif
50
51/* Until these are reliably available in linux/prctl.h */
52#ifndef PR_SET_SECCOMP
53# define PR_SET_SECCOMP 22
54#endif
55
56/* For seccomp_filter using BPF. */
57#ifndef PR_SET_NO_NEW_PRIVS
58# define PR_SET_NO_NEW_PRIVS 38
59#endif
60#ifndef SECCOMP_MODE_FILTER
61# define SECCOMP_MODE_FILTER 2 /* uses user-supplied filter. */
62#endif
63
64struct binding {
65	char *src;
66	char *dest;
67	int writeable;
68	struct binding *next;
69};
70
71struct minijail {
72	/*
73	 * WARNING: if you add a flag here you need to make sure it's
74	 * accounted for in minijail_pre{enter|exec}() below.
75	 */
76	struct {
77		int uid:1;
78		int gid:1;
79		int caps:1;
80		int vfs:1;
81		int enter_vfs:1;
82		int pids:1;
83		int net:1;
84		int seccomp:1;
85		int readonly:1;
86		int usergroups:1;
87		int ptrace:1;
88		int no_new_privs:1;
89		int seccomp_filter:1;
90		int log_seccomp_filter:1;
91		int chroot:1;
92		int mount_tmp:1;
93	} flags;
94	uid_t uid;
95	gid_t gid;
96	gid_t usergid;
97	char *user;
98	uint64_t caps;
99	pid_t initpid;
100	int mountns_fd;
101	int filter_len;
102	int binding_count;
103	char *chrootdir;
104	struct sock_fprog *filter_prog;
105	struct binding *bindings_head;
106	struct binding *bindings_tail;
107};
108
109/*
110 * Strip out flags meant for the parent.
111 * We keep things that are not inherited across execve(2) (e.g. capabilities),
112 * or are easier to set after execve(2) (e.g. seccomp filters).
113 */
114void minijail_preenter(struct minijail *j)
115{
116	j->flags.vfs = 0;
117	j->flags.enter_vfs = 0;
118	j->flags.readonly = 0;
119	j->flags.pids = 0;
120}
121
122/*
123 * Strip out flags meant for the child.
124 * We keep things that are inherited across execve(2).
125 */
126void minijail_preexec(struct minijail *j)
127{
128	int vfs = j->flags.vfs;
129	int enter_vfs = j->flags.enter_vfs;
130	int readonly = j->flags.readonly;
131	if (j->user)
132		free(j->user);
133	j->user = NULL;
134	memset(&j->flags, 0, sizeof(j->flags));
135	/* Now restore anything we meant to keep. */
136	j->flags.vfs = vfs;
137	j->flags.enter_vfs = enter_vfs;
138	j->flags.readonly = readonly;
139	/* Note, |pids| will already have been used before this call. */
140}
141
142/* Minijail API. */
143
144struct minijail API *minijail_new(void)
145{
146	return calloc(1, sizeof(struct minijail));
147}
148
149void API minijail_change_uid(struct minijail *j, uid_t uid)
150{
151	if (uid == 0)
152		die("useless change to uid 0");
153	j->uid = uid;
154	j->flags.uid = 1;
155}
156
157void API minijail_change_gid(struct minijail *j, gid_t gid)
158{
159	if (gid == 0)
160		die("useless change to gid 0");
161	j->gid = gid;
162	j->flags.gid = 1;
163}
164
165int API minijail_change_user(struct minijail *j, const char *user)
166{
167	char *buf = NULL;
168	struct passwd pw;
169	struct passwd *ppw = NULL;
170	ssize_t sz = sysconf(_SC_GETPW_R_SIZE_MAX);
171	if (sz == -1)
172		sz = 65536;	/* your guess is as good as mine... */
173
174	/*
175	 * sysconf(_SC_GETPW_R_SIZE_MAX), under glibc, is documented to return
176	 * the maximum needed size of the buffer, so we don't have to search.
177	 */
178	buf = malloc(sz);
179	if (!buf)
180		return -ENOMEM;
181	getpwnam_r(user, &pw, buf, sz, &ppw);
182	/*
183	 * We're safe to free the buffer here. The strings inside pw point
184	 * inside buf, but we don't use any of them; this leaves the pointers
185	 * dangling but it's safe. ppw points at pw if getpwnam_r succeeded.
186	 */
187	free(buf);
188	/* getpwnam_r(3) does *not* set errno when |ppw| is NULL. */
189	if (!ppw)
190		return -1;
191	minijail_change_uid(j, ppw->pw_uid);
192	j->user = strdup(user);
193	if (!j->user)
194		return -ENOMEM;
195	j->usergid = ppw->pw_gid;
196	return 0;
197}
198
199int API minijail_change_group(struct minijail *j, const char *group)
200{
201	char *buf = NULL;
202	struct group gr;
203	struct group *pgr = NULL;
204	ssize_t sz = sysconf(_SC_GETGR_R_SIZE_MAX);
205	if (sz == -1)
206		sz = 65536;	/* and mine is as good as yours, really */
207
208	/*
209	 * sysconf(_SC_GETGR_R_SIZE_MAX), under glibc, is documented to return
210	 * the maximum needed size of the buffer, so we don't have to search.
211	 */
212	buf = malloc(sz);
213	if (!buf)
214		return -ENOMEM;
215	getgrnam_r(group, &gr, buf, sz, &pgr);
216	/*
217	 * We're safe to free the buffer here. The strings inside gr point
218	 * inside buf, but we don't use any of them; this leaves the pointers
219	 * dangling but it's safe. pgr points at gr if getgrnam_r succeeded.
220	 */
221	free(buf);
222	/* getgrnam_r(3) does *not* set errno when |pgr| is NULL. */
223	if (!pgr)
224		return -1;
225	minijail_change_gid(j, pgr->gr_gid);
226	return 0;
227}
228
229void API minijail_use_seccomp(struct minijail *j)
230{
231	j->flags.seccomp = 1;
232}
233
234void API minijail_no_new_privs(struct minijail *j)
235{
236	j->flags.no_new_privs = 1;
237}
238
239void API minijail_use_seccomp_filter(struct minijail *j)
240{
241	j->flags.seccomp_filter = 1;
242}
243
244void API minijail_log_seccomp_filter_failures(struct minijail *j)
245{
246	j->flags.log_seccomp_filter = 1;
247}
248
249void API minijail_use_caps(struct minijail *j, uint64_t capmask)
250{
251	j->caps = capmask;
252	j->flags.caps = 1;
253}
254
255void API minijail_namespace_vfs(struct minijail *j)
256{
257	j->flags.vfs = 1;
258}
259
260void API minijail_namespace_enter_vfs(struct minijail *j, const char *ns_path)
261{
262	int ns_fd = open(ns_path, O_RDONLY);
263	if (ns_fd < 0) {
264		pdie("failed to open namespace '%s'", ns_path);
265	}
266	j->mountns_fd = ns_fd;
267	j->flags.enter_vfs = 1;
268}
269
270void API minijail_namespace_pids(struct minijail *j)
271{
272	j->flags.vfs = 1;
273	j->flags.readonly = 1;
274	j->flags.pids = 1;
275}
276
277void API minijail_namespace_net(struct minijail *j)
278{
279	j->flags.net = 1;
280}
281
282void API minijail_remount_readonly(struct minijail *j)
283{
284	j->flags.vfs = 1;
285	j->flags.readonly = 1;
286}
287
288void API minijail_inherit_usergroups(struct minijail *j)
289{
290	j->flags.usergroups = 1;
291}
292
293void API minijail_disable_ptrace(struct minijail *j)
294{
295	j->flags.ptrace = 1;
296}
297
298int API minijail_enter_chroot(struct minijail *j, const char *dir)
299{
300	if (j->chrootdir)
301		return -EINVAL;
302	j->chrootdir = strdup(dir);
303	if (!j->chrootdir)
304		return -ENOMEM;
305	j->flags.chroot = 1;
306	return 0;
307}
308
309void API minijail_mount_tmp(struct minijail *j)
310{
311	j->flags.mount_tmp = 1;
312}
313
314int API minijail_bind(struct minijail *j, const char *src, const char *dest,
315		      int writeable)
316{
317	struct binding *b;
318
319	if (*dest != '/')
320		return -EINVAL;
321	b = calloc(1, sizeof(*b));
322	if (!b)
323		return -ENOMEM;
324	b->dest = strdup(dest);
325	if (!b->dest)
326		goto error;
327	b->src = strdup(src);
328	if (!b->src)
329		goto error;
330	b->writeable = writeable;
331
332	info("bind %s -> %s", src, dest);
333
334	/*
335	 * Force vfs namespacing so the bind mounts don't leak out into the
336	 * containing vfs namespace.
337	 */
338	minijail_namespace_vfs(j);
339
340	if (j->bindings_tail)
341		j->bindings_tail->next = b;
342	else
343		j->bindings_head = b;
344	j->bindings_tail = b;
345	j->binding_count++;
346
347	return 0;
348
349error:
350	free(b->src);
351	free(b->dest);
352	free(b);
353	return -ENOMEM;
354}
355
356void API minijail_parse_seccomp_filters(struct minijail *j, const char *path)
357{
358	FILE *file = fopen(path, "r");
359	if (!file) {
360		pdie("failed to open seccomp filter file '%s'", path);
361	}
362
363	struct sock_fprog *fprog = malloc(sizeof(struct sock_fprog));
364	if (compile_filter(file, fprog, j->flags.log_seccomp_filter)) {
365		die("failed to compile seccomp filter BPF program in '%s'",
366		    path);
367	}
368
369	j->filter_len = fprog->len;
370	j->filter_prog = fprog;
371
372	fclose(file);
373}
374
375struct marshal_state {
376	size_t available;
377	size_t total;
378	char *buf;
379};
380
381void marshal_state_init(struct marshal_state *state,
382			char *buf, size_t available)
383{
384	state->available = available;
385	state->buf = buf;
386	state->total = 0;
387}
388
389void marshal_append(struct marshal_state *state,
390		    char *src, size_t length)
391{
392	size_t copy_len = MIN(state->available, length);
393
394	/* Up to |available| will be written. */
395	if (copy_len) {
396		memcpy(state->buf, src, copy_len);
397		state->buf += copy_len;
398		state->available -= copy_len;
399	}
400	/* |total| will contain the expected length. */
401	state->total += length;
402}
403
404void minijail_marshal_helper(struct marshal_state *state,
405			     const struct minijail *j)
406{
407	struct binding *b = NULL;
408	marshal_append(state, (char *)j, sizeof(*j));
409	if (j->user)
410		marshal_append(state, j->user, strlen(j->user) + 1);
411	if (j->chrootdir)
412		marshal_append(state, j->chrootdir, strlen(j->chrootdir) + 1);
413	if (j->flags.seccomp_filter && j->filter_prog) {
414		struct sock_fprog *fp = j->filter_prog;
415		marshal_append(state, (char *)fp->filter,
416				fp->len * sizeof(struct sock_filter));
417	}
418	for (b = j->bindings_head; b; b = b->next) {
419		marshal_append(state, b->src, strlen(b->src) + 1);
420		marshal_append(state, b->dest, strlen(b->dest) + 1);
421		marshal_append(state, (char *)&b->writeable,
422				sizeof(b->writeable));
423	}
424}
425
426size_t API minijail_size(const struct minijail *j)
427{
428	struct marshal_state state;
429	marshal_state_init(&state, NULL, 0);
430	minijail_marshal_helper(&state, j);
431	return state.total;
432}
433
434int minijail_marshal(const struct minijail *j, char *buf, size_t available)
435{
436	struct marshal_state state;
437	marshal_state_init(&state, buf, available);
438	minijail_marshal_helper(&state, j);
439	return (state.total > available);
440}
441
442/* consumebytes: consumes @length bytes from a buffer @buf of length @buflength
443 * @length    Number of bytes to consume
444 * @buf       Buffer to consume from
445 * @buflength Size of @buf
446 *
447 * Returns a pointer to the base of the bytes, or NULL for errors.
448 */
449void *consumebytes(size_t length, char **buf, size_t *buflength)
450{
451	char *p = *buf;
452	if (length > *buflength)
453		return NULL;
454	*buf += length;
455	*buflength -= length;
456	return p;
457}
458
459/* consumestr: consumes a C string from a buffer @buf of length @length
460 * @buf    Buffer to consume
461 * @length Length of buffer
462 *
463 * Returns a pointer to the base of the string, or NULL for errors.
464 */
465char *consumestr(char **buf, size_t *buflength)
466{
467	size_t len = strnlen(*buf, *buflength);
468	if (len == *buflength)
469		/* There's no null-terminator */
470		return NULL;
471	return consumebytes(len + 1, buf, buflength);
472}
473
474int minijail_unmarshal(struct minijail *j, char *serialized, size_t length)
475{
476	int i;
477	int count;
478	int ret = -EINVAL;
479
480	if (length < sizeof(*j))
481		goto out;
482	memcpy((void *)j, serialized, sizeof(*j));
483	serialized += sizeof(*j);
484	length -= sizeof(*j);
485
486	/* Potentially stale pointers not used as signals. */
487	j->bindings_head = NULL;
488	j->bindings_tail = NULL;
489	j->filter_prog = NULL;
490
491	if (j->user) {		/* stale pointer */
492		char *user = consumestr(&serialized, &length);
493		if (!user)
494			goto clear_pointers;
495		j->user = strdup(user);
496		if (!j->user)
497			goto clear_pointers;
498	}
499
500	if (j->chrootdir) {	/* stale pointer */
501		char *chrootdir = consumestr(&serialized, &length);
502		if (!chrootdir)
503			goto bad_chrootdir;
504		j->chrootdir = strdup(chrootdir);
505		if (!j->chrootdir)
506			goto bad_chrootdir;
507	}
508
509	if (j->flags.seccomp_filter && j->filter_len > 0) {
510		size_t ninstrs = j->filter_len;
511		if (ninstrs > (SIZE_MAX / sizeof(struct sock_filter)) ||
512		    ninstrs > USHRT_MAX)
513			goto bad_filters;
514
515		size_t program_len = ninstrs * sizeof(struct sock_filter);
516		void *program = consumebytes(program_len, &serialized, &length);
517		if (!program)
518			goto bad_filters;
519
520		j->filter_prog = malloc(sizeof(struct sock_fprog));
521		j->filter_prog->len = ninstrs;
522		j->filter_prog->filter = malloc(program_len);
523		memcpy(j->filter_prog->filter, program, program_len);
524	}
525
526	count = j->binding_count;
527	j->binding_count = 0;
528	for (i = 0; i < count; ++i) {
529		int *writeable;
530		const char *dest;
531		const char *src = consumestr(&serialized, &length);
532		if (!src)
533			goto bad_bindings;
534		dest = consumestr(&serialized, &length);
535		if (!dest)
536			goto bad_bindings;
537		writeable = consumebytes(sizeof(*writeable), &serialized, &length);
538		if (!writeable)
539			goto bad_bindings;
540		if (minijail_bind(j, src, dest, *writeable))
541			goto bad_bindings;
542	}
543
544	return 0;
545
546bad_bindings:
547	if (j->flags.seccomp_filter && j->filter_len > 0) {
548		free(j->filter_prog->filter);
549		free(j->filter_prog);
550	}
551bad_filters:
552	if (j->chrootdir)
553		free(j->chrootdir);
554bad_chrootdir:
555	if (j->user)
556		free(j->user);
557clear_pointers:
558	j->user = NULL;
559	j->chrootdir = NULL;
560out:
561	return ret;
562}
563
564/* bind_one: Applies bindings from @b for @j, recursing as needed.
565 * @j Minijail these bindings are for
566 * @b Head of list of bindings
567 *
568 * Returns 0 for success.
569 */
570int bind_one(const struct minijail *j, struct binding *b)
571{
572	int ret = 0;
573	char *dest = NULL;
574	if (ret)
575		return ret;
576	/* dest has a leading "/" */
577	if (asprintf(&dest, "%s%s", j->chrootdir, b->dest) < 0)
578		return -ENOMEM;
579	ret = mount(b->src, dest, NULL, MS_BIND, NULL);
580	if (ret)
581		pdie("bind: %s -> %s", b->src, dest);
582	if (!b->writeable) {
583		ret = mount(b->src, dest, NULL,
584			    MS_BIND | MS_REMOUNT | MS_RDONLY, NULL);
585		if (ret)
586			pdie("bind ro: %s -> %s", b->src, dest);
587	}
588	free(dest);
589	if (b->next)
590		return bind_one(j, b->next);
591	return ret;
592}
593
594int enter_chroot(const struct minijail *j)
595{
596	int ret;
597	if (j->bindings_head && (ret = bind_one(j, j->bindings_head)))
598		return ret;
599
600	if (chroot(j->chrootdir))
601		return -errno;
602
603	if (chdir("/"))
604		return -errno;
605
606	return 0;
607}
608
609int mount_tmp(void)
610{
611	return mount("none", "/tmp", "tmpfs", 0, "size=128M,mode=777");
612}
613
614int remount_readonly(void)
615{
616	const char *kProcPath = "/proc";
617	const unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
618	/*
619	 * Right now, we're holding a reference to our parent's old mount of
620	 * /proc in our namespace, which means using MS_REMOUNT here would
621	 * mutate our parent's mount as well, even though we're in a VFS
622	 * namespace (!). Instead, remove their mount from our namespace
623	 * and make our own.
624	 */
625	if (umount(kProcPath))
626		return -errno;
627	if (mount("", kProcPath, "proc", kSafeFlags | MS_RDONLY, ""))
628		return -errno;
629	return 0;
630}
631
632void drop_ugid(const struct minijail *j)
633{
634	if (j->flags.usergroups) {
635		if (initgroups(j->user, j->usergid))
636			pdie("initgroups");
637	} else {
638		/* Only attempt to clear supplemental groups if we are changing
639		 * users. */
640		if ((j->uid || j->gid) && setgroups(0, NULL))
641			pdie("setgroups");
642	}
643
644	if (j->flags.gid && setresgid(j->gid, j->gid, j->gid))
645		pdie("setresgid");
646
647	if (j->flags.uid && setresuid(j->uid, j->uid, j->uid))
648		pdie("setresuid");
649}
650
651/*
652 * We specifically do not use cap_valid() as that only tells us the last
653 * valid cap we were *compiled* against (i.e. what the version of kernel
654 * headers says).  If we run on a different kernel version, then it's not
655 * uncommon for that to be less (if an older kernel) or more (if a newer
656 * kernel).  So suck up the answer via /proc.
657 */
658static int run_cap_valid(unsigned int cap)
659{
660	static unsigned int last_cap;
661
662	if (!last_cap) {
663		const char cap_file[] = "/proc/sys/kernel/cap_last_cap";
664		FILE *fp = fopen(cap_file, "re");
665		if (fscanf(fp, "%u", &last_cap) != 1)
666			pdie("fscanf(%s)", cap_file);
667		fclose(fp);
668	}
669
670	return cap <= last_cap;
671}
672
673void drop_caps(const struct minijail *j)
674{
675	cap_t caps = cap_get_proc();
676	cap_value_t flag[1];
677	const uint64_t one = 1;
678	unsigned int i;
679	if (!caps)
680		die("can't get process caps");
681	if (cap_clear_flag(caps, CAP_INHERITABLE))
682		die("can't clear inheritable caps");
683	if (cap_clear_flag(caps, CAP_EFFECTIVE))
684		die("can't clear effective caps");
685	if (cap_clear_flag(caps, CAP_PERMITTED))
686		die("can't clear permitted caps");
687	for (i = 0; i < sizeof(j->caps) * 8 && run_cap_valid(i); ++i) {
688		/* Keep CAP_SETPCAP for dropping bounding set bits. */
689		if (i != CAP_SETPCAP && !(j->caps & (one << i)))
690			continue;
691		flag[0] = i;
692		if (cap_set_flag(caps, CAP_EFFECTIVE, 1, flag, CAP_SET))
693			die("can't add effective cap");
694		if (cap_set_flag(caps, CAP_PERMITTED, 1, flag, CAP_SET))
695			die("can't add permitted cap");
696		if (cap_set_flag(caps, CAP_INHERITABLE, 1, flag, CAP_SET))
697			die("can't add inheritable cap");
698	}
699	if (cap_set_proc(caps))
700		die("can't apply initial cleaned capset");
701
702	/*
703	 * Instead of dropping bounding set first, do it here in case
704	 * the caller had a more permissive bounding set which could
705	 * have been used above to raise a capability that wasn't already
706	 * present. This requires CAP_SETPCAP, so we raised/kept it above.
707	 */
708	for (i = 0; i < sizeof(j->caps) * 8 && run_cap_valid(i); ++i) {
709		if (j->caps & (one << i))
710			continue;
711		if (prctl(PR_CAPBSET_DROP, i))
712			pdie("prctl(PR_CAPBSET_DROP)");
713	}
714
715	/* If CAP_SETPCAP wasn't specifically requested, now we remove it. */
716	if ((j->caps & (one << CAP_SETPCAP)) == 0) {
717		flag[0] = CAP_SETPCAP;
718		if (cap_set_flag(caps, CAP_EFFECTIVE, 1, flag, CAP_CLEAR))
719			die("can't clear effective cap");
720		if (cap_set_flag(caps, CAP_PERMITTED, 1, flag, CAP_CLEAR))
721			die("can't clear permitted cap");
722		if (cap_set_flag(caps, CAP_INHERITABLE, 1, flag, CAP_CLEAR))
723			die("can't clear inheritable cap");
724	}
725
726	if (cap_set_proc(caps))
727		die("can't apply final cleaned capset");
728
729	cap_free(caps);
730}
731
732void set_seccomp_filter(const struct minijail *j)
733{
734	/*
735	 * Set no_new_privs. See </kernel/seccomp.c> and </kernel/sys.c>
736	 * in the kernel source tree for an explanation of the parameters.
737	 */
738	if (j->flags.no_new_privs) {
739		if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
740			pdie("prctl(PR_SET_NO_NEW_PRIVS)");
741	}
742
743	/*
744	 * If we're logging seccomp filter failures,
745	 * install the SIGSYS handler first.
746	 */
747	if (j->flags.seccomp_filter && j->flags.log_seccomp_filter) {
748		if (install_sigsys_handler())
749			pdie("install SIGSYS handler");
750		warn("logging seccomp filter failures");
751	}
752
753	/*
754	 * Install the syscall filter.
755	 */
756	if (j->flags.seccomp_filter) {
757		if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, j->filter_prog))
758			pdie("prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER)");
759	}
760}
761
762void API minijail_enter(const struct minijail *j)
763{
764	if (j->flags.pids)
765		die("tried to enter a pid-namespaced jail;"
766		    " try minijail_run()?");
767
768	if (j->flags.usergroups && !j->user)
769		die("usergroup inheritance without username");
770
771	/*
772	 * We can't recover from failures if we've dropped privileges partially,
773	 * so we don't even try. If any of our operations fail, we abort() the
774	 * entire process.
775	 */
776	if (j->flags.enter_vfs && setns(j->mountns_fd, CLONE_NEWNS))
777		pdie("setns(CLONE_NEWNS)");
778
779	if (j->flags.vfs && unshare(CLONE_NEWNS))
780		pdie("unshare(vfs)");
781
782	if (j->flags.net && unshare(CLONE_NEWNET))
783		pdie("unshare(net)");
784
785	if (j->flags.chroot && enter_chroot(j))
786		pdie("chroot");
787
788	if (j->flags.chroot && j->flags.mount_tmp && mount_tmp())
789		pdie("mount_tmp");
790
791	if (j->flags.readonly && remount_readonly())
792		pdie("remount");
793
794	if (j->flags.caps) {
795		/*
796		 * POSIX capabilities are a bit tricky. If we drop our
797		 * capability to change uids, our attempt to use setuid()
798		 * below will fail. Hang on to root caps across setuid(), then
799		 * lock securebits.
800		 */
801		if (prctl(PR_SET_KEEPCAPS, 1))
802			pdie("prctl(PR_SET_KEEPCAPS)");
803		if (prctl
804		    (PR_SET_SECUREBITS, SECURE_ALL_BITS | SECURE_ALL_LOCKS))
805			pdie("prctl(PR_SET_SECUREBITS)");
806	}
807
808	/*
809	 * If we're setting no_new_privs, we can drop privileges
810	 * before setting seccomp filter. This way filter policies
811	 * don't need to allow privilege-dropping syscalls.
812	 */
813	if (j->flags.no_new_privs) {
814		drop_ugid(j);
815		if (j->flags.caps)
816			drop_caps(j);
817
818		set_seccomp_filter(j);
819	} else {
820		/*
821		 * If we're not setting no_new_privs,
822		 * we need to set seccomp filter *before* dropping privileges.
823		 * WARNING: this means that filter policies *must* allow
824		 * setgroups()/setresgid()/setresuid() for dropping root and
825		 * capget()/capset()/prctl() for dropping caps.
826		 */
827		set_seccomp_filter(j);
828
829		drop_ugid(j);
830		if (j->flags.caps)
831			drop_caps(j);
832	}
833
834	/*
835	 * seccomp has to come last since it cuts off all the other
836	 * privilege-dropping syscalls :)
837	 */
838	if (j->flags.seccomp && prctl(PR_SET_SECCOMP, 1))
839		pdie("prctl(PR_SET_SECCOMP)");
840}
841
842/* TODO(wad) will visibility affect this variable? */
843static int init_exitstatus = 0;
844
845void init_term(int __attribute__ ((unused)) sig)
846{
847	_exit(init_exitstatus);
848}
849
850int init(pid_t rootpid)
851{
852	pid_t pid;
853	int status;
854	/* so that we exit with the right status */
855	signal(SIGTERM, init_term);
856	/* TODO(wad) self jail with seccomp_filters here. */
857	while ((pid = wait(&status)) > 0) {
858		/*
859		 * This loop will only end when either there are no processes
860		 * left inside our pid namespace or we get a signal.
861		 */
862		if (pid == rootpid)
863			init_exitstatus = status;
864	}
865	if (!WIFEXITED(init_exitstatus))
866		_exit(MINIJAIL_ERR_INIT);
867	_exit(WEXITSTATUS(init_exitstatus));
868}
869
870int API minijail_from_fd(int fd, struct minijail *j)
871{
872	size_t sz = 0;
873	size_t bytes = read(fd, &sz, sizeof(sz));
874	char *buf;
875	int r;
876	if (sizeof(sz) != bytes)
877		return -EINVAL;
878	if (sz > USHRT_MAX)	/* Arbitrary sanity check */
879		return -E2BIG;
880	buf = malloc(sz);
881	if (!buf)
882		return -ENOMEM;
883	bytes = read(fd, buf, sz);
884	if (bytes != sz) {
885		free(buf);
886		return -EINVAL;
887	}
888	r = minijail_unmarshal(j, buf, sz);
889	free(buf);
890	return r;
891}
892
893int API minijail_to_fd(struct minijail *j, int fd)
894{
895	char *buf;
896	size_t sz = minijail_size(j);
897	ssize_t written;
898	int r;
899
900	if (!sz)
901		return -EINVAL;
902	buf = malloc(sz);
903	r = minijail_marshal(j, buf, sz);
904	if (r) {
905		free(buf);
906		return r;
907	}
908	/* Sends [size][minijail]. */
909	written = write(fd, &sz, sizeof(sz));
910	if (written != sizeof(sz)) {
911		free(buf);
912		return -EFAULT;
913	}
914	written = write(fd, buf, sz);
915	if (written < 0 || (size_t) written != sz) {
916		free(buf);
917		return -EFAULT;
918	}
919	free(buf);
920	return 0;
921}
922
923int setup_preload(void)
924{
925	char *oldenv = getenv(kLdPreloadEnvVar) ? : "";
926	char *newenv = malloc(strlen(oldenv) + 2 + strlen(PRELOADPATH));
927	if (!newenv)
928		return -ENOMEM;
929
930	/* Only insert a separating space if we have something to separate... */
931	sprintf(newenv, "%s%s%s", oldenv, strlen(oldenv) ? " " : "",
932		PRELOADPATH);
933
934	/* setenv() makes a copy of the string we give it */
935	setenv(kLdPreloadEnvVar, newenv, 1);
936	free(newenv);
937	return 0;
938}
939
940int setup_pipe(int fds[2])
941{
942	int r = pipe(fds);
943	char fd_buf[11];
944	if (r)
945		return r;
946	r = snprintf(fd_buf, sizeof(fd_buf), "%d", fds[0]);
947	if (r <= 0)
948		return -EINVAL;
949	setenv(kFdEnvVar, fd_buf, 1);
950	return 0;
951}
952
953int setup_pipe_end(int fds[2], size_t index)
954{
955	if (index > 1)
956		return -1;
957
958	close(fds[1 - index]);
959	return fds[index];
960}
961
962int setup_and_dupe_pipe_end(int fds[2], size_t index, int fd)
963{
964	if (index > 1)
965		return -1;
966
967	close(fds[1 - index]);
968	/* dup2(2) the corresponding end of the pipe into |fd|. */
969	return dup2(fds[index], fd);
970}
971
972int API minijail_run(struct minijail *j, const char *filename,
973		     char *const argv[])
974{
975	return minijail_run_pid_pipes(j, filename, argv,
976				      NULL, NULL, NULL, NULL);
977}
978
979int API minijail_run_pid(struct minijail *j, const char *filename,
980			 char *const argv[], pid_t *pchild_pid)
981{
982	return minijail_run_pid_pipes(j, filename, argv, pchild_pid,
983				      NULL, NULL, NULL);
984}
985
986int API minijail_run_pipe(struct minijail *j, const char *filename,
987			  char *const argv[], int *pstdin_fd)
988{
989	return minijail_run_pid_pipes(j, filename, argv, NULL, pstdin_fd,
990				      NULL, NULL);
991}
992
993int API minijail_run_pid_pipe(struct minijail *j, const char *filename,
994			      char *const argv[], pid_t *pchild_pid,
995			      int *pstdin_fd)
996{
997	return minijail_run_pid_pipes(j, filename, argv, pchild_pid, pstdin_fd,
998				      NULL, NULL);
999}
1000
1001int API minijail_run_pid_pipes(struct minijail *j, const char *filename,
1002			       char *const argv[], pid_t *pchild_pid,
1003			       int *pstdin_fd, int *pstdout_fd, int *pstderr_fd)
1004{
1005	char *oldenv, *oldenv_copy = NULL;
1006	pid_t child_pid;
1007	int pipe_fds[2];
1008	int stdin_fds[2];
1009	int stdout_fds[2];
1010	int stderr_fds[2];
1011	int ret;
1012	/* We need to remember this across the minijail_preexec() call. */
1013	int pid_namespace = j->flags.pids;
1014
1015	oldenv = getenv(kLdPreloadEnvVar);
1016	if (oldenv) {
1017		oldenv_copy = strdup(oldenv);
1018		if (!oldenv_copy)
1019			return -ENOMEM;
1020	}
1021
1022	if (setup_preload())
1023		return -EFAULT;
1024
1025	/*
1026	 * Before we fork(2) and execve(2) the child process, we need to open
1027	 * a pipe(2) to send the minijail configuration over.
1028	 */
1029	if (setup_pipe(pipe_fds))
1030		return -EFAULT;
1031
1032	/*
1033	 * If we want to write to the child process' standard input,
1034	 * create the pipe(2) now.
1035	 */
1036	if (pstdin_fd) {
1037		if (pipe(stdin_fds))
1038			return -EFAULT;
1039	}
1040
1041	/*
1042	 * If we want to read from the child process' standard output,
1043	 * create the pipe(2) now.
1044	 */
1045	if (pstdout_fd) {
1046		if (pipe(stdout_fds))
1047			return -EFAULT;
1048	}
1049
1050	/*
1051	 * If we want to read from the child process' standard error,
1052	 * create the pipe(2) now.
1053	 */
1054	if (pstderr_fd) {
1055		if (pipe(stderr_fds))
1056			return -EFAULT;
1057	}
1058
1059	/* Use sys_clone() if and only if we're creating a pid namespace.
1060	 *
1061	 * tl;dr: WARNING: do not mix pid namespaces and multithreading.
1062	 *
1063	 * In multithreaded programs, there are a bunch of locks inside libc,
1064	 * some of which may be held by other threads at the time that we call
1065	 * minijail_run_pid(). If we call fork(), glibc does its level best to
1066	 * ensure that we hold all of these locks before it calls clone()
1067	 * internally and drop them after clone() returns, but when we call
1068	 * sys_clone(2) directly, all that gets bypassed and we end up with a
1069	 * child address space where some of libc's important locks are held by
1070	 * other threads (which did not get cloned, and hence will never release
1071	 * those locks). This is okay so long as we call exec() immediately
1072	 * after, but a bunch of seemingly-innocent libc functions like setenv()
1073	 * take locks.
1074	 *
1075	 * Hence, only call sys_clone() if we need to, in order to get at pid
1076	 * namespacing. If we follow this path, the child's address space might
1077	 * have broken locks; you may only call functions that do not acquire
1078	 * any locks.
1079	 *
1080	 * Unfortunately, fork() acquires every lock it can get its hands on, as
1081	 * previously detailed, so this function is highly likely to deadlock
1082	 * later on (see "deadlock here") if we're multithreaded.
1083	 *
1084	 * We might hack around this by having the clone()d child (init of the
1085	 * pid namespace) return directly, rather than leaving the clone()d
1086	 * process hanging around to be init for the new namespace (and having
1087	 * its fork()ed child return in turn), but that process would be crippled
1088	 * with its libc locks potentially broken. We might try fork()ing in the
1089	 * parent before we clone() to ensure that we own all the locks, but
1090	 * then we have to have the forked child hanging around consuming
1091	 * resources (and possibly having file descriptors / shared memory
1092	 * regions / etc attached). We'd need to keep the child around to avoid
1093	 * having its children get reparented to init.
1094	 *
1095	 * TODO(ellyjones): figure out if the "forked child hanging around"
1096	 * problem is fixable or not. It would be nice if we worked in this
1097	 * case.
1098	 */
1099	if (pid_namespace)
1100		child_pid = syscall(SYS_clone, CLONE_NEWPID | SIGCHLD, NULL);
1101	else
1102		child_pid = fork();
1103
1104	if (child_pid < 0) {
1105		free(oldenv_copy);
1106		die("failed to fork child");
1107	}
1108
1109	if (child_pid) {
1110		/* Restore parent's LD_PRELOAD. */
1111		if (oldenv_copy) {
1112			setenv(kLdPreloadEnvVar, oldenv_copy, 1);
1113			free(oldenv_copy);
1114		} else {
1115			unsetenv(kLdPreloadEnvVar);
1116		}
1117		unsetenv(kFdEnvVar);
1118
1119		j->initpid = child_pid;
1120
1121		/* Send marshalled minijail. */
1122		close(pipe_fds[0]);	/* read endpoint */
1123		ret = minijail_to_fd(j, pipe_fds[1]);
1124		close(pipe_fds[1]);	/* write endpoint */
1125		if (ret) {
1126			kill(j->initpid, SIGKILL);
1127			die("failed to send marshalled minijail");
1128		}
1129
1130		if (pchild_pid)
1131			*pchild_pid = child_pid;
1132
1133		/*
1134		 * If we want to write to the child process' standard input,
1135		 * set up the write end of the pipe.
1136		 */
1137		if (pstdin_fd)
1138			*pstdin_fd = setup_pipe_end(stdin_fds,
1139						    1	/* write end */);
1140
1141		/*
1142		 * If we want to read from the child process' standard output,
1143		 * set up the read end of the pipe.
1144		 */
1145		if (pstdout_fd)
1146			*pstdout_fd = setup_pipe_end(stdout_fds,
1147						     0	/* read end */);
1148
1149		/*
1150		 * If we want to read from the child process' standard error,
1151		 * set up the read end of the pipe.
1152		 */
1153		if (pstderr_fd)
1154			*pstderr_fd = setup_pipe_end(stderr_fds,
1155						     0	/* read end */);
1156
1157		return 0;
1158	}
1159	free(oldenv_copy);
1160
1161	/*
1162	 * If we want to write to the jailed process' standard input,
1163	 * set up the read end of the pipe.
1164	 */
1165	if (pstdin_fd) {
1166		if (setup_and_dupe_pipe_end(stdin_fds, 0 /* read end */,
1167					    STDIN_FILENO) < 0)
1168			die("failed to set up stdin pipe");
1169	}
1170
1171	/*
1172	 * If we want to read from the jailed process' standard output,
1173	 * set up the write end of the pipe.
1174	 */
1175	if (pstdout_fd) {
1176		if (setup_and_dupe_pipe_end(stdout_fds, 1 /* write end */,
1177					    STDOUT_FILENO) < 0)
1178			die("failed to set up stdout pipe");
1179	}
1180
1181	/*
1182	 * If we want to read from the jailed process' standard error,
1183	 * set up the write end of the pipe.
1184	 */
1185	if (pstderr_fd) {
1186		if (setup_and_dupe_pipe_end(stderr_fds, 1 /* write end */,
1187					    STDERR_FILENO) < 0)
1188			die("failed to set up stderr pipe");
1189	}
1190
1191	/* Strip out flags that cannot be inherited across execve. */
1192	minijail_preexec(j);
1193	/* Jail this process and its descendants... */
1194	minijail_enter(j);
1195
1196	if (pid_namespace) {
1197		/*
1198		 * pid namespace: this process will become init inside the new
1199		 * namespace, so fork off a child to actually run the program
1200		 * (we don't want all programs we might exec to have to know
1201		 * how to be init).
1202		 *
1203		 * If we're multithreaded, we'll probably deadlock here. See
1204		 * WARNING above.
1205		 */
1206		child_pid = fork();
1207		if (child_pid < 0)
1208			_exit(child_pid);
1209		else if (child_pid > 0)
1210			init(child_pid);	/* never returns */
1211	}
1212
1213	/*
1214	 * If we aren't pid-namespaced:
1215	 *   calling process
1216	 *   -> execve()-ing process
1217	 * If we are:
1218	 *   calling process
1219	 *   -> init()-ing process
1220	 *      -> execve()-ing process
1221	 */
1222	_exit(execve(filename, argv, environ));
1223}
1224
1225int API minijail_run_static(struct minijail *j, const char *filename,
1226			    char *const argv[])
1227{
1228	pid_t child_pid;
1229	int pid_namespace = j->flags.pids;
1230
1231	if (j->flags.caps)
1232		die("caps not supported with static targets");
1233
1234	if (pid_namespace)
1235		child_pid = syscall(SYS_clone, CLONE_NEWPID | SIGCHLD, NULL);
1236	else
1237		child_pid = fork();
1238
1239	if (child_pid < 0) {
1240		die("failed to fork child");
1241	}
1242	if (child_pid > 0 ) {
1243		j->initpid = child_pid;
1244		return 0;
1245	}
1246
1247	/*
1248	 * We can now drop this child into the sandbox
1249	 * then execve the target.
1250	 */
1251
1252	j->flags.pids = 0;
1253	minijail_enter(j);
1254
1255	if (pid_namespace) {
1256		/*
1257		 * pid namespace: this process will become init inside the new
1258		 * namespace, so fork off a child to actually run the program
1259		 * (we don't want all programs we might exec to have to know
1260		 * how to be init).
1261		 *
1262		 * If we're multithreaded, we'll probably deadlock here. See
1263		 * WARNING above.
1264		 */
1265		child_pid = fork();
1266		if (child_pid < 0)
1267			_exit(child_pid);
1268		else if (child_pid > 0)
1269			init(child_pid);	/* never returns */
1270	}
1271
1272	_exit(execve(filename, argv, environ));
1273}
1274
1275int API minijail_kill(struct minijail *j)
1276{
1277	int st;
1278	if (kill(j->initpid, SIGTERM))
1279		return -errno;
1280	if (waitpid(j->initpid, &st, 0) < 0)
1281		return -errno;
1282	return st;
1283}
1284
1285int API minijail_wait(struct minijail *j)
1286{
1287	int st;
1288	if (waitpid(j->initpid, &st, 0) < 0)
1289		return -errno;
1290
1291	if (!WIFEXITED(st)) {
1292		int error_status = st;
1293		if (WIFSIGNALED(st)) {
1294			int signum = WTERMSIG(st);
1295			warn("child process %d received signal %d",
1296			     j->initpid, signum);
1297			/*
1298			 * We return MINIJAIL_ERR_JAIL if the process received
1299			 * SIGSYS, which happens when a syscall is blocked by
1300			 * seccomp filters.
1301			 * If not, we do what bash(1) does:
1302			 * $? = 128 + signum
1303			 */
1304			if (signum == SIGSYS) {
1305				error_status = MINIJAIL_ERR_JAIL;
1306			} else {
1307				error_status = 128 + signum;
1308			}
1309		}
1310		return error_status;
1311	}
1312
1313	int exit_status = WEXITSTATUS(st);
1314	if (exit_status != 0)
1315		info("child process %d exited with status %d",
1316		     j->initpid, exit_status);
1317
1318	return exit_status;
1319}
1320
1321void API minijail_destroy(struct minijail *j)
1322{
1323	if (j->flags.seccomp_filter && j->filter_prog) {
1324		free(j->filter_prog->filter);
1325		free(j->filter_prog);
1326	}
1327	while (j->bindings_head) {
1328		struct binding *b = j->bindings_head;
1329		j->bindings_head = j->bindings_head->next;
1330		free(b->dest);
1331		free(b->src);
1332		free(b);
1333	}
1334	j->bindings_tail = NULL;
1335	if (j->user)
1336		free(j->user);
1337	if (j->chrootdir)
1338		free(j->chrootdir);
1339	free(j);
1340}
1341