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