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