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