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:iP:"
72 #define OCI_VERSION_STRING "1.0.2"
100 struct sock_fprog
*ociseccomp
;
102 struct jail_capset capset
;
107 char *tmpoverlaysize
;
112 struct sysctl_val
**sysctl
;
134 gid_t
*additional_gids
;
135 size_t num_additional_gids
;
140 struct hook_execvpe
**createRuntime
;
141 struct hook_execvpe
**createContainer
;
142 struct hook_execvpe
**startContainer
;
143 struct hook_execvpe
**poststart
;
144 struct hook_execvpe
**poststop
;
146 struct rlimit
*rlimits
[RLIM_NLIMITS
];
148 bool set_oom_score_adj
;
149 struct mknod_args
**devices
;
152 struct blob_attr
*annotations
;
155 static struct blob_buf ocibuf
;
157 extern int pivot_root(const char *new_root
, const char *put_old
);
161 static char child_stack
[STACK_SIZE
];
163 static struct ubus_context
*parent_ctx
;
168 static inline bool has_namespaces(void)
170 return ((opts
.setns
.pid
!= -1) ||
171 (opts
.setns
.net
!= -1) ||
172 (opts
.setns
.ns
!= -1) ||
173 (opts
.setns
.ipc
!= -1) ||
174 (opts
.setns
.uts
!= -1) ||
175 (opts
.setns
.user
!= -1) ||
176 (opts
.setns
.cgroup
!= -1) ||
178 (opts
.setns
.time
!= -1) ||
183 static void free_hooklist(struct hook_execvpe
**hooklist
)
185 struct hook_execvpe
*cur
;
210 static void free_sysctl(void) {
211 struct sysctl_val
*cur
;
222 static void free_devices(void) {
223 struct mknod_args
**cur
;
237 static void free_rlimits(void) {
240 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
241 free(opts
.rlimits
[type
]);
244 static void free_opts(bool parent
) {
247 /* we need to keep argv, envp and seccomp filter in child */
248 if (parent
) { /* parent-only */
249 if (opts
.ociseccomp
) {
250 free(opts
.ociseccomp
->filter
);
251 free(opts
.ociseccomp
);
254 tmp
= opts
.jail_argv
;
258 free(opts
.jail_argv
);
265 } else { /* child-only */
278 free(opts
.annotations
);
279 free(opts
.ocibundle
);
281 free_hooklist(opts
.hooks
.createRuntime
);
282 free_hooklist(opts
.hooks
.createContainer
);
283 free_hooklist(opts
.hooks
.startContainer
);
284 free_hooklist(opts
.hooks
.poststart
);
285 free_hooklist(opts
.hooks
.poststop
);
288 static int mount_overlay(char *jail_root
, char *overlaydir
) {
289 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
290 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
293 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
296 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
299 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
302 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
306 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
307 * this is to work-around a bug in overlayfs described in the overlayfs-userns
309 * 3. modification of a file 'hithere' which is in l but not yet
310 * in u, and which is not owned by T, is not allowed, even if
311 * writes to u are allowed. This may be a bug in overlayfs,
312 * but it is safe behavior.
314 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
317 if (mkdir_p(upperetc
, 0755))
318 goto upper_etc_printf
;
320 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
321 goto upper_etc_printf
;
323 fd
= creat(upperresolvconf
, 0644);
325 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
326 goto upper_resolvconf_printf
;
330 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
332 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
337 upper_resolvconf_printf
:
338 free(upperresolvconf
);
351 static void pass_console(int console_fd
)
353 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
354 static struct blob_buf req
;
360 blob_buf_init(&req
, 0);
361 blobmsg_add_string(&req
, "name", opts
.name
);
363 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
364 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
365 INFO("ubus request failed\n");
370 ubus_free(child_ctx
);
373 static int create_dev_console(const char *jail_root
)
376 char dev_console_path
[PATH_MAX
];
377 int slave_console_fd
;
379 /* Open UNIX/98 virtual console */
380 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
381 if (console_fd
== -1)
384 console_fname
= ptsname(console_fd
);
385 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
390 unlockpt(console_fd
);
392 /* pass PTY master to procd */
393 pass_console(console_fd
);
395 /* mount-bind PTY slave to /dev/console in jail */
396 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
397 close(creat(dev_console_path
, 0620));
399 if (mount(console_fname
, dev_console_path
, NULL
, MS_BIND
, NULL
))
402 /* use PTY slave for stdio */
403 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
404 dup2(slave_console_fd
, 0);
405 dup2(slave_console_fd
, 1);
406 dup2(slave_console_fd
, 2);
407 close(slave_console_fd
);
409 INFO("using guest console %s\n", console_fname
);
418 static int hook_running
= 0;
419 static int hook_return_code
= 0;
420 static struct hook_execvpe
**current_hook
= NULL
;
421 typedef void (*hook_return_handler
)(void);
422 static hook_return_handler hook_return_cb
= NULL
;
424 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
425 static struct uloop_timeout hook_process_timeout
= {
426 .cb
= hook_process_timeout_cb
,
429 static void run_hooklist(void);
430 static void hook_process_handler(struct uloop_process
*c
, int ret
)
432 uloop_timeout_cancel(&hook_process_timeout
);
434 if (WIFEXITED(ret
)) {
435 hook_return_code
= WEXITSTATUS(ret
);
436 if (hook_return_code
)
437 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
439 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
442 hook_return_code
= WTERMSIG(ret
);
443 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
450 static struct uloop_process hook_process
= {
451 .cb
= hook_process_handler
,
454 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
456 DEBUG("hook process failed to stop, sending SIGKILL\n");
457 kill(hook_process
.pid
, SIGKILL
);
460 static void run_hooklist(void)
462 struct hook_execvpe
*hook
= *current_hook
;
468 DEBUG("executing hook %s\n", hook
->file
);
470 if (stat(hook
->file
, &s
))
471 hook_process_handler(&hook_process
, ENOENT
);
473 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
474 hook_process_handler(&hook_process
, EPERM
);
476 if (!((unsigned long)s
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
)))
477 hook_process_handler(&hook_process
, EPERM
);
480 hook_process
.pid
= fork();
481 if (hook_process
.pid
== 0) {
483 execve(hook
->file
, hook
->argv
, hook
->envp
);
484 ERROR("execve error %m\n");
486 } else if (hook_process
.pid
< 0) {
488 ERROR("hook fork error\n");
490 hook_process_handler(&hook_process
, errno
);
494 uloop_process_add(&hook_process
);
496 if (hook
->timeout
> 0)
497 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
501 DEBUG("uloop interrupted, killing jail process\n");
502 kill(hook_process
.pid
, SIGTERM
);
503 uloop_timeout_set(&hook_process_timeout
, 1000);
508 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
513 current_hook
= hooklist
;
514 hook_return_cb
= return_cb
;
519 static int apply_sysctl(const char *jail_root
)
521 struct sysctl_val
**cur
;
522 char *procdir
, *fname
;
528 asprintf(&procdir
, "%s/proc", jail_root
);
532 mkdir(procdir
, 0700);
533 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
539 asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
);
543 DEBUG("sysctl: writing '%s' to %s\n", (*cur
)->value
, fname
);
545 f
= open(fname
, O_WRONLY
);
547 ERROR("sysctl: can't open %s\n", fname
);
550 write(f
, (*cur
)->value
, strlen((*cur
)->value
));
563 /* glibc defines makedev calling a function. make sure it's a pure macro */
564 #if defined(__GLIBC__)
566 /* from musl's sys/sysmacros.h */
567 #define makedev(x,y) ( \
568 (((x)&0xfffff000ULL) << 32) | \
569 (((x)&0x00000fffULL) << 8) | \
570 (((y)&0xffffff00ULL) << 12) | \
571 (((y)&0x000000ffULL)) )
574 static struct mknod_args default_devices
[] = {
575 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
576 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
577 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
578 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
579 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
580 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
584 static int create_devices(void)
586 struct mknod_args
**cur
, *curdef
;
589 goto only_default_devices
;
594 DEBUG("creating %s (mode=%08o)\n", (*cur
)->path
, (*cur
)->mode
);
595 if (mknod((*cur
)->path
, (*cur
)->mode
, (*cur
)->dev
))
598 if (((*cur
)->uid
|| (*cur
)->gid
) &&
599 chown((*cur
)->path
, (*cur
)->uid
, (*cur
)->gid
))
605 only_default_devices
:
606 curdef
= default_devices
;
607 while(curdef
->path
) {
608 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
609 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
611 continue; /* may already exist, eg. due to a bind-mount */
613 if ((curdef
->uid
|| curdef
->gid
) &&
614 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
620 /* Dev symbolic links as defined in OCI spec */
621 symlink("/dev/pts/ptmx", "/dev/ptmx");
622 symlink("/proc/self/fd", "/dev/fd");
623 symlink("/proc/self/fd/0", "/dev/stdin");
624 symlink("/proc/self/fd/1", "/dev/stdout");
625 symlink("/proc/self/fd/2", "/dev/stderr");
630 static char jail_root
[] = "/tmp/ujail-XXXXXX";
631 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
632 static mode_t old_umask
;
633 static void enter_jail_fs(void);
634 static int build_jail_fs(void)
636 char *overlaydir
= NULL
;
638 old_umask
= umask(0);
640 if (mkdtemp(jail_root
) == NULL
) {
641 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
645 if (apply_sysctl(jail_root
)) {
646 ERROR("failed to apply sysctl values\n");
650 /* oldroot can't be MS_SHARED else pivot_root() fails */
651 if (mount("none", "/", NULL
, MS_REC
|MS_PRIVATE
, NULL
)) {
652 ERROR("private mount failed %m\n");
657 if (mount(opts
.extroot
, jail_root
, NULL
, MS_BIND
, NULL
)) {
658 ERROR("extroot mount failed %m\n");
662 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
663 ERROR("tmpfs mount failed %m\n");
668 if (opts
.tmpoverlaysize
) {
669 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
671 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
672 "mode=0755,size=%s", opts
.tmpoverlaysize
);
673 if (mkdtemp(tmpovdir
) == NULL
) {
674 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
677 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
679 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
682 overlaydir
= tmpovdir
;
686 overlaydir
= opts
.overlaydir
;
689 mount_overlay(jail_root
, overlaydir
);
691 if (chdir(jail_root
)) {
692 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
696 if (mount_all(jail_root
)) {
697 ERROR("mount_all() failed\n");
702 create_dev_console(jail_root
);
704 /* make sure /etc/resolv.conf exists if in new network namespace */
705 if (opts
.namespace & CLONE_NEWNET
) {
706 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
708 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
709 mkdir_p(jailetc
, 0755);
710 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
714 symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
717 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
722 static void post_jail_fs(void);
723 static void enter_jail_fs(void)
725 char dirbuf
[sizeof(jail_root
) + 4];
727 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
730 if (pivot_root(jail_root
, dirbuf
) == -1) {
731 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
735 ERROR("chdir(/) (after pivot_root) failed: %m\n");
739 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
740 umount2(dirbuf
, MNT_DETACH
);
742 if (opts
.tmpoverlaysize
) {
743 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
744 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
745 umount2(tmpdirbuf
, MNT_DETACH
);
749 umount2("/old", MNT_DETACH
);
752 if (create_devices()) {
753 ERROR("create_devices() failed\n");
757 mount(NULL
, "/", NULL
, MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
763 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
768 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
769 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
772 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
775 if (dprintf(map_file
, "%s", mapstr
)) {
785 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
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)
794 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
797 if (dprintf(map_file
, map_format
, 0, id
, 1) == -1) {
806 static int write_setgroups(pid_t child_pid
, bool allow
)
809 char setgroups_path
[64];
811 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
816 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) == -1) {
820 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
821 close(setgroups_file
);
825 close(setgroups_file
);
829 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
831 struct passwd
*p
= NULL
;
832 struct group
*g
= NULL
;
835 p
= getpwnam(opts
.user
);
837 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
838 opts
.user
, errno
, strerror(errno
));
842 *user_gid
= p
->pw_gid
;
849 g
= getgrnam(opts
.group
);
851 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
860 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
862 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
863 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
867 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
868 ERROR("failed to set group id %d: %m\n", gr_gid
);
872 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
873 ERROR("failed to set user id %d: %m\n", pw_uid
);
878 static int apply_rlimits(void)
882 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
883 if (opts
.rlimits
[resource
])
884 DEBUG("applying limits to resource %u\n", resource
);
886 if (opts
.rlimits
[resource
] &&
887 setrlimit(resource
, opts
.rlimits
[resource
]))
895 static char** build_envp(const char *seccomp
, char **ocienvp
)
897 static char *envp
[MAX_ENVP
];
898 static char preload_var
[PATH_MAX
];
899 static char seccomp_var
[PATH_MAX
];
900 static char debug_var
[] = "LD_DEBUG=all";
901 static char container_var
[] = "container=ujail";
902 const char *preload_lib
= find_lib("libpreload-seccomp.so");
907 if (seccomp
&& !preload_lib
) {
908 ERROR("failed to add preload-lib to env\n");
912 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
913 envp
[count
++] = seccomp_var
;
914 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
915 envp
[count
++] = preload_var
;
918 envp
[count
++] = container_var
;
921 envp
[count
++] = debug_var
;
924 while (addenv
&& *addenv
) {
925 envp
[count
++] = *(addenv
++);
926 if (count
>= MAX_ENVP
) {
927 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
934 static void usage(void)
936 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
937 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
938 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
939 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
940 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
941 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
942 fprintf(stderr
, "namespace jail options:\n");
943 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
944 fprintf(stderr
, " -N\t\tjail has network namespace\n");
945 fprintf(stderr
, " -f\t\tjail has user namespace\n");
946 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
947 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
948 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
949 fprintf(stderr
, " -p\t\tjail has /proc\n");
950 fprintf(stderr
, " -s\t\tjail has /sys\n");
951 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
952 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
953 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
954 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
955 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
956 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
957 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
958 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
959 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
960 fprintf(stderr
, " -y\t\tprovide jail console\n");
961 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
962 fprintf(stderr
, " -j\t\tstart container immediately\n");
963 fprintf(stderr
, " -P <pidfile>\tcreate <pidfile>\n");
964 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
965 and he has the same powers as root outside the jail,\n\
966 thus he can escape the jail and/or break stuff.\n\
967 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
968 If you use none of the namespace jail options,\n\
969 ujail will not use namespace/build a jail,\n\
970 and will only drop capabilities/apply seccomp filter.\n\n");
973 static int* get_namespace_fd(const unsigned int nstype
)
977 return &opts
.setns
.pid
;
979 return &opts
.setns
.net
;
981 return &opts
.setns
.ns
;
983 return &opts
.setns
.ipc
;
985 return &opts
.setns
.uts
;
987 return &opts
.setns
.user
;
988 case CLONE_NEWCGROUP
:
989 return &opts
.setns
.cgroup
;
992 return &opts
.setns
.time
;
999 static int setns_open(unsigned long nstype
)
1001 int *fd
= get_namespace_fd(nstype
);
1009 if (setns(*fd
, nstype
) == -1) {
1018 static int jail_running
= 0;
1019 static int jail_return_code
= 0;
1021 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1022 static struct uloop_timeout jail_process_timeout
= {
1023 .cb
= jail_process_timeout_cb
,
1025 static void poststop(void);
1026 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1028 uloop_timeout_cancel(&jail_process_timeout
);
1029 if (WIFEXITED(ret
)) {
1030 jail_return_code
= WEXITSTATUS(ret
);
1031 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1033 jail_return_code
= WTERMSIG(ret
);
1034 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1040 static struct uloop_process jail_process
= {
1041 .cb
= jail_process_handler
,
1044 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1046 DEBUG("jail process failed to stop, sending SIGKILL\n");
1047 kill(jail_process
.pid
, SIGKILL
);
1050 static void jail_handle_signal(int signo
)
1053 DEBUG("forwarding signal %d to the hook process\n", signo
);
1054 kill(hook_process
.pid
, signo
);
1058 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1059 kill(jail_process
.pid
, signo
);
1063 static void signals_init(void)
1068 sigfillset(&sigmask
);
1069 for (i
= 0; i
< _NSIG
; i
++) {
1070 struct sigaction s
= { 0 };
1072 if (!sigismember(&sigmask
, i
))
1074 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1077 s
.sa_handler
= jail_handle_signal
;
1078 sigaction(i
, &s
, NULL
);
1082 static void pre_exec_jail(struct uloop_timeout
*t
);
1083 static struct uloop_timeout pre_exec_timeout
= {
1084 .cb
= pre_exec_jail
,
1088 static int exec_jail(void *arg
)
1098 setns_open(CLONE_NEWUSER
);
1099 setns_open(CLONE_NEWNET
);
1100 setns_open(CLONE_NEWNS
);
1101 setns_open(CLONE_NEWIPC
);
1102 setns_open(CLONE_NEWUTS
);
1105 if (write(pipes
[1], buf
, 1) < 1) {
1106 ERROR("can't write to parent\n");
1107 return EXIT_FAILURE
;
1110 if (read(pipes
[2], buf
, 1) < 1) {
1111 ERROR("can't read from parent\n");
1112 return EXIT_FAILURE
;
1114 if (buf
[0] != 'O') {
1115 ERROR("parent had an error, child exiting\n");
1116 return EXIT_FAILURE
;
1119 if (opts
.namespace & CLONE_NEWCGROUP
)
1120 unshare(CLONE_NEWCGROUP
);
1122 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1123 if (setregid(0, 0) < 0) {
1127 if (setreuid(0, 0) < 0) {
1131 if (setgroups(0, NULL
) < 0) {
1132 ERROR("setgroups\n");
1137 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1138 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1139 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1143 uloop_timeout_add(&pre_exec_timeout
);
1149 static void pre_exec_jail(struct uloop_timeout
*t
)
1151 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1152 ERROR("failed to build jail fs\n");
1155 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1159 static void post_start_hook(void);
1160 static void post_jail_fs(void)
1164 if (read(pipes
[2], buf
, 1) < 1) {
1165 ERROR("can't read from parent\n");
1168 if (buf
[0] != '!') {
1169 ERROR("parent had an error, child exiting\n");
1174 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1177 static void post_start_hook(void)
1179 int pw_uid
, pw_gid
, gr_gid
;
1181 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1182 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1186 /* drop capabilities, retain those still needed to further setup jail */
1187 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1190 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1191 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1192 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1194 if (opts
.additional_gids
&&
1195 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1196 ERROR("setgroups failed: %m\n");
1203 if (prctl(PR_SET_SECUREBITS
, 0)) {
1204 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1208 /* drop remaining capabilities to end up with specified sets */
1209 if (applyOCIcapabilities(opts
.capset
, 0))
1212 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1213 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1217 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1221 if (opts
.cwd
&& chdir(opts
.cwd
))
1224 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1229 INFO("exec-ing %s\n", *opts
.jail_argv
);
1230 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1231 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1233 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1235 /* we get there only if execve fails */
1236 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1240 static int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1242 char pid_pid_path
[PATH_MAX
];
1244 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1246 return open(pid_pid_path
, O_RDONLY
);
1249 static void netns_updown(pid_t pid
, bool start
)
1251 static struct blob_buf req
;
1257 blob_buf_init(&req
, 0);
1258 blobmsg_add_string(&req
, "jail", opts
.name
);
1259 blobmsg_add_u32(&req
, "pid", pid
);
1260 blobmsg_add_u8(&req
, "start", start
);
1262 if (ubus_lookup_id(parent_ctx
, "network", &id
) ||
1263 ubus_invoke(parent_ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1264 INFO("ubus request failed\n");
1266 blob_buf_free(&req
);
1269 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1271 struct blob_attr
*cur
;
1274 blobmsg_for_each_attr(cur
, msg
, rem
)
1278 *envp
= calloc(1 + sz
, sizeof(char*));
1287 blobmsg_for_each_attr(cur
, msg
, rem
)
1288 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1302 static const struct blobmsg_policy oci_root_policy
[] = {
1303 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1304 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1307 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1309 static char rootpath
[PATH_MAX
] = { 0 };
1310 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1313 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1315 if (!tb
[OCI_ROOT_PATH
])
1318 strncpy(rootpath
, jsonfile
, PATH_MAX
);
1319 cur
= strrchr(rootpath
, '/');
1325 strncat(rootpath
, blobmsg_get_string(tb
[OCI_ROOT_PATH
]), PATH_MAX
- (strlen(rootpath
) + 1));
1327 opts
.extroot
= rootpath
;
1329 if (tb
[OCI_ROOT_READONLY
])
1330 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1344 static const struct blobmsg_policy oci_hook_policy
[] = {
1345 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1346 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1347 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1348 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1352 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1354 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1355 struct blob_attr
*cur
;
1359 blobmsg_for_each_attr(cur
, msg
, rem
)
1365 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1371 blobmsg_for_each_attr(cur
, msg
, rem
) {
1372 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1374 if (!tb
[OCI_HOOK_PATH
]) {
1379 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1380 if (tb
[OCI_HOOK_ARGS
]) {
1381 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1385 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1386 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1387 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1391 if (tb
[OCI_HOOK_ENV
]) {
1392 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1397 if (tb
[OCI_HOOK_TIMEOUT
])
1398 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1400 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1405 (*hooklist
)[idx
] = NULL
;
1407 DEBUG("added %d hooks\n", idx
);
1412 free_hooklist(*hooklist
);
1421 OCI_HOOKS_CREATERUNTIME
,
1422 OCI_HOOKS_CREATECONTAINER
,
1423 OCI_HOOKS_STARTCONTAINER
,
1424 OCI_HOOKS_POSTSTART
,
1429 static const struct blobmsg_policy oci_hooks_policy
[] = {
1430 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1431 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1432 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1433 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1434 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1435 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1438 static int parseOCIhooks(struct blob_attr
*msg
)
1440 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1443 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1445 if (tb
[OCI_HOOKS_PRESTART
])
1446 INFO("warning: ignoring deprecated prestart hook\n");
1448 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1449 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1454 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1455 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1457 goto out_createruntime
;
1460 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1461 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1463 goto out_createcontainer
;
1466 if (tb
[OCI_HOOKS_POSTSTART
]) {
1467 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1469 goto out_startcontainer
;
1472 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1473 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1481 free_hooklist(opts
.hooks
.poststart
);
1483 free_hooklist(opts
.hooks
.startContainer
);
1484 out_createcontainer
:
1485 free_hooklist(opts
.hooks
.createContainer
);
1487 free_hooklist(opts
.hooks
.createRuntime
);
1494 OCI_PROCESS_USER_UID
,
1495 OCI_PROCESS_USER_GID
,
1496 OCI_PROCESS_USER_UMASK
,
1497 OCI_PROCESS_USER_ADDITIONALGIDS
,
1498 __OCI_PROCESS_USER_MAX
,
1501 static const struct blobmsg_policy oci_process_user_policy
[] = {
1502 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1503 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1504 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1505 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1508 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1509 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1510 struct blob_attr
*cur
;
1514 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1516 if (tb
[OCI_PROCESS_USER_UID
])
1517 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1519 if (tb
[OCI_PROCESS_USER_GID
]) {
1520 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1521 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1525 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1528 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1530 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1535 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1538 /* always add primary GID to set of GIDs if set */
1540 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1542 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1543 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1545 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1547 opts
.num_additional_gids
= gidcnt
;
1549 DEBUG("read %zu additional groups\n", gidcnt
);
1552 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1553 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1554 opts
.set_umask
= true;
1561 OCI_PROCESS_RLIMIT_TYPE
,
1562 OCI_PROCESS_RLIMIT_SOFT
,
1563 OCI_PROCESS_RLIMIT_HARD
,
1564 __OCI_PROCESS_RLIMIT_MAX
,
1567 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1568 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1569 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1570 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1573 /* from manpage GETRLIMIT(2) */
1574 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1576 [RLIMIT_CORE
] = "CORE",
1577 [RLIMIT_CPU
] = "CPU",
1578 [RLIMIT_DATA
] = "DATA",
1579 [RLIMIT_FSIZE
] = "FSIZE",
1580 [RLIMIT_LOCKS
] = "LOCKS",
1581 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1582 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1583 [RLIMIT_NICE
] = "NICE",
1584 [RLIMIT_NOFILE
] = "NOFILE",
1585 [RLIMIT_NPROC
] = "NPROC",
1586 [RLIMIT_RSS
] = "RSS",
1587 [RLIMIT_RTPRIO
] = "RTPRIO",
1588 [RLIMIT_RTTIME
] = "RTTIME",
1589 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1590 [RLIMIT_STACK
] = "STACK",
1593 static int resolve_rlimit(char *type
) {
1594 unsigned int rltype
;
1596 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1597 if (rlimit_names
[rltype
] &&
1598 !strncmp("RLIMIT_", type
, 7) &&
1599 !strcmp(rlimit_names
[rltype
], type
+ 7))
1606 static int parseOCIrlimit(struct blob_attr
*msg
)
1608 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1610 struct rlimit
*curlim
;
1612 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1614 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1615 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1616 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1619 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1624 if (opts
.rlimits
[limtype
])
1627 curlim
= malloc(sizeof(struct rlimit
));
1628 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1629 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1631 opts
.rlimits
[limtype
] = curlim
;
1638 OCI_PROCESS_CAPABILITIES
,
1641 OCI_PROCESS_OOMSCOREADJ
,
1642 OCI_PROCESS_NONEWPRIVILEGES
,
1643 OCI_PROCESS_RLIMITS
,
1644 OCI_PROCESS_TERMINAL
,
1649 static const struct blobmsg_policy oci_process_policy
[] = {
1650 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1651 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1652 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1653 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1654 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1655 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1656 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1657 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1658 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1662 static int parseOCIprocess(struct blob_attr
*msg
)
1664 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1667 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1669 if (!tb
[OCI_PROCESS_ARGS
])
1672 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1676 if (tb
[OCI_PROCESS_TERMINAL
])
1677 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1679 if (tb
[OCI_PROCESS_NONEWPRIVILEGES
])
1680 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1682 if (tb
[OCI_PROCESS_CWD
])
1683 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1685 if (tb
[OCI_PROCESS_ENV
]) {
1686 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1691 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1694 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1695 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1698 if (tb
[OCI_PROCESS_RLIMITS
]) {
1699 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1700 res
= parseOCIrlimit(cur
);
1706 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1707 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1708 opts
.set_oom_score_adj
= true;
1715 OCI_LINUX_NAMESPACE_TYPE
,
1716 OCI_LINUX_NAMESPACE_PATH
,
1717 __OCI_LINUX_NAMESPACE_MAX
,
1720 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1721 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1722 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1725 static int resolve_nstype(char *type
) {
1726 if (!strcmp("pid", type
))
1727 return CLONE_NEWPID
;
1728 else if (!strcmp("network", type
))
1729 return CLONE_NEWNET
;
1730 else if (!strcmp("mount", type
))
1732 else if (!strcmp("ipc", type
))
1733 return CLONE_NEWIPC
;
1734 else if (!strcmp("uts", type
))
1735 return CLONE_NEWUTS
;
1736 else if (!strcmp("user", type
))
1737 return CLONE_NEWUSER
;
1738 else if (!strcmp("cgroup", type
))
1739 return CLONE_NEWCGROUP
;
1740 #ifdef CLONE_NEWTIME
1741 else if (!strcmp("time", type
))
1742 return CLONE_NEWTIME
;
1748 static int parseOCIlinuxns(struct blob_attr
*msg
)
1750 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1755 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1757 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1760 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1764 if (opts
.namespace & nstype
)
1767 setns
= get_namespace_fd(nstype
);
1775 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1776 DEBUG("opening existing %s namespace from path %s\n",
1777 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1778 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1780 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1782 return errno
?:ESTALE
;
1784 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
)
1787 DEBUG("opened existing %s namespace got filehandler %u\n",
1788 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1793 opts
.namespace |= nstype
;
1801 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1802 OCI_LINUX_UIDGIDMAP_HOSTID
,
1803 OCI_LINUX_UIDGIDMAP_SIZE
,
1804 __OCI_LINUX_UIDGIDMAP_MAX
,
1807 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1808 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1809 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1810 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1813 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1815 const char *map_format
= "%d %d %d\n";
1816 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1817 struct blob_attr
*cur
;
1821 unsigned int cnt
= 0;
1822 size_t totallen
= 0;
1824 /* count number of mappings */
1825 blobmsg_for_each_attr(cur
, msg
, rem
)
1831 /* allocate array for mappings */
1832 mappings
= calloc(1 + cnt
, sizeof(char*));
1836 mappings
[cnt
] = NULL
;
1839 blobmsg_for_each_attr(cur
, msg
, rem
) {
1840 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1842 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1843 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1844 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1847 /* write mapping line into allocated string */
1848 len
= asprintf(&mappings
[cnt
++], map_format
,
1849 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1850 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1851 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1859 /* allocate combined mapping string */
1860 map
= calloc(1 + totallen
, sizeof(char));
1866 /* concatenate mapping strings into combined string */
1867 curstr
= mappings
[0];
1869 strcat(map
, curstr
);
1887 OCI_DEVICES_FILEMODE
,
1893 static const struct blobmsg_policy oci_devices_policy
[] = {
1894 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1895 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1896 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
1897 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
1898 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
1899 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1900 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
1903 static mode_t
resolve_devtype(char *tstr
)
1905 if (!strcmp("c", tstr
) ||
1908 else if (!strcmp("b", tstr
))
1910 else if (!strcmp("p", tstr
))
1916 static int parseOCIdevices(struct blob_attr
*msg
)
1918 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
1919 struct blob_attr
*cur
;
1922 struct mknod_args
*tmp
;
1924 blobmsg_for_each_attr(cur
, msg
, rem
)
1927 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
1930 blobmsg_for_each_attr(cur
, msg
, rem
) {
1931 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1932 if (!tb
[OCI_DEVICES_TYPE
] ||
1933 !tb
[OCI_DEVICES_PATH
])
1936 tmp
= calloc(1, sizeof(struct mknod_args
));
1940 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1944 if (tmp
->mode
!= S_IFIFO
) {
1945 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
])
1948 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
1949 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
1952 if (tb
[OCI_DEVICES_FILEMODE
]) {
1953 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]))
1956 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
1958 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
1961 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
1963 if (tb
[OCI_DEVICES_UID
])
1964 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
1968 if (tb
[OCI_DEVICES_GID
])
1969 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
1973 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1974 opts
.devices
[cnt
++] = tmp
;
1977 opts
.devices
[cnt
] = NULL
;
1982 static int parseOCIsysctl(struct blob_attr
*msg
)
1984 struct blob_attr
*cur
;
1989 blobmsg_for_each_attr(cur
, msg
, rem
) {
1990 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
1999 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2004 blobmsg_for_each_attr(cur
, msg
, rem
) {
2005 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2006 if (!opts
.sysctl
[cnt
])
2009 /* replace '.' with '/' in entry name */
2010 tc
= tmp
= strdup(blobmsg_name(cur
));
2011 while ((tc
= strchr(tc
, '.')))
2014 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2015 opts
.sysctl
[cnt
]->entry
= tmp
;
2020 opts
.sysctl
[cnt
] = NULL
;
2027 OCI_LINUX_CGROUPSPATH
,
2028 OCI_LINUX_RESOURCES
,
2031 OCI_LINUX_NAMESPACES
,
2033 OCI_LINUX_UIDMAPPINGS
,
2034 OCI_LINUX_GIDMAPPINGS
,
2035 OCI_LINUX_MASKEDPATHS
,
2036 OCI_LINUX_READONLYPATHS
,
2037 OCI_LINUX_ROOTFSPROPAGATION
,
2041 static const struct blobmsg_policy oci_linux_policy
[] = {
2042 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2043 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2044 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2045 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2046 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2047 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2048 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2049 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2050 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2051 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2052 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2055 static int parseOCIlinux(struct blob_attr
*msg
)
2057 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2058 struct blob_attr
*cur
;
2062 char cgfullpath
[256] = "/sys/fs/cgroup";
2064 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2066 if (tb
[OCI_LINUX_NAMESPACES
]) {
2067 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2068 res
= parseOCIlinuxns(cur
);
2074 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2075 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2080 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2081 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2086 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2087 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2088 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, 0, NULL
, 0);
2094 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2095 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2096 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, 0, NULL
, 1);
2102 if (tb
[OCI_LINUX_SYSCTL
]) {
2103 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2108 if (tb
[OCI_LINUX_SECCOMP
]) {
2109 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2110 if (!opts
.ociseccomp
)
2114 if (tb
[OCI_LINUX_DEVICES
]) {
2115 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2120 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2121 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2122 if (cgpath
[0] == '/') {
2123 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2126 strcat(cgfullpath
, cgpath
);
2128 strcat(cgfullpath
, "/containers/");
2129 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2130 strcat(cgfullpath
, "/");
2131 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2134 strcat(cgfullpath
, cgpath
);
2137 strcat(cgfullpath
, "/containers/");
2138 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2139 strcat(cgfullpath
, "/");
2140 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2143 cgroups_init(cgfullpath
);
2145 if (tb
[OCI_LINUX_RESOURCES
]) {
2146 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2166 static const struct blobmsg_policy oci_policy
[] = {
2167 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2168 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2169 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2170 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2171 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2172 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2173 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2174 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2177 static int parseOCI(const char *jsonfile
)
2179 struct blob_attr
*tb
[__OCI_MAX
];
2180 struct blob_attr
*cur
;
2184 blob_buf_init(&ocibuf
, 0);
2185 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
))
2188 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2190 if (!tb
[OCI_VERSION
])
2193 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2194 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2198 if (tb
[OCI_HOSTNAME
])
2199 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2201 if (!tb
[OCI_PROCESS
])
2204 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2210 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2213 if (!tb
[OCI_MOUNTS
])
2216 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2217 if ((res
= parseOCImount(cur
)))
2220 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2223 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2226 if (tb
[OCI_ANNOTATIONS
])
2227 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2229 blob_buf_free(&ocibuf
);
2234 static int set_oom_score_adj(void)
2239 if (!opts
.set_oom_score_adj
)
2242 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2243 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2247 dprintf(f
, "%d", opts
.oom_score_adj
);
2261 static int jail_oci_state
= OCI_STATE_CREATED
;
2262 static void pipe_send_start_container(struct uloop_timeout
*t
);
2263 static struct uloop_timeout start_container_timeout
= {
2264 .cb
= pipe_send_start_container
,
2267 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2268 struct ubus_request_data
*req
, const char *method
,
2269 struct blob_attr
*msg
)
2271 if (jail_oci_state
!= OCI_STATE_CREATED
)
2272 return UBUS_STATUS_INVALID_ARGUMENT
;
2274 uloop_timeout_add(&start_container_timeout
);
2276 return UBUS_STATUS_OK
;
2279 static struct blob_buf bb
;
2280 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2281 struct ubus_request_data
*req
, const char *method
,
2282 struct blob_attr
*msg
)
2286 switch (jail_oci_state
) {
2287 case OCI_STATE_CREATING
:
2288 statusstr
= "creating";
2290 case OCI_STATE_CREATED
:
2291 statusstr
= "created";
2293 case OCI_STATE_RUNNING
:
2294 statusstr
= "running";
2296 case OCI_STATE_STOPPED
:
2297 statusstr
= "stopped";
2300 statusstr
= "unknown";
2303 blob_buf_init(&bb
, 0);
2304 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2305 blobmsg_add_string(&bb
, "id", opts
.name
);
2306 blobmsg_add_string(&bb
, "status", statusstr
);
2307 if (jail_oci_state
== OCI_STATE_CREATED
||
2308 jail_oci_state
== OCI_STATE_RUNNING
)
2309 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2311 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2313 if (opts
.annotations
)
2314 blobmsg_add_blob(&bb
, opts
.annotations
);
2316 ubus_send_reply(ctx
, req
, bb
.head
);
2318 return UBUS_STATUS_OK
;
2322 CONTAINER_KILL_ATTR_SIGNAL
,
2323 __CONTAINER_KILL_ATTR_MAX
,
2326 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2327 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2331 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2332 struct ubus_request_data
*req
, const char *method
,
2333 struct blob_attr
*msg
)
2335 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2338 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2340 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2342 sig
= blobmsg_get_u32(cur
);
2344 if (jail_oci_state
== OCI_STATE_CREATING
)
2345 return UBUS_STATUS_NOT_FOUND
;
2347 if (kill(jail_process
.pid
, sig
) == 0)
2351 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2352 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2353 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2356 return UBUS_STATUS_UNKNOWN_ERROR
;
2360 jail_writepid(pid_t pid
)
2367 _pidfile
= fopen(opts
.pidfile
, "w");
2368 if (_pidfile
== NULL
)
2371 if (fprintf(_pidfile
, "%d\n", pid
) < 0) {
2376 if (fclose(_pidfile
))
2382 static struct ubus_method container_methods
[] = {
2383 UBUS_METHOD_NOARG("start", handle_start
),
2384 UBUS_METHOD_NOARG("state", handle_state
),
2385 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2388 static struct ubus_object_type container_object_type
=
2389 UBUS_OBJECT_TYPE("container", container_methods
);
2391 static struct ubus_object container_object
= {
2392 .type
= &container_object_type
,
2393 .methods
= container_methods
,
2394 .n_methods
= ARRAY_SIZE(container_methods
),
2397 static void post_main(struct uloop_timeout
*t
);
2398 static struct uloop_timeout post_main_timeout
= {
2401 static int netns_fd
;
2402 static int pidns_fd
;
2403 #ifdef CLONE_NEWTIME
2404 static int timens_fd
;
2406 static void post_create_runtime(void);
2407 int main(int argc
, char **argv
)
2409 uid_t uid
= getuid();
2410 const char log
[] = "/dev/log";
2411 const char ubus
[] = "/var/run/ubus/ubus.sock";
2415 ERROR("not root, aborting: %m\n");
2416 return EXIT_FAILURE
;
2421 init_library_search();
2423 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2426 debug
= atoi(optarg
);
2429 opts
.namespace |= CLONE_NEWNS
;
2433 opts
.namespace |= CLONE_NEWNS
;
2437 opts
.namespace |= CLONE_NEWUSER
;
2440 opts
.namespace |= CLONE_NEWCGROUP
;
2443 opts
.extroot
= strdup(optarg
);
2446 opts
.namespace |= CLONE_NEWNS
;
2450 opts
.seccomp
= optarg
;
2451 add_mount_bind(optarg
, 1, -1);
2454 opts
.capabilities
= optarg
;
2457 opts
.no_new_privs
= 1;
2463 opts
.namespace |= CLONE_NEWNET
;
2466 opts
.namespace |= CLONE_NEWUTS
;
2467 opts
.hostname
= strdup(optarg
);
2470 opts
.namespace |= CLONE_NEWNS
;
2471 add_path_and_deps(optarg
, 1, 0, 0);
2474 opts
.namespace |= CLONE_NEWNS
;
2475 add_path_and_deps(optarg
, 0, 0, 0);
2478 opts
.namespace |= CLONE_NEWNS
;
2479 add_mount_bind(ubus
, 0, -1);
2482 opts
.namespace |= CLONE_NEWNS
;
2483 add_mount_bind(log
, 0, -1);
2489 opts
.group
= optarg
;
2492 opts
.overlaydir
= optarg
;
2495 opts
.tmpoverlaysize
= optarg
;
2498 opts
.require_jail
= 1;
2504 opts
.ocibundle
= strdup(optarg
);
2507 opts
.immediately
= true;
2510 opts
.pidfile
= strdup(optarg
);
2515 if (opts
.namespace && !opts
.ocibundle
)
2516 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2518 /* those are filehandlers, so -1 indicates unused */
2519 opts
.setns
.pid
= -1;
2520 opts
.setns
.net
= -1;
2522 opts
.setns
.ipc
= -1;
2523 opts
.setns
.uts
= -1;
2524 opts
.setns
.user
= -1;
2525 opts
.setns
.cgroup
= -1;
2526 #ifdef CLONE_NEWTIME
2527 opts
.setns
.time
= -1;
2530 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2531 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2535 if (opts
.ocibundle
) {
2539 asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
);
2540 ocires
= parseOCI(jsonfile
);
2543 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2548 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2549 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2553 /* no <binary> param found */
2554 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2556 return EXIT_FAILURE
;
2558 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
2559 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2561 return EXIT_FAILURE
;
2563 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2566 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2571 parent_ctx
= ubus_connect(NULL
);
2572 ubus_add_uloop(parent_ctx
);
2574 if (opts
.ocibundle
) {
2576 if (asprintf(&objname
, "container.%s", opts
.name
) < 0)
2579 container_object
.name
= objname
;
2580 ret
= ubus_add_object(parent_ctx
, &container_object
);
2582 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2587 /* deliberately not using 'else' on unrelated conditional branches */
2588 if (!opts
.ocibundle
) {
2589 /* allocate NULL-terminated array for argv */
2590 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(char**));
2591 if (!opts
.jail_argv
)
2592 return EXIT_FAILURE
;
2594 for (size_t s
= optind
; s
< argc
; s
++)
2595 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2597 if (opts
.namespace & CLONE_NEWUSER
)
2598 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2601 if (!opts
.extroot
) {
2602 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2603 ERROR("failed to load dependencies\n");
2608 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2609 ERROR("failed to load libpreload-seccomp.so\n");
2611 if (opts
.require_jail
)
2615 uloop_timeout_add(&post_main_timeout
);
2622 static void post_main(struct uloop_timeout
*t
)
2624 if (apply_rlimits()) {
2625 ERROR("error applying resource limits\n");
2630 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2632 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2635 if (has_namespaces()) {
2636 if (opts
.namespace & CLONE_NEWNS
) {
2637 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2638 add_mount_bind("/etc/passwd", 1, -1);
2639 add_mount_bind("/etc/group", 1, -1);
2642 #if defined(__GLIBC__)
2644 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2647 if (!(opts
.namespace & CLONE_NEWNET
)) {
2648 add_mount_bind("/etc/resolv.conf", 1, -1);
2649 } else if (opts
.setns
.net
== -1) {
2650 char hostdir
[PATH_MAX
];
2652 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2653 mkdir_p(hostdir
, 0755);
2654 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, 0, NULL
, -1);
2657 /* default mounts */
2658 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "size=1M", -1);
2659 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2661 if (opts
.procfs
|| opts
.ocibundle
) {
2662 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0, NULL
, -1);
2665 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2666 * which cannot be expressed with OCI spec, but happends to be very useful.
2667 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2669 * If not running in a new network namespace, only make /proc/sys read-only.
2670 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2671 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2672 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2674 * This works because mounts are executed in incrementing strcmp() order and
2675 * /proc/self/net appears there before /proc/sys/net and hence the operation
2676 * succeeds as the bind-mount of /proc/self/net is performed first and then
2677 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2678 * table (and in the alphabet).
2680 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, 0, NULL
, -1))
2681 if (opts
.namespace & CLONE_NEWNET
)
2682 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0, NULL
, -1))
2683 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0, NULL
, -1);
2686 if (opts
.sysfs
|| opts
.ocibundle
)
2687 add_mount("sysfs", "/sys", "sysfs", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0, NULL
, -1);
2690 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, 0, "mode=1777", -1);
2694 if (opts
.setns
.pid
!= -1) {
2695 pidns_fd
= ns_open_pid("pid", getpid());
2696 setns_open(CLONE_NEWPID
);
2701 #ifdef CLONE_NEWTIME
2702 if (opts
.setns
.time
!= -1) {
2703 timens_fd
= ns_open_pid("time", getpid());
2704 setns_open(CLONE_NEWTIME
);
2708 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
2710 jail_process
.pid
= fork();
2713 if (jail_process
.pid
> 0) {
2714 /* parent process */
2717 uloop_process_add(&jail_process
);
2720 if (pidns_fd
!= -1) {
2721 setns(pidns_fd
, CLONE_NEWPID
);
2724 #ifdef CLONE_NEWTIME
2725 if (timens_fd
!= -1)
2726 setns(timens_fd
, CLONE_NEWTIME
);
2730 if (opts
.setns
.net
!= -1)
2731 close(opts
.setns
.net
);
2732 if (opts
.setns
.ns
!= -1)
2733 close(opts
.setns
.ns
);
2734 if (opts
.setns
.ipc
!= -1)
2735 close(opts
.setns
.ipc
);
2736 if (opts
.setns
.uts
!= -1)
2737 close(opts
.setns
.uts
);
2738 if (opts
.setns
.user
!= -1)
2739 close(opts
.setns
.user
);
2740 if (opts
.setns
.cgroup
!= -1)
2741 close(opts
.setns
.cgroup
);
2744 if (read(pipes
[0], sig_buf
, 1) < 1) {
2745 ERROR("can't read from child\n");
2749 set_oom_score_adj();
2752 cgroups_apply(jail_process
.pid
);
2754 if (opts
.namespace & CLONE_NEWUSER
) {
2755 if (write_setgroups(jail_process
.pid
, true)) {
2756 ERROR("can't write setgroups\n");
2760 bool has_gr
= (opts
.gr_gid
!= -1);
2761 if (opts
.pw_uid
!= -1) {
2762 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2763 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2765 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2766 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2769 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2771 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2775 if (opts
.namespace & CLONE_NEWNET
) {
2777 ERROR("netns needs a named jail\n");
2780 netns_fd
= ns_open_pid("net", jail_process
.pid
);
2781 netns_updown(jail_process
.pid
, true);
2783 if (jail_writepid(jail_process
.pid
)) {
2784 ERROR("failed to write pidfile: %m\n");
2787 } else if (jail_process
.pid
== 0) {
2788 /* fork child process */
2789 exit(exec_jail(NULL
));
2791 ERROR("failed to clone/fork: %m\n");
2794 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
2797 static void post_poststart(void);
2798 static void post_create_runtime(void)
2803 if (write(pipes
[3], sig_buf
, 1) < 0) {
2804 ERROR("can't write to child\n");
2808 jail_oci_state
= OCI_STATE_CREATED
;
2809 if (opts
.ocibundle
&& !opts
.immediately
)
2810 uloop_run(); /* wait for 'start' command via ubus */
2812 pipe_send_start_container(NULL
);
2815 static void pipe_send_start_container(struct uloop_timeout
*t
)
2819 jail_oci_state
= OCI_STATE_RUNNING
;
2821 if (write(pipes
[3], sig_buf
, 1) < 0) {
2822 ERROR("can't write to child\n");
2827 run_hooks(opts
.hooks
.poststart
, post_poststart
);
2830 static void post_poststart(void)
2832 uloop_run(); /* idle here while jail is running */
2834 DEBUG("uloop interrupted, killing jail process\n");
2835 kill(jail_process
.pid
, SIGTERM
);
2836 uloop_timeout_set(&jail_process_timeout
, 1000);
2843 static void post_poststop(void);
2844 static void poststop(void) {
2845 if (opts
.namespace & CLONE_NEWNET
) {
2846 setns(netns_fd
, CLONE_NEWNET
);
2847 netns_updown(getpid(), false);
2850 run_hooks(opts
.hooks
.poststop
, post_poststop
);
2853 static void post_poststop(void)
2857 ubus_free(parent_ctx
);
2859 exit(jail_return_code
);