Home | History | Annotate | Download | only in minijail
      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 _DEFAULT_SOURCE
      8 #define _GNU_SOURCE
      9 
     10 #include <asm/unistd.h>
     11 #include <dirent.h>
     12 #include <errno.h>
     13 #include <fcntl.h>
     14 #include <grp.h>
     15 #include <linux/capability.h>
     16 #include <pwd.h>
     17 #include <sched.h>
     18 #include <signal.h>
     19 #include <stdbool.h>
     20 #include <stddef.h>
     21 #include <stdio.h>
     22 #include <stdlib.h>
     23 #include <string.h>
     24 #include <sys/capability.h>
     25 #include <sys/mount.h>
     26 #include <sys/param.h>
     27 #include <sys/prctl.h>
     28 #include <sys/resource.h>
     29 #include <sys/stat.h>
     30 #include <sys/types.h>
     31 #include <sys/user.h>
     32 #include <sys/wait.h>
     33 #include <syscall.h>
     34 #include <unistd.h>
     35 
     36 #include "libminijail.h"
     37 #include "libminijail-private.h"
     38 
     39 #include "signal_handler.h"
     40 #include "syscall_filter.h"
     41 #include "syscall_wrapper.h"
     42 #include "system.h"
     43 #include "util.h"
     44 
     45 /* Until these are reliably available in linux/prctl.h. */
     46 #ifndef PR_ALT_SYSCALL
     47 # define PR_ALT_SYSCALL 0x43724f53
     48 #endif
     49 
     50 /* Seccomp filter related flags. */
     51 #ifndef PR_SET_NO_NEW_PRIVS
     52 # define PR_SET_NO_NEW_PRIVS 38
     53 #endif
     54 
     55 #ifndef SECCOMP_MODE_FILTER
     56 #define SECCOMP_MODE_FILTER 2 /* Uses user-supplied filter. */
     57 #endif
     58 
     59 #ifndef SECCOMP_SET_MODE_STRICT
     60 # define SECCOMP_SET_MODE_STRICT 0
     61 #endif
     62 #ifndef SECCOMP_SET_MODE_FILTER
     63 # define SECCOMP_SET_MODE_FILTER 1
     64 #endif
     65 
     66 #ifndef SECCOMP_FILTER_FLAG_TSYNC
     67 # define SECCOMP_FILTER_FLAG_TSYNC 1
     68 #endif
     69 /* End seccomp filter related flags. */
     70 
     71 /* New cgroup namespace might not be in linux-headers yet. */
     72 #ifndef CLONE_NEWCGROUP
     73 # define CLONE_NEWCGROUP 0x02000000
     74 #endif
     75 
     76 #define MAX_CGROUPS 10 /* 10 different controllers supported by Linux. */
     77 
     78 #define MAX_RLIMITS 32 /* Currently there are 15 supported by Linux. */
     79 
     80 /* Keyctl commands. */
     81 #define KEYCTL_JOIN_SESSION_KEYRING 1
     82 
     83 struct minijail_rlimit {
     84 	int type;
     85 	uint32_t cur;
     86 	uint32_t max;
     87 };
     88 
     89 struct mountpoint {
     90 	char *src;
     91 	char *dest;
     92 	char *type;
     93 	char *data;
     94 	int has_data;
     95 	unsigned long flags;
     96 	struct mountpoint *next;
     97 };
     98 
     99 struct minijail {
    100 	/*
    101 	 * WARNING: if you add a flag here you need to make sure it's
    102 	 * accounted for in minijail_pre{enter|exec}() below.
    103 	 */
    104 	struct {
    105 		int uid : 1;
    106 		int gid : 1;
    107 		int inherit_suppl_gids : 1;
    108 		int set_suppl_gids : 1;
    109 		int keep_suppl_gids : 1;
    110 		int use_caps : 1;
    111 		int capbset_drop : 1;
    112 		int set_ambient_caps : 1;
    113 		int vfs : 1;
    114 		int enter_vfs : 1;
    115 		int skip_remount_private : 1;
    116 		int pids : 1;
    117 		int ipc : 1;
    118 		int uts : 1;
    119 		int net : 1;
    120 		int enter_net : 1;
    121 		int ns_cgroups : 1;
    122 		int userns : 1;
    123 		int disable_setgroups : 1;
    124 		int seccomp : 1;
    125 		int remount_proc_ro : 1;
    126 		int no_new_privs : 1;
    127 		int seccomp_filter : 1;
    128 		int seccomp_filter_tsync : 1;
    129 		int seccomp_filter_logging : 1;
    130 		int chroot : 1;
    131 		int pivot_root : 1;
    132 		int mount_tmp : 1;
    133 		int do_init : 1;
    134 		int pid_file : 1;
    135 		int cgroups : 1;
    136 		int alt_syscall : 1;
    137 		int reset_signal_mask : 1;
    138 		int close_open_fds : 1;
    139 		int new_session_keyring : 1;
    140 		int forward_signals : 1;
    141 	} flags;
    142 	uid_t uid;
    143 	gid_t gid;
    144 	gid_t usergid;
    145 	char *user;
    146 	size_t suppl_gid_count;
    147 	gid_t *suppl_gid_list;
    148 	uint64_t caps;
    149 	uint64_t cap_bset;
    150 	pid_t initpid;
    151 	int mountns_fd;
    152 	int netns_fd;
    153 	char *chrootdir;
    154 	char *pid_file_path;
    155 	char *uidmap;
    156 	char *gidmap;
    157 	char *hostname;
    158 	size_t filter_len;
    159 	struct sock_fprog *filter_prog;
    160 	char *alt_syscall_table;
    161 	struct mountpoint *mounts_head;
    162 	struct mountpoint *mounts_tail;
    163 	size_t mounts_count;
    164 	size_t tmpfs_size;
    165 	char *cgroups[MAX_CGROUPS];
    166 	size_t cgroup_count;
    167 	struct minijail_rlimit rlimits[MAX_RLIMITS];
    168 	size_t rlimit_count;
    169 	uint64_t securebits_skip_mask;
    170 };
    171 
    172 /*
    173  * Strip out flags meant for the parent.
    174  * We keep things that are not inherited across execve(2) (e.g. capabilities),
    175  * or are easier to set after execve(2) (e.g. seccomp filters).
    176  */
    177 void minijail_preenter(struct minijail *j)
    178 {
    179 	j->flags.vfs = 0;
    180 	j->flags.enter_vfs = 0;
    181 	j->flags.skip_remount_private = 0;
    182 	j->flags.remount_proc_ro = 0;
    183 	j->flags.pids = 0;
    184 	j->flags.do_init = 0;
    185 	j->flags.pid_file = 0;
    186 	j->flags.cgroups = 0;
    187 	j->flags.forward_signals = 0;
    188 }
    189 
    190 /*
    191  * Strip out flags meant for the child.
    192  * We keep things that are inherited across execve(2).
    193  */
    194 void minijail_preexec(struct minijail *j)
    195 {
    196 	int vfs = j->flags.vfs;
    197 	int enter_vfs = j->flags.enter_vfs;
    198 	int skip_remount_private = j->flags.skip_remount_private;
    199 	int remount_proc_ro = j->flags.remount_proc_ro;
    200 	int userns = j->flags.userns;
    201 	if (j->user)
    202 		free(j->user);
    203 	j->user = NULL;
    204 	if (j->suppl_gid_list)
    205 		free(j->suppl_gid_list);
    206 	j->suppl_gid_list = NULL;
    207 	memset(&j->flags, 0, sizeof(j->flags));
    208 	/* Now restore anything we meant to keep. */
    209 	j->flags.vfs = vfs;
    210 	j->flags.enter_vfs = enter_vfs;
    211 	j->flags.skip_remount_private = skip_remount_private;
    212 	j->flags.remount_proc_ro = remount_proc_ro;
    213 	j->flags.userns = userns;
    214 	/* Note, |pids| will already have been used before this call. */
    215 }
    216 
    217 /* Minijail API. */
    218 
    219 struct minijail API *minijail_new(void)
    220 {
    221 	return calloc(1, sizeof(struct minijail));
    222 }
    223 
    224 void API minijail_change_uid(struct minijail *j, uid_t uid)
    225 {
    226 	if (uid == 0)
    227 		die("useless change to uid 0");
    228 	j->uid = uid;
    229 	j->flags.uid = 1;
    230 }
    231 
    232 void API minijail_change_gid(struct minijail *j, gid_t gid)
    233 {
    234 	if (gid == 0)
    235 		die("useless change to gid 0");
    236 	j->gid = gid;
    237 	j->flags.gid = 1;
    238 }
    239 
    240 void API minijail_set_supplementary_gids(struct minijail *j, size_t size,
    241 					 const gid_t *list)
    242 {
    243 	size_t i;
    244 
    245 	if (j->flags.inherit_suppl_gids)
    246 		die("cannot inherit *and* set supplementary groups");
    247 	if (j->flags.keep_suppl_gids)
    248 		die("cannot keep *and* set supplementary groups");
    249 
    250 	if (size == 0) {
    251 		/* Clear supplementary groups. */
    252 		j->suppl_gid_list = NULL;
    253 		j->suppl_gid_count = 0;
    254 		j->flags.set_suppl_gids = 1;
    255 		return;
    256 	}
    257 
    258 	/* Copy the gid_t array. */
    259 	j->suppl_gid_list = calloc(size, sizeof(gid_t));
    260 	if (!j->suppl_gid_list) {
    261 		die("failed to allocate internal supplementary group array");
    262 	}
    263 	for (i = 0; i < size; i++) {
    264 		j->suppl_gid_list[i] = list[i];
    265 	}
    266 	j->suppl_gid_count = size;
    267 	j->flags.set_suppl_gids = 1;
    268 }
    269 
    270 void API minijail_keep_supplementary_gids(struct minijail *j) {
    271 	j->flags.keep_suppl_gids = 1;
    272 }
    273 
    274 int API minijail_change_user(struct minijail *j, const char *user)
    275 {
    276 	char *buf = NULL;
    277 	struct passwd pw;
    278 	struct passwd *ppw = NULL;
    279 	ssize_t sz = sysconf(_SC_GETPW_R_SIZE_MAX);
    280 	if (sz == -1)
    281 		sz = 65536;	/* your guess is as good as mine... */
    282 
    283 	/*
    284 	 * sysconf(_SC_GETPW_R_SIZE_MAX), under glibc, is documented to return
    285 	 * the maximum needed size of the buffer, so we don't have to search.
    286 	 */
    287 	buf = malloc(sz);
    288 	if (!buf)
    289 		return -ENOMEM;
    290 	getpwnam_r(user, &pw, buf, sz, &ppw);
    291 	/*
    292 	 * We're safe to free the buffer here. The strings inside |pw| point
    293 	 * inside |buf|, but we don't use any of them; this leaves the pointers
    294 	 * dangling but it's safe. |ppw| points at |pw| if getpwnam_r(3)
    295 	 * succeeded.
    296 	 */
    297 	free(buf);
    298 	/* getpwnam_r(3) does *not* set errno when |ppw| is NULL. */
    299 	if (!ppw)
    300 		return -1;
    301 	minijail_change_uid(j, ppw->pw_uid);
    302 	j->user = strdup(user);
    303 	if (!j->user)
    304 		return -ENOMEM;
    305 	j->usergid = ppw->pw_gid;
    306 	return 0;
    307 }
    308 
    309 int API minijail_change_group(struct minijail *j, const char *group)
    310 {
    311 	char *buf = NULL;
    312 	struct group gr;
    313 	struct group *pgr = NULL;
    314 	ssize_t sz = sysconf(_SC_GETGR_R_SIZE_MAX);
    315 	if (sz == -1)
    316 		sz = 65536;	/* and mine is as good as yours, really */
    317 
    318 	/*
    319 	 * sysconf(_SC_GETGR_R_SIZE_MAX), under glibc, is documented to return
    320 	 * the maximum needed size of the buffer, so we don't have to search.
    321 	 */
    322 	buf = malloc(sz);
    323 	if (!buf)
    324 		return -ENOMEM;
    325 	getgrnam_r(group, &gr, buf, sz, &pgr);
    326 	/*
    327 	 * We're safe to free the buffer here. The strings inside gr point
    328 	 * inside buf, but we don't use any of them; this leaves the pointers
    329 	 * dangling but it's safe. pgr points at gr if getgrnam_r succeeded.
    330 	 */
    331 	free(buf);
    332 	/* getgrnam_r(3) does *not* set errno when |pgr| is NULL. */
    333 	if (!pgr)
    334 		return -1;
    335 	minijail_change_gid(j, pgr->gr_gid);
    336 	return 0;
    337 }
    338 
    339 void API minijail_use_seccomp(struct minijail *j)
    340 {
    341 	j->flags.seccomp = 1;
    342 }
    343 
    344 void API minijail_no_new_privs(struct minijail *j)
    345 {
    346 	j->flags.no_new_privs = 1;
    347 }
    348 
    349 void API minijail_use_seccomp_filter(struct minijail *j)
    350 {
    351 	j->flags.seccomp_filter = 1;
    352 }
    353 
    354 void API minijail_set_seccomp_filter_tsync(struct minijail *j)
    355 {
    356 	if (j->filter_len > 0 && j->filter_prog != NULL) {
    357 		die("minijail_set_seccomp_filter_tsync() must be called "
    358 		    "before minijail_parse_seccomp_filters()");
    359 	}
    360 	j->flags.seccomp_filter_tsync = 1;
    361 }
    362 
    363 void API minijail_log_seccomp_filter_failures(struct minijail *j)
    364 {
    365 	if (j->filter_len > 0 && j->filter_prog != NULL) {
    366 		die("minijail_log_seccomp_filter_failures() must be called "
    367 		    "before minijail_parse_seccomp_filters()");
    368 	}
    369 	j->flags.seccomp_filter_logging = 1;
    370 }
    371 
    372 void API minijail_use_caps(struct minijail *j, uint64_t capmask)
    373 {
    374 	/*
    375 	 * 'minijail_use_caps' configures a runtime-capabilities-only
    376 	 * environment, including a bounding set matching the thread's runtime
    377 	 * (permitted|inheritable|effective) sets.
    378 	 * Therefore, it will override any existing bounding set configurations
    379 	 * since the latter would allow gaining extra runtime capabilities from
    380 	 * file capabilities.
    381 	 */
    382 	if (j->flags.capbset_drop) {
    383 		warn("overriding bounding set configuration");
    384 		j->cap_bset = 0;
    385 		j->flags.capbset_drop = 0;
    386 	}
    387 	j->caps = capmask;
    388 	j->flags.use_caps = 1;
    389 }
    390 
    391 void API minijail_capbset_drop(struct minijail *j, uint64_t capmask)
    392 {
    393 	if (j->flags.use_caps) {
    394 		/*
    395 		 * 'minijail_use_caps' will have already configured a capability
    396 		 * bounding set matching the (permitted|inheritable|effective)
    397 		 * sets. Abort if the user tries to configure a separate
    398 		 * bounding set. 'minijail_capbset_drop' and 'minijail_use_caps'
    399 		 * are mutually exclusive.
    400 		 */
    401 		die("runtime capabilities already configured, can't drop "
    402 		    "bounding set separately");
    403 	}
    404 	j->cap_bset = capmask;
    405 	j->flags.capbset_drop = 1;
    406 }
    407 
    408 void API minijail_set_ambient_caps(struct minijail *j)
    409 {
    410 	j->flags.set_ambient_caps = 1;
    411 }
    412 
    413 void API minijail_reset_signal_mask(struct minijail *j)
    414 {
    415 	j->flags.reset_signal_mask = 1;
    416 }
    417 
    418 void API minijail_namespace_vfs(struct minijail *j)
    419 {
    420 	j->flags.vfs = 1;
    421 }
    422 
    423 void API minijail_namespace_enter_vfs(struct minijail *j, const char *ns_path)
    424 {
    425 	int ns_fd = open(ns_path, O_RDONLY | O_CLOEXEC);
    426 	if (ns_fd < 0) {
    427 		pdie("failed to open namespace '%s'", ns_path);
    428 	}
    429 	j->mountns_fd = ns_fd;
    430 	j->flags.enter_vfs = 1;
    431 }
    432 
    433 void API minijail_new_session_keyring(struct minijail *j)
    434 {
    435 	j->flags.new_session_keyring = 1;
    436 }
    437 
    438 void API minijail_skip_setting_securebits(struct minijail *j,
    439 					  uint64_t securebits_skip_mask)
    440 {
    441 	j->securebits_skip_mask = securebits_skip_mask;
    442 }
    443 
    444 void API minijail_skip_remount_private(struct minijail *j)
    445 {
    446 	j->flags.skip_remount_private = 1;
    447 }
    448 
    449 void API minijail_namespace_pids(struct minijail *j)
    450 {
    451 	j->flags.vfs = 1;
    452 	j->flags.remount_proc_ro = 1;
    453 	j->flags.pids = 1;
    454 	j->flags.do_init = 1;
    455 }
    456 
    457 void API minijail_namespace_ipc(struct minijail *j)
    458 {
    459 	j->flags.ipc = 1;
    460 }
    461 
    462 void API minijail_namespace_uts(struct minijail *j)
    463 {
    464 	j->flags.uts = 1;
    465 }
    466 
    467 int API minijail_namespace_set_hostname(struct minijail *j, const char *name)
    468 {
    469 	if (j->hostname)
    470 		return -EINVAL;
    471 	minijail_namespace_uts(j);
    472 	j->hostname = strdup(name);
    473 	if (!j->hostname)
    474 		return -ENOMEM;
    475 	return 0;
    476 }
    477 
    478 void API minijail_namespace_net(struct minijail *j)
    479 {
    480 	j->flags.net = 1;
    481 }
    482 
    483 void API minijail_namespace_enter_net(struct minijail *j, const char *ns_path)
    484 {
    485 	int ns_fd = open(ns_path, O_RDONLY | O_CLOEXEC);
    486 	if (ns_fd < 0) {
    487 		pdie("failed to open namespace '%s'", ns_path);
    488 	}
    489 	j->netns_fd = ns_fd;
    490 	j->flags.enter_net = 1;
    491 }
    492 
    493 void API minijail_namespace_cgroups(struct minijail *j)
    494 {
    495 	j->flags.ns_cgroups = 1;
    496 }
    497 
    498 void API minijail_close_open_fds(struct minijail *j)
    499 {
    500 	j->flags.close_open_fds = 1;
    501 }
    502 
    503 void API minijail_remount_proc_readonly(struct minijail *j)
    504 {
    505 	j->flags.vfs = 1;
    506 	j->flags.remount_proc_ro = 1;
    507 }
    508 
    509 void API minijail_namespace_user(struct minijail *j)
    510 {
    511 	j->flags.userns = 1;
    512 }
    513 
    514 void API minijail_namespace_user_disable_setgroups(struct minijail *j)
    515 {
    516 	j->flags.disable_setgroups = 1;
    517 }
    518 
    519 int API minijail_uidmap(struct minijail *j, const char *uidmap)
    520 {
    521 	j->uidmap = strdup(uidmap);
    522 	if (!j->uidmap)
    523 		return -ENOMEM;
    524 	char *ch;
    525 	for (ch = j->uidmap; *ch; ch++) {
    526 		if (*ch == ',')
    527 			*ch = '\n';
    528 	}
    529 	return 0;
    530 }
    531 
    532 int API minijail_gidmap(struct minijail *j, const char *gidmap)
    533 {
    534 	j->gidmap = strdup(gidmap);
    535 	if (!j->gidmap)
    536 		return -ENOMEM;
    537 	char *ch;
    538 	for (ch = j->gidmap; *ch; ch++) {
    539 		if (*ch == ',')
    540 			*ch = '\n';
    541 	}
    542 	return 0;
    543 }
    544 
    545 void API minijail_inherit_usergroups(struct minijail *j)
    546 {
    547 	j->flags.inherit_suppl_gids = 1;
    548 }
    549 
    550 void API minijail_run_as_init(struct minijail *j)
    551 {
    552 	/*
    553 	 * Since the jailed program will become 'init' in the new PID namespace,
    554 	 * Minijail does not need to fork an 'init' process.
    555 	 */
    556 	j->flags.do_init = 0;
    557 }
    558 
    559 int API minijail_enter_chroot(struct minijail *j, const char *dir)
    560 {
    561 	if (j->chrootdir)
    562 		return -EINVAL;
    563 	j->chrootdir = strdup(dir);
    564 	if (!j->chrootdir)
    565 		return -ENOMEM;
    566 	j->flags.chroot = 1;
    567 	return 0;
    568 }
    569 
    570 int API minijail_enter_pivot_root(struct minijail *j, const char *dir)
    571 {
    572 	if (j->chrootdir)
    573 		return -EINVAL;
    574 	j->chrootdir = strdup(dir);
    575 	if (!j->chrootdir)
    576 		return -ENOMEM;
    577 	j->flags.pivot_root = 1;
    578 	return 0;
    579 }
    580 
    581 char API *minijail_get_original_path(struct minijail *j,
    582 				     const char *path_inside_chroot)
    583 {
    584 	struct mountpoint *b;
    585 
    586 	b = j->mounts_head;
    587 	while (b) {
    588 		/*
    589 		 * If |path_inside_chroot| is the exact destination of a
    590 		 * mount, then the original path is exactly the source of
    591 		 * the mount.
    592 		 *  for example: "-b /some/path/exe,/chroot/path/exe"
    593 		 *    mount source = /some/path/exe, mount dest =
    594 		 *    /chroot/path/exe Then when getting the original path of
    595 		 *    "/chroot/path/exe", the source of that mount,
    596 		 *    "/some/path/exe" is what should be returned.
    597 		 */
    598 		if (!strcmp(b->dest, path_inside_chroot))
    599 			return strdup(b->src);
    600 
    601 		/*
    602 		 * If |path_inside_chroot| is within the destination path of a
    603 		 * mount, take the suffix of the chroot path relative to the
    604 		 * mount destination path, and append it to the mount source
    605 		 * path.
    606 		 */
    607 		if (!strncmp(b->dest, path_inside_chroot, strlen(b->dest))) {
    608 			const char *relative_path =
    609 				path_inside_chroot + strlen(b->dest);
    610 			return path_join(b->src, relative_path);
    611 		}
    612 		b = b->next;
    613 	}
    614 
    615 	/* If there is a chroot path, append |path_inside_chroot| to that. */
    616 	if (j->chrootdir)
    617 		return path_join(j->chrootdir, path_inside_chroot);
    618 
    619 	/* No chroot, so the path outside is the same as it is inside. */
    620 	return strdup(path_inside_chroot);
    621 }
    622 
    623 size_t minijail_get_tmpfs_size(const struct minijail *j)
    624 {
    625 	return j->tmpfs_size;
    626 }
    627 
    628 void API minijail_mount_tmp(struct minijail *j)
    629 {
    630 	minijail_mount_tmp_size(j, 64 * 1024 * 1024);
    631 }
    632 
    633 void API minijail_mount_tmp_size(struct minijail *j, size_t size)
    634 {
    635 	j->tmpfs_size = size;
    636 	j->flags.mount_tmp = 1;
    637 }
    638 
    639 int API minijail_write_pid_file(struct minijail *j, const char *path)
    640 {
    641 	j->pid_file_path = strdup(path);
    642 	if (!j->pid_file_path)
    643 		return -ENOMEM;
    644 	j->flags.pid_file = 1;
    645 	return 0;
    646 }
    647 
    648 int API minijail_add_to_cgroup(struct minijail *j, const char *path)
    649 {
    650 	if (j->cgroup_count >= MAX_CGROUPS)
    651 		return -ENOMEM;
    652 	j->cgroups[j->cgroup_count] = strdup(path);
    653 	if (!j->cgroups[j->cgroup_count])
    654 		return -ENOMEM;
    655 	j->cgroup_count++;
    656 	j->flags.cgroups = 1;
    657 	return 0;
    658 }
    659 
    660 int API minijail_rlimit(struct minijail *j, int type, uint32_t cur,
    661 			uint32_t max)
    662 {
    663 	size_t i;
    664 
    665 	if (j->rlimit_count >= MAX_RLIMITS)
    666 		return -ENOMEM;
    667 	/* It's an error if the caller sets the same rlimit multiple times. */
    668 	for (i = 0; i < j->rlimit_count; i++) {
    669 		if (j->rlimits[i].type == type)
    670 			return -EEXIST;
    671 	}
    672 
    673 	j->rlimits[j->rlimit_count].type = type;
    674 	j->rlimits[j->rlimit_count].cur = cur;
    675 	j->rlimits[j->rlimit_count].max = max;
    676 	j->rlimit_count++;
    677 	return 0;
    678 }
    679 
    680 int API minijail_forward_signals(struct minijail *j)
    681 {
    682 	j->flags.forward_signals = 1;
    683 	return 0;
    684 }
    685 
    686 int API minijail_mount_with_data(struct minijail *j, const char *src,
    687 				 const char *dest, const char *type,
    688 				 unsigned long flags, const char *data)
    689 {
    690 	struct mountpoint *m;
    691 
    692 	if (*dest != '/')
    693 		return -EINVAL;
    694 	m = calloc(1, sizeof(*m));
    695 	if (!m)
    696 		return -ENOMEM;
    697 	m->dest = strdup(dest);
    698 	if (!m->dest)
    699 		goto error;
    700 	m->src = strdup(src);
    701 	if (!m->src)
    702 		goto error;
    703 	m->type = strdup(type);
    704 	if (!m->type)
    705 		goto error;
    706 	if (data) {
    707 		m->data = strdup(data);
    708 		if (!m->data)
    709 			goto error;
    710 		m->has_data = 1;
    711 	}
    712 	m->flags = flags;
    713 
    714 	info("mount %s -> %s type '%s'", src, dest, type);
    715 
    716 	/*
    717 	 * Force vfs namespacing so the mounts don't leak out into the
    718 	 * containing vfs namespace.
    719 	 */
    720 	minijail_namespace_vfs(j);
    721 
    722 	if (j->mounts_tail)
    723 		j->mounts_tail->next = m;
    724 	else
    725 		j->mounts_head = m;
    726 	j->mounts_tail = m;
    727 	j->mounts_count++;
    728 
    729 	return 0;
    730 
    731 error:
    732 	free(m->type);
    733 	free(m->src);
    734 	free(m->dest);
    735 	free(m);
    736 	return -ENOMEM;
    737 }
    738 
    739 int API minijail_mount(struct minijail *j, const char *src, const char *dest,
    740 		       const char *type, unsigned long flags)
    741 {
    742 	return minijail_mount_with_data(j, src, dest, type, flags, NULL);
    743 }
    744 
    745 int API minijail_bind(struct minijail *j, const char *src, const char *dest,
    746 		      int writeable)
    747 {
    748 	unsigned long flags = MS_BIND;
    749 
    750 	if (!writeable)
    751 		flags |= MS_RDONLY;
    752 
    753 	return minijail_mount(j, src, dest, "", flags);
    754 }
    755 
    756 static void clear_seccomp_options(struct minijail *j)
    757 {
    758 	j->flags.seccomp_filter = 0;
    759 	j->flags.seccomp_filter_tsync = 0;
    760 	j->flags.seccomp_filter_logging = 0;
    761 	j->filter_len = 0;
    762 	j->filter_prog = NULL;
    763 	j->flags.no_new_privs = 0;
    764 }
    765 
    766 static int seccomp_should_parse_filters(struct minijail *j)
    767 {
    768 	if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, NULL) == -1) {
    769 		/*
    770 		 * |errno| will be set to EINVAL when seccomp has not been
    771 		 * compiled into the kernel. On certain platforms and kernel
    772 		 * versions this is not a fatal failure. In that case, and only
    773 		 * in that case, disable seccomp and skip loading the filters.
    774 		 */
    775 		if ((errno == EINVAL) && seccomp_can_softfail()) {
    776 			warn("not loading seccomp filters, seccomp filter not "
    777 			     "supported");
    778 			clear_seccomp_options(j);
    779 			return 0;
    780 		}
    781 		/*
    782 		 * If |errno| != EINVAL or seccomp_can_softfail() is false,
    783 		 * we can proceed. Worst case scenario minijail_enter() will
    784 		 * abort() if seccomp fails.
    785 		 */
    786 	}
    787 	if (j->flags.seccomp_filter_tsync) {
    788 		/* Are the seccomp(2) syscall and the TSYNC option supported? */
    789 		if (sys_seccomp(SECCOMP_SET_MODE_FILTER,
    790 				SECCOMP_FILTER_FLAG_TSYNC, NULL) == -1) {
    791 			int saved_errno = errno;
    792 			if (saved_errno == ENOSYS && seccomp_can_softfail()) {
    793 				warn("seccomp(2) syscall not supported");
    794 				clear_seccomp_options(j);
    795 				return 0;
    796 			} else if (saved_errno == EINVAL &&
    797 				   seccomp_can_softfail()) {
    798 				warn(
    799 				    "seccomp filter thread sync not supported");
    800 				clear_seccomp_options(j);
    801 				return 0;
    802 			}
    803 			/*
    804 			 * Similar logic here. If seccomp_can_softfail() is
    805 			 * false, or |errno| != ENOSYS, or |errno| != EINVAL,
    806 			 * we can proceed. Worst case scenario minijail_enter()
    807 			 * will abort() if seccomp or TSYNC fail.
    808 			 */
    809 		}
    810 	}
    811 	return 1;
    812 }
    813 
    814 static int parse_seccomp_filters(struct minijail *j, FILE *policy_file)
    815 {
    816 	struct sock_fprog *fprog = malloc(sizeof(struct sock_fprog));
    817 	int use_ret_trap =
    818 	    j->flags.seccomp_filter_tsync || j->flags.seccomp_filter_logging;
    819 	int allow_logging = j->flags.seccomp_filter_logging;
    820 
    821 	if (compile_filter(policy_file, fprog, use_ret_trap, allow_logging)) {
    822 		free(fprog);
    823 		return -1;
    824 	}
    825 
    826 	j->filter_len = fprog->len;
    827 	j->filter_prog = fprog;
    828 	return 0;
    829 }
    830 
    831 void API minijail_parse_seccomp_filters(struct minijail *j, const char *path)
    832 {
    833 	if (!seccomp_should_parse_filters(j))
    834 		return;
    835 
    836 	FILE *file = fopen(path, "r");
    837 	if (!file) {
    838 		pdie("failed to open seccomp filter file '%s'", path);
    839 	}
    840 
    841 	if (parse_seccomp_filters(j, file) != 0) {
    842 		die("failed to compile seccomp filter BPF program in '%s'",
    843 		    path);
    844 	}
    845 	fclose(file);
    846 }
    847 
    848 void API minijail_parse_seccomp_filters_from_fd(struct minijail *j, int fd)
    849 {
    850 	if (!seccomp_should_parse_filters(j))
    851 		return;
    852 
    853 	FILE *file = fdopen(fd, "r");
    854 	if (!file) {
    855 		pdie("failed to associate stream with fd %d", fd);
    856 	}
    857 
    858 	if (parse_seccomp_filters(j, file) != 0) {
    859 		die("failed to compile seccomp filter BPF program from fd %d",
    860 		    fd);
    861 	}
    862 	fclose(file);
    863 }
    864 
    865 int API minijail_use_alt_syscall(struct minijail *j, const char *table)
    866 {
    867 	j->alt_syscall_table = strdup(table);
    868 	if (!j->alt_syscall_table)
    869 		return -ENOMEM;
    870 	j->flags.alt_syscall = 1;
    871 	return 0;
    872 }
    873 
    874 struct marshal_state {
    875 	size_t available;
    876 	size_t total;
    877 	char *buf;
    878 };
    879 
    880 void marshal_state_init(struct marshal_state *state, char *buf,
    881 			size_t available)
    882 {
    883 	state->available = available;
    884 	state->buf = buf;
    885 	state->total = 0;
    886 }
    887 
    888 void marshal_append(struct marshal_state *state, void *src, size_t length)
    889 {
    890 	size_t copy_len = MIN(state->available, length);
    891 
    892 	/* Up to |available| will be written. */
    893 	if (copy_len) {
    894 		memcpy(state->buf, src, copy_len);
    895 		state->buf += copy_len;
    896 		state->available -= copy_len;
    897 	}
    898 	/* |total| will contain the expected length. */
    899 	state->total += length;
    900 }
    901 
    902 void marshal_mount(struct marshal_state *state, const struct mountpoint *m)
    903 {
    904 	marshal_append(state, m->src, strlen(m->src) + 1);
    905 	marshal_append(state, m->dest, strlen(m->dest) + 1);
    906 	marshal_append(state, m->type, strlen(m->type) + 1);
    907 	marshal_append(state, (char *)&m->has_data, sizeof(m->has_data));
    908 	if (m->has_data)
    909 		marshal_append(state, m->data, strlen(m->data) + 1);
    910 	marshal_append(state, (char *)&m->flags, sizeof(m->flags));
    911 }
    912 
    913 void minijail_marshal_helper(struct marshal_state *state,
    914 			     const struct minijail *j)
    915 {
    916 	struct mountpoint *m = NULL;
    917 	size_t i;
    918 
    919 	marshal_append(state, (char *)j, sizeof(*j));
    920 	if (j->user)
    921 		marshal_append(state, j->user, strlen(j->user) + 1);
    922 	if (j->suppl_gid_list) {
    923 		marshal_append(state, j->suppl_gid_list,
    924 			       j->suppl_gid_count * sizeof(gid_t));
    925 	}
    926 	if (j->chrootdir)
    927 		marshal_append(state, j->chrootdir, strlen(j->chrootdir) + 1);
    928 	if (j->hostname)
    929 		marshal_append(state, j->hostname, strlen(j->hostname) + 1);
    930 	if (j->alt_syscall_table) {
    931 		marshal_append(state, j->alt_syscall_table,
    932 			       strlen(j->alt_syscall_table) + 1);
    933 	}
    934 	if (j->flags.seccomp_filter && j->filter_prog) {
    935 		struct sock_fprog *fp = j->filter_prog;
    936 		marshal_append(state, (char *)fp->filter,
    937 			       fp->len * sizeof(struct sock_filter));
    938 	}
    939 	for (m = j->mounts_head; m; m = m->next) {
    940 		marshal_mount(state, m);
    941 	}
    942 	for (i = 0; i < j->cgroup_count; ++i)
    943 		marshal_append(state, j->cgroups[i], strlen(j->cgroups[i]) + 1);
    944 }
    945 
    946 size_t API minijail_size(const struct minijail *j)
    947 {
    948 	struct marshal_state state;
    949 	marshal_state_init(&state, NULL, 0);
    950 	minijail_marshal_helper(&state, j);
    951 	return state.total;
    952 }
    953 
    954 int minijail_marshal(const struct minijail *j, char *buf, size_t available)
    955 {
    956 	struct marshal_state state;
    957 	marshal_state_init(&state, buf, available);
    958 	minijail_marshal_helper(&state, j);
    959 	return (state.total > available);
    960 }
    961 
    962 int minijail_unmarshal(struct minijail *j, char *serialized, size_t length)
    963 {
    964 	size_t i;
    965 	size_t count;
    966 	int ret = -EINVAL;
    967 
    968 	if (length < sizeof(*j))
    969 		goto out;
    970 	memcpy((void *)j, serialized, sizeof(*j));
    971 	serialized += sizeof(*j);
    972 	length -= sizeof(*j);
    973 
    974 	/* Potentially stale pointers not used as signals. */
    975 	j->pid_file_path = NULL;
    976 	j->uidmap = NULL;
    977 	j->gidmap = NULL;
    978 	j->mounts_head = NULL;
    979 	j->mounts_tail = NULL;
    980 	j->filter_prog = NULL;
    981 
    982 	if (j->user) {		/* stale pointer */
    983 		char *user = consumestr(&serialized, &length);
    984 		if (!user)
    985 			goto clear_pointers;
    986 		j->user = strdup(user);
    987 		if (!j->user)
    988 			goto clear_pointers;
    989 	}
    990 
    991 	if (j->suppl_gid_list) {	/* stale pointer */
    992 		if (j->suppl_gid_count > NGROUPS_MAX) {
    993 			goto bad_gid_list;
    994 		}
    995 		size_t gid_list_size = j->suppl_gid_count * sizeof(gid_t);
    996 		void *gid_list_bytes =
    997 		    consumebytes(gid_list_size, &serialized, &length);
    998 		if (!gid_list_bytes)
    999 			goto bad_gid_list;
   1000 
   1001 		j->suppl_gid_list = calloc(j->suppl_gid_count, sizeof(gid_t));
   1002 		if (!j->suppl_gid_list)
   1003 			goto bad_gid_list;
   1004 
   1005 		memcpy(j->suppl_gid_list, gid_list_bytes, gid_list_size);
   1006 	}
   1007 
   1008 	if (j->chrootdir) {	/* stale pointer */
   1009 		char *chrootdir = consumestr(&serialized, &length);
   1010 		if (!chrootdir)
   1011 			goto bad_chrootdir;
   1012 		j->chrootdir = strdup(chrootdir);
   1013 		if (!j->chrootdir)
   1014 			goto bad_chrootdir;
   1015 	}
   1016 
   1017 	if (j->hostname) {	/* stale pointer */
   1018 		char *hostname = consumestr(&serialized, &length);
   1019 		if (!hostname)
   1020 			goto bad_hostname;
   1021 		j->hostname = strdup(hostname);
   1022 		if (!j->hostname)
   1023 			goto bad_hostname;
   1024 	}
   1025 
   1026 	if (j->alt_syscall_table) {	/* stale pointer */
   1027 		char *alt_syscall_table = consumestr(&serialized, &length);
   1028 		if (!alt_syscall_table)
   1029 			goto bad_syscall_table;
   1030 		j->alt_syscall_table = strdup(alt_syscall_table);
   1031 		if (!j->alt_syscall_table)
   1032 			goto bad_syscall_table;
   1033 	}
   1034 
   1035 	if (j->flags.seccomp_filter && j->filter_len > 0) {
   1036 		size_t ninstrs = j->filter_len;
   1037 		if (ninstrs > (SIZE_MAX / sizeof(struct sock_filter)) ||
   1038 		    ninstrs > USHRT_MAX)
   1039 			goto bad_filters;
   1040 
   1041 		size_t program_len = ninstrs * sizeof(struct sock_filter);
   1042 		void *program = consumebytes(program_len, &serialized, &length);
   1043 		if (!program)
   1044 			goto bad_filters;
   1045 
   1046 		j->filter_prog = malloc(sizeof(struct sock_fprog));
   1047 		if (!j->filter_prog)
   1048 			goto bad_filters;
   1049 
   1050 		j->filter_prog->len = ninstrs;
   1051 		j->filter_prog->filter = malloc(program_len);
   1052 		if (!j->filter_prog->filter)
   1053 			goto bad_filter_prog_instrs;
   1054 
   1055 		memcpy(j->filter_prog->filter, program, program_len);
   1056 	}
   1057 
   1058 	count = j->mounts_count;
   1059 	j->mounts_count = 0;
   1060 	for (i = 0; i < count; ++i) {
   1061 		unsigned long *flags;
   1062 		int *has_data;
   1063 		const char *dest;
   1064 		const char *type;
   1065 		const char *data = NULL;
   1066 		const char *src = consumestr(&serialized, &length);
   1067 		if (!src)
   1068 			goto bad_mounts;
   1069 		dest = consumestr(&serialized, &length);
   1070 		if (!dest)
   1071 			goto bad_mounts;
   1072 		type = consumestr(&serialized, &length);
   1073 		if (!type)
   1074 			goto bad_mounts;
   1075 		has_data = consumebytes(sizeof(*has_data), &serialized,
   1076 					&length);
   1077 		if (!has_data)
   1078 			goto bad_mounts;
   1079 		if (*has_data) {
   1080 			data = consumestr(&serialized, &length);
   1081 			if (!data)
   1082 				goto bad_mounts;
   1083 		}
   1084 		flags = consumebytes(sizeof(*flags), &serialized, &length);
   1085 		if (!flags)
   1086 			goto bad_mounts;
   1087 		if (minijail_mount_with_data(j, src, dest, type, *flags, data))
   1088 			goto bad_mounts;
   1089 	}
   1090 
   1091 	count = j->cgroup_count;
   1092 	j->cgroup_count = 0;
   1093 	for (i = 0; i < count; ++i) {
   1094 		char *cgroup = consumestr(&serialized, &length);
   1095 		if (!cgroup)
   1096 			goto bad_cgroups;
   1097 		j->cgroups[i] = strdup(cgroup);
   1098 		if (!j->cgroups[i])
   1099 			goto bad_cgroups;
   1100 		++j->cgroup_count;
   1101 	}
   1102 
   1103 	return 0;
   1104 
   1105 bad_cgroups:
   1106 	while (j->mounts_head) {
   1107 		struct mountpoint *m = j->mounts_head;
   1108 		j->mounts_head = j->mounts_head->next;
   1109 		free(m->data);
   1110 		free(m->type);
   1111 		free(m->dest);
   1112 		free(m->src);
   1113 		free(m);
   1114 	}
   1115 	for (i = 0; i < j->cgroup_count; ++i)
   1116 		free(j->cgroups[i]);
   1117 bad_mounts:
   1118 	if (j->flags.seccomp_filter && j->filter_len > 0) {
   1119 		free(j->filter_prog->filter);
   1120 		free(j->filter_prog);
   1121 	}
   1122 bad_filter_prog_instrs:
   1123 	if (j->filter_prog)
   1124 		free(j->filter_prog);
   1125 bad_filters:
   1126 	if (j->alt_syscall_table)
   1127 		free(j->alt_syscall_table);
   1128 bad_syscall_table:
   1129 	if (j->chrootdir)
   1130 		free(j->chrootdir);
   1131 bad_chrootdir:
   1132 	if (j->hostname)
   1133 		free(j->hostname);
   1134 bad_hostname:
   1135 	if (j->suppl_gid_list)
   1136 		free(j->suppl_gid_list);
   1137 bad_gid_list:
   1138 	if (j->user)
   1139 		free(j->user);
   1140 clear_pointers:
   1141 	j->user = NULL;
   1142 	j->suppl_gid_list = NULL;
   1143 	j->chrootdir = NULL;
   1144 	j->hostname = NULL;
   1145 	j->alt_syscall_table = NULL;
   1146 	j->cgroup_count = 0;
   1147 out:
   1148 	return ret;
   1149 }
   1150 
   1151 /*
   1152  * mount_one: Applies mounts from @m for @j, recursing as needed.
   1153  * @j Minijail these mounts are for
   1154  * @m Head of list of mounts
   1155  *
   1156  * Returns 0 for success.
   1157  */
   1158 static int mount_one(const struct minijail *j, struct mountpoint *m)
   1159 {
   1160 	int ret;
   1161 	char *dest;
   1162 	int remount_ro = 0;
   1163 
   1164 	/* |dest| has a leading "/". */
   1165 	if (asprintf(&dest, "%s%s", j->chrootdir, m->dest) < 0)
   1166 		return -ENOMEM;
   1167 
   1168 	if (setup_mount_destination(m->src, dest, j->uid, j->gid))
   1169 		pdie("creating mount target '%s' failed", dest);
   1170 
   1171 	/*
   1172 	 * R/O bind mounts have to be remounted since 'bind' and 'ro'
   1173 	 * can't both be specified in the original bind mount.
   1174 	 * Remount R/O after the initial mount.
   1175 	 */
   1176 	if ((m->flags & MS_BIND) && (m->flags & MS_RDONLY)) {
   1177 		remount_ro = 1;
   1178 		m->flags &= ~MS_RDONLY;
   1179 	}
   1180 
   1181 	ret = mount(m->src, dest, m->type, m->flags, m->data);
   1182 	if (ret)
   1183 		pdie("mount: %s -> %s", m->src, dest);
   1184 
   1185 	if (remount_ro) {
   1186 		m->flags |= MS_RDONLY;
   1187 		ret = mount(m->src, dest, NULL,
   1188 			    m->flags | MS_REMOUNT, m->data);
   1189 		if (ret)
   1190 			pdie("bind ro: %s -> %s", m->src, dest);
   1191 	}
   1192 
   1193 	free(dest);
   1194 	if (m->next)
   1195 		return mount_one(j, m->next);
   1196 	return ret;
   1197 }
   1198 
   1199 static int enter_chroot(const struct minijail *j)
   1200 {
   1201 	int ret;
   1202 
   1203 	if (j->mounts_head && (ret = mount_one(j, j->mounts_head)))
   1204 		return ret;
   1205 
   1206 	if (chroot(j->chrootdir))
   1207 		return -errno;
   1208 
   1209 	if (chdir("/"))
   1210 		return -errno;
   1211 
   1212 	return 0;
   1213 }
   1214 
   1215 static int enter_pivot_root(const struct minijail *j)
   1216 {
   1217 	int ret, oldroot, newroot;
   1218 
   1219 	if (j->mounts_head && (ret = mount_one(j, j->mounts_head)))
   1220 		return ret;
   1221 
   1222 	/*
   1223 	 * Keep the fd for both old and new root.
   1224 	 * It will be used in fchdir(2) later.
   1225 	 */
   1226 	oldroot = open("/", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
   1227 	if (oldroot < 0)
   1228 		pdie("failed to open / for fchdir");
   1229 	newroot = open(j->chrootdir, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
   1230 	if (newroot < 0)
   1231 		pdie("failed to open %s for fchdir", j->chrootdir);
   1232 
   1233 	/*
   1234 	 * To ensure j->chrootdir is the root of a filesystem,
   1235 	 * do a self bind mount.
   1236 	 */
   1237 	if (mount(j->chrootdir, j->chrootdir, "bind", MS_BIND | MS_REC, ""))
   1238 		pdie("failed to bind mount '%s'", j->chrootdir);
   1239 	if (chdir(j->chrootdir))
   1240 		return -errno;
   1241 	if (syscall(SYS_pivot_root, ".", "."))
   1242 		pdie("pivot_root");
   1243 
   1244 	/*
   1245 	 * Now the old root is mounted on top of the new root. Use fchdir(2) to
   1246 	 * change to the old root and unmount it.
   1247 	 */
   1248 	if (fchdir(oldroot))
   1249 		pdie("failed to fchdir to old /");
   1250 
   1251 	/*
   1252 	 * If j->flags.skip_remount_private was enabled for minijail_enter(),
   1253 	 * there could be a shared mount point under |oldroot|. In that case,
   1254 	 * mounts under this shared mount point will be unmounted below, and
   1255 	 * this unmounting will propagate to the original mount namespace
   1256 	 * (because the mount point is shared). To prevent this unexpected
   1257 	 * unmounting, remove these mounts from their peer groups by recursively
   1258 	 * remounting them as MS_PRIVATE.
   1259 	 */
   1260 	if (mount(NULL, ".", NULL, MS_REC | MS_PRIVATE, NULL))
   1261 		pdie("failed to mount(/, private) before umount(/)");
   1262 	/* The old root might be busy, so use lazy unmount. */
   1263 	if (umount2(".", MNT_DETACH))
   1264 		pdie("umount(/)");
   1265 	/* Change back to the new root. */
   1266 	if (fchdir(newroot))
   1267 		return -errno;
   1268 	if (close(oldroot))
   1269 		return -errno;
   1270 	if (close(newroot))
   1271 		return -errno;
   1272 	if (chroot("/"))
   1273 		return -errno;
   1274 	/* Set correct CWD for getcwd(3). */
   1275 	if (chdir("/"))
   1276 		return -errno;
   1277 
   1278 	return 0;
   1279 }
   1280 
   1281 static int mount_tmp(const struct minijail *j)
   1282 {
   1283 	const char fmt[] = "size=%zu,mode=1777";
   1284 	/* Count for the user storing ULLONG_MAX literally + extra space. */
   1285 	char data[sizeof(fmt) + sizeof("18446744073709551615ULL")];
   1286 	int ret;
   1287 
   1288 	ret = snprintf(data, sizeof(data), fmt, j->tmpfs_size);
   1289 
   1290 	if (ret <= 0)
   1291 		pdie("tmpfs size spec error");
   1292 	else if ((size_t)ret >= sizeof(data))
   1293 		pdie("tmpfs size spec too large");
   1294 	return mount("none", "/tmp", "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID,
   1295 		     data);
   1296 }
   1297 
   1298 static int remount_proc_readonly(const struct minijail *j)
   1299 {
   1300 	const char *kProcPath = "/proc";
   1301 	const unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
   1302 	/*
   1303 	 * Right now, we're holding a reference to our parent's old mount of
   1304 	 * /proc in our namespace, which means using MS_REMOUNT here would
   1305 	 * mutate our parent's mount as well, even though we're in a VFS
   1306 	 * namespace (!). Instead, remove their mount from our namespace lazily
   1307 	 * (MNT_DETACH) and make our own.
   1308 	 */
   1309 	if (umount2(kProcPath, MNT_DETACH)) {
   1310 		/*
   1311 		 * If we are in a new user namespace, umount(2) will fail.
   1312 		 * See http://man7.org/linux/man-pages/man7/user_namespaces.7.html
   1313 		 */
   1314 		if (j->flags.userns) {
   1315 			info("umount(/proc, MNT_DETACH) failed, "
   1316 			     "this is expected when using user namespaces");
   1317 		} else {
   1318 			return -errno;
   1319 		}
   1320 	}
   1321 	if (mount("proc", kProcPath, "proc", kSafeFlags | MS_RDONLY, ""))
   1322 		return -errno;
   1323 	return 0;
   1324 }
   1325 
   1326 static void kill_child_and_die(const struct minijail *j, const char *msg)
   1327 {
   1328 	kill(j->initpid, SIGKILL);
   1329 	die("%s", msg);
   1330 }
   1331 
   1332 static void write_pid_file_or_die(const struct minijail *j)
   1333 {
   1334 	if (write_pid_to_path(j->initpid, j->pid_file_path))
   1335 		kill_child_and_die(j, "failed to write pid file");
   1336 }
   1337 
   1338 static void add_to_cgroups_or_die(const struct minijail *j)
   1339 {
   1340 	size_t i;
   1341 
   1342 	for (i = 0; i < j->cgroup_count; ++i) {
   1343 		if (write_pid_to_path(j->initpid, j->cgroups[i]))
   1344 			kill_child_and_die(j, "failed to add to cgroups");
   1345 	}
   1346 }
   1347 
   1348 static void set_rlimits_or_die(const struct minijail *j)
   1349 {
   1350 	size_t i;
   1351 
   1352 	for (i = 0; i < j->rlimit_count; ++i) {
   1353 		struct rlimit limit;
   1354 		limit.rlim_cur = j->rlimits[i].cur;
   1355 		limit.rlim_max = j->rlimits[i].max;
   1356 		if (prlimit(j->initpid, j->rlimits[i].type, &limit, NULL))
   1357 			kill_child_and_die(j, "failed to set rlimit");
   1358 	}
   1359 }
   1360 
   1361 static void write_ugid_maps_or_die(const struct minijail *j)
   1362 {
   1363 	if (j->uidmap && write_proc_file(j->initpid, j->uidmap, "uid_map") != 0)
   1364 		kill_child_and_die(j, "failed to write uid_map");
   1365 	if (j->gidmap && j->flags.disable_setgroups) {
   1366 		/* Older kernels might not have the /proc/<pid>/setgroups files. */
   1367 		int ret = write_proc_file(j->initpid, "deny", "setgroups");
   1368 		if (ret != 0) {
   1369 			if (ret == -ENOENT) {
   1370 				/* See http://man7.org/linux/man-pages/man7/user_namespaces.7.html. */
   1371 				warn("could not disable setgroups(2)");
   1372 			} else
   1373 				kill_child_and_die(j, "failed to disable setgroups(2)");
   1374 		}
   1375 	}
   1376 	if (j->gidmap && write_proc_file(j->initpid, j->gidmap, "gid_map") != 0)
   1377 		kill_child_and_die(j, "failed to write gid_map");
   1378 }
   1379 
   1380 static void enter_user_namespace(const struct minijail *j)
   1381 {
   1382 	if (j->uidmap && setresuid(0, 0, 0))
   1383 		pdie("user_namespaces: setresuid(0, 0, 0) failed");
   1384 	if (j->gidmap && setresgid(0, 0, 0))
   1385 		pdie("user_namespaces: setresgid(0, 0, 0) failed");
   1386 }
   1387 
   1388 static void parent_setup_complete(int *pipe_fds)
   1389 {
   1390 	close(pipe_fds[0]);
   1391 	close(pipe_fds[1]);
   1392 }
   1393 
   1394 /*
   1395  * wait_for_parent_setup: Called by the child process to wait for any
   1396  * further parent-side setup to complete before continuing.
   1397  */
   1398 static void wait_for_parent_setup(int *pipe_fds)
   1399 {
   1400 	char buf;
   1401 
   1402 	close(pipe_fds[1]);
   1403 
   1404 	/* Wait for parent to complete setup and close the pipe. */
   1405 	if (read(pipe_fds[0], &buf, 1) != 0)
   1406 		die("failed to sync with parent");
   1407 	close(pipe_fds[0]);
   1408 }
   1409 
   1410 static void drop_ugid(const struct minijail *j)
   1411 {
   1412 	if (j->flags.inherit_suppl_gids + j->flags.keep_suppl_gids +
   1413 	    j->flags.set_suppl_gids > 1) {
   1414 		die("can only do one of inherit, keep, or set supplementary "
   1415 		    "groups");
   1416 	}
   1417 
   1418 	if (j->flags.inherit_suppl_gids) {
   1419 		if (initgroups(j->user, j->usergid))
   1420 			pdie("initgroups(%s, %d) failed", j->user, j->usergid);
   1421 	} else if (j->flags.set_suppl_gids) {
   1422 		if (setgroups(j->suppl_gid_count, j->suppl_gid_list))
   1423 			pdie("setgroups(suppl_gids) failed");
   1424 	} else if (!j->flags.keep_suppl_gids) {
   1425 		/*
   1426 		 * Only attempt to clear supplementary groups if we are changing
   1427 		 * users or groups.
   1428 		 */
   1429 		if ((j->flags.uid || j->flags.gid) && setgroups(0, NULL))
   1430 			pdie("setgroups(0, NULL) failed");
   1431 	}
   1432 
   1433 	if (j->flags.gid && setresgid(j->gid, j->gid, j->gid))
   1434 		pdie("setresgid(%d, %d, %d) failed", j->gid, j->gid, j->gid);
   1435 
   1436 	if (j->flags.uid && setresuid(j->uid, j->uid, j->uid))
   1437 		pdie("setresuid(%d, %d, %d) failed", j->uid, j->uid, j->uid);
   1438 }
   1439 
   1440 static void drop_capbset(uint64_t keep_mask, unsigned int last_valid_cap)
   1441 {
   1442 	const uint64_t one = 1;
   1443 	unsigned int i;
   1444 	for (i = 0; i < sizeof(keep_mask) * 8 && i <= last_valid_cap; ++i) {
   1445 		if (keep_mask & (one << i))
   1446 			continue;
   1447 		if (prctl(PR_CAPBSET_DROP, i))
   1448 			pdie("could not drop capability from bounding set");
   1449 	}
   1450 }
   1451 
   1452 static void drop_caps(const struct minijail *j, unsigned int last_valid_cap)
   1453 {
   1454 	if (!j->flags.use_caps)
   1455 		return;
   1456 
   1457 	cap_t caps = cap_get_proc();
   1458 	cap_value_t flag[1];
   1459 	const size_t ncaps = sizeof(j->caps) * 8;
   1460 	const uint64_t one = 1;
   1461 	unsigned int i;
   1462 	if (!caps)
   1463 		die("can't get process caps");
   1464 	if (cap_clear(caps))
   1465 		die("can't clear caps");
   1466 
   1467 	for (i = 0; i < ncaps && i <= last_valid_cap; ++i) {
   1468 		/* Keep CAP_SETPCAP for dropping bounding set bits. */
   1469 		if (i != CAP_SETPCAP && !(j->caps & (one << i)))
   1470 			continue;
   1471 		flag[0] = i;
   1472 		if (cap_set_flag(caps, CAP_EFFECTIVE, 1, flag, CAP_SET))
   1473 			die("can't add effective cap");
   1474 		if (cap_set_flag(caps, CAP_PERMITTED, 1, flag, CAP_SET))
   1475 			die("can't add permitted cap");
   1476 		if (cap_set_flag(caps, CAP_INHERITABLE, 1, flag, CAP_SET))
   1477 			die("can't add inheritable cap");
   1478 	}
   1479 	if (cap_set_proc(caps))
   1480 		die("can't apply initial cleaned capset");
   1481 
   1482 	/*
   1483 	 * Instead of dropping bounding set first, do it here in case
   1484 	 * the caller had a more permissive bounding set which could
   1485 	 * have been used above to raise a capability that wasn't already
   1486 	 * present. This requires CAP_SETPCAP, so we raised/kept it above.
   1487 	 */
   1488 	drop_capbset(j->caps, last_valid_cap);
   1489 
   1490 	/* If CAP_SETPCAP wasn't specifically requested, now we remove it. */
   1491 	if ((j->caps & (one << CAP_SETPCAP)) == 0) {
   1492 		flag[0] = CAP_SETPCAP;
   1493 		if (cap_set_flag(caps, CAP_EFFECTIVE, 1, flag, CAP_CLEAR))
   1494 			die("can't clear effective cap");
   1495 		if (cap_set_flag(caps, CAP_PERMITTED, 1, flag, CAP_CLEAR))
   1496 			die("can't clear permitted cap");
   1497 		if (cap_set_flag(caps, CAP_INHERITABLE, 1, flag, CAP_CLEAR))
   1498 			die("can't clear inheritable cap");
   1499 	}
   1500 
   1501 	if (cap_set_proc(caps))
   1502 		die("can't apply final cleaned capset");
   1503 
   1504 	/*
   1505 	 * If ambient capabilities are supported, clear all capabilities first,
   1506 	 * then raise the requested ones.
   1507 	 */
   1508 	if (j->flags.set_ambient_caps) {
   1509 		if (!cap_ambient_supported()) {
   1510 			pdie("ambient capabilities not supported");
   1511 		}
   1512 		if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) !=
   1513 		    0) {
   1514 			pdie("can't clear ambient capabilities");
   1515 		}
   1516 
   1517 		for (i = 0; i < ncaps && i <= last_valid_cap; ++i) {
   1518 			if (!(j->caps & (one << i)))
   1519 				continue;
   1520 
   1521 			if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0,
   1522 				  0) != 0) {
   1523 				pdie("prctl(PR_CAP_AMBIENT, "
   1524 				     "PR_CAP_AMBIENT_RAISE, %u) failed",
   1525 				     i);
   1526 			}
   1527 		}
   1528 	}
   1529 
   1530 	cap_free(caps);
   1531 }
   1532 
   1533 static void set_seccomp_filter(const struct minijail *j)
   1534 {
   1535 	/*
   1536 	 * Set no_new_privs. See </kernel/seccomp.c> and </kernel/sys.c>
   1537 	 * in the kernel source tree for an explanation of the parameters.
   1538 	 */
   1539 	if (j->flags.no_new_privs) {
   1540 		if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
   1541 			pdie("prctl(PR_SET_NO_NEW_PRIVS)");
   1542 	}
   1543 
   1544 	/*
   1545 	 * Code running with ASan
   1546 	 * (https://github.com/google/sanitizers/wiki/AddressSanitizer)
   1547 	 * will make system calls not included in the syscall filter policy,
   1548 	 * which will likely crash the program. Skip setting seccomp filter in
   1549 	 * that case.
   1550 	 * 'running_with_asan()' has no inputs and is completely defined at
   1551 	 * build time, so this cannot be used by an attacker to skip setting
   1552 	 * seccomp filter.
   1553 	 */
   1554 	if (j->flags.seccomp_filter && running_with_asan()) {
   1555 		warn("running with ASan, not setting seccomp filter");
   1556 		return;
   1557 	}
   1558 
   1559 	if (j->flags.seccomp_filter) {
   1560 		if (j->flags.seccomp_filter_logging) {
   1561 			/*
   1562 			 * If logging seccomp filter failures,
   1563 			 * install the SIGSYS handler first.
   1564 			 */
   1565 			if (install_sigsys_handler())
   1566 				pdie("failed to install SIGSYS handler");
   1567 			warn("logging seccomp filter failures");
   1568 		} else if (j->flags.seccomp_filter_tsync) {
   1569 			/*
   1570 			 * If setting thread sync,
   1571 			 * reset the SIGSYS signal handler so that
   1572 			 * the entire thread group is killed.
   1573 			 */
   1574 			if (signal(SIGSYS, SIG_DFL) == SIG_ERR)
   1575 				pdie("failed to reset SIGSYS disposition");
   1576 			info("reset SIGSYS disposition");
   1577 		}
   1578 	}
   1579 
   1580 	/*
   1581 	 * Install the syscall filter.
   1582 	 */
   1583 	if (j->flags.seccomp_filter) {
   1584 		if (j->flags.seccomp_filter_tsync) {
   1585 			if (sys_seccomp(SECCOMP_SET_MODE_FILTER,
   1586 					SECCOMP_FILTER_FLAG_TSYNC,
   1587 					j->filter_prog)) {
   1588 				pdie("seccomp(tsync) failed");
   1589 			}
   1590 		} else {
   1591 			if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER,
   1592 				  j->filter_prog)) {
   1593 				pdie("prctl(seccomp_filter) failed");
   1594 			}
   1595 		}
   1596 	}
   1597 }
   1598 
   1599 static pid_t forward_pid = -1;
   1600 
   1601 static void forward_signal(__attribute__((unused)) int nr,
   1602 			   __attribute__((unused)) siginfo_t *siginfo,
   1603 			   __attribute__((unused)) void *void_context)
   1604 {
   1605 	if (forward_pid != -1) {
   1606 		kill(forward_pid, nr);
   1607 	}
   1608 }
   1609 
   1610 static void install_signal_handlers(void)
   1611 {
   1612 	struct sigaction act;
   1613 
   1614 	memset(&act, 0, sizeof(act));
   1615 	act.sa_sigaction = &forward_signal;
   1616 	act.sa_flags = SA_SIGINFO | SA_RESTART;
   1617 
   1618 	/* Handle all signals, except SIGCHLD. */
   1619 	for (int nr = 1; nr < NSIG; nr++) {
   1620 		/*
   1621 		 * We don't care if we get EINVAL: that just means that we
   1622 		 * can't handle this signal, so let's skip it and continue.
   1623 		 */
   1624 		sigaction(nr, &act, NULL);
   1625 	}
   1626 	/* Reset SIGCHLD's handler. */
   1627 	signal(SIGCHLD, SIG_DFL);
   1628 
   1629 	/* Handle real-time signals. */
   1630 	for (int nr = SIGRTMIN; nr <= SIGRTMAX; nr++) {
   1631 		sigaction(nr, &act, NULL);
   1632 	}
   1633 }
   1634 
   1635 void API minijail_enter(const struct minijail *j)
   1636 {
   1637 	/*
   1638 	 * If we're dropping caps, get the last valid cap from /proc now,
   1639 	 * since /proc can be unmounted before drop_caps() is called.
   1640 	 */
   1641 	unsigned int last_valid_cap = 0;
   1642 	if (j->flags.capbset_drop || j->flags.use_caps)
   1643 		last_valid_cap = get_last_valid_cap();
   1644 
   1645 	if (j->flags.pids)
   1646 		die("tried to enter a pid-namespaced jail;"
   1647 		    " try minijail_run()?");
   1648 
   1649 	if (j->flags.inherit_suppl_gids && !j->user)
   1650 		die("cannot inherit supplementary groups without setting a "
   1651 		    "username");
   1652 
   1653 	/*
   1654 	 * We can't recover from failures if we've dropped privileges partially,
   1655 	 * so we don't even try. If any of our operations fail, we abort() the
   1656 	 * entire process.
   1657 	 */
   1658 	if (j->flags.enter_vfs && setns(j->mountns_fd, CLONE_NEWNS))
   1659 		pdie("setns(CLONE_NEWNS) failed");
   1660 
   1661 	if (j->flags.vfs) {
   1662 		if (unshare(CLONE_NEWNS))
   1663 			pdie("unshare(CLONE_NEWNS) failed");
   1664 		/*
   1665 		 * Unless asked not to, remount all filesystems as private.
   1666 		 * If they are shared, new bind mounts will creep out of our
   1667 		 * namespace.
   1668 		 * https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
   1669 		 */
   1670 		if (!j->flags.skip_remount_private) {
   1671 			if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL))
   1672 				pdie("mount(NULL, /, NULL, MS_REC | MS_PRIVATE,"
   1673 				     " NULL) failed");
   1674 		}
   1675 	}
   1676 
   1677 	if (j->flags.ipc && unshare(CLONE_NEWIPC)) {
   1678 		pdie("unshare(CLONE_NEWIPC) failed");
   1679 	}
   1680 
   1681 	if (j->flags.uts) {
   1682 		if (unshare(CLONE_NEWUTS))
   1683 			pdie("unshare(CLONE_NEWUTS) failed");
   1684 
   1685 		if (j->hostname && sethostname(j->hostname, strlen(j->hostname)))
   1686 			pdie("sethostname(%s) failed", j->hostname);
   1687 	}
   1688 
   1689 	if (j->flags.enter_net) {
   1690 		if (setns(j->netns_fd, CLONE_NEWNET))
   1691 			pdie("setns(CLONE_NEWNET) failed");
   1692 	} else if (j->flags.net) {
   1693 		if (unshare(CLONE_NEWNET))
   1694 			pdie("unshare(CLONE_NEWNET) failed");
   1695 		config_net_loopback();
   1696 	}
   1697 
   1698 	if (j->flags.ns_cgroups && unshare(CLONE_NEWCGROUP))
   1699 		pdie("unshare(CLONE_NEWCGROUP) failed");
   1700 
   1701 	if (j->flags.new_session_keyring) {
   1702 		if (syscall(SYS_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL) < 0)
   1703 			pdie("keyctl(KEYCTL_JOIN_SESSION_KEYRING) failed");
   1704 	}
   1705 
   1706 	if (j->flags.chroot && enter_chroot(j))
   1707 		pdie("chroot");
   1708 
   1709 	if (j->flags.pivot_root && enter_pivot_root(j))
   1710 		pdie("pivot_root");
   1711 
   1712 	if (j->flags.mount_tmp && mount_tmp(j))
   1713 		pdie("mount_tmp");
   1714 
   1715 	if (j->flags.remount_proc_ro && remount_proc_readonly(j))
   1716 		pdie("remount");
   1717 
   1718 	/*
   1719 	 * If we're only dropping capabilities from the bounding set, but not
   1720 	 * from the thread's (permitted|inheritable|effective) sets, do it now.
   1721 	 */
   1722 	if (j->flags.capbset_drop) {
   1723 		drop_capbset(j->cap_bset, last_valid_cap);
   1724 	}
   1725 
   1726 	if (j->flags.use_caps) {
   1727 		/*
   1728 		 * POSIX capabilities are a bit tricky. If we drop our
   1729 		 * capability to change uids, our attempt to use setuid()
   1730 		 * below will fail. Hang on to root caps across setuid(), then
   1731 		 * lock securebits.
   1732 		 */
   1733 		if (prctl(PR_SET_KEEPCAPS, 1))
   1734 			pdie("prctl(PR_SET_KEEPCAPS) failed");
   1735 
   1736 		if (lock_securebits(j->securebits_skip_mask) < 0) {
   1737 			pdie("locking securebits failed");
   1738 		}
   1739 	}
   1740 
   1741 	if (j->flags.no_new_privs) {
   1742 		/*
   1743 		 * If we're setting no_new_privs, we can drop privileges
   1744 		 * before setting seccomp filter. This way filter policies
   1745 		 * don't need to allow privilege-dropping syscalls.
   1746 		 */
   1747 		drop_ugid(j);
   1748 		drop_caps(j, last_valid_cap);
   1749 		set_seccomp_filter(j);
   1750 	} else {
   1751 		/*
   1752 		 * If we're not setting no_new_privs,
   1753 		 * we need to set seccomp filter *before* dropping privileges.
   1754 		 * WARNING: this means that filter policies *must* allow
   1755 		 * setgroups()/setresgid()/setresuid() for dropping root and
   1756 		 * capget()/capset()/prctl() for dropping caps.
   1757 		 */
   1758 		set_seccomp_filter(j);
   1759 		drop_ugid(j);
   1760 		drop_caps(j, last_valid_cap);
   1761 	}
   1762 
   1763 	/*
   1764 	 * Select the specified alternate syscall table.  The table must not
   1765 	 * block prctl(2) if we're using seccomp as well.
   1766 	 */
   1767 	if (j->flags.alt_syscall) {
   1768 		if (prctl(PR_ALT_SYSCALL, 1, j->alt_syscall_table))
   1769 			pdie("prctl(PR_ALT_SYSCALL) failed");
   1770 	}
   1771 
   1772 	/*
   1773 	 * seccomp has to come last since it cuts off all the other
   1774 	 * privilege-dropping syscalls :)
   1775 	 */
   1776 	if (j->flags.seccomp && prctl(PR_SET_SECCOMP, 1)) {
   1777 		if ((errno == EINVAL) && seccomp_can_softfail()) {
   1778 			warn("seccomp not supported");
   1779 			return;
   1780 		}
   1781 		pdie("prctl(PR_SET_SECCOMP) failed");
   1782 	}
   1783 }
   1784 
   1785 /* TODO(wad): will visibility affect this variable? */
   1786 static int init_exitstatus = 0;
   1787 
   1788 void init_term(int __attribute__ ((unused)) sig)
   1789 {
   1790 	_exit(init_exitstatus);
   1791 }
   1792 
   1793 void init(pid_t rootpid)
   1794 {
   1795 	pid_t pid;
   1796 	int status;
   1797 	/* So that we exit with the right status. */
   1798 	signal(SIGTERM, init_term);
   1799 	/* TODO(wad): self jail with seccomp filters here. */
   1800 	while ((pid = wait(&status)) > 0) {
   1801 		/*
   1802 		 * This loop will only end when either there are no processes
   1803 		 * left inside our pid namespace or we get a signal.
   1804 		 */
   1805 		if (pid == rootpid)
   1806 			init_exitstatus = status;
   1807 	}
   1808 	if (!WIFEXITED(init_exitstatus))
   1809 		_exit(MINIJAIL_ERR_INIT);
   1810 	_exit(WEXITSTATUS(init_exitstatus));
   1811 }
   1812 
   1813 int API minijail_from_fd(int fd, struct minijail *j)
   1814 {
   1815 	size_t sz = 0;
   1816 	size_t bytes = read(fd, &sz, sizeof(sz));
   1817 	char *buf;
   1818 	int r;
   1819 	if (sizeof(sz) != bytes)
   1820 		return -EINVAL;
   1821 	if (sz > USHRT_MAX)	/* arbitrary sanity check */
   1822 		return -E2BIG;
   1823 	buf = malloc(sz);
   1824 	if (!buf)
   1825 		return -ENOMEM;
   1826 	bytes = read(fd, buf, sz);
   1827 	if (bytes != sz) {
   1828 		free(buf);
   1829 		return -EINVAL;
   1830 	}
   1831 	r = minijail_unmarshal(j, buf, sz);
   1832 	free(buf);
   1833 	return r;
   1834 }
   1835 
   1836 int API minijail_to_fd(struct minijail *j, int fd)
   1837 {
   1838 	char *buf;
   1839 	size_t sz = minijail_size(j);
   1840 	ssize_t written;
   1841 	int r;
   1842 
   1843 	if (!sz)
   1844 		return -EINVAL;
   1845 	buf = malloc(sz);
   1846 	r = minijail_marshal(j, buf, sz);
   1847 	if (r) {
   1848 		free(buf);
   1849 		return r;
   1850 	}
   1851 	/* Sends [size][minijail]. */
   1852 	written = write(fd, &sz, sizeof(sz));
   1853 	if (written != sizeof(sz)) {
   1854 		free(buf);
   1855 		return -EFAULT;
   1856 	}
   1857 	written = write(fd, buf, sz);
   1858 	if (written < 0 || (size_t) written != sz) {
   1859 		free(buf);
   1860 		return -EFAULT;
   1861 	}
   1862 	free(buf);
   1863 	return 0;
   1864 }
   1865 
   1866 int setup_preload(void)
   1867 {
   1868 #if defined(__ANDROID__)
   1869 	/* Don't use LDPRELOAD on Android. */
   1870 	return 0;
   1871 #else
   1872 	char *oldenv = getenv(kLdPreloadEnvVar) ? : "";
   1873 	char *newenv = malloc(strlen(oldenv) + 2 + strlen(PRELOADPATH));
   1874 	if (!newenv)
   1875 		return -ENOMEM;
   1876 
   1877 	/* Only insert a separating space if we have something to separate... */
   1878 	sprintf(newenv, "%s%s%s", oldenv, strlen(oldenv) ? " " : "",
   1879 		PRELOADPATH);
   1880 
   1881 	/* setenv() makes a copy of the string we give it. */
   1882 	setenv(kLdPreloadEnvVar, newenv, 1);
   1883 	free(newenv);
   1884 	return 0;
   1885 #endif
   1886 }
   1887 
   1888 static int setup_pipe(int fds[2])
   1889 {
   1890 	int r = pipe(fds);
   1891 	char fd_buf[11];
   1892 	if (r)
   1893 		return r;
   1894 	r = snprintf(fd_buf, sizeof(fd_buf), "%d", fds[0]);
   1895 	if (r <= 0)
   1896 		return -EINVAL;
   1897 	setenv(kFdEnvVar, fd_buf, 1);
   1898 	return 0;
   1899 }
   1900 
   1901 static int close_open_fds(int *inheritable_fds, size_t size)
   1902 {
   1903 	const char *kFdPath = "/proc/self/fd";
   1904 
   1905 	DIR *d = opendir(kFdPath);
   1906 	struct dirent *dir_entry;
   1907 
   1908 	if (d == NULL)
   1909 		return -1;
   1910 	int dir_fd = dirfd(d);
   1911 	while ((dir_entry = readdir(d)) != NULL) {
   1912 		size_t i;
   1913 		char *end;
   1914 		bool should_close = true;
   1915 		const int fd = strtol(dir_entry->d_name, &end, 10);
   1916 
   1917 		if ((*end) != '\0') {
   1918 			continue;
   1919 		}
   1920 		/*
   1921 		 * We might have set up some pipes that we want to share with
   1922 		 * the parent process, and should not be closed.
   1923 		 */
   1924 		for (i = 0; i < size; ++i) {
   1925 			if (fd == inheritable_fds[i]) {
   1926 				should_close = false;
   1927 				break;
   1928 			}
   1929 		}
   1930 		/* Also avoid closing the directory fd. */
   1931 		if (should_close && fd != dir_fd)
   1932 			close(fd);
   1933 	}
   1934 	closedir(d);
   1935 	return 0;
   1936 }
   1937 
   1938 int minijail_run_internal(struct minijail *j, const char *filename,
   1939 			  char *const argv[], pid_t *pchild_pid,
   1940 			  int *pstdin_fd, int *pstdout_fd, int *pstderr_fd,
   1941 			  int use_preload);
   1942 
   1943 int API minijail_run(struct minijail *j, const char *filename,
   1944 		     char *const argv[])
   1945 {
   1946 	return minijail_run_internal(j, filename, argv, NULL, NULL, NULL, NULL,
   1947 				     true);
   1948 }
   1949 
   1950 int API minijail_run_pid(struct minijail *j, const char *filename,
   1951 			 char *const argv[], pid_t *pchild_pid)
   1952 {
   1953 	return minijail_run_internal(j, filename, argv, pchild_pid,
   1954 				     NULL, NULL, NULL, true);
   1955 }
   1956 
   1957 int API minijail_run_pipe(struct minijail *j, const char *filename,
   1958 			  char *const argv[], int *pstdin_fd)
   1959 {
   1960 	return minijail_run_internal(j, filename, argv, NULL, pstdin_fd,
   1961 				     NULL, NULL, true);
   1962 }
   1963 
   1964 int API minijail_run_pid_pipes(struct minijail *j, const char *filename,
   1965 			       char *const argv[], pid_t *pchild_pid,
   1966 			       int *pstdin_fd, int *pstdout_fd, int *pstderr_fd)
   1967 {
   1968 	return minijail_run_internal(j, filename, argv, pchild_pid,
   1969 				     pstdin_fd, pstdout_fd, pstderr_fd, true);
   1970 }
   1971 
   1972 int API minijail_run_no_preload(struct minijail *j, const char *filename,
   1973 				char *const argv[])
   1974 {
   1975 	return minijail_run_internal(j, filename, argv, NULL, NULL, NULL, NULL,
   1976 				     false);
   1977 }
   1978 
   1979 int API minijail_run_pid_pipes_no_preload(struct minijail *j,
   1980 					  const char *filename,
   1981 					  char *const argv[],
   1982 					  pid_t *pchild_pid,
   1983 					  int *pstdin_fd, int *pstdout_fd,
   1984 					  int *pstderr_fd)
   1985 {
   1986 	return minijail_run_internal(j, filename, argv, pchild_pid,
   1987 				     pstdin_fd, pstdout_fd, pstderr_fd, false);
   1988 }
   1989 
   1990 int minijail_run_internal(struct minijail *j, const char *filename,
   1991 			  char *const argv[], pid_t *pchild_pid,
   1992 			  int *pstdin_fd, int *pstdout_fd, int *pstderr_fd,
   1993 			  int use_preload)
   1994 {
   1995 	char *oldenv, *oldenv_copy = NULL;
   1996 	pid_t child_pid;
   1997 	int pipe_fds[2];
   1998 	int stdin_fds[2];
   1999 	int stdout_fds[2];
   2000 	int stderr_fds[2];
   2001 	int child_sync_pipe_fds[2];
   2002 	int sync_child = 0;
   2003 	int ret;
   2004 	/* We need to remember this across the minijail_preexec() call. */
   2005 	int pid_namespace = j->flags.pids;
   2006 	int do_init = j->flags.do_init;
   2007 
   2008 	if (use_preload) {
   2009 		oldenv = getenv(kLdPreloadEnvVar);
   2010 		if (oldenv) {
   2011 			oldenv_copy = strdup(oldenv);
   2012 			if (!oldenv_copy)
   2013 				return -ENOMEM;
   2014 		}
   2015 
   2016 		if (setup_preload())
   2017 			return -EFAULT;
   2018 	}
   2019 
   2020 	if (!use_preload) {
   2021 		if (j->flags.use_caps && j->caps != 0 &&
   2022 		    !j->flags.set_ambient_caps) {
   2023 			die("non-empty, non-ambient capabilities are not "
   2024 			    "supported without LD_PRELOAD");
   2025 		}
   2026 	}
   2027 
   2028 	/*
   2029 	 * Make the process group ID of this process equal to its PID.
   2030 	 * In the non-interactive case (e.g. when the parent process is started
   2031 	 * from init) this ensures the parent process and the jailed process
   2032 	 * can be killed together.
   2033 	 * When the parent process is started from the console this ensures
   2034 	 * the call to setsid(2) in the jailed process succeeds.
   2035 	 *
   2036 	 * Don't fail on EPERM, since setpgid(0, 0) can only EPERM when
   2037 	 * the process is already a process group leader.
   2038 	 */
   2039 	if (setpgid(0 /* use calling PID */, 0 /* make PGID = PID */)) {
   2040 		if (errno != EPERM) {
   2041 			pdie("setpgid(0, 0) failed");
   2042 		}
   2043 	}
   2044 
   2045 	if (use_preload) {
   2046 		/*
   2047 		 * Before we fork(2) and execve(2) the child process, we need
   2048 		 * to open a pipe(2) to send the minijail configuration over.
   2049 		 */
   2050 		if (setup_pipe(pipe_fds))
   2051 			return -EFAULT;
   2052 	}
   2053 
   2054 	/*
   2055 	 * If we want to write to the child process' standard input,
   2056 	 * create the pipe(2) now.
   2057 	 */
   2058 	if (pstdin_fd) {
   2059 		if (pipe(stdin_fds))
   2060 			return -EFAULT;
   2061 	}
   2062 
   2063 	/*
   2064 	 * If we want to read from the child process' standard output,
   2065 	 * create the pipe(2) now.
   2066 	 */
   2067 	if (pstdout_fd) {
   2068 		if (pipe(stdout_fds))
   2069 			return -EFAULT;
   2070 	}
   2071 
   2072 	/*
   2073 	 * If we want to read from the child process' standard error,
   2074 	 * create the pipe(2) now.
   2075 	 */
   2076 	if (pstderr_fd) {
   2077 		if (pipe(stderr_fds))
   2078 			return -EFAULT;
   2079 	}
   2080 
   2081 	/*
   2082 	 * If we want to set up a new uid/gid map in the user namespace,
   2083 	 * or if we need to add the child process to cgroups, create the pipe(2)
   2084 	 * to sync between parent and child.
   2085 	 */
   2086 	if (j->flags.userns || j->flags.cgroups) {
   2087 		sync_child = 1;
   2088 		if (pipe(child_sync_pipe_fds))
   2089 			return -EFAULT;
   2090 	}
   2091 
   2092 	/*
   2093 	 * Use sys_clone() if and only if we're creating a pid namespace.
   2094 	 *
   2095 	 * tl;dr: WARNING: do not mix pid namespaces and multithreading.
   2096 	 *
   2097 	 * In multithreaded programs, there are a bunch of locks inside libc,
   2098 	 * some of which may be held by other threads at the time that we call
   2099 	 * minijail_run_pid(). If we call fork(), glibc does its level best to
   2100 	 * ensure that we hold all of these locks before it calls clone()
   2101 	 * internally and drop them after clone() returns, but when we call
   2102 	 * sys_clone(2) directly, all that gets bypassed and we end up with a
   2103 	 * child address space where some of libc's important locks are held by
   2104 	 * other threads (which did not get cloned, and hence will never release
   2105 	 * those locks). This is okay so long as we call exec() immediately
   2106 	 * after, but a bunch of seemingly-innocent libc functions like setenv()
   2107 	 * take locks.
   2108 	 *
   2109 	 * Hence, only call sys_clone() if we need to, in order to get at pid
   2110 	 * namespacing. If we follow this path, the child's address space might
   2111 	 * have broken locks; you may only call functions that do not acquire
   2112 	 * any locks.
   2113 	 *
   2114 	 * Unfortunately, fork() acquires every lock it can get its hands on, as
   2115 	 * previously detailed, so this function is highly likely to deadlock
   2116 	 * later on (see "deadlock here") if we're multithreaded.
   2117 	 *
   2118 	 * We might hack around this by having the clone()d child (init of the
   2119 	 * pid namespace) return directly, rather than leaving the clone()d
   2120 	 * process hanging around to be init for the new namespace (and having
   2121 	 * its fork()ed child return in turn), but that process would be
   2122 	 * crippled with its libc locks potentially broken. We might try
   2123 	 * fork()ing in the parent before we clone() to ensure that we own all
   2124 	 * the locks, but then we have to have the forked child hanging around
   2125 	 * consuming resources (and possibly having file descriptors / shared
   2126 	 * memory regions / etc attached). We'd need to keep the child around to
   2127 	 * avoid having its children get reparented to init.
   2128 	 *
   2129 	 * TODO(ellyjones): figure out if the "forked child hanging around"
   2130 	 * problem is fixable or not. It would be nice if we worked in this
   2131 	 * case.
   2132 	 */
   2133 	if (pid_namespace) {
   2134 		int clone_flags = CLONE_NEWPID | SIGCHLD;
   2135 		if (j->flags.userns)
   2136 			clone_flags |= CLONE_NEWUSER;
   2137 		child_pid = syscall(SYS_clone, clone_flags, NULL);
   2138 	} else {
   2139 		child_pid = fork();
   2140 	}
   2141 
   2142 	if (child_pid < 0) {
   2143 		if (use_preload) {
   2144 			free(oldenv_copy);
   2145 		}
   2146 		die("failed to fork child");
   2147 	}
   2148 
   2149 	if (child_pid) {
   2150 		if (use_preload) {
   2151 			/* Restore parent's LD_PRELOAD. */
   2152 			if (oldenv_copy) {
   2153 				setenv(kLdPreloadEnvVar, oldenv_copy, 1);
   2154 				free(oldenv_copy);
   2155 			} else {
   2156 				unsetenv(kLdPreloadEnvVar);
   2157 			}
   2158 			unsetenv(kFdEnvVar);
   2159 		}
   2160 
   2161 		j->initpid = child_pid;
   2162 
   2163 		if (j->flags.forward_signals) {
   2164 			forward_pid = child_pid;
   2165 			install_signal_handlers();
   2166 		}
   2167 
   2168 		if (j->flags.pid_file)
   2169 			write_pid_file_or_die(j);
   2170 
   2171 		if (j->flags.cgroups)
   2172 			add_to_cgroups_or_die(j);
   2173 
   2174 		if (j->rlimit_count)
   2175 			set_rlimits_or_die(j);
   2176 
   2177 		if (j->flags.userns)
   2178 			write_ugid_maps_or_die(j);
   2179 
   2180 		if (sync_child)
   2181 			parent_setup_complete(child_sync_pipe_fds);
   2182 
   2183 		if (use_preload) {
   2184 			/* Send marshalled minijail. */
   2185 			close(pipe_fds[0]);	/* read endpoint */
   2186 			ret = minijail_to_fd(j, pipe_fds[1]);
   2187 			close(pipe_fds[1]);	/* write endpoint */
   2188 			if (ret) {
   2189 				kill(j->initpid, SIGKILL);
   2190 				die("failed to send marshalled minijail");
   2191 			}
   2192 		}
   2193 
   2194 		if (pchild_pid)
   2195 			*pchild_pid = child_pid;
   2196 
   2197 		/*
   2198 		 * If we want to write to the child process' standard input,
   2199 		 * set up the write end of the pipe.
   2200 		 */
   2201 		if (pstdin_fd)
   2202 			*pstdin_fd = setup_pipe_end(stdin_fds,
   2203 						    1 /* write end */);
   2204 
   2205 		/*
   2206 		 * If we want to read from the child process' standard output,
   2207 		 * set up the read end of the pipe.
   2208 		 */
   2209 		if (pstdout_fd)
   2210 			*pstdout_fd = setup_pipe_end(stdout_fds,
   2211 						     0 /* read end */);
   2212 
   2213 		/*
   2214 		 * If we want to read from the child process' standard error,
   2215 		 * set up the read end of the pipe.
   2216 		 */
   2217 		if (pstderr_fd)
   2218 			*pstderr_fd = setup_pipe_end(stderr_fds,
   2219 						     0 /* read end */);
   2220 
   2221 		return 0;
   2222 	}
   2223 	/* Child process. */
   2224 	free(oldenv_copy);
   2225 
   2226 	if (j->flags.reset_signal_mask) {
   2227 		sigset_t signal_mask;
   2228 		if (sigemptyset(&signal_mask) != 0)
   2229 			pdie("sigemptyset failed");
   2230 		if (sigprocmask(SIG_SETMASK, &signal_mask, NULL) != 0)
   2231 			pdie("sigprocmask failed");
   2232 	}
   2233 
   2234 	if (j->flags.close_open_fds) {
   2235 		const size_t kMaxInheritableFdsSize = 10;
   2236 		int inheritable_fds[kMaxInheritableFdsSize];
   2237 		size_t size = 0;
   2238 		if (use_preload) {
   2239 			inheritable_fds[size++] = pipe_fds[0];
   2240 			inheritable_fds[size++] = pipe_fds[1];
   2241 		}
   2242 		if (sync_child) {
   2243 			inheritable_fds[size++] = child_sync_pipe_fds[0];
   2244 			inheritable_fds[size++] = child_sync_pipe_fds[1];
   2245 		}
   2246 		if (pstdin_fd) {
   2247 			inheritable_fds[size++] = stdin_fds[0];
   2248 			inheritable_fds[size++] = stdin_fds[1];
   2249 		}
   2250 		if (pstdout_fd) {
   2251 			inheritable_fds[size++] = stdout_fds[0];
   2252 			inheritable_fds[size++] = stdout_fds[1];
   2253 		}
   2254 		if (pstderr_fd) {
   2255 			inheritable_fds[size++] = stderr_fds[0];
   2256 			inheritable_fds[size++] = stderr_fds[1];
   2257 		}
   2258 
   2259 		if (close_open_fds(inheritable_fds, size) < 0)
   2260 			die("failed to close open file descriptors");
   2261 	}
   2262 
   2263 	if (sync_child)
   2264 		wait_for_parent_setup(child_sync_pipe_fds);
   2265 
   2266 	if (j->flags.userns)
   2267 		enter_user_namespace(j);
   2268 
   2269 	/*
   2270 	 * If we want to write to the jailed process' standard input,
   2271 	 * set up the read end of the pipe.
   2272 	 */
   2273 	if (pstdin_fd) {
   2274 		if (setup_and_dupe_pipe_end(stdin_fds, 0 /* read end */,
   2275 					    STDIN_FILENO) < 0)
   2276 			die("failed to set up stdin pipe");
   2277 	}
   2278 
   2279 	/*
   2280 	 * If we want to read from the jailed process' standard output,
   2281 	 * set up the write end of the pipe.
   2282 	 */
   2283 	if (pstdout_fd) {
   2284 		if (setup_and_dupe_pipe_end(stdout_fds, 1 /* write end */,
   2285 					    STDOUT_FILENO) < 0)
   2286 			die("failed to set up stdout pipe");
   2287 	}
   2288 
   2289 	/*
   2290 	 * If we want to read from the jailed process' standard error,
   2291 	 * set up the write end of the pipe.
   2292 	 */
   2293 	if (pstderr_fd) {
   2294 		if (setup_and_dupe_pipe_end(stderr_fds, 1 /* write end */,
   2295 					    STDERR_FILENO) < 0)
   2296 			die("failed to set up stderr pipe");
   2297 	}
   2298 
   2299 	/*
   2300 	 * If any of stdin, stdout, or stderr are TTYs, create a new session.
   2301 	 * This prevents the jailed process from using the TIOCSTI ioctl
   2302 	 * to push characters into the parent process terminal's input buffer,
   2303 	 * therefore escaping the jail.
   2304 	 */
   2305 	if (isatty(STDIN_FILENO) || isatty(STDOUT_FILENO) ||
   2306 	    isatty(STDERR_FILENO)) {
   2307 		if (setsid() < 0) {
   2308 			pdie("setsid() failed");
   2309 		}
   2310 	}
   2311 
   2312 	/* If running an init program, let it decide when/how to mount /proc. */
   2313 	if (pid_namespace && !do_init)
   2314 		j->flags.remount_proc_ro = 0;
   2315 
   2316 	if (use_preload) {
   2317 		/* Strip out flags that cannot be inherited across execve(2). */
   2318 		minijail_preexec(j);
   2319 	} else {
   2320 		/*
   2321 		 * If not using LD_PRELOAD, do all jailing before execve(2).
   2322 		 * Note that PID namespaces can only be entered on fork(2),
   2323 		 * so that flag is still cleared.
   2324 		 */
   2325 		j->flags.pids = 0;
   2326 	}
   2327 	/* Jail this process, then execve(2) the target. */
   2328 	minijail_enter(j);
   2329 
   2330 	if (pid_namespace && do_init) {
   2331 		/*
   2332 		 * pid namespace: this process will become init inside the new
   2333 		 * namespace. We don't want all programs we might exec to have
   2334 		 * to know how to be init. Normally (do_init == 1) we fork off
   2335 		 * a child to actually run the program. If |do_init == 0|, we
   2336 		 * let the program keep pid 1 and be init.
   2337 		 *
   2338 		 * If we're multithreaded, we'll probably deadlock here. See
   2339 		 * WARNING above.
   2340 		 */
   2341 		child_pid = fork();
   2342 		if (child_pid < 0) {
   2343 			_exit(child_pid);
   2344 		} else if (child_pid > 0) {
   2345 			/*
   2346 			 * Best effort. Don't bother checking the return value.
   2347 			 */
   2348 			prctl(PR_SET_NAME, "minijail-init");
   2349 			init(child_pid);	/* Never returns. */
   2350 		}
   2351 	}
   2352 
   2353 	/*
   2354 	 * If we aren't pid-namespaced, or the jailed program asked to be init:
   2355 	 *   calling process
   2356 	 *   -> execve()-ing process
   2357 	 * If we are:
   2358 	 *   calling process
   2359 	 *   -> init()-ing process
   2360 	 *      -> execve()-ing process
   2361 	 */
   2362 	ret = execve(filename, argv, environ);
   2363 	if (ret == -1) {
   2364 		pwarn("execve(%s) failed", filename);
   2365 	}
   2366 	_exit(ret);
   2367 }
   2368 
   2369 int API minijail_kill(struct minijail *j)
   2370 {
   2371 	int st;
   2372 	if (kill(j->initpid, SIGTERM))
   2373 		return -errno;
   2374 	if (waitpid(j->initpid, &st, 0) < 0)
   2375 		return -errno;
   2376 	return st;
   2377 }
   2378 
   2379 int API minijail_wait(struct minijail *j)
   2380 {
   2381 	int st;
   2382 	if (waitpid(j->initpid, &st, 0) < 0)
   2383 		return -errno;
   2384 
   2385 	if (!WIFEXITED(st)) {
   2386 		int error_status = st;
   2387 		if (WIFSIGNALED(st)) {
   2388 			int signum = WTERMSIG(st);
   2389 			warn("child process %d received signal %d",
   2390 			     j->initpid, signum);
   2391 			/*
   2392 			 * We return MINIJAIL_ERR_JAIL if the process received
   2393 			 * SIGSYS, which happens when a syscall is blocked by
   2394 			 * seccomp filters.
   2395 			 * If not, we do what bash(1) does:
   2396 			 * $? = 128 + signum
   2397 			 */
   2398 			if (signum == SIGSYS) {
   2399 				error_status = MINIJAIL_ERR_JAIL;
   2400 			} else {
   2401 				error_status = 128 + signum;
   2402 			}
   2403 		}
   2404 		return error_status;
   2405 	}
   2406 
   2407 	int exit_status = WEXITSTATUS(st);
   2408 	if (exit_status != 0)
   2409 		info("child process %d exited with status %d",
   2410 		     j->initpid, exit_status);
   2411 
   2412 	return exit_status;
   2413 }
   2414 
   2415 void API minijail_destroy(struct minijail *j)
   2416 {
   2417 	size_t i;
   2418 
   2419 	if (j->flags.seccomp_filter && j->filter_prog) {
   2420 		free(j->filter_prog->filter);
   2421 		free(j->filter_prog);
   2422 	}
   2423 	while (j->mounts_head) {
   2424 		struct mountpoint *m = j->mounts_head;
   2425 		j->mounts_head = j->mounts_head->next;
   2426 		free(m->data);
   2427 		free(m->type);
   2428 		free(m->dest);
   2429 		free(m->src);
   2430 		free(m);
   2431 	}
   2432 	j->mounts_tail = NULL;
   2433 	if (j->user)
   2434 		free(j->user);
   2435 	if (j->suppl_gid_list)
   2436 		free(j->suppl_gid_list);
   2437 	if (j->chrootdir)
   2438 		free(j->chrootdir);
   2439 	if (j->pid_file_path)
   2440 		free(j->pid_file_path);
   2441 	if (j->uidmap)
   2442 		free(j->uidmap);
   2443 	if (j->gidmap)
   2444 		free(j->gidmap);
   2445 	if (j->hostname)
   2446 		free(j->hostname);
   2447 	if (j->alt_syscall_table)
   2448 		free(j->alt_syscall_table);
   2449 	for (i = 0; i < j->cgroup_count; ++i)
   2450 		free(j->cgroups[i]);
   2451 	free(j);
   2452 }
   2453