jail: parse and apply POSIX rlimits
[project/procd.git] / jail / jail.c
1 /*
2 * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
3 * Copyright (C) 2020 Daniel Golle <daniel@makrotopia.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 #define _GNU_SOURCE
16 #include <sys/mount.h>
17 #include <sys/prctl.h>
18 #include <sys/wait.h>
19 #include <sys/types.h>
20 #include <sys/time.h>
21 #include <sys/resource.h>
22 #include <sys/stat.h>
23
24 /* musl only defined 15 limit types, make sure all 16 are supported */
25 #ifndef RLIMIT_RTTIME
26 #define RLIMIT_RTTIME 15
27 #undef RLIMIT_NLIMITS
28 #define RLIMIT_NLIMITS 16
29 #undef RLIM_NLIMITS
30 #define RLIM_NLIMITS 16
31 #endif
32
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <pwd.h>
37 #include <grp.h>
38 #include <string.h>
39 #include <fcntl.h>
40 #include <sched.h>
41 #include <linux/limits.h>
42 #include <linux/filter.h>
43 #include <signal.h>
44 #include <inttypes.h>
45
46 #include "capabilities.h"
47 #include "elf.h"
48 #include "fs.h"
49 #include "jail.h"
50 #include "log.h"
51 #include "seccomp-oci.h"
52
53 #include <libubox/utils.h>
54 #include <libubox/blobmsg.h>
55 #include <libubox/blobmsg_json.h>
56 #include <libubox/list.h>
57 #include <libubox/vlist.h>
58 #include <libubox/uloop.h>
59 #include <libubus.h>
60
61 #ifndef CLONE_NEWCGROUP
62 #define CLONE_NEWCGROUP 0x02000000
63 #endif
64
65 #define STACK_SIZE (1024 * 1024)
66 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:"
67
68 struct hook_execvpe {
69 char *file;
70 char **argv;
71 char **envp;
72 int timeout;
73 };
74
75 struct sysctl_val {
76 char *entry;
77 char *value;
78 };
79
80 static struct {
81 char *name;
82 char *hostname;
83 char **jail_argv;
84 char *cwd;
85 char *seccomp;
86 struct sock_fprog *ociseccomp;
87 char *capabilities;
88 struct jail_capset capset;
89 char *user;
90 char *group;
91 char *extroot;
92 char *overlaydir;
93 char *tmpoverlaysize;
94 char **envp;
95 char *uidmap;
96 char *gidmap;
97 struct sysctl_val **sysctl;
98 int no_new_privs;
99 int namespace;
100 int procfs;
101 int ronly;
102 int sysfs;
103 int console;
104 int pw_uid;
105 int pw_gid;
106 int gr_gid;
107 gid_t *additional_gids;
108 size_t num_additional_gids;
109 mode_t umask;
110 bool set_umask;
111 int require_jail;
112 struct {
113 struct hook_execvpe **createRuntime;
114 struct hook_execvpe **createContainer;
115 struct hook_execvpe **startContainer;
116 struct hook_execvpe **poststart;
117 struct hook_execvpe **poststop;
118 } hooks;
119 struct rlimit *rlimits[RLIM_NLIMITS];
120 } opts;
121
122 static void free_hooklist(struct hook_execvpe **hooklist)
123 {
124 struct hook_execvpe *cur;
125 char **tmp;
126
127 if (!hooklist)
128 return;
129
130 cur = *hooklist;
131 while (cur) {
132 free(cur->file);
133 tmp = cur->argv;
134 while (tmp)
135 free(*(tmp++));
136
137 free(cur->argv);
138
139 tmp = cur->envp;
140 while (tmp)
141 free(*(tmp++));
142
143 free(cur->envp);
144 free(cur++);
145 }
146 free(hooklist);
147 }
148
149 static void free_sysctl(void) {
150 struct sysctl_val *cur;
151 cur = *opts.sysctl;
152
153 while (cur) {
154 free(cur->entry);
155 free(cur->value);
156 free(cur++);
157 }
158 free(opts.sysctl);
159 }
160
161 static void free_rlimits(void) {
162 int type;
163
164 for (type = 0; type < RLIM_NLIMITS; ++type)
165 free(opts.rlimits[type]);
166 }
167
168 static void free_opts(bool child) {
169 char **tmp;
170
171 /* we need to keep argv, envp and seccomp filter in child */
172 if (child) {
173 if (opts.ociseccomp) {
174 free(opts.ociseccomp->filter);
175 free(opts.ociseccomp);
176 }
177
178 tmp = opts.jail_argv;
179 while(tmp)
180 free(*(tmp++));
181
182 free(opts.jail_argv);
183
184 tmp = opts.envp;
185 while (tmp)
186 free(*(tmp++));
187
188 free(opts.envp);
189 };
190
191 free_rlimits();
192 free_sysctl();
193 free(opts.hostname);
194 free(opts.cwd);
195 free(opts.extroot);
196 free(opts.uidmap);
197 free(opts.gidmap);
198 free_hooklist(opts.hooks.createRuntime);
199 free_hooklist(opts.hooks.createContainer);
200 free_hooklist(opts.hooks.startContainer);
201 free_hooklist(opts.hooks.poststart);
202 free_hooklist(opts.hooks.poststop);
203 }
204
205 static struct blob_buf ocibuf;
206
207 extern int pivot_root(const char *new_root, const char *put_old);
208
209 int debug = 0;
210
211 static char child_stack[STACK_SIZE];
212
213 int console_fd;
214
215 static int mount_overlay(char *jail_root, char *overlaydir) {
216 char *upperdir, *workdir, *optsstr, *upperetc, *upperresolvconf;
217 const char mountoptsformat[] = "lowerdir=%s,upperdir=%s,workdir=%s";
218 int ret = -1, fd;
219
220 if (asprintf(&upperdir, "%s%s", overlaydir, "/upper") < 0)
221 goto out;
222
223 if (asprintf(&workdir, "%s%s", overlaydir, "/work") < 0)
224 goto upper_printf;
225
226 if (asprintf(&optsstr, mountoptsformat, jail_root, upperdir, workdir) < 0)
227 goto work_printf;
228
229 if (mkdir_p(upperdir, 0755) || mkdir_p(workdir, 0755))
230 goto opts_printf;
231
232 /*
233 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
234 * this is to work-around a bug in overlayfs described in the overlayfs-userns
235 * patch:
236 * 3. modification of a file 'hithere' which is in l but not yet
237 * in u, and which is not owned by T, is not allowed, even if
238 * writes to u are allowed. This may be a bug in overlayfs,
239 * but it is safe behavior.
240 */
241 if (asprintf(&upperetc, "%s/etc", upperdir) < 0)
242 goto opts_printf;
243
244 if (mkdir_p(upperetc, 0755))
245 goto upper_etc_printf;
246
247 if (asprintf(&upperresolvconf, "%s/resolv.conf", upperetc) < 0)
248 goto upper_etc_printf;
249
250 fd = creat(upperresolvconf, 0644);
251 if (fd == -1) {
252 ERROR("creat(%s) failed: %m\n", upperresolvconf);
253 goto upper_resolvconf_printf;
254 }
255 close(fd);
256
257 DEBUG("mount -t overlay %s %s (%s)\n", jail_root, jail_root, optsstr);
258
259 if (mount(jail_root, jail_root, "overlay", MS_NOATIME, optsstr))
260 goto opts_printf;
261
262 ret = 0;
263
264 upper_resolvconf_printf:
265 free(upperresolvconf);
266 upper_etc_printf:
267 free(upperetc);
268 opts_printf:
269 free(optsstr);
270 work_printf:
271 free(workdir);
272 upper_printf:
273 free(upperdir);
274 out:
275 return ret;
276 }
277
278 static void pass_console(int console_fd)
279 {
280 struct ubus_context *ctx = ubus_connect(NULL);
281 static struct blob_buf req;
282 uint32_t id;
283
284 if (!ctx)
285 return;
286
287 blob_buf_init(&req, 0);
288 blobmsg_add_string(&req, "name", opts.name);
289
290 if (ubus_lookup_id(ctx, "container", &id) ||
291 ubus_invoke_fd(ctx, id, "console_set", req.head, NULL, NULL, 3000, console_fd))
292 INFO("ubus request failed\n");
293 else
294 close(console_fd);
295
296 blob_buf_free(&req);
297 ubus_free(ctx);
298 }
299
300 static int create_dev_console(const char *jail_root)
301 {
302 char *console_fname;
303 char dev_console_path[PATH_MAX];
304 int slave_console_fd;
305
306 /* Open UNIX/98 virtual console */
307 console_fd = posix_openpt(O_RDWR | O_NOCTTY);
308 if (console_fd == -1)
309 return -1;
310
311 console_fname = ptsname(console_fd);
312 DEBUG("got console fd %d and PTS client name %s\n", console_fd, console_fname);
313 if (!console_fname)
314 goto no_console;
315
316 grantpt(console_fd);
317 unlockpt(console_fd);
318
319 /* pass PTY master to procd */
320 pass_console(console_fd);
321
322 /* mount-bind PTY slave to /dev/console in jail */
323 snprintf(dev_console_path, sizeof(dev_console_path), "%s/dev/console", jail_root);
324 close(creat(dev_console_path, 0620));
325
326 if (mount(console_fname, dev_console_path, NULL, MS_BIND, NULL))
327 goto no_console;
328
329 /* use PTY slave for stdio */
330 slave_console_fd = open(console_fname, O_RDWR); /* | O_NOCTTY */
331 dup2(slave_console_fd, 0);
332 dup2(slave_console_fd, 1);
333 dup2(slave_console_fd, 2);
334 close(slave_console_fd);
335
336 INFO("using guest console %s\n", console_fname);
337
338 return 0;
339
340 no_console:
341 close(console_fd);
342 return 1;
343 }
344
345 static int hook_running = 0;
346 static int hook_return_code = 0;
347
348 static void hook_process_timeout_cb(struct uloop_timeout *t);
349 static struct uloop_timeout hook_process_timeout = {
350 .cb = hook_process_timeout_cb,
351 };
352
353 static void hook_process_handler(struct uloop_process *c, int ret)
354 {
355 uloop_timeout_cancel(&hook_process_timeout);
356 if (WIFEXITED(ret)) {
357 hook_return_code = WEXITSTATUS(ret);
358 DEBUG("hook (%d) exited with exit: %d\n", c->pid, hook_return_code);
359 } else {
360 hook_return_code = WTERMSIG(ret);
361 DEBUG("hook (%d) exited with signal: %d\n", c->pid, hook_return_code);
362 }
363 hook_running = 0;
364 uloop_end();
365 }
366
367 static struct uloop_process hook_process = {
368 .cb = hook_process_handler,
369 };
370
371 static void hook_process_timeout_cb(struct uloop_timeout *t)
372 {
373 DEBUG("hook process failed to stop, sending SIGKILL\n");
374 kill(hook_process.pid, SIGKILL);
375 }
376
377 static int run_hook(struct hook_execvpe *hook)
378 {
379 struct stat s;
380
381 DEBUG("executing hook %s\n", hook->file);
382
383 if (stat(hook->file, &s))
384 return ENOENT;
385
386 if (!((unsigned long)s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
387 return EPERM;
388
389 if (!((unsigned long)s.st_mode & (S_IRUSR | S_IRGRP | S_IROTH)))
390 return EPERM;
391
392 uloop_init();
393
394 hook_running = 1;
395 hook_process.pid = fork();
396 if (hook_process.pid > 0) {
397 /* parent */
398 uloop_process_add(&hook_process);
399
400 if (hook->timeout > 0)
401 uloop_timeout_set(&hook_process_timeout, 1000 * hook->timeout);
402
403 uloop_run();
404 if (hook_running) {
405 DEBUG("uloop interrupted, killing hook process\n");
406 kill(hook_process.pid, SIGTERM);
407 uloop_timeout_set(&hook_process_timeout, 1000);
408 uloop_run();
409 }
410 uloop_done();
411
412 waitpid(hook_process.pid, NULL, WCONTINUED);
413
414 return hook_return_code;
415 } else if (hook_process.pid == 0) {
416 /* child */
417 execvpe(hook->file, hook->argv, hook->envp);
418 hook_running = 0;
419 _exit(errno);
420 } else {
421 /* fork error */
422 hook_running = 0;
423 return errno;
424 }
425 }
426
427 static int run_hooks(struct hook_execvpe **hooklist)
428 {
429 struct hook_execvpe **cur;
430 int res;
431
432 if (!hooklist)
433 return 0; /* Nothing to do */
434
435 cur = hooklist;
436
437 while (*cur) {
438 res = run_hook(*cur);
439 if (res)
440 DEBUG(" error running hook %s\n", (*cur)->file);
441 else
442 DEBUG(" success running hook %s\n", (*cur)->file);
443
444 ++cur;
445 }
446
447 return 0;
448 }
449
450 static int apply_sysctl(const char *jail_root)
451 {
452 struct sysctl_val **cur;
453 char *procdir, *fname;
454 int f;
455
456 if (!opts.sysctl)
457 return 0;
458
459 asprintf(&procdir, "%s/proc", jail_root);
460 if (!procdir)
461 return ENOMEM;
462
463 mkdir(procdir, 0700);
464 if (mount("proc", procdir, "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0))
465 return EPERM;
466
467 cur = opts.sysctl;
468
469 while (*cur) {
470 asprintf(&fname, "%s/sys/%s", procdir, (*cur)->entry);
471 if (!fname)
472 return ENOMEM;
473
474 DEBUG("sysctl: writing '%s' to %s\n", (*cur)->value, fname);
475
476 f = open(fname, O_WRONLY);
477 if (f == -1) {
478 ERROR("sysctl: can't open %s\n", fname);
479 return errno;
480 }
481 write(f, (*cur)->value, strlen((*cur)->value));
482
483 free(fname);
484 close(f);
485 ++cur;
486 }
487 umount(procdir);
488 rmdir(procdir);
489 free(procdir);
490
491 return 0;
492 }
493
494 static int build_jail_fs(void)
495 {
496 char jail_root[] = "/tmp/ujail-XXXXXX";
497 char tmpovdir[] = "/tmp/ujail-overlay-XXXXXX";
498 char tmpdevdir[] = "/tmp/ujail-XXXXXX/dev";
499 char tmpdevptsdir[] = "/tmp/ujail-XXXXXX/dev/pts";
500 char *overlaydir = NULL;
501
502 if (mkdtemp(jail_root) == NULL) {
503 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
504 return -1;
505 }
506
507 if (apply_sysctl(jail_root)) {
508 ERROR("failed to apply sysctl values\n");
509 return -1;
510 }
511
512 /* oldroot can't be MS_SHARED else pivot_root() fails */
513 if (mount("none", "/", NULL, MS_REC|MS_PRIVATE, NULL)) {
514 ERROR("private mount failed %m\n");
515 return -1;
516 }
517
518 if (opts.extroot) {
519 if (mount(opts.extroot, jail_root, NULL, MS_BIND, NULL)) {
520 ERROR("extroot mount failed %m\n");
521 return -1;
522 }
523 } else {
524 if (mount("tmpfs", jail_root, "tmpfs", MS_NOATIME, "mode=0755")) {
525 ERROR("tmpfs mount failed %m\n");
526 return -1;
527 }
528 }
529
530 if (opts.tmpoverlaysize) {
531 char mountoptsstr[] = "mode=0755,size=XXXXXXXX";
532
533 snprintf(mountoptsstr, sizeof(mountoptsstr),
534 "mode=0755,size=%s", opts.tmpoverlaysize);
535 if (mkdtemp(tmpovdir) == NULL) {
536 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
537 return -1;
538 }
539 if (mount("tmpfs", tmpovdir, "tmpfs", MS_NOATIME,
540 mountoptsstr)) {
541 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts.tmpoverlaysize);
542 return -1;
543 }
544 overlaydir = tmpovdir;
545 }
546
547 if (opts.overlaydir)
548 overlaydir = opts.overlaydir;
549
550 if (overlaydir)
551 mount_overlay(jail_root, overlaydir);
552
553 if (chdir(jail_root)) {
554 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root);
555 return -1;
556 }
557
558 snprintf(tmpdevdir, sizeof(tmpdevdir), "%s/dev", jail_root);
559 mkdir_p(tmpdevdir, 0755);
560 if (mount(NULL, tmpdevdir, "tmpfs", MS_NOATIME | MS_NOEXEC | MS_NOSUID, "size=1M"))
561 return -1;
562
563 snprintf(tmpdevptsdir, sizeof(tmpdevptsdir), "%s/dev/pts", jail_root);
564 mkdir_p(tmpdevptsdir, 0755);
565 if (mount(NULL, tmpdevptsdir, "devpts", MS_NOATIME | MS_NOEXEC | MS_NOSUID, NULL))
566 return -1;
567
568 if (opts.console)
569 create_dev_console(jail_root);
570
571 if (mount_all(jail_root)) {
572 ERROR("mount_all() failed\n");
573 return -1;
574 }
575
576 /* make sure /etc/resolv.conf exists if in new network namespace */
577 if (opts.namespace & CLONE_NEWNET) {
578 char jailetc[PATH_MAX], jaillink[PATH_MAX];
579
580 snprintf(jailetc, PATH_MAX, "%s/etc", jail_root);
581 mkdir_p(jailetc, 0755);
582 snprintf(jaillink, PATH_MAX, "%s/etc/resolv.conf", jail_root);
583 if (overlaydir)
584 unlink(jaillink);
585
586 symlink("../tmp/resolv.conf.d/resolv.conf.auto", jaillink);
587 }
588
589 run_hooks(opts.hooks.createContainer);
590
591 char dirbuf[sizeof(jail_root) + 4];
592 snprintf(dirbuf, sizeof(dirbuf), "%s/old", jail_root);
593 mkdir(dirbuf, 0755);
594
595 if (pivot_root(jail_root, dirbuf) == -1) {
596 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root, dirbuf);
597 return -1;
598 }
599 if (chdir("/")) {
600 ERROR("chdir(/) (after pivot_root) failed: %m\n");
601 return -1;
602 }
603
604 snprintf(dirbuf, sizeof(dirbuf), "/old%s", jail_root);
605 umount2(dirbuf, MNT_DETACH);
606 rmdir(dirbuf);
607 if (opts.tmpoverlaysize) {
608 char tmpdirbuf[sizeof(tmpovdir) + 4];
609 snprintf(tmpdirbuf, sizeof(tmpdirbuf), "/old%s", tmpovdir);
610 umount2(tmpdirbuf, MNT_DETACH);
611 rmdir(tmpdirbuf);
612 }
613
614 umount2("/old", MNT_DETACH);
615 rmdir("/old");
616
617 if (opts.procfs) {
618 mkdir("/proc", 0755);
619 mount("proc", "/proc", "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
620 /*
621 * make /proc/sys read-only while keeping read-write to
622 * /proc/sys/net if CLONE_NEWNET is set.
623 */
624 if (opts.namespace & CLONE_NEWNET)
625 mount("/proc/sys/net", "/proc/self/net", NULL, MS_BIND, 0);
626
627 mount("/proc/sys", "/proc/sys", NULL, MS_BIND, 0);
628 mount(NULL, "/proc/sys", NULL, MS_REMOUNT | MS_RDONLY, 0);
629 mount(NULL, "/proc", NULL, MS_REMOUNT, 0);
630
631 if (opts.namespace & CLONE_NEWNET)
632 mount("/proc/self/net", "/proc/sys/net", NULL, MS_MOVE, 0);
633 }
634 if (opts.sysfs) {
635 mkdir("/sys", 0755);
636 mount("sysfs", "/sys", "sysfs", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RDONLY, 0);
637 }
638 if (opts.ronly)
639 mount(NULL, "/", NULL, MS_REMOUNT | MS_BIND | MS_RDONLY, 0);
640
641 return 0;
642 }
643
644 static int write_uid_gid_map(pid_t child_pid, bool gidmap, char *mapstr)
645 {
646 int map_file;
647 char map_path[64];
648
649 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
650 child_pid, gidmap?"gid_map":"uid_map") < 0)
651 return -1;
652
653 if ((map_file = open(map_path, O_WRONLY)) == -1)
654 return -1;
655
656 if (dprintf(map_file, "%s", mapstr)) {
657 close(map_file);
658 return -1;
659 }
660
661 close(map_file);
662 free(mapstr);
663 return 0;
664 }
665
666 static int write_single_uid_gid_map(pid_t child_pid, bool gidmap, int id)
667 {
668 int map_file;
669 char map_path[64];
670 const char *map_format = "%d %d %d\n";
671 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
672 child_pid, gidmap?"gid_map":"uid_map") < 0)
673 return -1;
674
675 if ((map_file = open(map_path, O_WRONLY)) == -1)
676 return -1;
677
678 if (dprintf(map_file, map_format, 0, id, 1) == -1) {
679 close(map_file);
680 return -1;
681 }
682
683 close(map_file);
684 return 0;
685 }
686
687 static int write_setgroups(pid_t child_pid, bool allow)
688 {
689 int setgroups_file;
690 char setgroups_path[64];
691
692 if (snprintf(setgroups_path, sizeof(setgroups_path), "/proc/%d/setgroups",
693 child_pid) < 0) {
694 return -1;
695 }
696
697 if ((setgroups_file = open(setgroups_path, O_WRONLY)) == -1) {
698 return -1;
699 }
700
701 if (dprintf(setgroups_file, "%s", allow?"allow":"deny") == -1) {
702 close(setgroups_file);
703 return -1;
704 }
705
706 close(setgroups_file);
707 return 0;
708 }
709
710 static void get_jail_user(int *user, int *user_gid, int *gr_gid)
711 {
712 struct passwd *p = NULL;
713 struct group *g = NULL;
714
715 if (opts.user) {
716 p = getpwnam(opts.user);
717 if (!p) {
718 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
719 opts.user, errno, strerror(errno));
720 exit(EXIT_FAILURE);
721 }
722 *user = p->pw_uid;
723 *user_gid = p->pw_gid;
724 } else {
725 *user = -1;
726 *user_gid = -1;
727 }
728
729 if (opts.group) {
730 g = getgrnam(opts.group);
731 if (!g) {
732 ERROR("failed to get gid for group %s: %m\n", opts.group);
733 exit(EXIT_FAILURE);
734 }
735 *gr_gid = g->gr_gid;
736 } else {
737 *gr_gid = -1;
738 }
739 };
740
741 static void set_jail_user(int pw_uid, int user_gid, int gr_gid)
742 {
743 if (opts.user && (user_gid != -1) && initgroups(opts.user, user_gid)) {
744 ERROR("failed to initgroups() for user %s: %m\n", opts.user);
745 exit(EXIT_FAILURE);
746 }
747
748 if ((gr_gid != -1) && setregid(gr_gid, gr_gid)) {
749 ERROR("failed to set group id %d: %m\n", gr_gid);
750 exit(EXIT_FAILURE);
751 }
752
753 if ((pw_uid != -1) && setreuid(pw_uid, pw_uid)) {
754 ERROR("failed to set user id %d: %m\n", pw_uid);
755 exit(EXIT_FAILURE);
756 }
757 }
758
759 static int apply_rlimits(void)
760 {
761 int resource;
762
763 for (resource = 0; resource < RLIM_NLIMITS; ++resource) {
764 if (opts.rlimits[resource])
765 DEBUG("applying limits to resource %u\n", resource);
766
767 if (opts.rlimits[resource] &&
768 setrlimit(resource, opts.rlimits[resource]))
769 return errno;
770 }
771
772 return 0;
773 }
774
775 #define MAX_ENVP 8
776 static char** build_envp(const char *seccomp, char **ocienvp)
777 {
778 static char *envp[MAX_ENVP];
779 static char preload_var[PATH_MAX];
780 static char seccomp_var[PATH_MAX];
781 static char debug_var[] = "LD_DEBUG=all";
782 static char container_var[] = "container=ujail";
783 const char *preload_lib = find_lib("libpreload-seccomp.so");
784 char **addenv;
785
786 int count = 0;
787
788 if (seccomp && !preload_lib) {
789 ERROR("failed to add preload-lib to env\n");
790 return NULL;
791 }
792 if (seccomp) {
793 snprintf(seccomp_var, sizeof(seccomp_var), "SECCOMP_FILE=%s", seccomp);
794 envp[count++] = seccomp_var;
795 snprintf(preload_var, sizeof(preload_var), "LD_PRELOAD=%s", preload_lib);
796 envp[count++] = preload_var;
797 }
798
799 envp[count++] = container_var;
800
801 if (debug > 1)
802 envp[count++] = debug_var;
803
804 addenv = ocienvp;
805 while (addenv && *addenv) {
806 envp[count++] = *(addenv++);
807 if (count >= MAX_ENVP) {
808 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP);
809 break;
810 }
811 }
812 return envp;
813 }
814
815 static void usage(void)
816 {
817 fprintf(stderr, "ujail <options> -- <binary> <params ...>\n");
818 fprintf(stderr, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
819 fprintf(stderr, " -S <file>\tseccomp filter config\n");
820 fprintf(stderr, " -C <file>\tcapabilities drop config\n");
821 fprintf(stderr, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
822 fprintf(stderr, " -n <name>\tthe name of the jail\n");
823 fprintf(stderr, "namespace jail options:\n");
824 fprintf(stderr, " -h <hostname>\tchange the hostname of the jail\n");
825 fprintf(stderr, " -N\t\tjail has network namespace\n");
826 fprintf(stderr, " -f\t\tjail has user namespace\n");
827 fprintf(stderr, " -F\t\tjail has cgroups namespace\n");
828 fprintf(stderr, " -r <file>\treadonly files that should be staged\n");
829 fprintf(stderr, " -w <file>\twriteable files that should be staged\n");
830 fprintf(stderr, " -p\t\tjail has /proc\n");
831 fprintf(stderr, " -s\t\tjail has /sys\n");
832 fprintf(stderr, " -l\t\tjail has /dev/log\n");
833 fprintf(stderr, " -u\t\tjail has a ubus socket\n");
834 fprintf(stderr, " -U <name>\tuser to run jailed process\n");
835 fprintf(stderr, " -G <name>\tgroup to run jailed process\n");
836 fprintf(stderr, " -o\t\tremont jail root (/) read only\n");
837 fprintf(stderr, " -R <dir>\texternal jail rootfs (system container)\n");
838 fprintf(stderr, " -O <dir>\tdirectory for r/w overlayfs\n");
839 fprintf(stderr, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
840 fprintf(stderr, " -E\t\tfail if jail cannot be setup\n");
841 fprintf(stderr, " -y\t\tprovide jail console\n");
842 fprintf(stderr, " -J <dir>\tstart OCI bundle\n");
843 fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
844 and he has the same powers as root outside the jail,\n\
845 thus he can escape the jail and/or break stuff.\n\
846 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
847 If you use none of the namespace jail options,\n\
848 ujail will not use namespace/build a jail,\n\
849 and will only drop capabilities/apply seccomp filter.\n\n");
850 }
851
852 static int exec_jail(void *pipes_ptr)
853 {
854 int *pipes = (int*)pipes_ptr;
855 char buf[1];
856 int pw_uid, pw_gid, gr_gid;
857
858 close(pipes[0]);
859 close(pipes[3]);
860
861 buf[0] = 'i';
862 if (write(pipes[1], buf, 1) < 1) {
863 ERROR("can't write to parent\n");
864 exit(EXIT_FAILURE);
865 }
866 if (read(pipes[2], buf, 1) < 1) {
867 ERROR("can't read from parent\n");
868 exit(EXIT_FAILURE);
869 }
870 if (buf[0] != 'O') {
871 ERROR("parent had an error, child exiting\n");
872 exit(EXIT_FAILURE);
873 }
874
875 close(pipes[1]);
876 close(pipes[2]);
877
878 if (opts.namespace & CLONE_NEWUSER) {
879 if (setregid(0, 0) < 0) {
880 ERROR("setgid\n");
881 exit(EXIT_FAILURE);
882 }
883 if (setreuid(0, 0) < 0) {
884 ERROR("setuid\n");
885 exit(EXIT_FAILURE);
886 }
887 if (setgroups(0, NULL) < 0) {
888 ERROR("setgroups\n");
889 exit(EXIT_FAILURE);
890 }
891 }
892
893 if (opts.namespace && opts.hostname && strlen(opts.hostname) > 0
894 && sethostname(opts.hostname, strlen(opts.hostname))) {
895 ERROR("sethostname(%s) failed: %m\n", opts.hostname);
896 exit(EXIT_FAILURE);
897 }
898
899 if ((opts.namespace & CLONE_NEWNS) && build_jail_fs()) {
900 ERROR("failed to build jail fs\n");
901 exit(EXIT_FAILURE);
902 }
903 run_hooks(opts.hooks.startContainer);
904
905 if (!(opts.namespace & CLONE_NEWUSER)) {
906 get_jail_user(&pw_uid, &pw_gid, &gr_gid);
907
908 set_jail_user(opts.pw_uid?:pw_uid, opts.pw_gid?:pw_gid, opts.gr_gid?:gr_gid);
909 }
910
911 if (opts.additional_gids &&
912 (setgroups(opts.num_additional_gids, opts.additional_gids) < 0)) {
913 ERROR("setgroups failed: %m\n");
914 exit(EXIT_FAILURE);
915 }
916
917 if (opts.set_umask)
918 umask(opts.umask);
919
920 if (applyOCIcapabilities(opts.capset))
921 exit(EXIT_FAILURE);
922
923 if (opts.capabilities && drop_capabilities(opts.capabilities))
924 exit(EXIT_FAILURE);
925
926 if (opts.no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
927 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
928 exit(EXIT_FAILURE);
929 }
930
931 char **envp = build_envp(opts.seccomp, opts.envp);
932 if (!envp)
933 exit(EXIT_FAILURE);
934
935 if (opts.cwd && chdir(opts.cwd))
936 exit(EXIT_FAILURE);
937
938 if (opts.ociseccomp && applyOCIlinuxseccomp(opts.ociseccomp))
939 exit(EXIT_FAILURE);
940
941 uloop_end();
942 free_opts(false);
943 INFO("exec-ing %s\n", *opts.jail_argv);
944 if (opts.envp) /* respect PATH if potentially set in ENV */
945 execvpe(*opts.jail_argv, opts.jail_argv, envp);
946 else
947 execve(*opts.jail_argv, opts.jail_argv, envp);
948
949 /* we get there only if execve fails */
950 ERROR("failed to execve %s: %m\n", *opts.jail_argv);
951 exit(EXIT_FAILURE);
952 }
953
954 static int jail_running = 0;
955 static int jail_return_code = 0;
956
957 static void jail_process_timeout_cb(struct uloop_timeout *t);
958 static struct uloop_timeout jail_process_timeout = {
959 .cb = jail_process_timeout_cb,
960 };
961
962 static void jail_process_handler(struct uloop_process *c, int ret)
963 {
964 uloop_timeout_cancel(&jail_process_timeout);
965 if (WIFEXITED(ret)) {
966 jail_return_code = WEXITSTATUS(ret);
967 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
968 } else {
969 jail_return_code = WTERMSIG(ret);
970 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
971 }
972 jail_running = 0;
973 uloop_end();
974 }
975
976 static struct uloop_process jail_process = {
977 .cb = jail_process_handler,
978 };
979
980 static void jail_process_timeout_cb(struct uloop_timeout *t)
981 {
982 DEBUG("jail process failed to stop, sending SIGKILL\n");
983 kill(jail_process.pid, SIGKILL);
984 }
985
986 static void jail_handle_signal(int signo)
987 {
988 if (hook_running) {
989 DEBUG("forwarding signal %d to the hook process\n", signo);
990 kill(hook_process.pid, signo);
991 }
992
993 if (jail_running) {
994 DEBUG("forwarding signal %d to the jailed process\n", signo);
995 kill(jail_process.pid, signo);
996 }
997 }
998
999 static int netns_open_pid(const pid_t target_ns)
1000 {
1001 char pid_net_path[PATH_MAX];
1002
1003 snprintf(pid_net_path, sizeof(pid_net_path), "/proc/%u/ns/net", target_ns);
1004
1005 return open(pid_net_path, O_RDONLY);
1006 }
1007
1008 static void netns_updown(pid_t pid, bool start)
1009 {
1010 struct ubus_context *ctx = ubus_connect(NULL);
1011 static struct blob_buf req;
1012 uint32_t id;
1013
1014 if (!ctx)
1015 return;
1016
1017 blob_buf_init(&req, 0);
1018 blobmsg_add_string(&req, "jail", opts.name);
1019 blobmsg_add_u32(&req, "pid", pid);
1020 blobmsg_add_u8(&req, "start", start);
1021
1022 if (ubus_lookup_id(ctx, "network", &id) ||
1023 ubus_invoke(ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
1024 INFO("ubus request failed\n");
1025
1026 blob_buf_free(&req);
1027 ubus_free(ctx);
1028 }
1029
1030 static int parseOCIenvarray(struct blob_attr *msg, char ***envp)
1031 {
1032 struct blob_attr *cur;
1033 int sz = 0, rem;
1034
1035 blobmsg_for_each_attr(cur, msg, rem)
1036 ++sz;
1037
1038 if (sz > 0) {
1039 *envp = calloc(1 + sz, sizeof(char*));
1040 if (!(*envp))
1041 return ENOMEM;
1042 } else {
1043 *envp = NULL;
1044 return 0;
1045 }
1046
1047 sz = 0;
1048 blobmsg_for_each_attr(cur, msg, rem)
1049 (*envp)[sz++] = strdup(blobmsg_get_string(cur));
1050
1051 if (sz)
1052 (*envp)[sz] = NULL;
1053
1054 return 0;
1055 }
1056
1057 enum {
1058 OCI_ROOT_PATH,
1059 OCI_ROOT_READONLY,
1060 __OCI_ROOT_MAX,
1061 };
1062
1063 static const struct blobmsg_policy oci_root_policy[] = {
1064 [OCI_ROOT_PATH] = { "path", BLOBMSG_TYPE_STRING },
1065 [OCI_ROOT_READONLY] = { "readonly", BLOBMSG_TYPE_BOOL },
1066 };
1067
1068 static int parseOCIroot(const char *jsonfile, struct blob_attr *msg)
1069 {
1070 static char rootpath[PATH_MAX] = { 0 };
1071 struct blob_attr *tb[__OCI_ROOT_MAX];
1072 char *cur;
1073
1074 blobmsg_parse(oci_root_policy, __OCI_ROOT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1075
1076 if (!tb[OCI_ROOT_PATH])
1077 return ENODATA;
1078
1079 strncpy(rootpath, jsonfile, PATH_MAX);
1080 cur = strrchr(rootpath, '/');
1081
1082 if (!cur)
1083 return ENOTDIR;
1084
1085 *(++cur) = '\0';
1086 strncat(rootpath, blobmsg_get_string(tb[OCI_ROOT_PATH]), PATH_MAX - (strlen(rootpath) + 1));
1087
1088 opts.extroot = rootpath;
1089
1090 opts.ronly = blobmsg_get_bool(tb[OCI_ROOT_READONLY]);
1091
1092 return 0;
1093 }
1094
1095
1096 enum {
1097 OCI_HOOK_PATH,
1098 OCI_HOOK_ARGS,
1099 OCI_HOOK_ENV,
1100 OCI_HOOK_TIMEOUT,
1101 __OCI_HOOK_MAX,
1102 };
1103
1104 static const struct blobmsg_policy oci_hook_policy[] = {
1105 [OCI_HOOK_PATH] = { "path", BLOBMSG_TYPE_STRING },
1106 [OCI_HOOK_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
1107 [OCI_HOOK_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
1108 [OCI_HOOK_TIMEOUT] = { "timeout", BLOBMSG_TYPE_INT32 },
1109 };
1110
1111
1112 static int parseOCIhook(struct hook_execvpe ***hooklist, struct blob_attr *msg)
1113 {
1114 struct blob_attr *tb[__OCI_HOOK_MAX];
1115 struct blob_attr *cur;
1116 int rem, ret = 0;
1117 int idx = 0;
1118
1119 blobmsg_for_each_attr(cur, msg, rem)
1120 ++idx;
1121
1122 if (!idx)
1123 return 0;
1124
1125 *hooklist = calloc(idx + 1, sizeof(struct hook_execvpe *));
1126 idx = 0;
1127
1128 if (!(*hooklist))
1129 return ENOMEM;
1130
1131 blobmsg_for_each_attr(cur, msg, rem) {
1132 blobmsg_parse(oci_hook_policy, __OCI_HOOK_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1133
1134 if (!tb[OCI_HOOK_PATH]) {
1135 ret = EINVAL;
1136 goto errout;
1137 }
1138
1139 (*hooklist)[idx] = malloc(sizeof(struct hook_execvpe));
1140 if (tb[OCI_HOOK_ARGS]) {
1141 ret = parseOCIenvarray(tb[OCI_HOOK_ARGS], &((*hooklist)[idx]->argv));
1142 if (ret)
1143 goto errout;
1144 } else {
1145 (*hooklist)[idx]->argv = calloc(2, sizeof(char *));
1146 ((*hooklist)[idx]->argv)[0] = strdup(blobmsg_get_string(tb[OCI_HOOK_PATH]));
1147 ((*hooklist)[idx]->argv)[1] = NULL;
1148 };
1149
1150
1151 if (tb[OCI_HOOK_ENV]) {
1152 ret = parseOCIenvarray(tb[OCI_HOOK_ENV], &((*hooklist)[idx]->envp));
1153 if (ret)
1154 goto errout;
1155 }
1156
1157 if (tb[OCI_HOOK_TIMEOUT])
1158 (*hooklist)[idx]->timeout = blobmsg_get_u32(tb[OCI_HOOK_TIMEOUT]);
1159
1160 (*hooklist)[idx]->file = strdup(blobmsg_get_string(tb[OCI_HOOK_PATH]));
1161
1162 ++idx;
1163 }
1164
1165 (*hooklist)[idx] = NULL;
1166
1167 DEBUG("added %d hooks\n", idx);
1168
1169 return 0;
1170
1171 errout:
1172 free_hooklist(*hooklist);
1173 *hooklist = NULL;
1174
1175 return ret;
1176 };
1177
1178
1179 enum {
1180 OCI_HOOKS_PRESTART,
1181 OCI_HOOKS_CREATERUNTIME,
1182 OCI_HOOKS_CREATECONTAINER,
1183 OCI_HOOKS_STARTCONTAINER,
1184 OCI_HOOKS_POSTSTART,
1185 OCI_HOOKS_POSTSTOP,
1186 __OCI_HOOKS_MAX,
1187 };
1188
1189 static const struct blobmsg_policy oci_hooks_policy[] = {
1190 [OCI_HOOKS_PRESTART] = { "prestart", BLOBMSG_TYPE_ARRAY },
1191 [OCI_HOOKS_CREATERUNTIME] = { "createRuntime", BLOBMSG_TYPE_ARRAY },
1192 [OCI_HOOKS_CREATECONTAINER] = { "createContainer", BLOBMSG_TYPE_ARRAY },
1193 [OCI_HOOKS_STARTCONTAINER] = { "startContainer", BLOBMSG_TYPE_ARRAY },
1194 [OCI_HOOKS_POSTSTART] = { "poststart", BLOBMSG_TYPE_ARRAY },
1195 [OCI_HOOKS_POSTSTOP] = { "poststop", BLOBMSG_TYPE_ARRAY },
1196 };
1197
1198 static int parseOCIhooks(struct blob_attr *msg)
1199 {
1200 struct blob_attr *tb[__OCI_HOOKS_MAX];
1201 int ret;
1202
1203 blobmsg_parse(oci_hooks_policy, __OCI_HOOKS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1204
1205 if (tb[OCI_HOOKS_PRESTART])
1206 INFO("warning: ignoring deprecated prestart hook\n");
1207
1208 if (tb[OCI_HOOKS_CREATERUNTIME]) {
1209 ret = parseOCIhook(&opts.hooks.createRuntime, tb[OCI_HOOKS_CREATERUNTIME]);
1210 if (ret)
1211 return ret;
1212 }
1213
1214 if (tb[OCI_HOOKS_CREATECONTAINER]) {
1215 ret = parseOCIhook(&opts.hooks.createContainer, tb[OCI_HOOKS_CREATECONTAINER]);
1216 if (ret)
1217 goto out_createruntime;
1218 }
1219
1220 if (tb[OCI_HOOKS_STARTCONTAINER]) {
1221 ret = parseOCIhook(&opts.hooks.startContainer, tb[OCI_HOOKS_STARTCONTAINER]);
1222 if (ret)
1223 goto out_createcontainer;
1224 }
1225
1226 if (tb[OCI_HOOKS_POSTSTART]) {
1227 ret = parseOCIhook(&opts.hooks.poststart, tb[OCI_HOOKS_POSTSTART]);
1228 if (ret)
1229 goto out_startcontainer;
1230 }
1231
1232 if (tb[OCI_HOOKS_POSTSTOP]) {
1233 ret = parseOCIhook(&opts.hooks.poststop, tb[OCI_HOOKS_POSTSTOP]);
1234 if (ret)
1235 goto out_poststart;
1236 }
1237
1238 return 0;
1239
1240 out_poststart:
1241 free_hooklist(opts.hooks.poststart);
1242 out_startcontainer:
1243 free_hooklist(opts.hooks.startContainer);
1244 out_createcontainer:
1245 free_hooklist(opts.hooks.createContainer);
1246 out_createruntime:
1247 free_hooklist(opts.hooks.createRuntime);
1248
1249 return ret;
1250 };
1251
1252
1253 enum {
1254 OCI_PROCESS_USER_UID,
1255 OCI_PROCESS_USER_GID,
1256 OCI_PROCESS_USER_UMASK,
1257 OCI_PROCESS_USER_ADDITIONALGIDS,
1258 __OCI_PROCESS_USER_MAX,
1259 };
1260
1261 static const struct blobmsg_policy oci_process_user_policy[] = {
1262 [OCI_PROCESS_USER_UID] = { "uid", BLOBMSG_TYPE_INT32 },
1263 [OCI_PROCESS_USER_GID] = { "gid", BLOBMSG_TYPE_INT32 },
1264 [OCI_PROCESS_USER_UMASK] = { "umask", BLOBMSG_TYPE_INT32 },
1265 [OCI_PROCESS_USER_ADDITIONALGIDS] = { "additionalGids", BLOBMSG_TYPE_ARRAY },
1266 };
1267
1268 static int parseOCIprocessuser(struct blob_attr *msg) {
1269 struct blob_attr *tb[__OCI_PROCESS_USER_MAX];
1270 struct blob_attr *cur;
1271 int rem;
1272 int has_gid = 0;
1273
1274 blobmsg_parse(oci_process_user_policy, __OCI_PROCESS_USER_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1275
1276 if (tb[OCI_PROCESS_USER_UID])
1277 opts.pw_uid = blobmsg_get_u32(tb[OCI_PROCESS_USER_UID]);
1278
1279 if (tb[OCI_PROCESS_USER_GID]) {
1280 opts.pw_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
1281 opts.gr_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
1282 has_gid = 1;
1283 }
1284
1285 if (tb[OCI_PROCESS_USER_ADDITIONALGIDS]) {
1286 size_t gidcnt = 0;
1287
1288 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_USER_ADDITIONALGIDS], rem) {
1289 ++gidcnt;
1290 if (has_gid && (blobmsg_get_u32(cur) == opts.gr_gid))
1291 continue;
1292 }
1293
1294 if (gidcnt) {
1295 opts.additional_gids = calloc(gidcnt + has_gid, sizeof(gid_t));
1296 gidcnt = 0;
1297
1298 /* always add primary GID to set of GIDs if set */
1299 if (has_gid)
1300 opts.additional_gids[gidcnt++] = opts.gr_gid;
1301
1302 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_USER_ADDITIONALGIDS], rem) {
1303 if (has_gid && (blobmsg_get_u32(cur) == opts.gr_gid))
1304 continue;
1305 opts.additional_gids[gidcnt++] = blobmsg_get_u32(cur);
1306 }
1307 opts.num_additional_gids = gidcnt;
1308 }
1309 DEBUG("read %lu additional groups\n", gidcnt);
1310 }
1311
1312 if (tb[OCI_PROCESS_USER_UMASK]) {
1313 opts.umask = blobmsg_get_u32(tb[OCI_PROCESS_USER_UMASK]);
1314 opts.set_umask = true;
1315 }
1316
1317 return 0;
1318 }
1319
1320 /* from manpage GETRLIMIT(2) */
1321 static const char* const rlimit_names[RLIM_NLIMITS] = {
1322 [RLIMIT_AS] = "AS",
1323 [RLIMIT_CORE] = "CORE",
1324 [RLIMIT_CPU] = "CPU",
1325 [RLIMIT_DATA] = "DATA",
1326 [RLIMIT_FSIZE] = "FSIZE",
1327 [RLIMIT_LOCKS] = "LOCKS",
1328 [RLIMIT_MEMLOCK] = "MEMLOCK",
1329 [RLIMIT_MSGQUEUE] = "MSGQUEUE",
1330 [RLIMIT_NICE] = "NICE",
1331 [RLIMIT_NOFILE] = "NOFILE",
1332 [RLIMIT_NPROC] = "NPROC",
1333 [RLIMIT_RSS] = "RSS",
1334 [RLIMIT_RTPRIO] = "RTPRIO",
1335 [RLIMIT_RTTIME] = "RTTIME",
1336 [RLIMIT_SIGPENDING] = "SIGPENDING",
1337 [RLIMIT_STACK] = "STACK",
1338 };
1339
1340 static int resolve_rlimit(char *type) {
1341 unsigned int rltype;
1342
1343 for (rltype = 0; rltype < RLIM_NLIMITS; ++rltype)
1344 if (rlimit_names[rltype] &&
1345 !strncmp("RLIMIT_", type, 7) &&
1346 !strcmp(rlimit_names[rltype], type + 7))
1347 return rltype;
1348
1349 return -1;
1350 }
1351
1352
1353 static int parseOCIrlimits(struct blob_attr *msg)
1354 {
1355 struct blob_attr *cur, *cure;
1356 int rem, reme;
1357 int limtype = -1;
1358 struct rlimit *curlim;
1359 rlim_t soft, hard;
1360 bool sethard = false, setsoft = false;
1361
1362 blobmsg_for_each_attr(cur, msg, rem) {
1363 blobmsg_for_each_attr(cure, cur, reme) {
1364 if (!strcmp(blobmsg_name(cure), "type") && (blobmsg_type(cure) == BLOBMSG_TYPE_STRING)) {
1365 limtype = resolve_rlimit(blobmsg_get_string(cure));
1366 } else if (!strcmp(blobmsg_name(cure), "soft")) {
1367 switch (blobmsg_type(cure)) {
1368 case BLOBMSG_TYPE_INT32:
1369 soft = blobmsg_get_u32(cure);
1370 break;
1371 case BLOBMSG_TYPE_INT64:
1372 soft = blobmsg_get_u64(cure);
1373 break;
1374 default:
1375 return EINVAL;
1376 }
1377 setsoft = true;
1378 } else if (!strcmp(blobmsg_name(cure), "hard")) {
1379 switch (blobmsg_type(cure)) {
1380 case BLOBMSG_TYPE_INT32:
1381 hard = blobmsg_get_u32(cure);
1382 break;
1383 case BLOBMSG_TYPE_INT64:
1384 hard = blobmsg_get_u64(cure);
1385 break;
1386 default:
1387 return EINVAL;
1388 }
1389 sethard = true;
1390 } else {
1391 return EINVAL;
1392 }
1393 }
1394
1395 if (limtype < 0)
1396 return EINVAL;
1397
1398 if (opts.rlimits[limtype])
1399 return ENOTUNIQ;
1400
1401 if (!sethard || !setsoft)
1402 return ENODATA;
1403
1404 curlim = malloc(sizeof(struct rlimit));
1405 curlim->rlim_cur = soft;
1406 curlim->rlim_max = hard;
1407
1408 opts.rlimits[limtype] = curlim;
1409 }
1410
1411 return 0;
1412 };
1413
1414 enum {
1415 OCI_PROCESS_ARGS,
1416 OCI_PROCESS_CAPABILITIES,
1417 OCI_PROCESS_CWD,
1418 OCI_PROCESS_ENV,
1419 OCI_PROCESS_NONEWPRIVILEGES,
1420 OCI_PROCESS_RLIMITS,
1421 OCI_PROCESS_TERMINAL,
1422 OCI_PROCESS_USER,
1423 __OCI_PROCESS_MAX,
1424 };
1425
1426 static const struct blobmsg_policy oci_process_policy[] = {
1427 [OCI_PROCESS_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
1428 [OCI_PROCESS_CAPABILITIES] = { "capabilities", BLOBMSG_TYPE_TABLE },
1429 [OCI_PROCESS_CWD] = { "cwd", BLOBMSG_TYPE_STRING },
1430 [OCI_PROCESS_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
1431 [OCI_PROCESS_NONEWPRIVILEGES] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL },
1432 [OCI_PROCESS_RLIMITS] = { "rlimits", BLOBMSG_TYPE_ARRAY },
1433 [OCI_PROCESS_TERMINAL] = { "terminal", BLOBMSG_TYPE_BOOL },
1434 [OCI_PROCESS_USER] = { "user", BLOBMSG_TYPE_TABLE },
1435 };
1436
1437
1438 static int parseOCIprocess(struct blob_attr *msg)
1439 {
1440 struct blob_attr *tb[__OCI_PROCESS_MAX];
1441 int res;
1442
1443 blobmsg_parse(oci_process_policy, __OCI_PROCESS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1444
1445 if (!tb[OCI_PROCESS_ARGS])
1446 return ENOENT;
1447
1448 res = parseOCIenvarray(tb[OCI_PROCESS_ARGS], &opts.jail_argv);
1449 if (res)
1450 return res;
1451
1452 opts.console = blobmsg_get_bool(tb[OCI_PROCESS_TERMINAL]);
1453 opts.no_new_privs = blobmsg_get_bool(tb[OCI_PROCESS_NONEWPRIVILEGES]);
1454
1455 if (tb[OCI_PROCESS_CWD])
1456 opts.cwd = strdup(blobmsg_get_string(tb[OCI_PROCESS_CWD]));
1457
1458 if (tb[OCI_PROCESS_ENV]) {
1459 res = parseOCIenvarray(tb[OCI_PROCESS_ENV], &opts.envp);
1460 if (res)
1461 return res;
1462 }
1463
1464 if (tb[OCI_PROCESS_USER] && (res = parseOCIprocessuser(tb[OCI_PROCESS_USER])))
1465 return res;
1466
1467 if (tb[OCI_PROCESS_CAPABILITIES] &&
1468 (res = parseOCIcapabilities(&opts.capset, tb[OCI_PROCESS_CAPABILITIES])))
1469 return res;
1470
1471 if (tb[OCI_PROCESS_RLIMITS] &&
1472 (res = parseOCIrlimits(tb[OCI_PROCESS_RLIMITS])))
1473 return res;
1474
1475 return 0;
1476 }
1477
1478 enum {
1479 OCI_LINUX_NAMESPACE_TYPE,
1480 OCI_LINUX_NAMESPACE_PATH,
1481 __OCI_LINUX_NAMESPACE_MAX,
1482 };
1483
1484 static const struct blobmsg_policy oci_linux_namespace_policy[] = {
1485 [OCI_LINUX_NAMESPACE_TYPE] = { "type", BLOBMSG_TYPE_STRING },
1486 [OCI_LINUX_NAMESPACE_PATH] = { "path", BLOBMSG_TYPE_STRING },
1487 };
1488
1489 static unsigned int resolve_nstype(char *type) {
1490 if (!strcmp("pid", type))
1491 return CLONE_NEWPID;
1492 else if (!strcmp("network", type))
1493 return CLONE_NEWNET;
1494 else if (!strcmp("mount", type))
1495 return CLONE_NEWNS;
1496 else if (!strcmp("ipc", type))
1497 return CLONE_NEWIPC;
1498 else if (!strcmp("uts", type))
1499 return CLONE_NEWUTS;
1500 else if (!strcmp("user", type))
1501 return CLONE_NEWUSER;
1502 else if (!strcmp("cgroup", type))
1503 return CLONE_NEWCGROUP;
1504 else
1505 return 0;
1506 }
1507
1508 static int parseOCIlinuxns(struct blob_attr *msg)
1509 {
1510 struct blob_attr *tb[__OCI_LINUX_NAMESPACE_MAX];
1511
1512 blobmsg_parse(oci_linux_namespace_policy, __OCI_LINUX_NAMESPACE_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1513
1514 if (!tb[OCI_LINUX_NAMESPACE_TYPE])
1515 return EINVAL;
1516
1517 if (tb[OCI_LINUX_NAMESPACE_PATH])
1518 return ENOTSUP; /* ToDo */
1519
1520 opts.namespace |= resolve_nstype(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]));
1521
1522 return 0;
1523 };
1524
1525
1526 enum {
1527 OCI_LINUX_UIDGIDMAP_CONTAINERID,
1528 OCI_LINUX_UIDGIDMAP_HOSTID,
1529 OCI_LINUX_UIDGIDMAP_SIZE,
1530 __OCI_LINUX_UIDGIDMAP_MAX,
1531 };
1532
1533 static const struct blobmsg_policy oci_linux_uidgidmap_policy[] = {
1534 [OCI_LINUX_UIDGIDMAP_CONTAINERID] = { "containerID", BLOBMSG_TYPE_INT32 },
1535 [OCI_LINUX_UIDGIDMAP_HOSTID] = { "hostID", BLOBMSG_TYPE_INT32 },
1536 [OCI_LINUX_UIDGIDMAP_SIZE] = { "size", BLOBMSG_TYPE_INT32 },
1537 };
1538
1539 static int parseOCIuidgidmappings(struct blob_attr *msg, bool is_gidmap)
1540 {
1541 const char *map_format = "%d %d %d\n";
1542 struct blob_attr *tb[__OCI_LINUX_UIDGIDMAP_MAX];
1543 struct blob_attr *cur;
1544 int rem, len;
1545 char **mappings;
1546 char *map, *curstr;
1547 unsigned int cnt = 0;
1548 size_t totallen = 0;
1549
1550 /* count number of mappings */
1551 blobmsg_for_each_attr(cur, msg, rem)
1552 cnt++;
1553
1554 if (!cnt)
1555 return 0;
1556
1557 /* allocate array for mappings */
1558 mappings = calloc(1 + cnt, sizeof(char*));
1559 if (!mappings)
1560 return ENOMEM;
1561
1562 mappings[cnt] = NULL;
1563
1564 cnt = 0;
1565 blobmsg_for_each_attr(cur, msg, rem) {
1566 blobmsg_parse(oci_linux_uidgidmap_policy, __OCI_LINUX_UIDGIDMAP_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1567
1568 if (!tb[OCI_LINUX_UIDGIDMAP_CONTAINERID] ||
1569 !tb[OCI_LINUX_UIDGIDMAP_HOSTID] ||
1570 !tb[OCI_LINUX_UIDGIDMAP_SIZE])
1571 return EINVAL;
1572
1573 /* write mapping line into allocated string */
1574 len = asprintf(&mappings[cnt++], map_format,
1575 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
1576 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
1577 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
1578
1579 if (len < 0)
1580 return ENOMEM;
1581
1582 totallen += len;
1583 }
1584
1585 /* allocate combined mapping string */
1586 map = calloc(1 + totallen, sizeof(char));
1587 if (!map)
1588 return ENOMEM;
1589
1590 map[0] = '\0';
1591
1592 /* concatenate mapping strings into combined string */
1593 curstr = mappings[0];
1594 while (curstr) {
1595 strcat(map, curstr);
1596 free(curstr++);
1597 }
1598 free(mappings);
1599
1600 if (is_gidmap)
1601 opts.gidmap = map;
1602 else
1603 opts.uidmap = map;
1604
1605 return 0;
1606 }
1607
1608 enum {
1609 OCI_LINUX_RESOURCES,
1610 OCI_LINUX_SECCOMP,
1611 OCI_LINUX_SYSCTL,
1612 OCI_LINUX_NAMESPACES,
1613 OCI_LINUX_UIDMAPPINGS,
1614 OCI_LINUX_GIDMAPPINGS,
1615 OCI_LINUX_MASKEDPATHS,
1616 OCI_LINUX_READONLYPATHS,
1617 OCI_LINUX_ROOTFSPROPAGATION,
1618 __OCI_LINUX_MAX,
1619 };
1620
1621 static const struct blobmsg_policy oci_linux_policy[] = {
1622 [OCI_LINUX_RESOURCES] = { "resources", BLOBMSG_TYPE_TABLE },
1623 [OCI_LINUX_SECCOMP] = { "seccomp", BLOBMSG_TYPE_TABLE },
1624 [OCI_LINUX_SYSCTL] = { "sysctl", BLOBMSG_TYPE_TABLE },
1625 [OCI_LINUX_NAMESPACES] = { "namespaces", BLOBMSG_TYPE_ARRAY },
1626 [OCI_LINUX_UIDMAPPINGS] = { "uidMappings", BLOBMSG_TYPE_ARRAY },
1627 [OCI_LINUX_GIDMAPPINGS] = { "gidMappings", BLOBMSG_TYPE_ARRAY },
1628 [OCI_LINUX_MASKEDPATHS] = { "maskedPaths", BLOBMSG_TYPE_ARRAY },
1629 [OCI_LINUX_READONLYPATHS] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY },
1630 [OCI_LINUX_ROOTFSPROPAGATION] = { "rootfsPropagation", BLOBMSG_TYPE_STRING },
1631 };
1632
1633 static int parseOCIsysctl(struct blob_attr *msg)
1634 {
1635 struct blob_attr *cur;
1636 int rem;
1637 char *tmp, *tc;
1638 size_t cnt = 0;
1639
1640 blobmsg_for_each_attr(cur, msg, rem) {
1641 if (!blobmsg_name(cur) || !blobmsg_get_string(cur))
1642 return EINVAL;
1643
1644 ++cnt;
1645 }
1646
1647 if (!cnt)
1648 return 0;
1649
1650 opts.sysctl = calloc(cnt + 1, sizeof(struct sysctl_val *));
1651 if (!opts.sysctl)
1652 return ENOMEM;
1653
1654 cnt = 0;
1655 blobmsg_for_each_attr(cur, msg, rem) {
1656 opts.sysctl[cnt] = malloc(sizeof(struct sysctl_val));
1657 if (!opts.sysctl[cnt])
1658 return ENOMEM;
1659
1660 /* replace '.' with '/' in entry name */
1661 tc = tmp = strdup(blobmsg_name(cur));
1662 while ((tc = strchr(tc, '.')))
1663 *tc = '/';
1664
1665 opts.sysctl[cnt]->value = strdup(blobmsg_get_string(cur));
1666 opts.sysctl[cnt]->entry = tmp;
1667
1668 ++cnt;
1669 }
1670
1671 opts.sysctl[cnt] = NULL;
1672
1673 return 0;
1674 }
1675
1676 static int parseOCIlinux(struct blob_attr *msg)
1677 {
1678 struct blob_attr *tb[__OCI_LINUX_MAX];
1679 struct blob_attr *cur;
1680 int rem;
1681 int res = 0;
1682
1683 blobmsg_parse(oci_linux_policy, __OCI_LINUX_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1684
1685 if (tb[OCI_LINUX_NAMESPACES]) {
1686 blobmsg_for_each_attr(cur, tb[OCI_LINUX_NAMESPACES], rem) {
1687 res = parseOCIlinuxns(cur);
1688 if (res)
1689 return res;
1690 }
1691 }
1692
1693 if (tb[OCI_LINUX_UIDMAPPINGS]) {
1694 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 0);
1695 if (res)
1696 return res;
1697 }
1698
1699 if (tb[OCI_LINUX_GIDMAPPINGS]) {
1700 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 1);
1701 if (res)
1702 return res;
1703 }
1704
1705 if (tb[OCI_LINUX_READONLYPATHS]) {
1706 blobmsg_for_each_attr(cur, tb[OCI_LINUX_READONLYPATHS], rem) {
1707 res = add_mount(NULL, blobmsg_get_string(cur), NULL, MS_BIND | MS_REC | MS_RDONLY, NULL, 0);
1708 if (res)
1709 return res;
1710 }
1711 }
1712
1713 if (tb[OCI_LINUX_MASKEDPATHS]) {
1714 blobmsg_for_each_attr(cur, tb[OCI_LINUX_MASKEDPATHS], rem) {
1715 res = add_mount((void *)(-1), blobmsg_get_string(cur), NULL, 0, NULL, 1);
1716 if (res)
1717 return res;
1718 }
1719 }
1720
1721 if (tb[OCI_LINUX_SYSCTL]) {
1722 res = parseOCIsysctl(tb[OCI_LINUX_SYSCTL]);
1723 if (res)
1724 return res;
1725 }
1726
1727 if (tb[OCI_LINUX_SECCOMP]) {
1728 opts.ociseccomp = parseOCIlinuxseccomp(tb[OCI_LINUX_SECCOMP]);
1729 if (!opts.ociseccomp)
1730 return EINVAL;
1731 }
1732
1733 return 0;
1734 }
1735
1736 enum {
1737 OCI_VERSION,
1738 OCI_HOSTNAME,
1739 OCI_PROCESS,
1740 OCI_ROOT,
1741 OCI_MOUNTS,
1742 OCI_HOOKS,
1743 OCI_LINUX,
1744 __OCI_MAX,
1745 };
1746
1747 static const struct blobmsg_policy oci_policy[] = {
1748 [OCI_VERSION] = { "ociVersion", BLOBMSG_TYPE_STRING },
1749 [OCI_HOSTNAME] = { "hostname", BLOBMSG_TYPE_STRING },
1750 [OCI_PROCESS] = { "process", BLOBMSG_TYPE_TABLE },
1751 [OCI_ROOT] = { "root", BLOBMSG_TYPE_TABLE },
1752 [OCI_MOUNTS] = { "mounts", BLOBMSG_TYPE_ARRAY },
1753 [OCI_HOOKS] = { "hooks", BLOBMSG_TYPE_TABLE },
1754 [OCI_LINUX] = { "linux", BLOBMSG_TYPE_TABLE },
1755 };
1756
1757 static int parseOCI(const char *jsonfile)
1758 {
1759 struct blob_attr *tb[__OCI_MAX];
1760 struct blob_attr *cur;
1761 int rem;
1762 int res;
1763
1764 blob_buf_init(&ocibuf, 0);
1765 if (!blobmsg_add_json_from_file(&ocibuf, jsonfile))
1766 return ENOENT;
1767
1768 blobmsg_parse(oci_policy, __OCI_MAX, tb, blob_data(ocibuf.head), blob_len(ocibuf.head));
1769
1770 if (!tb[OCI_VERSION])
1771 return ENOMSG;
1772
1773 if (strncmp("1.0", blobmsg_get_string(tb[OCI_VERSION]), 3)) {
1774 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb[OCI_VERSION]));
1775 return ENOTSUP;
1776 }
1777
1778 if (tb[OCI_HOSTNAME])
1779 opts.hostname = strdup(blobmsg_get_string(tb[OCI_HOSTNAME]));
1780
1781 if (!tb[OCI_PROCESS])
1782 return ENODATA;
1783
1784 if ((res = parseOCIprocess(tb[OCI_PROCESS])))
1785 return res;
1786
1787 if (!tb[OCI_ROOT])
1788 return ENODATA;
1789
1790 if ((res = parseOCIroot(jsonfile, tb[OCI_ROOT])))
1791 return res;
1792
1793 if (!tb[OCI_MOUNTS])
1794 return ENODATA;
1795
1796 blobmsg_for_each_attr(cur, tb[OCI_MOUNTS], rem)
1797 if ((res = parseOCImount(cur)))
1798 return res;
1799
1800 if (tb[OCI_LINUX] && (res = parseOCIlinux(tb[OCI_LINUX])))
1801 return res;
1802
1803 if (tb[OCI_HOOKS] && (res = parseOCIhooks(tb[OCI_HOOKS])))
1804 return res;
1805
1806 blob_buf_free(&ocibuf);
1807
1808 return 0;
1809 }
1810
1811 int main(int argc, char **argv)
1812 {
1813 sigset_t sigmask;
1814 uid_t uid = getuid();
1815 const char log[] = "/dev/log";
1816 const char ubus[] = "/var/run/ubus.sock";
1817 char *jsonfile = NULL;
1818 int i, ch;
1819 int pipes[4];
1820 char sig_buf[1];
1821 int netns_fd;
1822
1823 if (uid) {
1824 ERROR("not root, aborting: %m\n");
1825 return EXIT_FAILURE;
1826 }
1827
1828 umask(022);
1829 mount_list_init();
1830 init_library_search();
1831
1832 while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
1833 switch (ch) {
1834 case 'd':
1835 debug = atoi(optarg);
1836 break;
1837 case 'p':
1838 opts.namespace |= CLONE_NEWNS;
1839 opts.procfs = 1;
1840 break;
1841 case 'o':
1842 opts.namespace |= CLONE_NEWNS;
1843 opts.ronly = 1;
1844 break;
1845 case 'f':
1846 opts.namespace |= CLONE_NEWUSER;
1847 break;
1848 case 'F':
1849 opts.namespace |= CLONE_NEWCGROUP;
1850 break;
1851 case 'R':
1852 opts.extroot = strdup(optarg);
1853 break;
1854 case 's':
1855 opts.namespace |= CLONE_NEWNS;
1856 opts.sysfs = 1;
1857 break;
1858 case 'S':
1859 opts.seccomp = optarg;
1860 add_mount_bind(optarg, 1, -1);
1861 break;
1862 case 'C':
1863 opts.capabilities = optarg;
1864 break;
1865 case 'c':
1866 opts.no_new_privs = 1;
1867 break;
1868 case 'n':
1869 opts.name = optarg;
1870 break;
1871 case 'N':
1872 opts.namespace |= CLONE_NEWNET;
1873 break;
1874 case 'h':
1875 opts.namespace |= CLONE_NEWUTS;
1876 opts.hostname = strdup(optarg);
1877 break;
1878 case 'r':
1879 opts.namespace |= CLONE_NEWNS;
1880 add_path_and_deps(optarg, 1, 0, 0);
1881 break;
1882 case 'w':
1883 opts.namespace |= CLONE_NEWNS;
1884 add_path_and_deps(optarg, 0, 0, 0);
1885 break;
1886 case 'u':
1887 opts.namespace |= CLONE_NEWNS;
1888 add_mount_bind(ubus, 0, -1);
1889 break;
1890 case 'l':
1891 opts.namespace |= CLONE_NEWNS;
1892 add_mount_bind(log, 0, -1);
1893 break;
1894 case 'U':
1895 opts.user = optarg;
1896 break;
1897 case 'G':
1898 opts.group = optarg;
1899 break;
1900 case 'O':
1901 opts.overlaydir = optarg;
1902 break;
1903 case 'T':
1904 opts.tmpoverlaysize = optarg;
1905 break;
1906 case 'E':
1907 opts.require_jail = 1;
1908 break;
1909 case 'y':
1910 opts.console = 1;
1911 break;
1912 case 'J':
1913 asprintf(&jsonfile, "%s/config.json", optarg);
1914 break;
1915 }
1916 }
1917
1918 if (opts.namespace)
1919 opts.namespace |= CLONE_NEWIPC | CLONE_NEWPID;
1920
1921 if (jsonfile) {
1922 int ocires;
1923 ocires = parseOCI(jsonfile);
1924 free(jsonfile);
1925 if (ocires) {
1926 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires), ocires);
1927 return ocires;
1928 }
1929 }
1930
1931 if (opts.tmpoverlaysize && strlen(opts.tmpoverlaysize) > 8) {
1932 ERROR("size parameter too long: \"%s\"\n", opts.tmpoverlaysize);
1933 return -1;
1934 }
1935
1936 /* no <binary> param found */
1937 if (!jsonfile && (argc - optind < 1)) {
1938 usage();
1939 return EXIT_FAILURE;
1940 }
1941 if (!(opts.namespace||opts.capabilities||opts.seccomp)) {
1942 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
1943 usage();
1944 return EXIT_FAILURE;
1945 }
1946 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
1947 opts.namespace,
1948 opts.capabilities != 0 || opts.capset.apply,
1949 opts.seccomp != 0 || opts.ociseccomp != 0);
1950
1951 if (!jsonfile) {
1952 /* allocate NULL-terminated array for argv */
1953 opts.jail_argv = calloc(1 + argc - optind, sizeof(char**));
1954 if (!opts.jail_argv)
1955 return EXIT_FAILURE;
1956
1957 for (size_t s = optind; s < argc; s++)
1958 opts.jail_argv[s - optind] = strdup(argv[s]);
1959
1960 if (opts.namespace & CLONE_NEWUSER)
1961 get_jail_user(&opts.pw_uid, &opts.pw_gid, &opts.gr_gid);
1962 }
1963
1964 if (!opts.extroot) {
1965 if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
1966 ERROR("failed to load dependencies\n");
1967 return -1;
1968 }
1969 }
1970
1971 if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
1972 ERROR("failed to load libpreload-seccomp.so\n");
1973 opts.seccomp = 0;
1974 if (opts.require_jail)
1975 return -1;
1976 }
1977
1978 if (apply_rlimits()) {
1979 ERROR("error applying resource limits\n");
1980 exit(EXIT_FAILURE);
1981 }
1982
1983 if (opts.name)
1984 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
1985
1986 sigfillset(&sigmask);
1987 for (i = 0; i < _NSIG; i++) {
1988 struct sigaction s = { 0 };
1989
1990 if (!sigismember(&sigmask, i))
1991 continue;
1992 if ((i == SIGCHLD) || (i == SIGPIPE) || (i == SIGSEGV))
1993 continue;
1994
1995 s.sa_handler = jail_handle_signal;
1996 sigaction(i, &s, NULL);
1997 }
1998
1999 if (opts.namespace) {
2000 if (opts.namespace & CLONE_NEWNS) {
2001 add_mount_bind("/dev/full", 0, -1);
2002 add_mount_bind("/dev/null", 0, -1);
2003 add_mount_bind("/dev/random", 0, -1);
2004 add_mount_bind("/dev/urandom", 0, -1);
2005 add_mount_bind("/dev/zero", 0, -1);
2006 add_mount_bind("/dev/ptmx", 0, -1);
2007 add_mount_bind("/dev/tty", 0, -1);
2008
2009 if (!opts.extroot && (opts.user || opts.group)) {
2010 add_mount_bind("/etc/passwd", 0, -1);
2011 add_mount_bind("/etc/group", 0, -1);
2012 }
2013
2014 #if defined(__GLIBC__)
2015 if (!opts.extroot)
2016 add_mount_bind("/etc/nsswitch.conf", 0, -1);
2017 #endif
2018
2019 if (!(opts.namespace & CLONE_NEWNET)) {
2020 add_mount_bind("/etc/resolv.conf", 0, -1);
2021 } else {
2022 char hostdir[PATH_MAX];
2023
2024 snprintf(hostdir, PATH_MAX, "/tmp/resolv.conf-%s.d", opts.name);
2025 mkdir_p(hostdir, 0755);
2026 add_mount(hostdir, "/tmp/resolv.conf.d", NULL, MS_BIND | MS_NOEXEC | MS_NOATIME | MS_NOSUID | MS_NODEV | MS_RDONLY, NULL, -1);
2027 }
2028 }
2029
2030 if (pipe(&pipes[0]) < 0 || pipe(&pipes[2]) < 0)
2031 return -1;
2032
2033 jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, SIGCHLD | opts.namespace, &pipes);
2034 } else {
2035 jail_process.pid = fork();
2036 }
2037
2038 if (jail_process.pid > 0) {
2039 jail_running = 1;
2040 seteuid(0);
2041 /* parent process */
2042 close(pipes[1]);
2043 close(pipes[2]);
2044 run_hooks(opts.hooks.createRuntime);
2045 if (read(pipes[0], sig_buf, 1) < 1) {
2046 ERROR("can't read from child\n");
2047 return -1;
2048 }
2049 close(pipes[0]);
2050 if (opts.namespace & CLONE_NEWUSER) {
2051 if (write_setgroups(jail_process.pid, true)) {
2052 ERROR("can't write setgroups\n");
2053 return -1;
2054 }
2055 if (!opts.uidmap) {
2056 bool has_gr = (opts.gr_gid != -1);
2057 if (opts.pw_uid != -1) {
2058 write_single_uid_gid_map(jail_process.pid, 0, opts.pw_uid);
2059 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:opts.pw_gid);
2060 } else {
2061 write_single_uid_gid_map(jail_process.pid, 0, 65534);
2062 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:65534);
2063 }
2064 } else {
2065 write_uid_gid_map(jail_process.pid, 0, opts.uidmap);
2066 if (opts.gidmap)
2067 write_uid_gid_map(jail_process.pid, 1, opts.gidmap);
2068 }
2069 }
2070
2071 if (opts.namespace & CLONE_NEWNET) {
2072 if (!opts.name) {
2073 ERROR("netns needs a named jail\n");
2074 return -1;
2075 }
2076 netns_fd = netns_open_pid(jail_process.pid);
2077 netns_updown(jail_process.pid, true);
2078 }
2079
2080 sig_buf[0] = 'O';
2081 if (write(pipes[3], sig_buf, 1) < 0) {
2082 ERROR("can't write to child\n");
2083 return -1;
2084 }
2085 close(pipes[3]);
2086 run_hooks(opts.hooks.poststart);
2087
2088 uloop_init();
2089 uloop_process_add(&jail_process);
2090 uloop_run();
2091 if (jail_running) {
2092 DEBUG("uloop interrupted, killing jail process\n");
2093 kill(jail_process.pid, SIGTERM);
2094 uloop_timeout_set(&jail_process_timeout, 1000);
2095 uloop_run();
2096 }
2097 uloop_done();
2098 if (opts.namespace & CLONE_NEWNET) {
2099 setns(netns_fd, CLONE_NEWNET);
2100 netns_updown(getpid(), false);
2101 close(netns_fd);
2102 }
2103 run_hooks(opts.hooks.poststop);
2104 free_opts(true);
2105 return jail_return_code;
2106 } else if (jail_process.pid == 0) {
2107 /* fork child process */
2108 return exec_jail(NULL);
2109 } else {
2110 ERROR("failed to clone/fork: %m\n");
2111 return EXIT_FAILURE;
2112 }
2113 }