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