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