fc8d8247c5d521e255368e00768255f0b55fb3b5
[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 <assert.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <string.h>
41 #include <fcntl.h>
42 #include <sched.h>
43 #include <linux/filter.h>
44 #include <linux/limits.h>
45 #include <linux/nsfs.h>
46 #include <linux/securebits.h>
47 #include <signal.h>
48 #include <inttypes.h>
49
50 #include "capabilities.h"
51 #include "elf.h"
52 #include "fs.h"
53 #include "jail.h"
54 #include "log.h"
55 #include "seccomp-oci.h"
56 #include "cgroups.h"
57
58 #include <libubox/blobmsg.h>
59 #include <libubox/blobmsg_json.h>
60 #include <libubox/list.h>
61 #include <libubox/vlist.h>
62 #include <libubox/uloop.h>
63 #include <libubox/utils.h>
64 #include <libubus.h>
65
66 #ifndef CLONE_NEWCGROUP
67 #define CLONE_NEWCGROUP 0x02000000
68 #endif
69
70 #define STACK_SIZE (1024 * 1024)
71 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:iP:"
72
73 #define OCI_VERSION_STRING "1.0.2"
74
75 struct hook_execvpe {
76 char *file;
77 char **argv;
78 char **envp;
79 int timeout;
80 };
81
82 struct sysctl_val {
83 char *entry;
84 char *value;
85 };
86
87 struct mknod_args {
88 char *path;
89 mode_t mode;
90 dev_t dev;
91 uid_t uid;
92 gid_t gid;
93 };
94
95 static struct {
96 char *name;
97 char *hostname;
98 char **jail_argv;
99 char *cwd;
100 char *seccomp;
101 struct sock_fprog *ociseccomp;
102 char *capabilities;
103 struct jail_capset capset;
104 char *user;
105 char *group;
106 char *extroot;
107 char *overlaydir;
108 char *tmpoverlaysize;
109 char **envp;
110 char *uidmap;
111 char *gidmap;
112 char *pidfile;
113 struct sysctl_val **sysctl;
114 int no_new_privs;
115 int namespace;
116 struct {
117 int pid;
118 int net;
119 int ns;
120 int ipc;
121 int uts;
122 int user;
123 int cgroup;
124 #ifdef CLONE_NEWTIME
125 int time;
126 #endif
127 } setns;
128 int procfs;
129 int ronly;
130 int sysfs;
131 int console;
132 int pw_uid;
133 int pw_gid;
134 int gr_gid;
135 int root_map_uid;
136 gid_t *additional_gids;
137 size_t num_additional_gids;
138 mode_t umask;
139 bool set_umask;
140 int require_jail;
141 struct {
142 struct hook_execvpe **createRuntime;
143 struct hook_execvpe **createContainer;
144 struct hook_execvpe **startContainer;
145 struct hook_execvpe **poststart;
146 struct hook_execvpe **poststop;
147 } hooks;
148 struct rlimit *rlimits[RLIM_NLIMITS];
149 int oom_score_adj;
150 bool set_oom_score_adj;
151 struct mknod_args **devices;
152 char *ocibundle;
153 bool immediately;
154 struct blob_attr *annotations;
155 } opts;
156
157 static struct blob_buf ocibuf;
158
159 extern int pivot_root(const char *new_root, const char *put_old);
160
161 int debug = 0;
162
163 static char child_stack[STACK_SIZE];
164
165 static struct ubus_context *parent_ctx;
166
167 int console_fd;
168
169
170 static inline bool has_namespaces(void)
171 {
172 return ((opts.setns.pid != -1) ||
173 (opts.setns.net != -1) ||
174 (opts.setns.ns != -1) ||
175 (opts.setns.ipc != -1) ||
176 (opts.setns.uts != -1) ||
177 (opts.setns.user != -1) ||
178 (opts.setns.cgroup != -1) ||
179 #ifdef CLONE_NEWTIME
180 (opts.setns.time != -1) ||
181 #endif
182 opts.namespace);
183 }
184
185 static void free_oci_envp(char **p) {
186 char **tmp;
187
188 if (p) {
189 tmp = p;
190 while (*tmp)
191 free(*(tmp++));
192
193 free(p);
194 }
195 }
196
197 static void free_hooklist(struct hook_execvpe **hooklist)
198 {
199 struct hook_execvpe *cur;
200
201 if (!hooklist)
202 return;
203
204 cur = *hooklist;
205 while (cur) {
206 free_oci_envp(cur->argv);
207 free_oci_envp(cur->envp);
208 free(cur->file);
209 free(cur++);
210 }
211 free(hooklist);
212 }
213
214 static void free_sysctl(void) {
215 struct sysctl_val *cur;
216 cur = *opts.sysctl;
217
218 while (cur) {
219 free(cur->entry);
220 free(cur->value);
221 free(cur++);
222 }
223 free(opts.sysctl);
224 }
225
226 static void free_devices(void) {
227 struct mknod_args **cur;
228
229 if (!opts.devices)
230 return;
231
232 cur = opts.devices;
233
234 while (*cur) {
235 free((*cur)->path);
236 free(*(cur++));
237 }
238 free(opts.devices);
239 }
240
241 static void free_rlimits(void) {
242 int type;
243
244 for (type = 0; type < RLIM_NLIMITS; ++type)
245 free(opts.rlimits[type]);
246 }
247
248 static void free_opts(bool parent) {
249
250 free_library_search();
251 mount_free();
252 cgroups_free();
253
254 /* we need to keep argv, envp and seccomp filter in child */
255 if (parent) { /* parent-only */
256 if (opts.ociseccomp) {
257 free(opts.ociseccomp->filter);
258 free(opts.ociseccomp);
259 }
260
261 free_oci_envp(opts.jail_argv);
262 free_oci_envp(opts.envp);
263 }
264
265 free_rlimits();
266 free_sysctl();
267 free_devices();
268 free(opts.hostname);
269 free(opts.cwd);
270 free(opts.uidmap);
271 free(opts.gidmap);
272 free(opts.annotations);
273 free(opts.extroot);
274 free(opts.overlaydir);
275 free_hooklist(opts.hooks.createRuntime);
276 free_hooklist(opts.hooks.createContainer);
277 free_hooklist(opts.hooks.startContainer);
278 free_hooklist(opts.hooks.poststart);
279 free_hooklist(opts.hooks.poststop);
280 }
281
282 static int mount_overlay(char *jail_root, char *overlaydir) {
283 char *upperdir, *workdir, *optsstr, *upperetc, *upperresolvconf;
284 const char mountoptsformat[] = "lowerdir=%s,upperdir=%s,workdir=%s";
285 int ret = -1, fd;
286
287 if (asprintf(&upperdir, "%s%s", overlaydir, "/upper") < 0)
288 goto out;
289
290 if (asprintf(&workdir, "%s%s", overlaydir, "/work") < 0)
291 goto upper_printf;
292
293 if (asprintf(&optsstr, mountoptsformat, jail_root, upperdir, workdir) < 0)
294 goto work_printf;
295
296 if (mkdir_p(upperdir, 0755) || mkdir_p(workdir, 0755))
297 goto opts_printf;
298
299 /*
300 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
301 * this is to work-around a bug in overlayfs described in the overlayfs-userns
302 * patch:
303 * 3. modification of a file 'hithere' which is in l but not yet
304 * in u, and which is not owned by T, is not allowed, even if
305 * writes to u are allowed. This may be a bug in overlayfs,
306 * but it is safe behavior.
307 */
308 if (asprintf(&upperetc, "%s/etc", upperdir) < 0)
309 goto opts_printf;
310
311 if (mkdir_p(upperetc, 0755))
312 goto upper_etc_printf;
313
314 if (asprintf(&upperresolvconf, "%s/resolv.conf", upperetc) < 0)
315 goto upper_etc_printf;
316
317 fd = creat(upperresolvconf, 0644);
318 if (fd < 0) {
319 if (errno != EEXIST)
320 ERROR("creat(%s) failed: %m\n", upperresolvconf);
321 } else {
322 close(fd);
323 }
324 DEBUG("mount -t overlay %s %s (%s)\n", jail_root, jail_root, optsstr);
325
326 if (mount(jail_root, jail_root, "overlay", MS_NOATIME, optsstr))
327 goto upper_resolvconf_printf;
328
329 ret = 0;
330
331 upper_resolvconf_printf:
332 free(upperresolvconf);
333 upper_etc_printf:
334 free(upperetc);
335 opts_printf:
336 free(optsstr);
337 work_printf:
338 free(workdir);
339 upper_printf:
340 free(upperdir);
341 out:
342 return ret;
343 }
344
345 static void pass_console(int console_fd)
346 {
347 struct ubus_context *child_ctx = ubus_connect(NULL);
348 static struct blob_buf req;
349 uint32_t id;
350
351 if (!child_ctx)
352 return;
353
354 blob_buf_init(&req, 0);
355 blobmsg_add_string(&req, "name", opts.name);
356
357 if (ubus_lookup_id(child_ctx, "container", &id) ||
358 ubus_invoke_fd(child_ctx, id, "console_set", req.head, NULL, NULL, 3000, console_fd))
359 INFO("ubus request failed\n");
360 else
361 close(console_fd);
362
363 blob_buf_free(&req);
364 ubus_free(child_ctx);
365 }
366
367 static int create_dev_console(const char *jail_root)
368 {
369 char *console_fname;
370 char dev_console_path[PATH_MAX];
371 int slave_console_fd;
372
373 /* Open UNIX/98 virtual console */
374 console_fd = posix_openpt(O_RDWR | O_NOCTTY);
375 if (console_fd < 0)
376 return -1;
377
378 console_fname = ptsname(console_fd);
379 DEBUG("got console fd %d and PTS client name %s\n", console_fd, console_fname);
380 if (!console_fname)
381 goto no_console;
382
383 grantpt(console_fd);
384 unlockpt(console_fd);
385
386 /* pass PTY master to procd */
387 pass_console(console_fd);
388
389 /* mount-bind PTY slave to /dev/console in jail */
390 snprintf(dev_console_path, sizeof(dev_console_path), "%s/dev/console", jail_root);
391 close(creat(dev_console_path, 0620));
392
393 if (mount(console_fname, dev_console_path, "bind", MS_BIND, NULL))
394 goto no_console;
395
396 /* use PTY slave for stdio */
397 slave_console_fd = open(console_fname, O_RDWR); /* | O_NOCTTY */
398 dup2(slave_console_fd, 0);
399 dup2(slave_console_fd, 1);
400 dup2(slave_console_fd, 2);
401 close(slave_console_fd);
402
403 INFO("using guest console %s\n", console_fname);
404
405 return 0;
406
407 no_console:
408 close(console_fd);
409 return 1;
410 }
411
412 static int hook_running = 0;
413 static int hook_return_code = 0;
414 static struct hook_execvpe **current_hook = NULL;
415 typedef void (*hook_return_handler)(void);
416 static hook_return_handler hook_return_cb = NULL;
417
418 static void hook_process_timeout_cb(struct uloop_timeout *t);
419 static struct uloop_timeout hook_process_timeout = {
420 .cb = hook_process_timeout_cb,
421 };
422
423 static void run_hooklist(void);
424 static void hook_process_handler(struct uloop_process *c, int ret)
425 {
426 uloop_timeout_cancel(&hook_process_timeout);
427
428 if (WIFEXITED(ret)) {
429 hook_return_code = WEXITSTATUS(ret);
430 if (hook_return_code)
431 ERROR("hook (%d) exited with exit: %d\n", c->pid, hook_return_code);
432 else
433 DEBUG("hook (%d) exited with exit: %d\n", c->pid, hook_return_code);
434
435 } else {
436 hook_return_code = WTERMSIG(ret);
437 ERROR("hook (%d) exited with signal: %d\n", c->pid, hook_return_code);
438 }
439 hook_running = 0;
440 ++current_hook;
441 run_hooklist();
442 }
443
444 static struct uloop_process hook_process = {
445 .cb = hook_process_handler,
446 };
447
448 static void hook_process_timeout_cb(struct uloop_timeout *t)
449 {
450 DEBUG("hook process failed to stop, sending SIGKILL\n");
451 kill(hook_process.pid, SIGKILL);
452 }
453
454 static void run_hooklist(void)
455 {
456 struct hook_execvpe *hook = *current_hook;
457 struct stat s;
458
459 if (!hook)
460 hook_return_cb();
461
462 DEBUG("executing hook %s\n", hook->file);
463
464 if (stat(hook->file, &s))
465 hook_process_handler(&hook_process, ENOENT);
466
467 if (!((unsigned long)s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
468 hook_process_handler(&hook_process, EPERM);
469
470 hook_running = 1;
471 hook_process.pid = fork();
472 if (hook_process.pid == 0) {
473 /* child */
474 execve(hook->file, hook->argv, hook->envp);
475 ERROR("execve error %m\n");
476 _exit(errno);
477 } else if (hook_process.pid < 0) {
478 /* fork error */
479 ERROR("hook fork error\n");
480 hook_running = 0;
481 hook_process_handler(&hook_process, errno);
482 }
483
484 /* parent */
485 uloop_process_add(&hook_process);
486
487 if (hook->timeout > 0)
488 uloop_timeout_set(&hook_process_timeout, 1000 * hook->timeout);
489
490 uloop_run();
491 if (hook_running) {
492 DEBUG("uloop interrupted, killing jail process\n");
493 kill(hook_process.pid, SIGTERM);
494 uloop_timeout_set(&hook_process_timeout, 1000);
495 uloop_run();
496 }
497 }
498
499 static void run_hooks(struct hook_execvpe **hooklist, hook_return_handler return_cb)
500 {
501 if (!hooklist)
502 return_cb();
503
504 current_hook = hooklist;
505 hook_return_cb = return_cb;
506
507 run_hooklist();
508 }
509
510 static int apply_sysctl(const char *jail_root)
511 {
512 struct sysctl_val **cur;
513 char *procdir, *fname;
514 int f;
515
516 if (!opts.sysctl)
517 return 0;
518
519 if (asprintf(&procdir, "%s/proc", jail_root) < 0)
520 return ENOMEM;
521
522 mkdir(procdir, 0700);
523 if (mount("proc", procdir, "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0))
524 return EPERM;
525
526 cur = opts.sysctl;
527
528 while (*cur) {
529 if (asprintf(&fname, "%s/sys/%s", procdir, (*cur)->entry) < 0)
530 return ENOMEM;
531
532 DEBUG("sysctl: writing '%s' to %s\n", (*cur)->value, fname);
533
534 f = open(fname, O_WRONLY);
535 if (f < 0) {
536 ERROR("sysctl: can't open %s\n", fname);
537 free(fname);
538 return errno;
539 }
540 if (write(f, (*cur)->value, strlen((*cur)->value)) < 0) {
541 ERROR("sysctl: write to %s\n", fname);
542 free(fname);
543 close(f);
544 return errno;
545 }
546
547 free(fname);
548 close(f);
549 ++cur;
550 }
551 umount(procdir);
552 rmdir(procdir);
553 free(procdir);
554
555 return 0;
556 }
557
558 /* glibc defines makedev calling a function. make sure it's a pure macro */
559 #if defined(__GLIBC__)
560 #undef makedev
561 /* from musl's sys/sysmacros.h */
562 #define makedev(x,y) ( \
563 (((x)&0xfffff000ULL) << 32) | \
564 (((x)&0x00000fffULL) << 8) | \
565 (((y)&0xffffff00ULL) << 12) | \
566 (((y)&0x000000ffULL)) )
567 #endif
568
569 static struct mknod_args default_devices[] = {
570 { .path = "/dev/null", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 3) },
571 { .path = "/dev/zero", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 5) },
572 { .path = "/dev/full", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 7) },
573 { .path = "/dev/random", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 8) },
574 { .path = "/dev/urandom", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 9) },
575 { .path = "/dev/tty", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP), .dev = makedev(5, 0), .gid = 5 },
576 { 0 },
577 };
578
579 static int create_devices(void)
580 {
581 struct mknod_args **cur, *curdef;
582
583 if (!opts.devices)
584 goto only_default_devices;
585
586 cur = opts.devices;
587
588 while (*cur) {
589 DEBUG("creating %s (mode=%08o)\n", (*cur)->path, (*cur)->mode);
590 if (mknod((*cur)->path, (*cur)->mode, (*cur)->dev))
591 return errno;
592
593 if (((*cur)->uid || (*cur)->gid) &&
594 chown((*cur)->path, (*cur)->uid, (*cur)->gid))
595 return errno;
596
597 ++cur;
598 }
599
600 only_default_devices:
601 curdef = default_devices;
602 while(curdef->path) {
603 DEBUG("creating %s (mode=%08o)\n", curdef->path, curdef->mode);
604 if (mknod(curdef->path, curdef->mode, curdef->dev)) {
605 ++curdef;
606 continue; /* may already exist, eg. due to a bind-mount */
607 }
608 if ((curdef->uid || curdef->gid) &&
609 chown(curdef->path, curdef->uid, curdef->gid))
610 return errno;
611
612 ++curdef;
613 }
614
615 /* Dev symbolic links as defined in OCI spec */
616 (void) symlink("/dev/pts/ptmx", "/dev/ptmx");
617 (void) symlink("/proc/self/fd", "/dev/fd");
618 (void) symlink("/proc/self/fd/0", "/dev/stdin");
619 (void) symlink("/proc/self/fd/1", "/dev/stdout");
620 (void) symlink("/proc/self/fd/2", "/dev/stderr");
621
622 return 0;
623 }
624
625 static char jail_root[] = "/tmp/ujail-XXXXXX";
626 static char tmpovdir[] = "/tmp/ujail-overlay-XXXXXX";
627 static mode_t old_umask;
628 static void enter_jail_fs(void);
629 static int build_jail_fs(void)
630 {
631 char *overlaydir = NULL;
632 int ret;
633
634 old_umask = umask(0);
635
636 if (mkdtemp(jail_root) == NULL) {
637 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
638 return -1;
639 }
640
641 if (apply_sysctl(jail_root)) {
642 ERROR("failed to apply sysctl values\n");
643 return -1;
644 }
645
646 /* oldroot can't be MS_SHARED else pivot_root() fails */
647 if (mount("none", "/", "none", MS_REC|MS_PRIVATE, NULL)) {
648 ERROR("private mount failed %m\n");
649 return -1;
650 }
651
652 if (opts.extroot) {
653 if (mount(opts.extroot, jail_root, "bind", MS_BIND, NULL)) {
654 ERROR("extroot mount failed %m\n");
655 return -1;
656 }
657 } else {
658 if (mount("tmpfs", jail_root, "tmpfs", MS_NOATIME, "mode=0755")) {
659 ERROR("tmpfs mount failed %m\n");
660 return -1;
661 }
662 }
663
664 if (opts.tmpoverlaysize) {
665 char mountoptsstr[] = "mode=0755,size=XXXXXXXX";
666
667 snprintf(mountoptsstr, sizeof(mountoptsstr),
668 "mode=0755,size=%s", opts.tmpoverlaysize);
669 if (mkdtemp(tmpovdir) == NULL) {
670 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
671 return -1;
672 }
673 if (mount("tmpfs", tmpovdir, "tmpfs", MS_NOATIME,
674 mountoptsstr)) {
675 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts.tmpoverlaysize);
676 return -1;
677 }
678 overlaydir = tmpovdir;
679 }
680
681 if (opts.overlaydir)
682 overlaydir = opts.overlaydir;
683
684 if (overlaydir) {
685 ret = mount_overlay(jail_root, overlaydir);
686 if (ret)
687 return ret;
688 }
689
690 if (chdir(jail_root)) {
691 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root);
692 return -1;
693 }
694
695 if (mount_all(jail_root)) {
696 ERROR("mount_all() failed\n");
697 return -1;
698 }
699
700 if (opts.console)
701 create_dev_console(jail_root);
702
703 /* make sure /etc/resolv.conf exists if in new network namespace */
704 if (!opts.extroot && opts.namespace & CLONE_NEWNET) {
705 char jailetc[PATH_MAX], jaillink[PATH_MAX];
706
707 snprintf(jailetc, PATH_MAX, "%s/etc", jail_root);
708 mkdir_p(jailetc, 0755);
709 snprintf(jaillink, PATH_MAX, "%s/etc/resolv.conf", jail_root);
710 if (overlaydir)
711 unlink(jaillink);
712
713 (void) symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink);
714 }
715
716 run_hooks(opts.hooks.createContainer, enter_jail_fs);
717
718 return 0;
719 }
720
721 static bool exit_from_child;
722 static void free_and_exit(int ret)
723 {
724 if (!exit_from_child && opts.ocibundle)
725 cgroups_free();
726
727 if (!exit_from_child && parent_ctx)
728 ubus_free(parent_ctx);
729
730 free_opts(!exit_from_child);
731
732 exit(ret);
733 }
734
735 static void post_jail_fs(void);
736 static void enter_jail_fs(void)
737 {
738 char dirbuf[sizeof(jail_root) + 4];
739
740 snprintf(dirbuf, sizeof(dirbuf), "%s/old", jail_root);
741 mkdir(dirbuf, 0755);
742
743 if (pivot_root(jail_root, dirbuf) == -1) {
744 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root, dirbuf);
745 free_and_exit(-1);
746 }
747 if (chdir("/")) {
748 ERROR("chdir(/) (after pivot_root) failed: %m\n");
749 free_and_exit(-1);
750 }
751
752 snprintf(dirbuf, sizeof(dirbuf), "/old%s", jail_root);
753 umount2(dirbuf, MNT_DETACH);
754 rmdir(dirbuf);
755 if (opts.tmpoverlaysize) {
756 char tmpdirbuf[sizeof(tmpovdir) + 4];
757 snprintf(tmpdirbuf, sizeof(tmpdirbuf), "/old%s", tmpovdir);
758 umount2(tmpdirbuf, MNT_DETACH);
759 rmdir(tmpdirbuf);
760 }
761
762 umount2("/old", MNT_DETACH);
763 rmdir("/old");
764
765 if (create_devices()) {
766 ERROR("create_devices() failed\n");
767 free_and_exit(-1);
768 }
769 if (opts.ronly)
770 mount(NULL, "/", "bind", MS_REMOUNT | MS_BIND | MS_RDONLY, 0);
771
772 umask(old_umask);
773 post_jail_fs();
774 }
775
776 static int write_uid_gid_map(pid_t child_pid, bool gidmap, char *mapstr)
777 {
778 int map_file;
779 char map_path[64];
780
781 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
782 child_pid, gidmap?"gid_map":"uid_map") < 0)
783 return -1;
784
785 if ((map_file = open(map_path, O_WRONLY)) < 0)
786 return -1;
787
788 if (dprintf(map_file, "%s", mapstr)) {
789 close(map_file);
790 return -1;
791 }
792
793 close(map_file);
794 return 0;
795 }
796
797 static int write_single_uid_gid_map(pid_t child_pid, bool gidmap, int id)
798 {
799 int map_file;
800 char map_path[64];
801 const char *map_format = "%d %d %d\n";
802 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
803 child_pid, gidmap?"gid_map":"uid_map") < 0)
804 return -1;
805
806 if ((map_file = open(map_path, O_WRONLY)) < 0)
807 return -1;
808
809 if (dprintf(map_file, map_format, 0, id, 1) < 0) {
810 close(map_file);
811 return -1;
812 }
813
814 close(map_file);
815 return 0;
816 }
817
818 static int write_setgroups(pid_t child_pid, bool allow)
819 {
820 int setgroups_file;
821 char setgroups_path[64];
822
823 if (snprintf(setgroups_path, sizeof(setgroups_path), "/proc/%d/setgroups",
824 child_pid) < 0) {
825 return -1;
826 }
827
828 if ((setgroups_file = open(setgroups_path, O_WRONLY)) < 0) {
829 return -1;
830 }
831
832 if (dprintf(setgroups_file, "%s", allow?"allow":"deny") == -1) {
833 close(setgroups_file);
834 return -1;
835 }
836
837 close(setgroups_file);
838 return 0;
839 }
840
841 static void get_jail_user(int *user, int *user_gid, int *gr_gid)
842 {
843 struct passwd *p = NULL;
844 struct group *g = NULL;
845
846 if (opts.user) {
847 p = getpwnam(opts.user);
848 if (!p) {
849 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
850 opts.user, errno, strerror(errno));
851 free_and_exit(EXIT_FAILURE);
852 }
853 *user = p->pw_uid;
854 *user_gid = p->pw_gid;
855 } else {
856 *user = -1;
857 *user_gid = -1;
858 }
859
860 if (opts.group) {
861 g = getgrnam(opts.group);
862 if (!g) {
863 ERROR("failed to get gid for group %s: %m\n", opts.group);
864 free_and_exit(EXIT_FAILURE);
865 }
866 *gr_gid = g->gr_gid;
867 } else {
868 *gr_gid = -1;
869 }
870 };
871
872 static void set_jail_user(int pw_uid, int user_gid, int gr_gid)
873 {
874 if (opts.user && (user_gid != -1) && initgroups(opts.user, user_gid)) {
875 ERROR("failed to initgroups() for user %s: %m\n", opts.user);
876 free_and_exit(EXIT_FAILURE);
877 }
878
879 if ((gr_gid != -1) && setregid(gr_gid, gr_gid)) {
880 ERROR("failed to set group id %d: %m\n", gr_gid);
881 free_and_exit(EXIT_FAILURE);
882 }
883
884 if ((pw_uid != -1) && setreuid(pw_uid, pw_uid)) {
885 ERROR("failed to set user id %d: %m\n", pw_uid);
886 free_and_exit(EXIT_FAILURE);
887 }
888 }
889
890 static int apply_rlimits(void)
891 {
892 int resource;
893
894 for (resource = 0; resource < RLIM_NLIMITS; ++resource) {
895 if (opts.rlimits[resource])
896 DEBUG("applying limits to resource %u\n", resource);
897
898 if (opts.rlimits[resource] &&
899 setrlimit(resource, opts.rlimits[resource]))
900 return errno;
901 }
902
903 return 0;
904 }
905
906 #define MAX_ENVP 64
907 static char** build_envp(const char *seccomp, char **ocienvp)
908 {
909 static char *envp[MAX_ENVP];
910 static char preload_var[PATH_MAX];
911 static char seccomp_var[PATH_MAX];
912 static char seccomp_debug_var[20];
913 static char debug_var[] = "LD_DEBUG=all";
914 static char container_var[] = "container=ujail";
915 const char *preload_lib = find_lib("libpreload-seccomp.so");
916 char **addenv;
917
918 int count = 0;
919
920 if (seccomp && !preload_lib) {
921 ERROR("failed to add preload-lib to env\n");
922 return NULL;
923 }
924 if (seccomp) {
925 snprintf(seccomp_var, sizeof(seccomp_var), "SECCOMP_FILE=%s", seccomp);
926 envp[count++] = seccomp_var;
927 snprintf(seccomp_debug_var, sizeof(seccomp_debug_var), "SECCOMP_DEBUG=%2d", debug);
928 envp[count++] = seccomp_debug_var;
929 snprintf(preload_var, sizeof(preload_var), "LD_PRELOAD=%s", preload_lib);
930 envp[count++] = preload_var;
931 }
932
933 envp[count++] = container_var;
934
935 if (debug > 1)
936 envp[count++] = debug_var;
937
938 addenv = ocienvp;
939 while (addenv && *addenv) {
940 envp[count++] = *(addenv++);
941 if (count >= MAX_ENVP) {
942 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP);
943 break;
944 }
945 }
946 return envp;
947 }
948
949 static void usage(void)
950 {
951 fprintf(stderr, "ujail <options> -- <binary> <params ...>\n");
952 fprintf(stderr, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
953 fprintf(stderr, " -S <file>\tseccomp filter config\n");
954 fprintf(stderr, " -C <file>\tcapabilities drop config\n");
955 fprintf(stderr, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
956 fprintf(stderr, " -n <name>\tthe name of the jail\n");
957 fprintf(stderr, "namespace jail options:\n");
958 fprintf(stderr, " -h <hostname>\tchange the hostname of the jail\n");
959 fprintf(stderr, " -N\t\tjail has network namespace\n");
960 fprintf(stderr, " -f\t\tjail has user namespace\n");
961 fprintf(stderr, " -F\t\tjail has cgroups namespace\n");
962 fprintf(stderr, " -r <file>\treadonly files that should be staged\n");
963 fprintf(stderr, " -w <file>\twriteable files that should be staged\n");
964 fprintf(stderr, " -p\t\tjail has /proc\n");
965 fprintf(stderr, " -s\t\tjail has /sys\n");
966 fprintf(stderr, " -l\t\tjail has /dev/log\n");
967 fprintf(stderr, " -u\t\tjail has a ubus socket\n");
968 fprintf(stderr, " -U <name>\tuser to run jailed process\n");
969 fprintf(stderr, " -G <name>\tgroup to run jailed process\n");
970 fprintf(stderr, " -o\t\tremont jail root (/) read only\n");
971 fprintf(stderr, " -R <dir>\texternal jail rootfs (system container)\n");
972 fprintf(stderr, " -O <dir>\tdirectory for r/w overlayfs\n");
973 fprintf(stderr, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
974 fprintf(stderr, " -E\t\tfail if jail cannot be setup\n");
975 fprintf(stderr, " -y\t\tprovide jail console\n");
976 fprintf(stderr, " -J <dir>\tcreate container from OCI bundle\n");
977 fprintf(stderr, " -i\t\tstart container immediately\n");
978 fprintf(stderr, " -P <pidfile>\tcreate <pidfile>\n");
979 fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
980 and he has the same powers as root outside the jail,\n\
981 thus he can escape the jail and/or break stuff.\n\
982 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
983 If you use none of the namespace jail options,\n\
984 ujail will not use namespace/build a jail,\n\
985 and will only drop capabilities/apply seccomp filter.\n\n");
986 }
987
988 static int* get_namespace_fd(const unsigned int nstype)
989 {
990 switch (nstype) {
991 case CLONE_NEWPID:
992 return &opts.setns.pid;
993 case CLONE_NEWNET:
994 return &opts.setns.net;
995 case CLONE_NEWNS:
996 return &opts.setns.ns;
997 case CLONE_NEWIPC:
998 return &opts.setns.ipc;
999 case CLONE_NEWUTS:
1000 return &opts.setns.uts;
1001 case CLONE_NEWUSER:
1002 return &opts.setns.user;
1003 case CLONE_NEWCGROUP:
1004 return &opts.setns.cgroup;
1005 #ifdef CLONE_NEWTIME
1006 case CLONE_NEWTIME:
1007 return &opts.setns.time;
1008 #endif
1009 default:
1010 return NULL;
1011 }
1012 }
1013
1014 static int setns_open(unsigned long nstype)
1015 {
1016 int *fd = get_namespace_fd(nstype);
1017
1018 assert(fd != NULL);
1019
1020 if (*fd < 0)
1021 return 0;
1022
1023 if (setns(*fd, nstype) == -1) {
1024 close(*fd);
1025 return errno;
1026 }
1027
1028 close(*fd);
1029 return 0;
1030 }
1031
1032 static int jail_running = 0;
1033 static int jail_return_code = 0;
1034
1035 static void jail_process_timeout_cb(struct uloop_timeout *t);
1036 static struct uloop_timeout jail_process_timeout = {
1037 .cb = jail_process_timeout_cb,
1038 };
1039 static void poststop(void);
1040 static void jail_process_handler(struct uloop_process *c, int ret)
1041 {
1042 uloop_timeout_cancel(&jail_process_timeout);
1043 if (WIFEXITED(ret)) {
1044 jail_return_code = WEXITSTATUS(ret);
1045 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
1046 } else {
1047 jail_return_code = WTERMSIG(ret);
1048 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
1049 }
1050 jail_running = 0;
1051 poststop();
1052 }
1053
1054 static struct uloop_process jail_process = {
1055 .cb = jail_process_handler,
1056 };
1057
1058 static void jail_process_timeout_cb(struct uloop_timeout *t)
1059 {
1060 DEBUG("jail process failed to stop, sending SIGKILL\n");
1061 kill(jail_process.pid, SIGKILL);
1062 }
1063
1064 static void jail_handle_signal(int signo)
1065 {
1066 if (hook_running) {
1067 DEBUG("forwarding signal %d to the hook process\n", signo);
1068 kill(hook_process.pid, signo);
1069 }
1070
1071 if (jail_running) {
1072 DEBUG("forwarding signal %d to the jailed process\n", signo);
1073 kill(jail_process.pid, signo);
1074 }
1075 }
1076
1077 static void signals_init(void)
1078 {
1079 int i;
1080 sigset_t sigmask;
1081
1082 sigfillset(&sigmask);
1083 for (i = 0; i < _NSIG; i++) {
1084 struct sigaction s = { 0 };
1085
1086 if (!sigismember(&sigmask, i))
1087 continue;
1088 if ((i == SIGCHLD) || (i == SIGPIPE) || (i == SIGSEGV))
1089 continue;
1090
1091 s.sa_handler = jail_handle_signal;
1092 sigaction(i, &s, NULL);
1093 }
1094 }
1095
1096 static void pre_exec_jail(struct uloop_timeout *t);
1097 static struct uloop_timeout pre_exec_timeout = {
1098 .cb = pre_exec_jail,
1099 };
1100
1101 int pipes[4];
1102 static int exec_jail(void *arg)
1103 {
1104 char buf[1];
1105
1106 exit_from_child = true;
1107 prctl(PR_SET_SECUREBITS, 0);
1108
1109 uloop_init();
1110 signals_init();
1111
1112 close(pipes[0]);
1113 close(pipes[3]);
1114
1115 setns_open(CLONE_NEWUSER);
1116 setns_open(CLONE_NEWNET);
1117 setns_open(CLONE_NEWNS);
1118 setns_open(CLONE_NEWIPC);
1119 setns_open(CLONE_NEWUTS);
1120
1121 buf[0] = 'i';
1122 if (write(pipes[1], buf, 1) < 1) {
1123 ERROR("can't write to parent\n");
1124 return EXIT_FAILURE;
1125 }
1126 close(pipes[1]);
1127 if (read(pipes[2], buf, 1) < 1) {
1128 ERROR("can't read from parent\n");
1129 return EXIT_FAILURE;
1130 }
1131 if (buf[0] != 'O') {
1132 ERROR("parent had an error, child exiting\n");
1133 return EXIT_FAILURE;
1134 }
1135
1136 if (opts.namespace & CLONE_NEWCGROUP)
1137 unshare(CLONE_NEWCGROUP);
1138
1139 setns_open(CLONE_NEWCGROUP);
1140
1141 if ((opts.namespace & CLONE_NEWUSER) || (opts.setns.user != -1)) {
1142 if (setregid(0, 0) < 0) {
1143 ERROR("setgid\n");
1144 free_and_exit(EXIT_FAILURE);
1145 }
1146 if (setreuid(0, 0) < 0) {
1147 ERROR("setuid\n");
1148 free_and_exit(EXIT_FAILURE);
1149 }
1150 if (setgroups(0, NULL) < 0) {
1151 ERROR("setgroups\n");
1152 free_and_exit(EXIT_FAILURE);
1153 }
1154 }
1155
1156 if (opts.namespace && opts.hostname && strlen(opts.hostname) > 0
1157 && sethostname(opts.hostname, strlen(opts.hostname))) {
1158 ERROR("sethostname(%s) failed: %m\n", opts.hostname);
1159 free_and_exit(EXIT_FAILURE);
1160 }
1161
1162 uloop_timeout_add(&pre_exec_timeout);
1163 uloop_run();
1164
1165 free_and_exit(-1);
1166 return -1;
1167 }
1168
1169 static void pre_exec_jail(struct uloop_timeout *t)
1170 {
1171 if ((opts.namespace & CLONE_NEWNS) && build_jail_fs()) {
1172 ERROR("failed to build jail fs\n");
1173 free_and_exit(EXIT_FAILURE);
1174 } else {
1175 run_hooks(opts.hooks.createContainer, post_jail_fs);
1176 }
1177 }
1178
1179 static void post_start_hook(void);
1180 static void post_jail_fs(void)
1181 {
1182 char buf[1];
1183
1184 if (read(pipes[2], buf, 1) < 1) {
1185 ERROR("can't read from parent\n");
1186 free_and_exit(EXIT_FAILURE);
1187 }
1188 if (buf[0] != '!') {
1189 ERROR("parent had an error, child exiting\n");
1190 free_and_exit(EXIT_FAILURE);
1191 }
1192 close(pipes[2]);
1193
1194 run_hooks(opts.hooks.startContainer, post_start_hook);
1195 }
1196
1197 static void post_start_hook(void)
1198 {
1199 int pw_uid, pw_gid, gr_gid;
1200
1201 /*
1202 * make sure setuid/setgid won't drop capabilities in case capabilities
1203 * have been specified explicitely.
1204 */
1205 if (opts.capset.apply) {
1206 if (prctl(PR_SET_SECUREBITS, SECBIT_NO_SETUID_FIXUP)) {
1207 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1208 free_and_exit(EXIT_FAILURE);
1209 }
1210 }
1211
1212 /* drop capabilities, retain those still needed to further setup jail */
1213 if (applyOCIcapabilities(opts.capset, (1LLU << CAP_SETGID) | (1LLU << CAP_SETUID) | (1LLU << CAP_SETPCAP)))
1214 free_and_exit(EXIT_FAILURE);
1215
1216 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1217 get_jail_user(&pw_uid, &pw_gid, &gr_gid);
1218 set_jail_user(opts.pw_uid?:pw_uid, opts.pw_gid?:pw_gid, opts.gr_gid?:gr_gid);
1219
1220 if (opts.additional_gids &&
1221 (setgroups(opts.num_additional_gids, opts.additional_gids) < 0)) {
1222 ERROR("setgroups failed: %m\n");
1223 free_and_exit(EXIT_FAILURE);
1224 }
1225
1226 if (opts.set_umask)
1227 umask(opts.umask);
1228
1229 /* restore securebits back to normal (and lock them if not in userns) */
1230 if (opts.capset.apply) {
1231 if (prctl(PR_SET_SECUREBITS, (opts.namespace & CLONE_NEWUSER)?0:
1232 SECBIT_KEEP_CAPS_LOCKED|SECBIT_NO_SETUID_FIXUP_LOCKED|SECBIT_NOROOT_LOCKED)) {
1233 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1234 free_and_exit(EXIT_FAILURE);
1235 }
1236 }
1237
1238 /* drop remaining capabilities to end up with specified sets */
1239 if (applyOCIcapabilities(opts.capset, 0))
1240 free_and_exit(EXIT_FAILURE);
1241
1242 if (opts.no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
1243 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1244 free_and_exit(EXIT_FAILURE);
1245 }
1246
1247 char **envp = build_envp(opts.seccomp, opts.envp);
1248 if (!envp)
1249 free_and_exit(EXIT_FAILURE);
1250
1251 if (opts.cwd && chdir(opts.cwd))
1252 free_and_exit(EXIT_FAILURE);
1253
1254 if (opts.ociseccomp && applyOCIlinuxseccomp(opts.ociseccomp))
1255 free_and_exit(EXIT_FAILURE);
1256
1257 uloop_end();
1258 free_opts(false);
1259 INFO("exec-ing %s\n", *opts.jail_argv);
1260 if (opts.envp) /* respect PATH if potentially set in ENV */
1261 execvpe(*opts.jail_argv, opts.jail_argv, envp);
1262 else
1263 execve(*opts.jail_argv, opts.jail_argv, envp);
1264
1265 /* we get there only if execve fails */
1266 ERROR("failed to execve %s: %m\n", *opts.jail_argv);
1267 exit(EXIT_FAILURE);
1268 }
1269
1270 static int ns_open_pid(const char *nstype, const pid_t target_ns)
1271 {
1272 char pid_pid_path[PATH_MAX];
1273
1274 snprintf(pid_pid_path, sizeof(pid_pid_path), "/proc/%u/ns/%s", target_ns, nstype);
1275
1276 return open(pid_pid_path, O_RDONLY);
1277 }
1278
1279 static void netns_updown(pid_t pid, bool start)
1280 {
1281 static struct blob_buf req;
1282 uint32_t id;
1283
1284 if (!parent_ctx)
1285 return;
1286
1287 blob_buf_init(&req, 0);
1288 blobmsg_add_string(&req, "jail", opts.name);
1289 blobmsg_add_u32(&req, "pid", pid);
1290 blobmsg_add_u8(&req, "start", start);
1291
1292 if (ubus_lookup_id(parent_ctx, "network", &id) ||
1293 ubus_invoke(parent_ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
1294 INFO("ubus request failed\n");
1295
1296 blob_buf_free(&req);
1297 }
1298
1299 static int parseOCIenvarray(struct blob_attr *msg, char ***envp)
1300 {
1301 struct blob_attr *cur;
1302 int sz = 0, rem;
1303
1304 blobmsg_for_each_attr(cur, msg, rem)
1305 ++sz;
1306
1307 if (sz > 0) {
1308 *envp = calloc(1 + sz, sizeof(char*));
1309 if (!(*envp))
1310 return ENOMEM;
1311 } else {
1312 *envp = NULL;
1313 return 0;
1314 }
1315
1316 sz = 0;
1317 blobmsg_for_each_attr(cur, msg, rem)
1318 (*envp)[sz++] = strdup(blobmsg_get_string(cur));
1319
1320 if (sz)
1321 (*envp)[sz] = NULL;
1322
1323 return 0;
1324 }
1325
1326 enum {
1327 OCI_ROOT_PATH,
1328 OCI_ROOT_READONLY,
1329 __OCI_ROOT_MAX,
1330 };
1331
1332 static const struct blobmsg_policy oci_root_policy[] = {
1333 [OCI_ROOT_PATH] = { "path", BLOBMSG_TYPE_STRING },
1334 [OCI_ROOT_READONLY] = { "readonly", BLOBMSG_TYPE_BOOL },
1335 };
1336
1337 static int parseOCIroot(const char *jsonfile, struct blob_attr *msg)
1338 {
1339 char extroot[PATH_MAX] = { 0 };
1340 struct blob_attr *tb[__OCI_ROOT_MAX];
1341 char *cur;
1342 char *root_path;
1343
1344 blobmsg_parse(oci_root_policy, __OCI_ROOT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1345
1346 if (!tb[OCI_ROOT_PATH])
1347 return ENODATA;
1348
1349 root_path = blobmsg_get_string(tb[OCI_ROOT_PATH]);
1350
1351 /* prepend bundle directory in case of relative paths */
1352 if (root_path[0] != '/') {
1353 strncpy(extroot, jsonfile, PATH_MAX - 1);
1354
1355 cur = strrchr(extroot, '/');
1356
1357 if (!cur)
1358 return ENOTDIR;
1359
1360 *(++cur) = '\0';
1361 }
1362
1363 strncat(extroot, root_path, PATH_MAX - (strlen(extroot) + 1));
1364
1365 /* follow symbolic link(s) */
1366 opts.extroot = realpath(extroot, NULL);
1367 if (!opts.extroot)
1368 return errno;
1369
1370 if (tb[OCI_ROOT_READONLY])
1371 opts.ronly = blobmsg_get_bool(tb[OCI_ROOT_READONLY]);
1372
1373 return 0;
1374 }
1375
1376
1377 enum {
1378 OCI_HOOK_PATH,
1379 OCI_HOOK_ARGS,
1380 OCI_HOOK_ENV,
1381 OCI_HOOK_TIMEOUT,
1382 __OCI_HOOK_MAX,
1383 };
1384
1385 static const struct blobmsg_policy oci_hook_policy[] = {
1386 [OCI_HOOK_PATH] = { "path", BLOBMSG_TYPE_STRING },
1387 [OCI_HOOK_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
1388 [OCI_HOOK_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
1389 [OCI_HOOK_TIMEOUT] = { "timeout", BLOBMSG_TYPE_INT32 },
1390 };
1391
1392
1393 static int parseOCIhook(struct hook_execvpe ***hooklist, struct blob_attr *msg)
1394 {
1395 struct blob_attr *tb[__OCI_HOOK_MAX];
1396 struct blob_attr *cur;
1397 int rem, ret = 0;
1398 int idx = 0;
1399
1400 blobmsg_for_each_attr(cur, msg, rem)
1401 ++idx;
1402
1403 if (!idx)
1404 return 0;
1405
1406 *hooklist = calloc(idx + 1, sizeof(struct hook_execvpe *));
1407 idx = 0;
1408
1409 if (!(*hooklist))
1410 return ENOMEM;
1411
1412 blobmsg_for_each_attr(cur, msg, rem) {
1413 blobmsg_parse(oci_hook_policy, __OCI_HOOK_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1414
1415 if (!tb[OCI_HOOK_PATH]) {
1416 ret = EINVAL;
1417 goto errout;
1418 }
1419
1420 (*hooklist)[idx] = calloc(1, sizeof(struct hook_execvpe));
1421 if (tb[OCI_HOOK_ARGS]) {
1422 ret = parseOCIenvarray(tb[OCI_HOOK_ARGS], &((*hooklist)[idx]->argv));
1423 if (ret)
1424 goto errout;
1425 } else {
1426 (*hooklist)[idx]->argv = calloc(2, sizeof(char *));
1427 ((*hooklist)[idx]->argv)[0] = strdup(blobmsg_get_string(tb[OCI_HOOK_PATH]));
1428 ((*hooklist)[idx]->argv)[1] = NULL;
1429 };
1430
1431
1432 if (tb[OCI_HOOK_ENV]) {
1433 ret = parseOCIenvarray(tb[OCI_HOOK_ENV], &((*hooklist)[idx]->envp));
1434 if (ret)
1435 goto errout;
1436 }
1437
1438 if (tb[OCI_HOOK_TIMEOUT])
1439 (*hooklist)[idx]->timeout = blobmsg_get_u32(tb[OCI_HOOK_TIMEOUT]);
1440
1441 (*hooklist)[idx]->file = strdup(blobmsg_get_string(tb[OCI_HOOK_PATH]));
1442
1443 ++idx;
1444 }
1445
1446 (*hooklist)[idx] = NULL;
1447
1448 DEBUG("added %d hooks\n", idx);
1449
1450 return 0;
1451
1452 errout:
1453 free_hooklist(*hooklist);
1454 *hooklist = NULL;
1455
1456 return ret;
1457 };
1458
1459
1460 enum {
1461 OCI_HOOKS_PRESTART,
1462 OCI_HOOKS_CREATERUNTIME,
1463 OCI_HOOKS_CREATECONTAINER,
1464 OCI_HOOKS_STARTCONTAINER,
1465 OCI_HOOKS_POSTSTART,
1466 OCI_HOOKS_POSTSTOP,
1467 __OCI_HOOKS_MAX,
1468 };
1469
1470 static const struct blobmsg_policy oci_hooks_policy[] = {
1471 [OCI_HOOKS_PRESTART] = { "prestart", BLOBMSG_TYPE_ARRAY },
1472 [OCI_HOOKS_CREATERUNTIME] = { "createRuntime", BLOBMSG_TYPE_ARRAY },
1473 [OCI_HOOKS_CREATECONTAINER] = { "createContainer", BLOBMSG_TYPE_ARRAY },
1474 [OCI_HOOKS_STARTCONTAINER] = { "startContainer", BLOBMSG_TYPE_ARRAY },
1475 [OCI_HOOKS_POSTSTART] = { "poststart", BLOBMSG_TYPE_ARRAY },
1476 [OCI_HOOKS_POSTSTOP] = { "poststop", BLOBMSG_TYPE_ARRAY },
1477 };
1478
1479 static int parseOCIhooks(struct blob_attr *msg)
1480 {
1481 struct blob_attr *tb[__OCI_HOOKS_MAX];
1482 int ret;
1483
1484 blobmsg_parse(oci_hooks_policy, __OCI_HOOKS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1485
1486 if (tb[OCI_HOOKS_PRESTART])
1487 INFO("warning: ignoring deprecated prestart hook\n");
1488
1489 if (tb[OCI_HOOKS_CREATERUNTIME]) {
1490 ret = parseOCIhook(&opts.hooks.createRuntime, tb[OCI_HOOKS_CREATERUNTIME]);
1491 if (ret)
1492 return ret;
1493 }
1494
1495 if (tb[OCI_HOOKS_CREATECONTAINER]) {
1496 ret = parseOCIhook(&opts.hooks.createContainer, tb[OCI_HOOKS_CREATECONTAINER]);
1497 if (ret)
1498 goto out_createruntime;
1499 }
1500
1501 if (tb[OCI_HOOKS_STARTCONTAINER]) {
1502 ret = parseOCIhook(&opts.hooks.startContainer, tb[OCI_HOOKS_STARTCONTAINER]);
1503 if (ret)
1504 goto out_createcontainer;
1505 }
1506
1507 if (tb[OCI_HOOKS_POSTSTART]) {
1508 ret = parseOCIhook(&opts.hooks.poststart, tb[OCI_HOOKS_POSTSTART]);
1509 if (ret)
1510 goto out_startcontainer;
1511 }
1512
1513 if (tb[OCI_HOOKS_POSTSTOP]) {
1514 ret = parseOCIhook(&opts.hooks.poststop, tb[OCI_HOOKS_POSTSTOP]);
1515 if (ret)
1516 goto out_poststart;
1517 }
1518
1519 return 0;
1520
1521 out_poststart:
1522 free_hooklist(opts.hooks.poststart);
1523 out_startcontainer:
1524 free_hooklist(opts.hooks.startContainer);
1525 out_createcontainer:
1526 free_hooklist(opts.hooks.createContainer);
1527 out_createruntime:
1528 free_hooklist(opts.hooks.createRuntime);
1529
1530 return ret;
1531 };
1532
1533
1534 enum {
1535 OCI_PROCESS_USER_UID,
1536 OCI_PROCESS_USER_GID,
1537 OCI_PROCESS_USER_UMASK,
1538 OCI_PROCESS_USER_ADDITIONALGIDS,
1539 __OCI_PROCESS_USER_MAX,
1540 };
1541
1542 static const struct blobmsg_policy oci_process_user_policy[] = {
1543 [OCI_PROCESS_USER_UID] = { "uid", BLOBMSG_TYPE_INT32 },
1544 [OCI_PROCESS_USER_GID] = { "gid", BLOBMSG_TYPE_INT32 },
1545 [OCI_PROCESS_USER_UMASK] = { "umask", BLOBMSG_TYPE_INT32 },
1546 [OCI_PROCESS_USER_ADDITIONALGIDS] = { "additionalGids", BLOBMSG_TYPE_ARRAY },
1547 };
1548
1549 static int parseOCIprocessuser(struct blob_attr *msg) {
1550 struct blob_attr *tb[__OCI_PROCESS_USER_MAX];
1551 struct blob_attr *cur;
1552 int rem;
1553 int has_gid = 0;
1554
1555 blobmsg_parse(oci_process_user_policy, __OCI_PROCESS_USER_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1556
1557 if (tb[OCI_PROCESS_USER_UID])
1558 opts.pw_uid = blobmsg_get_u32(tb[OCI_PROCESS_USER_UID]);
1559
1560 if (tb[OCI_PROCESS_USER_GID]) {
1561 opts.pw_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
1562 opts.gr_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
1563 has_gid = 1;
1564 }
1565
1566 if (tb[OCI_PROCESS_USER_ADDITIONALGIDS]) {
1567 size_t gidcnt = 0;
1568
1569 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_USER_ADDITIONALGIDS], rem) {
1570 ++gidcnt;
1571 if (has_gid && (blobmsg_get_u32(cur) == opts.gr_gid))
1572 continue;
1573 }
1574
1575 if (gidcnt) {
1576 opts.additional_gids = calloc(gidcnt + has_gid, sizeof(gid_t));
1577 gidcnt = 0;
1578
1579 /* always add primary GID to set of GIDs if set */
1580 if (has_gid)
1581 opts.additional_gids[gidcnt++] = opts.gr_gid;
1582
1583 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_USER_ADDITIONALGIDS], rem) {
1584 if (has_gid && (blobmsg_get_u32(cur) == opts.gr_gid))
1585 continue;
1586 opts.additional_gids[gidcnt++] = blobmsg_get_u32(cur);
1587 }
1588 opts.num_additional_gids = gidcnt;
1589 }
1590 DEBUG("read %zu additional groups\n", gidcnt);
1591 }
1592
1593 if (tb[OCI_PROCESS_USER_UMASK]) {
1594 opts.umask = blobmsg_get_u32(tb[OCI_PROCESS_USER_UMASK]);
1595 opts.set_umask = true;
1596 }
1597
1598 return 0;
1599 }
1600
1601 enum {
1602 OCI_PROCESS_RLIMIT_TYPE,
1603 OCI_PROCESS_RLIMIT_SOFT,
1604 OCI_PROCESS_RLIMIT_HARD,
1605 __OCI_PROCESS_RLIMIT_MAX,
1606 };
1607
1608 static const struct blobmsg_policy oci_process_rlimit_policy[] = {
1609 [OCI_PROCESS_RLIMIT_TYPE] = { "type", BLOBMSG_TYPE_STRING },
1610 [OCI_PROCESS_RLIMIT_SOFT] = { "soft", BLOBMSG_CAST_INT64 },
1611 [OCI_PROCESS_RLIMIT_HARD] = { "hard", BLOBMSG_CAST_INT64 },
1612 };
1613
1614 /* from manpage GETRLIMIT(2) */
1615 static const char* const rlimit_names[RLIM_NLIMITS] = {
1616 [RLIMIT_AS] = "AS",
1617 [RLIMIT_CORE] = "CORE",
1618 [RLIMIT_CPU] = "CPU",
1619 [RLIMIT_DATA] = "DATA",
1620 [RLIMIT_FSIZE] = "FSIZE",
1621 [RLIMIT_LOCKS] = "LOCKS",
1622 [RLIMIT_MEMLOCK] = "MEMLOCK",
1623 [RLIMIT_MSGQUEUE] = "MSGQUEUE",
1624 [RLIMIT_NICE] = "NICE",
1625 [RLIMIT_NOFILE] = "NOFILE",
1626 [RLIMIT_NPROC] = "NPROC",
1627 [RLIMIT_RSS] = "RSS",
1628 [RLIMIT_RTPRIO] = "RTPRIO",
1629 [RLIMIT_RTTIME] = "RTTIME",
1630 [RLIMIT_SIGPENDING] = "SIGPENDING",
1631 [RLIMIT_STACK] = "STACK",
1632 };
1633
1634 static int resolve_rlimit(char *type) {
1635 unsigned int rltype;
1636
1637 for (rltype = 0; rltype < RLIM_NLIMITS; ++rltype)
1638 if (rlimit_names[rltype] &&
1639 !strncmp("RLIMIT_", type, 7) &&
1640 !strcmp(rlimit_names[rltype], type + 7))
1641 return rltype;
1642
1643 return -1;
1644 }
1645
1646
1647 static int parseOCIrlimit(struct blob_attr *msg)
1648 {
1649 struct blob_attr *tb[__OCI_PROCESS_RLIMIT_MAX];
1650 int limtype = -1;
1651 struct rlimit *curlim;
1652
1653 blobmsg_parse(oci_process_rlimit_policy, __OCI_PROCESS_RLIMIT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1654
1655 if (!tb[OCI_PROCESS_RLIMIT_TYPE] ||
1656 !tb[OCI_PROCESS_RLIMIT_SOFT] ||
1657 !tb[OCI_PROCESS_RLIMIT_HARD])
1658 return ENODATA;
1659
1660 limtype = resolve_rlimit(blobmsg_get_string(tb[OCI_PROCESS_RLIMIT_TYPE]));
1661
1662 if (limtype < 0)
1663 return EINVAL;
1664
1665 if (opts.rlimits[limtype])
1666 return ENOTUNIQ;
1667
1668 curlim = malloc(sizeof(struct rlimit));
1669 curlim->rlim_cur = blobmsg_cast_u64(tb[OCI_PROCESS_RLIMIT_SOFT]);
1670 curlim->rlim_max = blobmsg_cast_u64(tb[OCI_PROCESS_RLIMIT_HARD]);
1671
1672 opts.rlimits[limtype] = curlim;
1673
1674 return 0;
1675 };
1676
1677 enum {
1678 OCI_PROCESS_ARGS,
1679 OCI_PROCESS_CAPABILITIES,
1680 OCI_PROCESS_CWD,
1681 OCI_PROCESS_ENV,
1682 OCI_PROCESS_OOMSCOREADJ,
1683 OCI_PROCESS_NONEWPRIVILEGES,
1684 OCI_PROCESS_RLIMITS,
1685 OCI_PROCESS_TERMINAL,
1686 OCI_PROCESS_USER,
1687 __OCI_PROCESS_MAX,
1688 };
1689
1690 static const struct blobmsg_policy oci_process_policy[] = {
1691 [OCI_PROCESS_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
1692 [OCI_PROCESS_CAPABILITIES] = { "capabilities", BLOBMSG_TYPE_TABLE },
1693 [OCI_PROCESS_CWD] = { "cwd", BLOBMSG_TYPE_STRING },
1694 [OCI_PROCESS_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
1695 [OCI_PROCESS_OOMSCOREADJ] = { "oomScoreAdj", BLOBMSG_TYPE_INT32 },
1696 [OCI_PROCESS_NONEWPRIVILEGES] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL },
1697 [OCI_PROCESS_RLIMITS] = { "rlimits", BLOBMSG_TYPE_ARRAY },
1698 [OCI_PROCESS_TERMINAL] = { "terminal", BLOBMSG_TYPE_BOOL },
1699 [OCI_PROCESS_USER] = { "user", BLOBMSG_TYPE_TABLE },
1700 };
1701
1702
1703 static int parseOCIprocess(struct blob_attr *msg)
1704 {
1705 struct blob_attr *tb[__OCI_PROCESS_MAX], *cur;
1706 int rem, res;
1707
1708 blobmsg_parse(oci_process_policy, __OCI_PROCESS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1709
1710 if (!tb[OCI_PROCESS_ARGS])
1711 return ENOENT;
1712
1713 res = parseOCIenvarray(tb[OCI_PROCESS_ARGS], &opts.jail_argv);
1714 if (res)
1715 return res;
1716
1717 if (tb[OCI_PROCESS_TERMINAL])
1718 opts.console = blobmsg_get_bool(tb[OCI_PROCESS_TERMINAL]);
1719
1720 if (tb[OCI_PROCESS_NONEWPRIVILEGES])
1721 opts.no_new_privs = blobmsg_get_bool(tb[OCI_PROCESS_NONEWPRIVILEGES]);
1722
1723 if (tb[OCI_PROCESS_CWD])
1724 opts.cwd = strdup(blobmsg_get_string(tb[OCI_PROCESS_CWD]));
1725
1726 if (tb[OCI_PROCESS_ENV]) {
1727 res = parseOCIenvarray(tb[OCI_PROCESS_ENV], &opts.envp);
1728 if (res)
1729 return res;
1730 }
1731
1732 if (tb[OCI_PROCESS_USER] && (res = parseOCIprocessuser(tb[OCI_PROCESS_USER])))
1733 return res;
1734
1735 if (tb[OCI_PROCESS_CAPABILITIES] &&
1736 (res = parseOCIcapabilities(&opts.capset, tb[OCI_PROCESS_CAPABILITIES])))
1737 return res;
1738
1739 if (tb[OCI_PROCESS_RLIMITS]) {
1740 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_RLIMITS], rem) {
1741 res = parseOCIrlimit(cur);
1742 if (res)
1743 return res;
1744 }
1745 }
1746
1747 if (tb[OCI_PROCESS_OOMSCOREADJ]) {
1748 opts.oom_score_adj = blobmsg_get_u32(tb[OCI_PROCESS_OOMSCOREADJ]);
1749 opts.set_oom_score_adj = true;
1750 }
1751
1752 return 0;
1753 }
1754
1755 enum {
1756 OCI_LINUX_NAMESPACE_TYPE,
1757 OCI_LINUX_NAMESPACE_PATH,
1758 __OCI_LINUX_NAMESPACE_MAX,
1759 };
1760
1761 static const struct blobmsg_policy oci_linux_namespace_policy[] = {
1762 [OCI_LINUX_NAMESPACE_TYPE] = { "type", BLOBMSG_TYPE_STRING },
1763 [OCI_LINUX_NAMESPACE_PATH] = { "path", BLOBMSG_TYPE_STRING },
1764 };
1765
1766 static int resolve_nstype(char *type) {
1767 if (!strcmp("pid", type))
1768 return CLONE_NEWPID;
1769 else if (!strcmp("network", type))
1770 return CLONE_NEWNET;
1771 else if (!strcmp("mount", type))
1772 return CLONE_NEWNS;
1773 else if (!strcmp("ipc", type))
1774 return CLONE_NEWIPC;
1775 else if (!strcmp("uts", type))
1776 return CLONE_NEWUTS;
1777 else if (!strcmp("user", type))
1778 return CLONE_NEWUSER;
1779 else if (!strcmp("cgroup", type))
1780 return CLONE_NEWCGROUP;
1781 #ifdef CLONE_NEWTIME
1782 else if (!strcmp("time", type))
1783 return CLONE_NEWTIME;
1784 #endif
1785 else
1786 return 0;
1787 }
1788
1789 static int parseOCIlinuxns(struct blob_attr *msg)
1790 {
1791 struct blob_attr *tb[__OCI_LINUX_NAMESPACE_MAX];
1792 int nstype;
1793 int *setns;
1794 int fd;
1795
1796 blobmsg_parse(oci_linux_namespace_policy, __OCI_LINUX_NAMESPACE_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1797
1798 if (!tb[OCI_LINUX_NAMESPACE_TYPE])
1799 return EINVAL;
1800
1801 nstype = resolve_nstype(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]));
1802 if (!nstype)
1803 return EINVAL;
1804
1805 if (opts.namespace & nstype)
1806 return ENOTUNIQ;
1807
1808 setns = get_namespace_fd(nstype);
1809
1810 if (!setns)
1811 return EFAULT;
1812
1813 if (*setns != -1)
1814 return ENOTUNIQ;
1815
1816 if (tb[OCI_LINUX_NAMESPACE_PATH]) {
1817 DEBUG("opening existing %s namespace from path %s\n",
1818 blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]),
1819 blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_PATH]));
1820
1821 fd = open(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_PATH]), O_RDONLY);
1822 if (fd < 0)
1823 return errno?:ESTALE;
1824
1825 if (ioctl(fd, NS_GET_NSTYPE) != nstype) {
1826 close(fd);
1827 return EINVAL;
1828 }
1829
1830 DEBUG("opened existing %s namespace got filehandler %u\n",
1831 blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]),
1832 fd);
1833
1834 *setns = fd;
1835 } else {
1836 opts.namespace |= nstype;
1837 }
1838
1839 return 0;
1840 }
1841
1842 static void get_jail_root_user(bool is_gidmap, uint32_t container_id, uint32_t host_id, uint32_t size)
1843 {
1844 if (container_id == 0 && size >= 1)
1845 if (!is_gidmap)
1846 opts.root_map_uid = host_id;
1847 }
1848
1849 enum {
1850 OCI_LINUX_UIDGIDMAP_CONTAINERID,
1851 OCI_LINUX_UIDGIDMAP_HOSTID,
1852 OCI_LINUX_UIDGIDMAP_SIZE,
1853 __OCI_LINUX_UIDGIDMAP_MAX,
1854 };
1855
1856 static const struct blobmsg_policy oci_linux_uidgidmap_policy[] = {
1857 [OCI_LINUX_UIDGIDMAP_CONTAINERID] = { "containerID", BLOBMSG_TYPE_INT32 },
1858 [OCI_LINUX_UIDGIDMAP_HOSTID] = { "hostID", BLOBMSG_TYPE_INT32 },
1859 [OCI_LINUX_UIDGIDMAP_SIZE] = { "size", BLOBMSG_TYPE_INT32 },
1860 };
1861
1862 static int parseOCIuidgidmappings(struct blob_attr *msg, bool is_gidmap)
1863 {
1864 struct blob_attr *tb[__OCI_LINUX_UIDGIDMAP_MAX];
1865 struct blob_attr *cur;
1866 int rem;
1867 char *map;
1868 size_t len, pos, totallen = 0;
1869
1870 blobmsg_for_each_attr(cur, msg, rem) {
1871 blobmsg_parse(oci_linux_uidgidmap_policy, __OCI_LINUX_UIDGIDMAP_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1872
1873 if (!tb[OCI_LINUX_UIDGIDMAP_CONTAINERID] ||
1874 !tb[OCI_LINUX_UIDGIDMAP_HOSTID] ||
1875 !tb[OCI_LINUX_UIDGIDMAP_SIZE])
1876 return EINVAL;
1877
1878 /* count length */
1879 totallen += snprintf(NULL, 0, "%d %d %d\n",
1880 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
1881 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
1882 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
1883 }
1884
1885 /* allocate combined mapping string */
1886 map = malloc(totallen + 1);
1887 if (!map)
1888 return ENOMEM;
1889
1890 pos = 0;
1891 blobmsg_for_each_attr(cur, msg, rem) {
1892 blobmsg_parse(oci_linux_uidgidmap_policy, __OCI_LINUX_UIDGIDMAP_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1893
1894 get_jail_root_user(is_gidmap, blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
1895 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
1896 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
1897
1898 /* write mapping line into pre-allocated string */
1899 len = snprintf(&map[pos], totallen + 1, "%d %d %d\n",
1900 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
1901 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
1902 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
1903 pos += len;
1904 totallen -= len;
1905 }
1906
1907 assert(totallen == 0);
1908
1909 if (is_gidmap)
1910 opts.gidmap = map;
1911 else
1912 opts.uidmap = map;
1913
1914 return 0;
1915 }
1916
1917 enum {
1918 OCI_DEVICES_TYPE,
1919 OCI_DEVICES_PATH,
1920 OCI_DEVICES_MAJOR,
1921 OCI_DEVICES_MINOR,
1922 OCI_DEVICES_FILEMODE,
1923 OCI_DEVICES_UID,
1924 OCI_DEVICES_GID,
1925 __OCI_DEVICES_MAX,
1926 };
1927
1928 static const struct blobmsg_policy oci_devices_policy[] = {
1929 [OCI_DEVICES_TYPE] = { "type", BLOBMSG_TYPE_STRING },
1930 [OCI_DEVICES_PATH] = { "path", BLOBMSG_TYPE_STRING },
1931 [OCI_DEVICES_MAJOR] = { "major", BLOBMSG_TYPE_INT32 },
1932 [OCI_DEVICES_MINOR] = { "minor", BLOBMSG_TYPE_INT32 },
1933 [OCI_DEVICES_FILEMODE] = { "fileMode", BLOBMSG_TYPE_INT32 },
1934 [OCI_DEVICES_UID] = { "uid", BLOBMSG_TYPE_INT32 },
1935 [OCI_DEVICES_GID] = { "uid", BLOBMSG_TYPE_INT32 },
1936 };
1937
1938 static mode_t resolve_devtype(char *tstr)
1939 {
1940 if (!strcmp("c", tstr) ||
1941 !strcmp("u", tstr))
1942 return S_IFCHR;
1943 else if (!strcmp("b", tstr))
1944 return S_IFBLK;
1945 else if (!strcmp("p", tstr))
1946 return S_IFIFO;
1947 else
1948 return 0;
1949 }
1950
1951 static int parseOCIdevices(struct blob_attr *msg)
1952 {
1953 struct blob_attr *tb[__OCI_DEVICES_MAX];
1954 struct blob_attr *cur;
1955 int rem;
1956 size_t cnt = 0;
1957 struct mknod_args *tmp;
1958
1959 blobmsg_for_each_attr(cur, msg, rem)
1960 ++cnt;
1961
1962 opts.devices = calloc(cnt + 1, sizeof(struct mknod_args *));
1963
1964 cnt = 0;
1965 blobmsg_for_each_attr(cur, msg, rem) {
1966 blobmsg_parse(oci_devices_policy, __OCI_DEVICES_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1967 if (!tb[OCI_DEVICES_TYPE] ||
1968 !tb[OCI_DEVICES_PATH])
1969 return ENODATA;
1970
1971 tmp = calloc(1, sizeof(struct mknod_args));
1972 if (!tmp)
1973 return ENOMEM;
1974
1975 tmp->mode = resolve_devtype(blobmsg_get_string(tb[OCI_DEVICES_TYPE]));
1976 if (!tmp->mode) {
1977 free(tmp);
1978 return EINVAL;
1979 }
1980
1981 if (tmp->mode != S_IFIFO) {
1982 if (!tb[OCI_DEVICES_MAJOR] || !tb[OCI_DEVICES_MINOR]) {
1983 free(tmp);
1984 return ENODATA;
1985 }
1986
1987 tmp->dev = makedev(blobmsg_get_u32(tb[OCI_DEVICES_MAJOR]),
1988 blobmsg_get_u32(tb[OCI_DEVICES_MINOR]));
1989 }
1990
1991 if (tb[OCI_DEVICES_FILEMODE]) {
1992 if (~(S_IRWXU|S_IRWXG|S_IRWXO) & blobmsg_get_u32(tb[OCI_DEVICES_FILEMODE])) {
1993 free(tmp);
1994 return EINVAL;
1995 }
1996
1997 tmp->mode |= blobmsg_get_u32(tb[OCI_DEVICES_FILEMODE]);
1998 } else {
1999 tmp->mode |= (S_IRUSR|S_IWUSR); /* 0600 */
2000 }
2001
2002 tmp->path = strdup(blobmsg_get_string(tb[OCI_DEVICES_PATH]));
2003
2004 if (tb[OCI_DEVICES_UID])
2005 tmp->uid = blobmsg_get_u32(tb[OCI_DEVICES_UID]);
2006 else
2007 tmp->uid = -1;
2008
2009 if (tb[OCI_DEVICES_GID])
2010 tmp->gid = blobmsg_get_u32(tb[OCI_DEVICES_GID]);
2011 else
2012 tmp->gid = -1;
2013
2014 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb[OCI_DEVICES_PATH]), blobmsg_get_string(tb[OCI_DEVICES_TYPE]));
2015 opts.devices[cnt++] = tmp;
2016 }
2017
2018 opts.devices[cnt] = NULL;
2019
2020 return 0;
2021 }
2022
2023 static int parseOCIsysctl(struct blob_attr *msg)
2024 {
2025 struct blob_attr *cur;
2026 int rem;
2027 char *tmp, *tc;
2028 size_t cnt = 0;
2029
2030 blobmsg_for_each_attr(cur, msg, rem) {
2031 if (!blobmsg_name(cur) || !blobmsg_get_string(cur))
2032 return EINVAL;
2033
2034 ++cnt;
2035 }
2036
2037 if (!cnt)
2038 return 0;
2039
2040 opts.sysctl = calloc(cnt + 1, sizeof(struct sysctl_val *));
2041 if (!opts.sysctl)
2042 return ENOMEM;
2043
2044 cnt = 0;
2045 blobmsg_for_each_attr(cur, msg, rem) {
2046 opts.sysctl[cnt] = malloc(sizeof(struct sysctl_val));
2047 if (!opts.sysctl[cnt])
2048 return ENOMEM;
2049
2050 /* replace '.' with '/' in entry name */
2051 tc = tmp = strdup(blobmsg_name(cur));
2052 while ((tc = strchr(tc, '.')))
2053 *tc = '/';
2054
2055 opts.sysctl[cnt]->value = strdup(blobmsg_get_string(cur));
2056 opts.sysctl[cnt]->entry = tmp;
2057
2058 ++cnt;
2059 }
2060
2061 opts.sysctl[cnt] = NULL;
2062
2063 return 0;
2064 }
2065
2066
2067 enum {
2068 OCI_LINUX_CGROUPSPATH,
2069 OCI_LINUX_RESOURCES,
2070 OCI_LINUX_SECCOMP,
2071 OCI_LINUX_SYSCTL,
2072 OCI_LINUX_NAMESPACES,
2073 OCI_LINUX_DEVICES,
2074 OCI_LINUX_UIDMAPPINGS,
2075 OCI_LINUX_GIDMAPPINGS,
2076 OCI_LINUX_MASKEDPATHS,
2077 OCI_LINUX_READONLYPATHS,
2078 OCI_LINUX_ROOTFSPROPAGATION,
2079 __OCI_LINUX_MAX,
2080 };
2081
2082 static const struct blobmsg_policy oci_linux_policy[] = {
2083 [OCI_LINUX_CGROUPSPATH] = { "cgroupsPath", BLOBMSG_TYPE_STRING },
2084 [OCI_LINUX_RESOURCES] = { "resources", BLOBMSG_TYPE_TABLE },
2085 [OCI_LINUX_SECCOMP] = { "seccomp", BLOBMSG_TYPE_TABLE },
2086 [OCI_LINUX_SYSCTL] = { "sysctl", BLOBMSG_TYPE_TABLE },
2087 [OCI_LINUX_NAMESPACES] = { "namespaces", BLOBMSG_TYPE_ARRAY },
2088 [OCI_LINUX_DEVICES] = { "devices", BLOBMSG_TYPE_ARRAY },
2089 [OCI_LINUX_UIDMAPPINGS] = { "uidMappings", BLOBMSG_TYPE_ARRAY },
2090 [OCI_LINUX_GIDMAPPINGS] = { "gidMappings", BLOBMSG_TYPE_ARRAY },
2091 [OCI_LINUX_MASKEDPATHS] = { "maskedPaths", BLOBMSG_TYPE_ARRAY },
2092 [OCI_LINUX_READONLYPATHS] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY },
2093 [OCI_LINUX_ROOTFSPROPAGATION] = { "rootfsPropagation", BLOBMSG_TYPE_STRING },
2094 };
2095
2096 static int parseOCIlinux(struct blob_attr *msg)
2097 {
2098 struct blob_attr *tb[__OCI_LINUX_MAX];
2099 struct blob_attr *cur;
2100 int rem;
2101 int res = 0;
2102 char *cgpath;
2103 char cgfullpath[256] = "/sys/fs/cgroup";
2104
2105 blobmsg_parse(oci_linux_policy, __OCI_LINUX_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
2106
2107 if (tb[OCI_LINUX_NAMESPACES]) {
2108 blobmsg_for_each_attr(cur, tb[OCI_LINUX_NAMESPACES], rem) {
2109 res = parseOCIlinuxns(cur);
2110 if (res)
2111 return res;
2112 }
2113 }
2114
2115 if (tb[OCI_LINUX_UIDMAPPINGS]) {
2116 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 0);
2117 if (res)
2118 return res;
2119 }
2120
2121 if (tb[OCI_LINUX_GIDMAPPINGS]) {
2122 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 1);
2123 if (res)
2124 return res;
2125 }
2126
2127 if (tb[OCI_LINUX_READONLYPATHS]) {
2128 blobmsg_for_each_attr(cur, tb[OCI_LINUX_READONLYPATHS], rem) {
2129 res = add_mount(NULL, blobmsg_get_string(cur), NULL, MS_BIND | MS_REC | MS_RDONLY, 0, NULL, 0);
2130 if (res)
2131 return res;
2132 }
2133 }
2134
2135 if (tb[OCI_LINUX_MASKEDPATHS]) {
2136 blobmsg_for_each_attr(cur, tb[OCI_LINUX_MASKEDPATHS], rem) {
2137 res = add_mount((void *)(-1), blobmsg_get_string(cur), NULL, 0, 0, NULL, 0);
2138 if (res)
2139 return res;
2140 }
2141 }
2142
2143 if (tb[OCI_LINUX_SYSCTL]) {
2144 res = parseOCIsysctl(tb[OCI_LINUX_SYSCTL]);
2145 if (res)
2146 return res;
2147 }
2148
2149 if (tb[OCI_LINUX_SECCOMP]) {
2150 opts.ociseccomp = parseOCIlinuxseccomp(tb[OCI_LINUX_SECCOMP]);
2151 if (!opts.ociseccomp)
2152 return EINVAL;
2153 }
2154
2155 if (tb[OCI_LINUX_DEVICES]) {
2156 res = parseOCIdevices(tb[OCI_LINUX_DEVICES]);
2157 if (res)
2158 return res;
2159 }
2160
2161 if (tb[OCI_LINUX_CGROUPSPATH]) {
2162 cgpath = blobmsg_get_string(tb[OCI_LINUX_CGROUPSPATH]);
2163 if (cgpath[0] == '/') {
2164 if (strlen(cgpath) >= (sizeof(cgfullpath) - strlen(cgfullpath)))
2165 return E2BIG;
2166
2167 strcat(cgfullpath, cgpath);
2168 } else {
2169 strcat(cgfullpath, "/containers/");
2170 strcat(cgfullpath, opts.name); /* should be container name rather than jail name */
2171 strcat(cgfullpath, "/");
2172 if (strlen(cgpath) >= (sizeof(cgfullpath) - strlen(cgfullpath)))
2173 return E2BIG;
2174
2175 strcat(cgfullpath, cgpath);
2176 }
2177 } else {
2178 strcat(cgfullpath, "/containers/");
2179 strcat(cgfullpath, opts.name); /* should be container name rather than jail name */
2180 strcat(cgfullpath, "/");
2181 strcat(cgfullpath, opts.name); /* should be container instance name rather than jail name */
2182 }
2183
2184 cgroups_init(cgfullpath);
2185
2186 if (tb[OCI_LINUX_RESOURCES]) {
2187 res = parseOCIlinuxcgroups(tb[OCI_LINUX_RESOURCES]);
2188 if (res)
2189 return res;
2190 }
2191
2192 return 0;
2193 }
2194
2195 enum {
2196 OCI_VERSION,
2197 OCI_HOSTNAME,
2198 OCI_PROCESS,
2199 OCI_ROOT,
2200 OCI_MOUNTS,
2201 OCI_HOOKS,
2202 OCI_LINUX,
2203 OCI_ANNOTATIONS,
2204 __OCI_MAX,
2205 };
2206
2207 static const struct blobmsg_policy oci_policy[] = {
2208 [OCI_VERSION] = { "ociVersion", BLOBMSG_TYPE_STRING },
2209 [OCI_HOSTNAME] = { "hostname", BLOBMSG_TYPE_STRING },
2210 [OCI_PROCESS] = { "process", BLOBMSG_TYPE_TABLE },
2211 [OCI_ROOT] = { "root", BLOBMSG_TYPE_TABLE },
2212 [OCI_MOUNTS] = { "mounts", BLOBMSG_TYPE_ARRAY },
2213 [OCI_HOOKS] = { "hooks", BLOBMSG_TYPE_TABLE },
2214 [OCI_LINUX] = { "linux", BLOBMSG_TYPE_TABLE },
2215 [OCI_ANNOTATIONS] = { "annotations", BLOBMSG_TYPE_TABLE },
2216 };
2217
2218 static int parseOCI(const char *jsonfile)
2219 {
2220 struct blob_attr *tb[__OCI_MAX];
2221 struct blob_attr *cur;
2222 int rem;
2223 int res;
2224
2225 blob_buf_init(&ocibuf, 0);
2226
2227 if (!blobmsg_add_json_from_file(&ocibuf, jsonfile)) {
2228 res=ENOENT;
2229 goto errout;
2230 }
2231
2232 blobmsg_parse(oci_policy, __OCI_MAX, tb, blob_data(ocibuf.head), blob_len(ocibuf.head));
2233
2234 if (!tb[OCI_VERSION]) {
2235 res=ENOMSG;
2236 goto errout;
2237 }
2238
2239 if (strncmp("1.0", blobmsg_get_string(tb[OCI_VERSION]), 3)) {
2240 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb[OCI_VERSION]));
2241 res=ENOTSUP;
2242 goto errout;
2243 }
2244
2245 if (tb[OCI_HOSTNAME])
2246 opts.hostname = strdup(blobmsg_get_string(tb[OCI_HOSTNAME]));
2247
2248 if (!tb[OCI_PROCESS]) {
2249 res=ENODATA;
2250 goto errout;
2251 }
2252
2253 if ((res = parseOCIprocess(tb[OCI_PROCESS])))
2254 goto errout;
2255
2256 if (!tb[OCI_ROOT]) {
2257 res=ENODATA;
2258 goto errout;
2259 }
2260 if ((res = parseOCIroot(jsonfile, tb[OCI_ROOT])))
2261 goto errout;
2262
2263 if (!tb[OCI_MOUNTS]) {
2264 res=ENODATA;
2265 goto errout;
2266 }
2267
2268 blobmsg_for_each_attr(cur, tb[OCI_MOUNTS], rem)
2269 if ((res = parseOCImount(cur)))
2270 goto errout;
2271
2272 if (tb[OCI_LINUX] && (res = parseOCIlinux(tb[OCI_LINUX])))
2273 goto errout;
2274
2275 if (tb[OCI_HOOKS] && (res = parseOCIhooks(tb[OCI_HOOKS])))
2276 goto errout;
2277
2278 if (tb[OCI_ANNOTATIONS])
2279 opts.annotations = blob_memdup(tb[OCI_ANNOTATIONS]);
2280
2281 errout:
2282 blob_buf_free(&ocibuf);
2283
2284 return res;
2285 }
2286
2287 static int set_oom_score_adj(void)
2288 {
2289 int f;
2290 char fname[32];
2291
2292 if (!opts.set_oom_score_adj)
2293 return 0;
2294
2295 snprintf(fname, sizeof(fname), "/proc/%u/oom_score_adj", jail_process.pid);
2296 f = open(fname, O_WRONLY | O_TRUNC);
2297 if (f < 0)
2298 return errno;
2299
2300 dprintf(f, "%d", opts.oom_score_adj);
2301 close(f);
2302
2303 return 0;
2304 }
2305
2306
2307 enum {
2308 OCI_STATE_CREATING,
2309 OCI_STATE_CREATED,
2310 OCI_STATE_RUNNING,
2311 OCI_STATE_STOPPED,
2312 };
2313
2314 static int jail_oci_state = OCI_STATE_CREATED;
2315 static void pipe_send_start_container(struct uloop_timeout *t);
2316 static struct uloop_timeout start_container_timeout = {
2317 .cb = pipe_send_start_container,
2318 };
2319
2320 static int handle_start(struct ubus_context *ctx, struct ubus_object *obj,
2321 struct ubus_request_data *req, const char *method,
2322 struct blob_attr *msg)
2323 {
2324 if (jail_oci_state != OCI_STATE_CREATED)
2325 return UBUS_STATUS_INVALID_ARGUMENT;
2326
2327 uloop_timeout_add(&start_container_timeout);
2328
2329 return UBUS_STATUS_OK;
2330 }
2331
2332 static struct blob_buf bb;
2333 static int handle_state(struct ubus_context *ctx, struct ubus_object *obj,
2334 struct ubus_request_data *req, const char *method,
2335 struct blob_attr *msg)
2336 {
2337 char *statusstr;
2338
2339 switch (jail_oci_state) {
2340 case OCI_STATE_CREATING:
2341 statusstr = "creating";
2342 break;
2343 case OCI_STATE_CREATED:
2344 statusstr = "created";
2345 break;
2346 case OCI_STATE_RUNNING:
2347 statusstr = "running";
2348 break;
2349 case OCI_STATE_STOPPED:
2350 statusstr = "stopped";
2351 break;
2352 default:
2353 statusstr = "unknown";
2354 }
2355
2356 blob_buf_init(&bb, 0);
2357 blobmsg_add_string(&bb, "ociVersion", OCI_VERSION_STRING);
2358 blobmsg_add_string(&bb, "id", opts.name);
2359 blobmsg_add_string(&bb, "status", statusstr);
2360 if (jail_oci_state == OCI_STATE_CREATED ||
2361 jail_oci_state == OCI_STATE_RUNNING)
2362 blobmsg_add_u32(&bb, "pid", jail_process.pid);
2363
2364 blobmsg_add_string(&bb, "bundle", opts.ocibundle);
2365
2366 if (opts.annotations)
2367 blobmsg_add_blob(&bb, opts.annotations);
2368
2369 ubus_send_reply(ctx, req, bb.head);
2370
2371 return UBUS_STATUS_OK;
2372 }
2373
2374 enum {
2375 CONTAINER_KILL_ATTR_SIGNAL,
2376 __CONTAINER_KILL_ATTR_MAX,
2377 };
2378
2379 static const struct blobmsg_policy container_kill_attrs[__CONTAINER_KILL_ATTR_MAX] = {
2380 [CONTAINER_KILL_ATTR_SIGNAL] = { "signal", BLOBMSG_TYPE_INT32 },
2381 };
2382
2383 static int
2384 container_handle_kill(struct ubus_context *ctx, struct ubus_object *obj,
2385 struct ubus_request_data *req, const char *method,
2386 struct blob_attr *msg)
2387 {
2388 struct blob_attr *tb[__CONTAINER_KILL_ATTR_MAX], *cur;
2389 int sig = SIGTERM;
2390
2391 blobmsg_parse(container_kill_attrs, __CONTAINER_KILL_ATTR_MAX, tb, blobmsg_data(msg), blobmsg_data_len(msg));
2392
2393 cur = tb[CONTAINER_KILL_ATTR_SIGNAL];
2394 if (cur)
2395 sig = blobmsg_get_u32(cur);
2396
2397 if (jail_oci_state == OCI_STATE_CREATING)
2398 return UBUS_STATUS_NOT_FOUND;
2399
2400 if (kill(jail_process.pid, sig) == 0)
2401 return 0;
2402
2403 switch (errno) {
2404 case EINVAL: return UBUS_STATUS_INVALID_ARGUMENT;
2405 case EPERM: return UBUS_STATUS_PERMISSION_DENIED;
2406 case ESRCH: return UBUS_STATUS_NOT_FOUND;
2407 }
2408
2409 return UBUS_STATUS_UNKNOWN_ERROR;
2410 }
2411
2412 static int
2413 jail_writepid(pid_t pid)
2414 {
2415 FILE *_pidfile;
2416
2417 if (!opts.pidfile)
2418 return 0;
2419
2420 _pidfile = fopen(opts.pidfile, "w");
2421 if (_pidfile == NULL)
2422 return errno;
2423
2424 if (fprintf(_pidfile, "%d\n", pid) < 0) {
2425 fclose(_pidfile);
2426 return errno;
2427 }
2428
2429 if (fclose(_pidfile))
2430 return errno;
2431
2432 return 0;
2433 }
2434
2435 static int checkpath(const char *path)
2436 {
2437 int dirfd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
2438 if (dirfd < 0) {
2439 ERROR("path %s open failed %m\n", path);
2440 return -1;
2441 }
2442 close(dirfd);
2443
2444 return 0;
2445 }
2446
2447 static struct ubus_method container_methods[] = {
2448 UBUS_METHOD_NOARG("start", handle_start),
2449 UBUS_METHOD_NOARG("state", handle_state),
2450 UBUS_METHOD("kill", container_handle_kill, container_kill_attrs),
2451 };
2452
2453 static struct ubus_object_type container_object_type =
2454 UBUS_OBJECT_TYPE("container", container_methods);
2455
2456 static struct ubus_object container_object = {
2457 .type = &container_object_type,
2458 .methods = container_methods,
2459 .n_methods = ARRAY_SIZE(container_methods),
2460 };
2461
2462 static void post_main(struct uloop_timeout *t);
2463 static struct uloop_timeout post_main_timeout = {
2464 .cb = post_main,
2465 };
2466 static int netns_fd;
2467 static int pidns_fd;
2468 #ifdef CLONE_NEWTIME
2469 static int timens_fd;
2470 #endif
2471 static void post_create_runtime(void);
2472 int main(int argc, char **argv)
2473 {
2474 uid_t uid = getuid();
2475 const char log[] = "/dev/log";
2476 const char ubus[] = "/var/run/ubus/ubus.sock";
2477 int ret = EXIT_FAILURE;
2478 int ch;
2479
2480 if (uid) {
2481 ERROR("not root, aborting: %m\n");
2482 return EXIT_FAILURE;
2483 }
2484
2485 umask(022);
2486 mount_list_init();
2487 init_library_search();
2488 cgroups_prepare();
2489 exit_from_child = false;
2490
2491 while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
2492 switch (ch) {
2493 case 'd':
2494 debug = atoi(optarg);
2495 break;
2496 case 'p':
2497 opts.namespace |= CLONE_NEWNS;
2498 opts.procfs = 1;
2499 break;
2500 case 'o':
2501 opts.namespace |= CLONE_NEWNS;
2502 opts.ronly = 1;
2503 break;
2504 case 'f':
2505 opts.namespace |= CLONE_NEWUSER;
2506 break;
2507 case 'F':
2508 opts.namespace |= CLONE_NEWCGROUP;
2509 break;
2510 case 'R':
2511 opts.extroot = realpath(optarg, NULL);
2512 break;
2513 case 's':
2514 opts.namespace |= CLONE_NEWNS;
2515 opts.sysfs = 1;
2516 break;
2517 case 'S':
2518 opts.seccomp = optarg;
2519 add_mount_bind(optarg, 1, -1);
2520 break;
2521 case 'C':
2522 opts.capabilities = optarg;
2523 break;
2524 case 'c':
2525 opts.no_new_privs = 1;
2526 break;
2527 case 'n':
2528 opts.name = optarg;
2529 break;
2530 case 'N':
2531 opts.namespace |= CLONE_NEWNET;
2532 break;
2533 case 'h':
2534 opts.namespace |= CLONE_NEWUTS;
2535 opts.hostname = strdup(optarg);
2536 break;
2537 case 'r':
2538 opts.namespace |= CLONE_NEWNS;
2539 add_path_and_deps(optarg, 1, 0, 0);
2540 break;
2541 case 'w':
2542 opts.namespace |= CLONE_NEWNS;
2543 add_path_and_deps(optarg, 0, 0, 0);
2544 break;
2545 case 'u':
2546 opts.namespace |= CLONE_NEWNS;
2547 add_mount_bind(ubus, 0, -1);
2548 break;
2549 case 'l':
2550 opts.namespace |= CLONE_NEWNS;
2551 add_mount_bind(log, 0, -1);
2552 break;
2553 case 'U':
2554 opts.user = optarg;
2555 break;
2556 case 'G':
2557 opts.group = optarg;
2558 break;
2559 case 'O':
2560 opts.overlaydir = realpath(optarg, NULL);
2561 break;
2562 case 'T':
2563 opts.tmpoverlaysize = optarg;
2564 break;
2565 case 'E':
2566 opts.require_jail = 1;
2567 break;
2568 case 'y':
2569 opts.console = 1;
2570 break;
2571 case 'J':
2572 opts.ocibundle = optarg;
2573 break;
2574 case 'i':
2575 opts.immediately = true;
2576 break;
2577 case 'P':
2578 opts.pidfile = optarg;
2579 break;
2580 }
2581 }
2582
2583 if (opts.namespace && !opts.ocibundle)
2584 opts.namespace |= CLONE_NEWIPC | CLONE_NEWPID;
2585
2586 /* those are filehandlers, so -1 indicates unused */
2587 opts.setns.pid = -1;
2588 opts.setns.net = -1;
2589 opts.setns.ns = -1;
2590 opts.setns.ipc = -1;
2591 opts.setns.uts = -1;
2592 opts.setns.user = -1;
2593 opts.setns.cgroup = -1;
2594 #ifdef CLONE_NEWTIME
2595 opts.setns.time = -1;
2596 #endif
2597
2598 /*
2599 * uid in parent user namespace representing root user in new
2600 * user namespace, defaults to nobody unless specified in uidMappings
2601 */
2602 opts.root_map_uid = 65534;
2603
2604 if (opts.capabilities && parseOCIcapabilities_from_file(&opts.capset, opts.capabilities)) {
2605 ERROR("failed to read capabilities from file %s\n", opts.capabilities);
2606 ret=-1;
2607 goto errout;
2608 }
2609
2610 if (opts.ocibundle) {
2611 char *jsonfile;
2612 int ocires;
2613
2614 if (!opts.name) {
2615 ERROR("OCI bundle needs a named jail\n");
2616 ret=-1;
2617 goto errout;
2618 }
2619 if (asprintf(&jsonfile, "%s/config.json", opts.ocibundle) < 0) {
2620 ret=-ENOMEM;
2621 goto errout;
2622 }
2623 ocires = parseOCI(jsonfile);
2624 free(jsonfile);
2625 if (ocires) {
2626 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires), ocires);
2627 ret=ocires;
2628 goto errout;
2629 }
2630 }
2631
2632 if (opts.namespace & CLONE_NEWNET) {
2633 if (!opts.name) {
2634 ERROR("netns needs a named jail\n");
2635 ret=-1;
2636 goto errout;
2637 }
2638 }
2639
2640
2641 if (opts.tmpoverlaysize && strlen(opts.tmpoverlaysize) > 8) {
2642 ERROR("size parameter too long: \"%s\"\n", opts.tmpoverlaysize);
2643 ret=-1;
2644 goto errout;
2645 }
2646
2647 if (opts.extroot && checkpath(opts.extroot)) {
2648 ERROR("invalid rootfs path '%s'", opts.extroot);
2649 ret=-1;
2650 goto errout;
2651 }
2652
2653 if (opts.overlaydir && checkpath(opts.overlaydir)) {
2654 ERROR("invalid rootfs overlay path '%s'", opts.overlaydir);
2655 ret=-1;
2656 goto errout;
2657 }
2658
2659 /* no <binary> param found */
2660 if (!opts.ocibundle && (argc - optind < 1)) {
2661 usage();
2662 ret=EXIT_FAILURE;
2663 goto errout;
2664 }
2665 if (!(opts.ocibundle||opts.namespace||opts.capabilities||opts.seccomp)) {
2666 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2667 usage();
2668 ret=EXIT_FAILURE;
2669 goto errout;
2670 }
2671 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2672 opts.namespace,
2673 opts.capset.apply,
2674 opts.seccomp != 0 || opts.ociseccomp != 0);
2675
2676 uloop_init();
2677 signals_init();
2678
2679 parent_ctx = ubus_connect(NULL);
2680 ubus_add_uloop(parent_ctx);
2681
2682 if (opts.ocibundle) {
2683 char *objname;
2684 if (asprintf(&objname, "container.%s", opts.name) < 0) {
2685 ret=-ENOMEM;
2686 goto errout;
2687 }
2688
2689 container_object.name = objname;
2690 ret = ubus_add_object(parent_ctx, &container_object);
2691 if (ret) {
2692 ERROR("Failed to add object: %s\n", ubus_strerror(ret));
2693 ret=-1;
2694 goto errout;
2695 }
2696 }
2697
2698 /* deliberately not using 'else' on unrelated conditional branches */
2699 if (!opts.ocibundle) {
2700 /* allocate NULL-terminated array for argv */
2701 opts.jail_argv = calloc(1 + argc - optind, sizeof(char**));
2702 if (!opts.jail_argv) {
2703 ret=EXIT_FAILURE;
2704 goto errout;
2705 }
2706 for (size_t s = optind; s < argc; s++)
2707 opts.jail_argv[s - optind] = strdup(argv[s]);
2708
2709 if (opts.namespace & CLONE_NEWUSER)
2710 get_jail_user(&opts.pw_uid, &opts.pw_gid, &opts.gr_gid);
2711 }
2712
2713 if (!opts.extroot) {
2714 if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
2715 ERROR("failed to load dependencies\n");
2716 ret=-1;
2717 goto errout;
2718 }
2719 }
2720
2721 if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2722 ERROR("failed to load libpreload-seccomp.so\n");
2723 opts.seccomp = 0;
2724 if (opts.require_jail) {
2725 ret=-1;
2726 goto errout;
2727 }
2728 }
2729
2730 uloop_timeout_add(&post_main_timeout);
2731 uloop_run();
2732
2733 errout:
2734 if (opts.ocibundle)
2735 cgroups_free();
2736
2737 free_opts(true);
2738
2739 return ret;
2740 }
2741
2742 static void post_main(struct uloop_timeout *t)
2743 {
2744 if (apply_rlimits()) {
2745 ERROR("error applying resource limits\n");
2746 free_and_exit(EXIT_FAILURE);
2747 }
2748
2749 if (opts.name)
2750 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
2751
2752 if (pipe(&pipes[0]) < 0 || pipe(&pipes[2]) < 0)
2753 free_and_exit(-1);
2754
2755 if (has_namespaces()) {
2756 if (opts.namespace & CLONE_NEWNS) {
2757 if (!opts.extroot && (opts.user || opts.group)) {
2758 add_mount_bind("/etc/passwd", 1, -1);
2759 add_mount_bind("/etc/group", 1, -1);
2760 }
2761
2762 #if defined(__GLIBC__)
2763 if (!opts.extroot)
2764 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2765 #endif
2766
2767 if (!(opts.namespace & CLONE_NEWNET)) {
2768 add_mount_bind("/etc/resolv.conf", 1, 0);
2769 } else if (opts.setns.ns == -1) {
2770 /* new mount namespace to provide /dev/resolv.conf.d */
2771 char hostdir[PATH_MAX];
2772
2773 snprintf(hostdir, PATH_MAX, "/tmp/resolv.conf-%s.d", opts.name);
2774 mkdir_p(hostdir, 0755);
2775 add_mount(hostdir, "/dev/resolv.conf.d", NULL, MS_BIND | MS_NOEXEC | MS_NOATIME | MS_NOSUID | MS_NODEV | MS_RDONLY, 0, NULL, 0);
2776 }
2777
2778 /* default mounts */
2779 add_mount(NULL, "/dev", "tmpfs", MS_NOATIME | MS_NOEXEC | MS_NOSUID, 0, "size=1M", -1);
2780 add_mount(NULL, "/dev/pts", "devpts", MS_NOATIME | MS_NOEXEC | MS_NOSUID, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2781
2782 if (opts.procfs || opts.ocibundle) {
2783 add_mount("proc", "/proc", "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0, NULL, -1);
2784
2785 /*
2786 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2787 * which cannot be expressed with OCI spec, but happends to be very useful.
2788 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2789 * readonlyPath.
2790 * If not running in a new network namespace, only make /proc/sys read-only.
2791 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2792 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2793 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2794 * /proc/sys/net.
2795 * This works because mounts are executed in incrementing strcmp() order and
2796 * /proc/self/net appears there before /proc/sys/net and hence the operation
2797 * succeeds as the bind-mount of /proc/self/net is performed first and then
2798 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2799 * table (and in the alphabet).
2800 */
2801 if (!add_mount(NULL, "/proc/sys", NULL, MS_BIND | MS_RDONLY, 0, NULL, -1))
2802 if (opts.namespace & CLONE_NEWNET)
2803 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL, MS_MOVE, 0, NULL, -1))
2804 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL, MS_BIND, 0, NULL, -1);
2805
2806 }
2807 if (opts.sysfs || opts.ocibundle)
2808 add_mount("sysfs", "/sys", "sysfs", MS_RELATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RDONLY, 0, NULL, -1);
2809
2810 if (opts.ocibundle)
2811 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID | MS_NOEXEC | MS_NODEV, 0, "mode=1777", -1);
2812
2813 }
2814
2815 if (opts.setns.pid != -1) {
2816 pidns_fd = ns_open_pid("pid", getpid());
2817 setns_open(CLONE_NEWPID);
2818 } else {
2819 pidns_fd = -1;
2820 }
2821
2822 #ifdef CLONE_NEWTIME
2823 if (opts.setns.time != -1) {
2824 timens_fd = ns_open_pid("time", getpid());
2825 setns_open(CLONE_NEWTIME);
2826 } else {
2827 timens_fd = -1;
2828 }
2829 #endif
2830
2831 if (opts.namespace & CLONE_NEWUSER) {
2832 if (prctl(PR_SET_SECUREBITS, SECBIT_NO_SETUID_FIXUP)) {
2833 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
2834 free_and_exit(EXIT_FAILURE);
2835 }
2836 if (seteuid(opts.root_map_uid)) {
2837 ERROR("seteuid(%d) failed: %m\n", opts.root_map_uid);
2838 free_and_exit(EXIT_FAILURE);
2839 }
2840 }
2841
2842 jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, SIGCHLD | (opts.namespace & (~CLONE_NEWCGROUP)), NULL);
2843 } else {
2844 jail_process.pid = fork();
2845 }
2846
2847 if (jail_process.pid > 0) {
2848 /* parent process */
2849 char sig_buf[1];
2850
2851 uloop_process_add(&jail_process);
2852 jail_running = 1;
2853 if (seteuid(0)) {
2854 ERROR("seteuid(%d) failed: %m\n", opts.root_map_uid);
2855 free_and_exit(EXIT_FAILURE);
2856 }
2857
2858 prctl(PR_SET_SECUREBITS, 0);
2859
2860 if (pidns_fd != -1) {
2861 setns(pidns_fd, CLONE_NEWPID);
2862 close(pidns_fd);
2863 }
2864 #ifdef CLONE_NEWTIME
2865 if (timens_fd != -1) {
2866 setns(timens_fd, CLONE_NEWTIME);
2867 close(timens_fd);
2868 }
2869 #endif
2870 if (opts.setns.net != -1)
2871 close(opts.setns.net);
2872 if (opts.setns.ns != -1)
2873 close(opts.setns.ns);
2874 if (opts.setns.ipc != -1)
2875 close(opts.setns.ipc);
2876 if (opts.setns.uts != -1)
2877 close(opts.setns.uts);
2878 if (opts.setns.user != -1)
2879 close(opts.setns.user);
2880 if (opts.setns.cgroup != -1)
2881 close(opts.setns.cgroup);
2882 close(pipes[1]);
2883 close(pipes[2]);
2884 if (read(pipes[0], sig_buf, 1) < 1) {
2885 ERROR("can't read from child\n");
2886 free_and_exit(-1);
2887 }
2888 close(pipes[0]);
2889 set_oom_score_adj();
2890
2891 if (opts.ocibundle)
2892 cgroups_apply(jail_process.pid);
2893
2894 if (opts.namespace & CLONE_NEWUSER) {
2895 if (write_setgroups(jail_process.pid, true)) {
2896 ERROR("can't write setgroups\n");
2897 free_and_exit(-1);
2898 }
2899 if (!opts.uidmap) {
2900 bool has_gr = (opts.gr_gid != -1);
2901 if (opts.pw_uid != -1) {
2902 write_single_uid_gid_map(jail_process.pid, 0, opts.pw_uid);
2903 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:opts.pw_gid);
2904 } else {
2905 write_single_uid_gid_map(jail_process.pid, 0, 65534);
2906 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:65534);
2907 }
2908 } else {
2909 write_uid_gid_map(jail_process.pid, 0, opts.uidmap);
2910 if (opts.gidmap)
2911 write_uid_gid_map(jail_process.pid, 1, opts.gidmap);
2912 }
2913 }
2914
2915 if (opts.namespace & CLONE_NEWNET) {
2916 netns_fd = ns_open_pid("net", jail_process.pid);
2917 netns_updown(jail_process.pid, true);
2918 }
2919
2920 if (jail_writepid(jail_process.pid)) {
2921 ERROR("failed to write pidfile: %m\n");
2922 free_and_exit(-1);
2923 }
2924 } else if (jail_process.pid == 0) {
2925 /* fork child process */
2926 free_and_exit(exec_jail(NULL));
2927 } else {
2928 ERROR("failed to clone/fork: %m\n");
2929 free_and_exit(EXIT_FAILURE);
2930 }
2931 run_hooks(opts.hooks.createRuntime, post_create_runtime);
2932 }
2933
2934 static void post_poststart(void);
2935 static void post_create_runtime(void)
2936 {
2937 char sig_buf[1];
2938
2939 sig_buf[0] = 'O';
2940 if (write(pipes[3], sig_buf, 1) < 0) {
2941 ERROR("can't write to child\n");
2942 free_and_exit(-1);
2943 }
2944
2945 jail_oci_state = OCI_STATE_CREATED;
2946 if (opts.ocibundle && !opts.immediately)
2947 uloop_run(); /* wait for 'start' command via ubus */
2948 else
2949 pipe_send_start_container(NULL);
2950 }
2951
2952 static void pipe_send_start_container(struct uloop_timeout *t)
2953 {
2954 char sig_buf[1];
2955
2956 jail_oci_state = OCI_STATE_RUNNING;
2957 sig_buf[0] = '!';
2958 if (write(pipes[3], sig_buf, 1) < 0) {
2959 ERROR("can't write to child\n");
2960 free_and_exit(-1);
2961 }
2962 close(pipes[3]);
2963
2964 run_hooks(opts.hooks.poststart, post_poststart);
2965 }
2966
2967 static void post_poststart(void)
2968 {
2969 uloop_run(); /* idle here while jail is running */
2970 if (jail_running) {
2971 DEBUG("uloop interrupted, killing jail process\n");
2972 kill(jail_process.pid, SIGTERM);
2973 uloop_timeout_set(&jail_process_timeout, 1000);
2974 uloop_run();
2975 }
2976 uloop_done();
2977 poststop();
2978 }
2979
2980 static void post_poststop(void);
2981 static void poststop(void) {
2982 if (opts.namespace & CLONE_NEWNET) {
2983 setns(netns_fd, CLONE_NEWNET);
2984 netns_updown(getpid(), false);
2985 close(netns_fd);
2986 }
2987 run_hooks(opts.hooks.poststop, post_poststop);
2988 }
2989
2990 static void post_poststop(void)
2991 {
2992 free_opts(true);
2993 if (parent_ctx)
2994 ubus_free(parent_ctx);
2995
2996 exit(jail_return_code);
2997 }