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