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