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