2 * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
3 * Copyright (C) 2020 Daniel Golle <daniel@makrotopia.org>
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
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.
16 #include <sys/mount.h>
17 #include <sys/prctl.h>
19 #include <sys/types.h>
21 #include <sys/resource.h>
23 #include <sys/sysmacros.h>
25 /* musl only defined 15 limit types, make sure all 16 are supported */
27 #define RLIMIT_RTTIME 15
29 #define RLIMIT_NLIMITS 16
31 #define RLIM_NLIMITS 16
42 #include <linux/filter.h>
43 #include <linux/limits.h>
44 #include <linux/nsfs.h>
45 #include <linux/securebits.h>
49 #include "capabilities.h"
54 #include "seccomp-oci.h"
57 #include <libubox/utils.h>
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>
65 #ifndef CLONE_NEWCGROUP
66 #define CLONE_NEWCGROUP 0x02000000
69 #define STACK_SIZE (1024 * 1024)
70 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:i"
72 #define OCI_VERSION_STRING "1.0.2"
100 struct sock_fprog
*ociseccomp
;
102 struct jail_capset capset
;
107 char *tmpoverlaysize
;
111 struct sysctl_val
**sysctl
;
133 gid_t
*additional_gids
;
134 size_t num_additional_gids
;
139 struct hook_execvpe
**createRuntime
;
140 struct hook_execvpe
**createContainer
;
141 struct hook_execvpe
**startContainer
;
142 struct hook_execvpe
**poststart
;
143 struct hook_execvpe
**poststop
;
145 struct rlimit
*rlimits
[RLIM_NLIMITS
];
147 bool set_oom_score_adj
;
148 struct mknod_args
**devices
;
151 struct blob_attr
*annotations
;
154 static struct blob_buf ocibuf
;
156 extern int pivot_root(const char *new_root
, const char *put_old
);
160 static char child_stack
[STACK_SIZE
];
162 static struct ubus_context
*parent_ctx
;
167 static inline bool has_namespaces(void)
169 return ((opts
.setns
.pid
!= -1) ||
170 (opts
.setns
.net
!= -1) ||
171 (opts
.setns
.ns
!= -1) ||
172 (opts
.setns
.ipc
!= -1) ||
173 (opts
.setns
.uts
!= -1) ||
174 (opts
.setns
.user
!= -1) ||
175 (opts
.setns
.cgroup
!= -1) ||
177 (opts
.setns
.time
!= -1) ||
182 static void free_hooklist(struct hook_execvpe
**hooklist
)
184 struct hook_execvpe
*cur
;
209 static void free_sysctl(void) {
210 struct sysctl_val
*cur
;
221 static void free_devices(void) {
222 struct mknod_args
**cur
;
236 static void free_rlimits(void) {
239 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
240 free(opts
.rlimits
[type
]);
243 static void free_opts(bool parent
) {
246 /* we need to keep argv, envp and seccomp filter in child */
247 if (parent
) { /* parent-only */
248 if (opts
.ociseccomp
) {
249 free(opts
.ociseccomp
->filter
);
250 free(opts
.ociseccomp
);
253 tmp
= opts
.jail_argv
;
257 free(opts
.jail_argv
);
264 } else { /* child-only */
277 free(opts
.annotations
);
278 free(opts
.ocibundle
);
279 free_hooklist(opts
.hooks
.createRuntime
);
280 free_hooklist(opts
.hooks
.createContainer
);
281 free_hooklist(opts
.hooks
.startContainer
);
282 free_hooklist(opts
.hooks
.poststart
);
283 free_hooklist(opts
.hooks
.poststop
);
286 static int mount_overlay(char *jail_root
, char *overlaydir
) {
287 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
288 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
291 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
294 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
297 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
300 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
304 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
305 * this is to work-around a bug in overlayfs described in the overlayfs-userns
307 * 3. modification of a file 'hithere' which is in l but not yet
308 * in u, and which is not owned by T, is not allowed, even if
309 * writes to u are allowed. This may be a bug in overlayfs,
310 * but it is safe behavior.
312 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
315 if (mkdir_p(upperetc
, 0755))
316 goto upper_etc_printf
;
318 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
319 goto upper_etc_printf
;
321 fd
= creat(upperresolvconf
, 0644);
323 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
324 goto upper_resolvconf_printf
;
328 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
330 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
335 upper_resolvconf_printf
:
336 free(upperresolvconf
);
349 static void pass_console(int console_fd
)
351 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
352 static struct blob_buf req
;
358 blob_buf_init(&req
, 0);
359 blobmsg_add_string(&req
, "name", opts
.name
);
361 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
362 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
363 INFO("ubus request failed\n");
368 ubus_free(child_ctx
);
371 static int create_dev_console(const char *jail_root
)
374 char dev_console_path
[PATH_MAX
];
375 int slave_console_fd
;
377 /* Open UNIX/98 virtual console */
378 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
379 if (console_fd
== -1)
382 console_fname
= ptsname(console_fd
);
383 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
388 unlockpt(console_fd
);
390 /* pass PTY master to procd */
391 pass_console(console_fd
);
393 /* mount-bind PTY slave to /dev/console in jail */
394 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
395 close(creat(dev_console_path
, 0620));
397 if (mount(console_fname
, dev_console_path
, NULL
, MS_BIND
, NULL
))
400 /* use PTY slave for stdio */
401 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
402 dup2(slave_console_fd
, 0);
403 dup2(slave_console_fd
, 1);
404 dup2(slave_console_fd
, 2);
405 close(slave_console_fd
);
407 INFO("using guest console %s\n", console_fname
);
416 static int hook_running
= 0;
417 static int hook_return_code
= 0;
418 static struct hook_execvpe
**current_hook
= NULL
;
419 typedef void (*hook_return_handler
)(void);
420 static hook_return_handler hook_return_cb
= NULL
;
422 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
423 static struct uloop_timeout hook_process_timeout
= {
424 .cb
= hook_process_timeout_cb
,
427 static void run_hooklist(void);
428 static void hook_process_handler(struct uloop_process
*c
, int ret
)
430 uloop_timeout_cancel(&hook_process_timeout
);
432 if (WIFEXITED(ret
)) {
433 hook_return_code
= WEXITSTATUS(ret
);
434 if (hook_return_code
)
435 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
437 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
440 hook_return_code
= WTERMSIG(ret
);
441 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
448 static struct uloop_process hook_process
= {
449 .cb
= hook_process_handler
,
452 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
454 DEBUG("hook process failed to stop, sending SIGKILL\n");
455 kill(hook_process
.pid
, SIGKILL
);
458 static void run_hooklist(void)
460 struct hook_execvpe
*hook
= *current_hook
;
466 DEBUG("executing hook %s\n", hook
->file
);
468 if (stat(hook
->file
, &s
))
469 hook_process_handler(&hook_process
, ENOENT
);
471 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
472 hook_process_handler(&hook_process
, EPERM
);
474 if (!((unsigned long)s
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
)))
475 hook_process_handler(&hook_process
, EPERM
);
478 hook_process
.pid
= fork();
479 if (hook_process
.pid
== 0) {
481 execve(hook
->file
, hook
->argv
, hook
->envp
);
482 ERROR("execve error %m\n");
484 } else if (hook_process
.pid
< 0) {
486 ERROR("hook fork error\n");
488 hook_process_handler(&hook_process
, errno
);
492 uloop_process_add(&hook_process
);
494 if (hook
->timeout
> 0)
495 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
499 DEBUG("uloop interrupted, killing jail process\n");
500 kill(hook_process
.pid
, SIGTERM
);
501 uloop_timeout_set(&hook_process_timeout
, 1000);
506 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
511 current_hook
= hooklist
;
512 hook_return_cb
= return_cb
;
517 static int apply_sysctl(const char *jail_root
)
519 struct sysctl_val
**cur
;
520 char *procdir
, *fname
;
526 asprintf(&procdir
, "%s/proc", jail_root
);
530 mkdir(procdir
, 0700);
531 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
537 asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
);
541 DEBUG("sysctl: writing '%s' to %s\n", (*cur
)->value
, fname
);
543 f
= open(fname
, O_WRONLY
);
545 ERROR("sysctl: can't open %s\n", fname
);
548 write(f
, (*cur
)->value
, strlen((*cur
)->value
));
561 /* glibc defines makedev calling a function. make sure it's a pure macro */
562 #if defined(__GLIBC__)
564 /* from musl's sys/sysmacros.h */
565 #define makedev(x,y) ( \
566 (((x)&0xfffff000ULL) << 32) | \
567 (((x)&0x00000fffULL) << 8) | \
568 (((y)&0xffffff00ULL) << 12) | \
569 (((y)&0x000000ffULL)) )
572 static struct mknod_args default_devices
[] = {
573 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
574 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
575 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
576 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
577 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
578 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
582 static int create_devices(void)
584 struct mknod_args
**cur
, *curdef
;
587 goto only_default_devices
;
592 DEBUG("creating %s (mode=%08o)\n", (*cur
)->path
, (*cur
)->mode
);
593 if (mknod((*cur
)->path
, (*cur
)->mode
, (*cur
)->dev
))
596 if (((*cur
)->uid
|| (*cur
)->gid
) &&
597 chown((*cur
)->path
, (*cur
)->uid
, (*cur
)->gid
))
603 only_default_devices
:
604 curdef
= default_devices
;
605 while(curdef
->path
) {
606 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
607 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
609 continue; /* may already exist, eg. due to a bind-mount */
611 if ((curdef
->uid
|| curdef
->gid
) &&
612 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
618 /* Dev symbolic links as defined in OCI spec */
619 symlink("/dev/pts/ptmx", "/dev/ptmx");
620 symlink("/proc/self/fd", "/dev/fd");
621 symlink("/proc/self/fd/0", "/dev/stdin");
622 symlink("/proc/self/fd/1", "/dev/stdout");
623 symlink("/proc/self/fd/2", "/dev/stderr");
628 static char jail_root
[] = "/tmp/ujail-XXXXXX";
629 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
630 static mode_t old_umask
;
631 static void enter_jail_fs(void);
632 static int build_jail_fs(void)
634 char *overlaydir
= NULL
;
636 old_umask
= umask(0);
638 if (mkdtemp(jail_root
) == NULL
) {
639 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
643 if (apply_sysctl(jail_root
)) {
644 ERROR("failed to apply sysctl values\n");
648 /* oldroot can't be MS_SHARED else pivot_root() fails */
649 if (mount("none", "/", NULL
, MS_REC
|MS_PRIVATE
, NULL
)) {
650 ERROR("private mount failed %m\n");
655 if (mount(opts
.extroot
, jail_root
, NULL
, MS_BIND
, NULL
)) {
656 ERROR("extroot mount failed %m\n");
660 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
661 ERROR("tmpfs mount failed %m\n");
666 if (opts
.tmpoverlaysize
) {
667 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
669 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
670 "mode=0755,size=%s", opts
.tmpoverlaysize
);
671 if (mkdtemp(tmpovdir
) == NULL
) {
672 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
675 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
677 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
680 overlaydir
= tmpovdir
;
684 overlaydir
= opts
.overlaydir
;
687 mount_overlay(jail_root
, overlaydir
);
689 if (chdir(jail_root
)) {
690 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
694 if (mount_all(jail_root
)) {
695 ERROR("mount_all() failed\n");
700 create_dev_console(jail_root
);
702 /* make sure /etc/resolv.conf exists if in new network namespace */
703 if (opts
.namespace & CLONE_NEWNET
) {
704 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
706 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
707 mkdir_p(jailetc
, 0755);
708 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
712 symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
715 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
720 static void post_jail_fs(void);
721 static void enter_jail_fs(void)
723 char dirbuf
[sizeof(jail_root
) + 4];
725 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
728 if (pivot_root(jail_root
, dirbuf
) == -1) {
729 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
733 ERROR("chdir(/) (after pivot_root) failed: %m\n");
737 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
738 umount2(dirbuf
, MNT_DETACH
);
740 if (opts
.tmpoverlaysize
) {
741 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
742 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
743 umount2(tmpdirbuf
, MNT_DETACH
);
747 umount2("/old", MNT_DETACH
);
750 if (create_devices()) {
751 ERROR("create_devices() failed\n");
755 mount(NULL
, "/", NULL
, MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
761 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
766 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
767 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
770 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
773 if (dprintf(map_file
, "%s", mapstr
)) {
783 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
787 const char *map_format
= "%d %d %d\n";
788 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
789 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
792 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
795 if (dprintf(map_file
, map_format
, 0, id
, 1) == -1) {
804 static int write_setgroups(pid_t child_pid
, bool allow
)
807 char setgroups_path
[64];
809 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
814 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) == -1) {
818 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
819 close(setgroups_file
);
823 close(setgroups_file
);
827 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
829 struct passwd
*p
= NULL
;
830 struct group
*g
= NULL
;
833 p
= getpwnam(opts
.user
);
835 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
836 opts
.user
, errno
, strerror(errno
));
840 *user_gid
= p
->pw_gid
;
847 g
= getgrnam(opts
.group
);
849 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
858 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
860 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
861 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
865 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
866 ERROR("failed to set group id %d: %m\n", gr_gid
);
870 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
871 ERROR("failed to set user id %d: %m\n", pw_uid
);
876 static int apply_rlimits(void)
880 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
881 if (opts
.rlimits
[resource
])
882 DEBUG("applying limits to resource %u\n", resource
);
884 if (opts
.rlimits
[resource
] &&
885 setrlimit(resource
, opts
.rlimits
[resource
]))
893 static char** build_envp(const char *seccomp
, char **ocienvp
)
895 static char *envp
[MAX_ENVP
];
896 static char preload_var
[PATH_MAX
];
897 static char seccomp_var
[PATH_MAX
];
898 static char debug_var
[] = "LD_DEBUG=all";
899 static char container_var
[] = "container=ujail";
900 const char *preload_lib
= find_lib("libpreload-seccomp.so");
905 if (seccomp
&& !preload_lib
) {
906 ERROR("failed to add preload-lib to env\n");
910 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
911 envp
[count
++] = seccomp_var
;
912 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
913 envp
[count
++] = preload_var
;
916 envp
[count
++] = container_var
;
919 envp
[count
++] = debug_var
;
922 while (addenv
&& *addenv
) {
923 envp
[count
++] = *(addenv
++);
924 if (count
>= MAX_ENVP
) {
925 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
932 static void usage(void)
934 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
935 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
936 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
937 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
938 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
939 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
940 fprintf(stderr
, "namespace jail options:\n");
941 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
942 fprintf(stderr
, " -N\t\tjail has network namespace\n");
943 fprintf(stderr
, " -f\t\tjail has user namespace\n");
944 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
945 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
946 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
947 fprintf(stderr
, " -p\t\tjail has /proc\n");
948 fprintf(stderr
, " -s\t\tjail has /sys\n");
949 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
950 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
951 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
952 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
953 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
954 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
955 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
956 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
957 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
958 fprintf(stderr
, " -y\t\tprovide jail console\n");
959 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
960 fprintf(stderr
, " -j\t\tstart container immediately\n");
961 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
962 and he has the same powers as root outside the jail,\n\
963 thus he can escape the jail and/or break stuff.\n\
964 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
965 If you use none of the namespace jail options,\n\
966 ujail will not use namespace/build a jail,\n\
967 and will only drop capabilities/apply seccomp filter.\n\n");
970 static int* get_namespace_fd(const unsigned int nstype
)
974 return &opts
.setns
.pid
;
976 return &opts
.setns
.net
;
978 return &opts
.setns
.ns
;
980 return &opts
.setns
.ipc
;
982 return &opts
.setns
.uts
;
984 return &opts
.setns
.user
;
985 case CLONE_NEWCGROUP
:
986 return &opts
.setns
.cgroup
;
989 return &opts
.setns
.time
;
996 static int setns_open(unsigned long nstype
)
998 int *fd
= get_namespace_fd(nstype
);
1006 if (setns(*fd
, nstype
) == -1) {
1015 static int jail_running
= 0;
1016 static int jail_return_code
= 0;
1018 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1019 static struct uloop_timeout jail_process_timeout
= {
1020 .cb
= jail_process_timeout_cb
,
1022 static void poststop(void);
1023 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1025 uloop_timeout_cancel(&jail_process_timeout
);
1026 if (WIFEXITED(ret
)) {
1027 jail_return_code
= WEXITSTATUS(ret
);
1028 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1030 jail_return_code
= WTERMSIG(ret
);
1031 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1037 static struct uloop_process jail_process
= {
1038 .cb
= jail_process_handler
,
1041 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1043 DEBUG("jail process failed to stop, sending SIGKILL\n");
1044 kill(jail_process
.pid
, SIGKILL
);
1047 static void jail_handle_signal(int signo
)
1050 DEBUG("forwarding signal %d to the hook process\n", signo
);
1051 kill(hook_process
.pid
, signo
);
1055 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1056 kill(jail_process
.pid
, signo
);
1060 static void signals_init(void)
1065 sigfillset(&sigmask
);
1066 for (i
= 0; i
< _NSIG
; i
++) {
1067 struct sigaction s
= { 0 };
1069 if (!sigismember(&sigmask
, i
))
1071 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1074 s
.sa_handler
= jail_handle_signal
;
1075 sigaction(i
, &s
, NULL
);
1079 static void pre_exec_jail(struct uloop_timeout
*t
);
1080 static struct uloop_timeout pre_exec_timeout
= {
1081 .cb
= pre_exec_jail
,
1085 static int exec_jail(void *arg
)
1095 setns_open(CLONE_NEWUSER
);
1096 setns_open(CLONE_NEWNET
);
1097 setns_open(CLONE_NEWNS
);
1098 setns_open(CLONE_NEWIPC
);
1099 setns_open(CLONE_NEWUTS
);
1102 if (write(pipes
[1], buf
, 1) < 1) {
1103 ERROR("can't write to parent\n");
1104 return EXIT_FAILURE
;
1107 if (read(pipes
[2], buf
, 1) < 1) {
1108 ERROR("can't read from parent\n");
1109 return EXIT_FAILURE
;
1111 if (buf
[0] != 'O') {
1112 ERROR("parent had an error, child exiting\n");
1113 return EXIT_FAILURE
;
1116 if (opts
.namespace & CLONE_NEWCGROUP
)
1117 unshare(CLONE_NEWCGROUP
);
1119 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1120 if (setregid(0, 0) < 0) {
1124 if (setreuid(0, 0) < 0) {
1128 if (setgroups(0, NULL
) < 0) {
1129 ERROR("setgroups\n");
1134 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1135 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1136 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1140 uloop_timeout_add(&pre_exec_timeout
);
1146 static void pre_exec_jail(struct uloop_timeout
*t
)
1148 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1149 ERROR("failed to build jail fs\n");
1152 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1156 static void post_start_hook(void);
1157 static void post_jail_fs(void)
1161 if (read(pipes
[2], buf
, 1) < 1) {
1162 ERROR("can't read from parent\n");
1165 if (buf
[0] != '!') {
1166 ERROR("parent had an error, child exiting\n");
1171 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1174 static void post_start_hook(void)
1176 int pw_uid
, pw_gid
, gr_gid
;
1178 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1179 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1183 /* drop capabilities, retain those still needed to further setup jail */
1184 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1187 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1188 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1189 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1191 if (opts
.additional_gids
&&
1192 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1193 ERROR("setgroups failed: %m\n");
1200 if (prctl(PR_SET_SECUREBITS
, 0)) {
1201 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1205 /* drop remaining capabilities to end up with specified sets */
1206 if (applyOCIcapabilities(opts
.capset
, 0))
1209 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1210 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1214 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1218 if (opts
.cwd
&& chdir(opts
.cwd
))
1221 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1226 INFO("exec-ing %s\n", *opts
.jail_argv
);
1227 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1228 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1230 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1232 /* we get there only if execve fails */
1233 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1237 static int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1239 char pid_pid_path
[PATH_MAX
];
1241 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1243 return open(pid_pid_path
, O_RDONLY
);
1246 static void netns_updown(pid_t pid
, bool start
)
1248 static struct blob_buf req
;
1254 blob_buf_init(&req
, 0);
1255 blobmsg_add_string(&req
, "jail", opts
.name
);
1256 blobmsg_add_u32(&req
, "pid", pid
);
1257 blobmsg_add_u8(&req
, "start", start
);
1259 if (ubus_lookup_id(parent_ctx
, "network", &id
) ||
1260 ubus_invoke(parent_ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1261 INFO("ubus request failed\n");
1263 blob_buf_free(&req
);
1266 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1268 struct blob_attr
*cur
;
1271 blobmsg_for_each_attr(cur
, msg
, rem
)
1275 *envp
= calloc(1 + sz
, sizeof(char*));
1284 blobmsg_for_each_attr(cur
, msg
, rem
)
1285 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1299 static const struct blobmsg_policy oci_root_policy
[] = {
1300 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1301 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1304 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1306 static char rootpath
[PATH_MAX
] = { 0 };
1307 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1310 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1312 if (!tb
[OCI_ROOT_PATH
])
1315 strncpy(rootpath
, jsonfile
, PATH_MAX
);
1316 cur
= strrchr(rootpath
, '/');
1322 strncat(rootpath
, blobmsg_get_string(tb
[OCI_ROOT_PATH
]), PATH_MAX
- (strlen(rootpath
) + 1));
1324 opts
.extroot
= rootpath
;
1326 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1340 static const struct blobmsg_policy oci_hook_policy
[] = {
1341 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1342 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1343 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1344 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1348 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1350 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1351 struct blob_attr
*cur
;
1355 blobmsg_for_each_attr(cur
, msg
, rem
)
1361 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1367 blobmsg_for_each_attr(cur
, msg
, rem
) {
1368 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1370 if (!tb
[OCI_HOOK_PATH
]) {
1375 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1376 if (tb
[OCI_HOOK_ARGS
]) {
1377 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1381 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1382 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1383 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1387 if (tb
[OCI_HOOK_ENV
]) {
1388 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1393 if (tb
[OCI_HOOK_TIMEOUT
])
1394 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1396 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1401 (*hooklist
)[idx
] = NULL
;
1403 DEBUG("added %d hooks\n", idx
);
1408 free_hooklist(*hooklist
);
1417 OCI_HOOKS_CREATERUNTIME
,
1418 OCI_HOOKS_CREATECONTAINER
,
1419 OCI_HOOKS_STARTCONTAINER
,
1420 OCI_HOOKS_POSTSTART
,
1425 static const struct blobmsg_policy oci_hooks_policy
[] = {
1426 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1427 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1428 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1429 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1430 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1431 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1434 static int parseOCIhooks(struct blob_attr
*msg
)
1436 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1439 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1441 if (tb
[OCI_HOOKS_PRESTART
])
1442 INFO("warning: ignoring deprecated prestart hook\n");
1444 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1445 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1450 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1451 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1453 goto out_createruntime
;
1456 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1457 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1459 goto out_createcontainer
;
1462 if (tb
[OCI_HOOKS_POSTSTART
]) {
1463 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1465 goto out_startcontainer
;
1468 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1469 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1477 free_hooklist(opts
.hooks
.poststart
);
1479 free_hooklist(opts
.hooks
.startContainer
);
1480 out_createcontainer
:
1481 free_hooklist(opts
.hooks
.createContainer
);
1483 free_hooklist(opts
.hooks
.createRuntime
);
1490 OCI_PROCESS_USER_UID
,
1491 OCI_PROCESS_USER_GID
,
1492 OCI_PROCESS_USER_UMASK
,
1493 OCI_PROCESS_USER_ADDITIONALGIDS
,
1494 __OCI_PROCESS_USER_MAX
,
1497 static const struct blobmsg_policy oci_process_user_policy
[] = {
1498 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1499 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1500 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1501 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1504 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1505 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1506 struct blob_attr
*cur
;
1510 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1512 if (tb
[OCI_PROCESS_USER_UID
])
1513 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1515 if (tb
[OCI_PROCESS_USER_GID
]) {
1516 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1517 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1521 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1524 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1526 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1531 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1534 /* always add primary GID to set of GIDs if set */
1536 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1538 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1539 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1541 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1543 opts
.num_additional_gids
= gidcnt
;
1545 DEBUG("read %zu additional groups\n", gidcnt
);
1548 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1549 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1550 opts
.set_umask
= true;
1557 OCI_PROCESS_RLIMIT_TYPE
,
1558 OCI_PROCESS_RLIMIT_SOFT
,
1559 OCI_PROCESS_RLIMIT_HARD
,
1560 __OCI_PROCESS_RLIMIT_MAX
,
1563 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1564 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1565 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1566 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1569 /* from manpage GETRLIMIT(2) */
1570 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1572 [RLIMIT_CORE
] = "CORE",
1573 [RLIMIT_CPU
] = "CPU",
1574 [RLIMIT_DATA
] = "DATA",
1575 [RLIMIT_FSIZE
] = "FSIZE",
1576 [RLIMIT_LOCKS
] = "LOCKS",
1577 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1578 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1579 [RLIMIT_NICE
] = "NICE",
1580 [RLIMIT_NOFILE
] = "NOFILE",
1581 [RLIMIT_NPROC
] = "NPROC",
1582 [RLIMIT_RSS
] = "RSS",
1583 [RLIMIT_RTPRIO
] = "RTPRIO",
1584 [RLIMIT_RTTIME
] = "RTTIME",
1585 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1586 [RLIMIT_STACK
] = "STACK",
1589 static int resolve_rlimit(char *type
) {
1590 unsigned int rltype
;
1592 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1593 if (rlimit_names
[rltype
] &&
1594 !strncmp("RLIMIT_", type
, 7) &&
1595 !strcmp(rlimit_names
[rltype
], type
+ 7))
1602 static int parseOCIrlimit(struct blob_attr
*msg
)
1604 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1606 struct rlimit
*curlim
;
1608 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1610 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1611 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1612 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1615 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1620 if (opts
.rlimits
[limtype
])
1623 curlim
= malloc(sizeof(struct rlimit
));
1624 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1625 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1627 opts
.rlimits
[limtype
] = curlim
;
1634 OCI_PROCESS_CAPABILITIES
,
1637 OCI_PROCESS_OOMSCOREADJ
,
1638 OCI_PROCESS_NONEWPRIVILEGES
,
1639 OCI_PROCESS_RLIMITS
,
1640 OCI_PROCESS_TERMINAL
,
1645 static const struct blobmsg_policy oci_process_policy
[] = {
1646 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1647 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1648 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1649 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1650 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1651 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1652 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1653 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1654 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1658 static int parseOCIprocess(struct blob_attr
*msg
)
1660 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1663 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1665 if (!tb
[OCI_PROCESS_ARGS
])
1668 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1672 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1673 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1675 if (tb
[OCI_PROCESS_CWD
])
1676 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1678 if (tb
[OCI_PROCESS_ENV
]) {
1679 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1684 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1687 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1688 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1691 if (tb
[OCI_PROCESS_RLIMITS
]) {
1692 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1693 res
= parseOCIrlimit(cur
);
1699 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1700 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1701 opts
.set_oom_score_adj
= true;
1708 OCI_LINUX_NAMESPACE_TYPE
,
1709 OCI_LINUX_NAMESPACE_PATH
,
1710 __OCI_LINUX_NAMESPACE_MAX
,
1713 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1714 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1715 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1718 static int resolve_nstype(char *type
) {
1719 if (!strcmp("pid", type
))
1720 return CLONE_NEWPID
;
1721 else if (!strcmp("network", type
))
1722 return CLONE_NEWNET
;
1723 else if (!strcmp("mount", type
))
1725 else if (!strcmp("ipc", type
))
1726 return CLONE_NEWIPC
;
1727 else if (!strcmp("uts", type
))
1728 return CLONE_NEWUTS
;
1729 else if (!strcmp("user", type
))
1730 return CLONE_NEWUSER
;
1731 else if (!strcmp("cgroup", type
))
1732 return CLONE_NEWCGROUP
;
1733 #ifdef CLONE_NEWTIME
1734 else if (!strcmp("time", type
))
1735 return CLONE_NEWTIME
;
1741 static int parseOCIlinuxns(struct blob_attr
*msg
)
1743 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1748 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1750 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1753 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1757 if (opts
.namespace & nstype
)
1760 setns
= get_namespace_fd(nstype
);
1768 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1769 DEBUG("opening existing %s namespace from path %s\n",
1770 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1771 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1773 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1775 return errno
?:ESTALE
;
1777 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
)
1780 DEBUG("opened existing %s namespace got filehandler %u\n",
1781 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1786 opts
.namespace |= nstype
;
1794 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1795 OCI_LINUX_UIDGIDMAP_HOSTID
,
1796 OCI_LINUX_UIDGIDMAP_SIZE
,
1797 __OCI_LINUX_UIDGIDMAP_MAX
,
1800 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1801 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1802 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1803 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1806 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1808 const char *map_format
= "%d %d %d\n";
1809 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1810 struct blob_attr
*cur
;
1814 unsigned int cnt
= 0;
1815 size_t totallen
= 0;
1817 /* count number of mappings */
1818 blobmsg_for_each_attr(cur
, msg
, rem
)
1824 /* allocate array for mappings */
1825 mappings
= calloc(1 + cnt
, sizeof(char*));
1829 mappings
[cnt
] = NULL
;
1832 blobmsg_for_each_attr(cur
, msg
, rem
) {
1833 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1835 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1836 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1837 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1840 /* write mapping line into allocated string */
1841 len
= asprintf(&mappings
[cnt
++], map_format
,
1842 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1843 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1844 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1852 /* allocate combined mapping string */
1853 map
= calloc(1 + totallen
, sizeof(char));
1859 /* concatenate mapping strings into combined string */
1860 curstr
= mappings
[0];
1862 strcat(map
, curstr
);
1880 OCI_DEVICES_FILEMODE
,
1886 static const struct blobmsg_policy oci_devices_policy
[] = {
1887 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1888 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1889 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
1890 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
1891 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
1892 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1893 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
1896 static mode_t
resolve_devtype(char *tstr
)
1898 if (!strcmp("c", tstr
) ||
1901 else if (!strcmp("b", tstr
))
1903 else if (!strcmp("p", tstr
))
1909 static int parseOCIdevices(struct blob_attr
*msg
)
1911 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
1912 struct blob_attr
*cur
;
1915 struct mknod_args
*tmp
;
1917 blobmsg_for_each_attr(cur
, msg
, rem
)
1920 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
1923 blobmsg_for_each_attr(cur
, msg
, rem
) {
1924 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1925 if (!tb
[OCI_DEVICES_TYPE
] ||
1926 !tb
[OCI_DEVICES_PATH
])
1929 tmp
= calloc(1, sizeof(struct mknod_args
));
1933 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1937 if (tmp
->mode
!= S_IFIFO
) {
1938 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
])
1941 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
1942 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
1945 if (tb
[OCI_DEVICES_FILEMODE
]) {
1946 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]))
1949 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
1951 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
1954 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
1956 if (tb
[OCI_DEVICES_UID
])
1957 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
1961 if (tb
[OCI_DEVICES_GID
])
1962 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
1966 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1967 opts
.devices
[cnt
++] = tmp
;
1970 opts
.devices
[cnt
] = NULL
;
1975 static int parseOCIsysctl(struct blob_attr
*msg
)
1977 struct blob_attr
*cur
;
1982 blobmsg_for_each_attr(cur
, msg
, rem
) {
1983 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
1992 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
1997 blobmsg_for_each_attr(cur
, msg
, rem
) {
1998 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
1999 if (!opts
.sysctl
[cnt
])
2002 /* replace '.' with '/' in entry name */
2003 tc
= tmp
= strdup(blobmsg_name(cur
));
2004 while ((tc
= strchr(tc
, '.')))
2007 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2008 opts
.sysctl
[cnt
]->entry
= tmp
;
2013 opts
.sysctl
[cnt
] = NULL
;
2020 OCI_LINUX_CGROUPSPATH
,
2021 OCI_LINUX_RESOURCES
,
2024 OCI_LINUX_NAMESPACES
,
2026 OCI_LINUX_UIDMAPPINGS
,
2027 OCI_LINUX_GIDMAPPINGS
,
2028 OCI_LINUX_MASKEDPATHS
,
2029 OCI_LINUX_READONLYPATHS
,
2030 OCI_LINUX_ROOTFSPROPAGATION
,
2034 static const struct blobmsg_policy oci_linux_policy
[] = {
2035 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2036 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2037 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2038 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2039 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2040 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2041 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2042 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2043 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2044 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2045 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2048 static int parseOCIlinux(struct blob_attr
*msg
)
2050 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2051 struct blob_attr
*cur
;
2055 char cgfullpath
[256] = "/sys/fs/cgroup";
2057 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2059 if (tb
[OCI_LINUX_NAMESPACES
]) {
2060 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2061 res
= parseOCIlinuxns(cur
);
2067 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2068 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2073 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2074 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2079 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2080 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2081 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, NULL
, 0);
2087 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2088 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2089 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, NULL
, 1);
2095 if (tb
[OCI_LINUX_SYSCTL
]) {
2096 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2101 if (tb
[OCI_LINUX_SECCOMP
]) {
2102 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2103 if (!opts
.ociseccomp
)
2107 if (tb
[OCI_LINUX_DEVICES
]) {
2108 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2113 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2114 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2115 if (cgpath
[0] == '/') {
2116 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2119 strcat(cgfullpath
, cgpath
);
2121 strcat(cgfullpath
, "/containers/");
2122 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2123 strcat(cgfullpath
, "/");
2124 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2127 strcat(cgfullpath
, cgpath
);
2130 strcat(cgfullpath
, "/containers/");
2131 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2132 strcat(cgfullpath
, "/");
2133 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2136 cgroups_init(cgfullpath
);
2138 if (tb
[OCI_LINUX_RESOURCES
]) {
2139 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2159 static const struct blobmsg_policy oci_policy
[] = {
2160 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2161 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2162 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2163 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2164 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2165 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2166 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2167 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2170 static int parseOCI(const char *jsonfile
)
2172 struct blob_attr
*tb
[__OCI_MAX
];
2173 struct blob_attr
*cur
;
2177 blob_buf_init(&ocibuf
, 0);
2178 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
))
2181 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2183 if (!tb
[OCI_VERSION
])
2186 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2187 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2191 if (tb
[OCI_HOSTNAME
])
2192 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2194 if (!tb
[OCI_PROCESS
])
2197 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2203 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2206 if (!tb
[OCI_MOUNTS
])
2209 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2210 if ((res
= parseOCImount(cur
)))
2213 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2216 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2219 if (tb
[OCI_ANNOTATIONS
])
2220 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2222 blob_buf_free(&ocibuf
);
2227 static int set_oom_score_adj(void)
2232 if (!opts
.set_oom_score_adj
)
2235 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2236 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2240 dprintf(f
, "%d", opts
.oom_score_adj
);
2254 static int jail_oci_state
= OCI_STATE_CREATED
;
2255 static void pipe_send_start_container(struct uloop_timeout
*t
);
2256 static struct uloop_timeout start_container_timeout
= {
2257 .cb
= pipe_send_start_container
,
2260 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2261 struct ubus_request_data
*req
, const char *method
,
2262 struct blob_attr
*msg
)
2264 if (jail_oci_state
!= OCI_STATE_CREATED
)
2265 return UBUS_STATUS_INVALID_ARGUMENT
;
2267 uloop_timeout_add(&start_container_timeout
);
2269 return UBUS_STATUS_OK
;
2272 static struct blob_buf bb
;
2273 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2274 struct ubus_request_data
*req
, const char *method
,
2275 struct blob_attr
*msg
)
2279 switch (jail_oci_state
) {
2280 case OCI_STATE_CREATING
:
2281 statusstr
= "creating";
2283 case OCI_STATE_CREATED
:
2284 statusstr
= "created";
2286 case OCI_STATE_RUNNING
:
2287 statusstr
= "running";
2289 case OCI_STATE_STOPPED
:
2290 statusstr
= "stopped";
2293 statusstr
= "unknown";
2296 blob_buf_init(&bb
, 0);
2297 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2298 blobmsg_add_string(&bb
, "id", opts
.name
);
2299 blobmsg_add_string(&bb
, "status", statusstr
);
2300 if (jail_oci_state
== OCI_STATE_CREATED
||
2301 jail_oci_state
== OCI_STATE_RUNNING
)
2302 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2304 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2306 if (opts
.annotations
)
2307 blobmsg_add_blob(&bb
, opts
.annotations
);
2309 ubus_send_reply(ctx
, req
, bb
.head
);
2311 return UBUS_STATUS_OK
;
2315 CONTAINER_KILL_ATTR_SIGNAL
,
2316 __CONTAINER_KILL_ATTR_MAX
,
2319 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2320 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2324 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2325 struct ubus_request_data
*req
, const char *method
,
2326 struct blob_attr
*msg
)
2328 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2331 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2333 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2335 sig
= blobmsg_get_u32(cur
);
2337 if (jail_oci_state
== OCI_STATE_CREATING
)
2338 return UBUS_STATUS_NOT_FOUND
;
2340 if (kill(jail_process
.pid
, sig
) == 0)
2344 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2345 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2346 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2349 return UBUS_STATUS_UNKNOWN_ERROR
;
2352 static struct ubus_method container_methods
[] = {
2353 UBUS_METHOD_NOARG("start", handle_start
),
2354 UBUS_METHOD_NOARG("state", handle_state
),
2355 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2358 static struct ubus_object_type container_object_type
=
2359 UBUS_OBJECT_TYPE("container", container_methods
);
2361 static struct ubus_object container_object
= {
2362 .type
= &container_object_type
,
2363 .methods
= container_methods
,
2364 .n_methods
= ARRAY_SIZE(container_methods
),
2367 static void post_main(struct uloop_timeout
*t
);
2368 static struct uloop_timeout post_main_timeout
= {
2371 static int netns_fd
;
2372 static int pidns_fd
;
2373 #ifdef CLONE_NEWTIME
2374 static int timens_fd
;
2376 static void post_create_runtime(void);
2377 int main(int argc
, char **argv
)
2379 uid_t uid
= getuid();
2380 const char log
[] = "/dev/log";
2381 const char ubus
[] = "/var/run/ubus/ubus.sock";
2385 ERROR("not root, aborting: %m\n");
2386 return EXIT_FAILURE
;
2391 init_library_search();
2393 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2396 debug
= atoi(optarg
);
2399 opts
.namespace |= CLONE_NEWNS
;
2403 opts
.namespace |= CLONE_NEWNS
;
2407 opts
.namespace |= CLONE_NEWUSER
;
2410 opts
.namespace |= CLONE_NEWCGROUP
;
2413 opts
.extroot
= strdup(optarg
);
2416 opts
.namespace |= CLONE_NEWNS
;
2420 opts
.seccomp
= optarg
;
2421 add_mount_bind(optarg
, 1, -1);
2424 opts
.capabilities
= optarg
;
2427 opts
.no_new_privs
= 1;
2433 opts
.namespace |= CLONE_NEWNET
;
2436 opts
.namespace |= CLONE_NEWUTS
;
2437 opts
.hostname
= strdup(optarg
);
2440 opts
.namespace |= CLONE_NEWNS
;
2441 add_path_and_deps(optarg
, 1, 0, 0);
2444 opts
.namespace |= CLONE_NEWNS
;
2445 add_path_and_deps(optarg
, 0, 0, 0);
2448 opts
.namespace |= CLONE_NEWNS
;
2449 add_mount_bind(ubus
, 0, -1);
2452 opts
.namespace |= CLONE_NEWNS
;
2453 add_mount_bind(log
, 0, -1);
2459 opts
.group
= optarg
;
2462 opts
.overlaydir
= optarg
;
2465 opts
.tmpoverlaysize
= optarg
;
2468 opts
.require_jail
= 1;
2474 opts
.ocibundle
= strdup(optarg
);
2477 opts
.immediately
= true;
2482 if (opts
.namespace && !opts
.ocibundle
)
2483 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2485 /* those are filehandlers, so -1 indicates unused */
2486 opts
.setns
.pid
= -1;
2487 opts
.setns
.net
= -1;
2489 opts
.setns
.ipc
= -1;
2490 opts
.setns
.uts
= -1;
2491 opts
.setns
.user
= -1;
2492 opts
.setns
.cgroup
= -1;
2493 #ifdef CLONE_NEWTIME
2494 opts
.setns
.time
= -1;
2497 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2498 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2502 if (opts
.ocibundle
) {
2506 asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
);
2507 ocires
= parseOCI(jsonfile
);
2510 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2515 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2516 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2520 /* no <binary> param found */
2521 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2523 return EXIT_FAILURE
;
2525 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
2526 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2528 return EXIT_FAILURE
;
2530 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2533 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2538 parent_ctx
= ubus_connect(NULL
);
2539 ubus_add_uloop(parent_ctx
);
2541 if (opts
.ocibundle
) {
2543 if (asprintf(&objname
, "container.%s", opts
.name
) < 0)
2546 container_object
.name
= objname
;
2547 ret
= ubus_add_object(parent_ctx
, &container_object
);
2549 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2554 /* deliberately not using 'else' on unrelated conditional branches */
2555 if (!opts
.ocibundle
) {
2556 /* allocate NULL-terminated array for argv */
2557 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(char**));
2558 if (!opts
.jail_argv
)
2559 return EXIT_FAILURE
;
2561 for (size_t s
= optind
; s
< argc
; s
++)
2562 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2564 if (opts
.namespace & CLONE_NEWUSER
)
2565 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2568 if (!opts
.extroot
) {
2569 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2570 ERROR("failed to load dependencies\n");
2575 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2576 ERROR("failed to load libpreload-seccomp.so\n");
2578 if (opts
.require_jail
)
2582 uloop_timeout_add(&post_main_timeout
);
2589 static void post_main(struct uloop_timeout
*t
)
2591 if (apply_rlimits()) {
2592 ERROR("error applying resource limits\n");
2597 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2599 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2602 if (has_namespaces()) {
2603 if (opts
.namespace & CLONE_NEWNS
) {
2604 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2605 add_mount_bind("/etc/passwd", 0, -1);
2606 add_mount_bind("/etc/group", 0, -1);
2609 #if defined(__GLIBC__)
2611 add_mount_bind("/etc/nsswitch.conf", 0, -1);
2614 if (!(opts
.namespace & CLONE_NEWNET
)) {
2615 add_mount_bind("/etc/resolv.conf", 0, -1);
2616 } else if (opts
.setns
.net
== -1) {
2617 char hostdir
[PATH_MAX
];
2619 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2620 mkdir_p(hostdir
, 0755);
2621 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, NULL
, -1);
2624 /* default mounts */
2625 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, "size=1M", -1);
2626 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2628 if (opts
.procfs
|| opts
.ocibundle
) {
2629 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, NULL
, -1);
2632 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2633 * which cannot be expressed with OCI spec, but happends to be very useful.
2634 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2636 * If not running in a new network namespace, only make /proc/sys read-only.
2637 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2638 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2639 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2641 * This works because mounts are executed in incrementing strcmp() order and
2642 * /proc/self/net appears there before /proc/sys/net and hence the operation
2643 * succeeds as the bind-mount of /proc/self/net is performed first and then
2644 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2645 * table (and in the alphabet).
2647 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, NULL
, -1))
2648 if (opts
.namespace & CLONE_NEWNET
)
2649 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, NULL
, -1))
2650 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, NULL
, -1);
2653 if (opts
.sysfs
|| opts
.ocibundle
)
2654 add_mount("sysfs", "/sys", "sysfs", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, NULL
, -1);
2657 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, "mode=1777", -1);
2661 if (opts
.setns
.pid
!= -1) {
2662 pidns_fd
= ns_open_pid("pid", getpid());
2663 setns_open(CLONE_NEWPID
);
2668 #ifdef CLONE_NEWTIME
2669 if (opts
.setns
.time
!= -1) {
2670 timens_fd
= ns_open_pid("time", getpid());
2671 setns_open(CLONE_NEWTIME
);
2675 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
2677 jail_process
.pid
= fork();
2680 if (jail_process
.pid
> 0) {
2681 /* parent process */
2684 uloop_process_add(&jail_process
);
2687 if (pidns_fd
!= -1) {
2688 setns(pidns_fd
, CLONE_NEWPID
);
2691 #ifdef CLONE_NEWTIME
2692 if (timens_fd
!= -1)
2693 setns(timens_fd
, CLONE_NEWTIME
);
2697 if (opts
.setns
.net
!= -1)
2698 close(opts
.setns
.net
);
2699 if (opts
.setns
.ns
!= -1)
2700 close(opts
.setns
.ns
);
2701 if (opts
.setns
.ipc
!= -1)
2702 close(opts
.setns
.ipc
);
2703 if (opts
.setns
.uts
!= -1)
2704 close(opts
.setns
.uts
);
2705 if (opts
.setns
.user
!= -1)
2706 close(opts
.setns
.user
);
2707 if (opts
.setns
.cgroup
!= -1)
2708 close(opts
.setns
.cgroup
);
2711 if (read(pipes
[0], sig_buf
, 1) < 1) {
2712 ERROR("can't read from child\n");
2716 set_oom_score_adj();
2719 cgroups_apply(jail_process
.pid
);
2721 if (opts
.namespace & CLONE_NEWUSER
) {
2722 if (write_setgroups(jail_process
.pid
, true)) {
2723 ERROR("can't write setgroups\n");
2727 bool has_gr
= (opts
.gr_gid
!= -1);
2728 if (opts
.pw_uid
!= -1) {
2729 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2730 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2732 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2733 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2736 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2738 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2742 if (opts
.namespace & CLONE_NEWNET
) {
2744 ERROR("netns needs a named jail\n");
2747 netns_fd
= ns_open_pid("net", jail_process
.pid
);
2748 netns_updown(jail_process
.pid
, true);
2750 } else if (jail_process
.pid
== 0) {
2751 /* fork child process */
2752 exit(exec_jail(NULL
));
2754 ERROR("failed to clone/fork: %m\n");
2757 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
2760 static void post_poststart(void);
2761 static void post_create_runtime(void)
2766 if (write(pipes
[3], sig_buf
, 1) < 0) {
2767 ERROR("can't write to child\n");
2771 jail_oci_state
= OCI_STATE_CREATED
;
2772 if (opts
.ocibundle
&& !opts
.immediately
)
2773 uloop_run(); /* wait for 'start' command via ubus */
2775 pipe_send_start_container(NULL
);
2778 static void pipe_send_start_container(struct uloop_timeout
*t
)
2782 jail_oci_state
= OCI_STATE_RUNNING
;
2784 if (write(pipes
[3], sig_buf
, 1) < 0) {
2785 ERROR("can't write to child\n");
2790 run_hooks(opts
.hooks
.poststart
, post_poststart
);
2793 static void post_poststart(void)
2795 uloop_run(); /* idle here while jail is running */
2797 DEBUG("uloop interrupted, killing jail process\n");
2798 kill(jail_process
.pid
, SIGTERM
);
2799 uloop_timeout_set(&jail_process_timeout
, 1000);
2806 static void post_poststop(void);
2807 static void poststop(void) {
2808 if (opts
.namespace & CLONE_NEWNET
) {
2809 setns(netns_fd
, CLONE_NEWNET
);
2810 netns_updown(getpid(), false);
2813 run_hooks(opts
.hooks
.poststop
, post_poststop
);
2816 static void post_poststop(void)
2820 ubus_free(parent_ctx
);
2822 exit(jail_return_code
);