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
43 #include <linux/filter.h>
44 #include <linux/limits.h>
45 #include <linux/nsfs.h>
46 #include <linux/securebits.h>
50 #include "capabilities.h"
55 #include "seccomp-oci.h"
59 #include <libubox/blobmsg.h>
60 #include <libubox/blobmsg_json.h>
61 #include <libubox/list.h>
62 #include <libubox/vlist.h>
63 #include <libubox/uloop.h>
64 #include <libubox/utils.h>
67 #ifndef CLONE_NEWCGROUP
68 #define CLONE_NEWCGROUP 0x02000000
71 #define STACK_SIZE (1024 * 1024)
72 #define OPT_ARGS "cC:d:e:EfFG:h:ij:J:ln:NoO:pP:r:R:sS:uU:w:t:T:y"
74 #define OCI_VERSION_STRING "1.0.2"
102 struct sock_fprog
*ociseccomp
;
104 struct jail_capset capset
;
109 char *tmpoverlaysize
;
114 struct sysctl_val
**sysctl
;
137 gid_t
*additional_gids
;
138 size_t num_additional_gids
;
143 struct hook_execvpe
**createRuntime
;
144 struct hook_execvpe
**createContainer
;
145 struct hook_execvpe
**startContainer
;
146 struct hook_execvpe
**poststart
;
147 struct hook_execvpe
**poststop
;
149 struct rlimit
*rlimits
[RLIM_NLIMITS
];
151 bool set_oom_score_adj
;
152 struct mknod_args
**devices
;
155 struct blob_attr
*annotations
;
159 static struct blob_buf ocibuf
;
161 extern int pivot_root(const char *new_root
, const char *put_old
);
165 static char child_stack
[STACK_SIZE
];
167 static struct ubus_context
*parent_ctx
;
172 static inline bool has_namespaces(void)
174 return ((opts
.setns
.pid
!= -1) ||
175 (opts
.setns
.net
!= -1) ||
176 (opts
.setns
.ns
!= -1) ||
177 (opts
.setns
.ipc
!= -1) ||
178 (opts
.setns
.uts
!= -1) ||
179 (opts
.setns
.user
!= -1) ||
180 (opts
.setns
.cgroup
!= -1) ||
182 (opts
.setns
.time
!= -1) ||
187 static void free_oci_envp(char **p
) {
199 static void free_hooklist(struct hook_execvpe
**hooklist
)
201 struct hook_execvpe
*cur
;
208 free_oci_envp(cur
->argv
);
209 free_oci_envp(cur
->envp
);
216 static void free_sysctl(void) {
217 struct sysctl_val
*cur
;
232 static void free_devices(void) {
233 struct mknod_args
**cur
;
247 static void free_rlimits(void) {
250 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
251 free(opts
.rlimits
[type
]);
254 static void free_opts(bool parent
) {
256 free_library_search();
260 /* we need to keep argv, envp and seccomp filter in child */
261 if (parent
) { /* parent-only */
262 if (opts
.ociseccomp
) {
263 free(opts
.ociseccomp
->filter
);
264 free(opts
.ociseccomp
);
267 free_oci_envp(opts
.jail_argv
);
268 free_oci_envp(opts
.envp
);
278 free(opts
.annotations
);
280 free(opts
.overlaydir
);
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);
326 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
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
))
333 goto upper_resolvconf_printf
;
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
);
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
, "bind", MS_BIND
, NULL
))
402 /* use PTY slave for stdio */
403 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
404 if (slave_console_fd
< 0)
407 dup2(slave_console_fd
, 0);
408 dup2(slave_console_fd
, 1);
409 dup2(slave_console_fd
, 2);
410 close(slave_console_fd
);
412 INFO("using guest console %s\n", console_fname
);
421 static int hook_running
= 0;
422 static int hook_return_code
= 0;
423 static struct hook_execvpe
**current_hook
= NULL
;
424 typedef void (*hook_return_handler
)(void);
425 static hook_return_handler hook_return_cb
= NULL
;
427 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
428 static struct uloop_timeout hook_process_timeout
= {
429 .cb
= hook_process_timeout_cb
,
432 static void run_hooklist(void);
433 static void hook_process_handler(struct uloop_process
*c
, int ret
)
435 uloop_timeout_cancel(&hook_process_timeout
);
437 if (WIFEXITED(ret
)) {
438 hook_return_code
= WEXITSTATUS(ret
);
439 if (hook_return_code
)
440 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
442 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
445 hook_return_code
= WTERMSIG(ret
);
446 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
453 static struct uloop_process hook_process
= {
454 .cb
= hook_process_handler
,
457 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
459 DEBUG("hook process failed to stop, sending SIGKILL\n");
460 kill(hook_process
.pid
, SIGKILL
);
463 static void run_hooklist(void)
465 struct hook_execvpe
*hook
= *current_hook
;
469 return hook_return_cb();
471 DEBUG("executing hook %s\n", hook
->file
);
473 if (stat(hook
->file
, &s
))
474 hook_process_handler(&hook_process
, ENOENT
);
476 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
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 if (asprintf(&procdir
, "%s/proc", jail_root
) < 0)
531 mkdir(procdir
, 0700);
532 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
538 if (asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
) < 0)
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
);
549 if (write(f
, (*cur
)->value
, strlen((*cur
)->value
)) < 0) {
550 ERROR("sysctl: write to %s\n", fname
);
567 /* glibc defines makedev calling a function. make sure it's a pure macro */
568 #if defined(__GLIBC__)
570 /* from musl's sys/sysmacros.h */
571 #define makedev(x,y) ( \
572 (((x)&0xfffff000ULL) << 32) | \
573 (((x)&0x00000fffULL) << 8) | \
574 (((y)&0xffffff00ULL) << 12) | \
575 (((y)&0x000000ffULL)) )
578 static struct mknod_args default_devices
[] = {
579 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
580 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
581 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
582 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
583 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
584 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
588 static int create_devices(void)
590 struct mknod_args
**cur
, *curdef
;
595 goto only_default_devices
;
601 /* don't allow devices outside of /dev */
602 if (strncmp(path
, "/dev", 4))
605 /* make sure parent folder exists */
606 tmp
= strrchr(path
, '/');
611 if (strcmp(path
, "/dev")) {
612 DEBUG("creating directory %s\n", path
);
618 DEBUG("creating %s (mode=%08o)\n", path
, (*cur
)->mode
);
621 if (mknod(path
, (*cur
)->mode
, (*cur
)->dev
))
624 /* change owner, if needed */
625 if (((*cur
)->uid
|| (*cur
)->gid
) &&
626 chown(path
, (*cur
)->uid
, (*cur
)->gid
))
632 only_default_devices
:
633 curdef
= default_devices
;
634 while(curdef
->path
) {
635 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
636 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
638 continue; /* may already exist, eg. due to a bind-mount */
640 if ((curdef
->uid
|| curdef
->gid
) &&
641 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
647 /* Dev symbolic links as defined in OCI spec */
648 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
650 WARNING("symlink() failed to create link to /dev/pts/ptmx");
652 ret
= symlink("/proc/self/fd", "/dev/fd");
654 WARNING("symlink() failed to create link to /proc/self/fd");
656 ret
= symlink("/proc/self/fd/0", "/dev/stdin");
658 WARNING("symlink() failed to create link to /proc/self/fd/0");
660 ret
= symlink("/proc/self/fd/1", "/dev/stdout");
662 WARNING("symlink() failed to create link to /proc/self/fd/1");
664 ret
= symlink("/proc/self/fd/2", "/dev/stderr");
666 WARNING("symlink() failed to create link to /proc/self/fd/2");
671 static char jail_root
[] = "/tmp/ujail-XXXXXX";
672 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
673 static mode_t old_umask
;
674 static void enter_jail_fs(void);
675 static int build_jail_fs(void)
677 char *overlaydir
= NULL
;
680 old_umask
= umask(0);
682 if (mkdtemp(jail_root
) == NULL
) {
683 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
687 if (apply_sysctl(jail_root
)) {
688 ERROR("failed to apply sysctl values\n");
692 /* oldroot can't be MS_SHARED else pivot_root() fails */
693 if (mount("none", "/", "none", MS_REC
|MS_PRIVATE
, NULL
)) {
694 ERROR("private mount failed %m\n");
699 if (mount(opts
.extroot
, jail_root
, "bind", MS_BIND
, NULL
)) {
700 ERROR("extroot mount failed %m\n");
704 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
705 ERROR("tmpfs mount failed %m\n");
710 if (opts
.tmpoverlaysize
) {
711 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
713 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
714 "mode=0755,size=%s", opts
.tmpoverlaysize
);
715 if (mkdtemp(tmpovdir
) == NULL
) {
716 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
719 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
721 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
724 overlaydir
= tmpovdir
;
728 overlaydir
= opts
.overlaydir
;
731 ret
= mount_overlay(jail_root
, overlaydir
);
736 if (chdir(jail_root
)) {
737 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
741 if (mount_all(jail_root
)) {
742 ERROR("mount_all() failed\n");
747 create_dev_console(jail_root
);
749 /* make sure /etc/resolv.conf exists if in new network namespace */
750 if (opts
.namespace & CLONE_NEWNET
) {
751 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
753 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
754 mkdir_p(jailetc
, 0755);
755 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
759 ret
= symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
761 WARNING("symlink() failed to create link to ../dev/resolv.conf.d/resolv.conf.auto");
764 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
769 static bool exit_from_child
;
770 static void free_and_exit(int ret
)
772 if (!exit_from_child
&& opts
.ocibundle
)
775 if (!exit_from_child
&& parent_ctx
)
776 ubus_free(parent_ctx
);
778 free_opts(!exit_from_child
);
783 static void post_jail_fs(void);
784 static void enter_jail_fs(void)
786 char dirbuf
[sizeof(jail_root
) + 4];
788 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
791 if (pivot_root(jail_root
, dirbuf
) == -1) {
792 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
796 ERROR("chdir(/) (after pivot_root) failed: %m\n");
800 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
801 umount2(dirbuf
, MNT_DETACH
);
803 if (opts
.tmpoverlaysize
) {
804 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
805 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
806 umount2(tmpdirbuf
, MNT_DETACH
);
810 umount2("/old", MNT_DETACH
);
813 if (create_devices()) {
814 ERROR("create_devices() failed\n");
818 mount(NULL
, "/", "bind", MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
824 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
829 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
830 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
833 if ((map_file
= open(map_path
, O_WRONLY
)) < 0)
836 if (dprintf(map_file
, "%s", mapstr
)) {
845 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
849 const char *map_format
= "%d %d %d\n";
850 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
851 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
854 if ((map_file
= open(map_path
, O_WRONLY
)) < 0)
857 if (dprintf(map_file
, map_format
, 0, id
, 1) < 0) {
866 static int write_setgroups(pid_t child_pid
, bool allow
)
869 char setgroups_path
[64];
871 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
876 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) < 0) {
880 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
881 close(setgroups_file
);
885 close(setgroups_file
);
889 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
891 struct passwd
*p
= NULL
;
892 struct group
*g
= NULL
;
895 p
= getpwnam(opts
.user
);
897 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
898 opts
.user
, errno
, strerror(errno
));
899 free_and_exit(EXIT_FAILURE
);
902 *user_gid
= p
->pw_gid
;
909 g
= getgrnam(opts
.group
);
911 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
912 free_and_exit(EXIT_FAILURE
);
920 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
922 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
923 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
924 free_and_exit(EXIT_FAILURE
);
927 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
928 ERROR("failed to set group id %d: %m\n", gr_gid
);
929 free_and_exit(EXIT_FAILURE
);
932 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
933 ERROR("failed to set user id %d: %m\n", pw_uid
);
934 free_and_exit(EXIT_FAILURE
);
938 static int apply_rlimits(void)
942 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
943 if (opts
.rlimits
[resource
])
944 DEBUG("applying limits to resource %u\n", resource
);
946 if (opts
.rlimits
[resource
] &&
947 setrlimit(resource
, opts
.rlimits
[resource
]))
955 static char** build_envp(const char *seccomp
, char **ocienvp
)
957 static char *envp
[MAX_ENVP
];
958 static char preload_var
[PATH_MAX
];
959 static char seccomp_var
[PATH_MAX
];
960 static char seccomp_debug_var
[20];
961 static char debug_var
[] = "LD_DEBUG=all";
962 static char container_var
[] = "container=ujail";
963 const char *preload_lib
= find_lib("libpreload-seccomp.so");
968 if (seccomp
&& !preload_lib
) {
969 ERROR("failed to add preload-lib to env\n");
973 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
974 envp
[count
++] = seccomp_var
;
975 snprintf(seccomp_debug_var
, sizeof(seccomp_debug_var
), "SECCOMP_DEBUG=%2d", debug
);
976 envp
[count
++] = seccomp_debug_var
;
977 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
978 envp
[count
++] = preload_var
;
981 envp
[count
++] = container_var
;
984 envp
[count
++] = debug_var
;
987 while (addenv
&& *addenv
) {
988 envp
[count
++] = *(addenv
++);
989 if (count
>= MAX_ENVP
) {
990 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
997 static void usage(void)
999 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
1000 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
1001 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
1002 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
1003 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
1004 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
1005 fprintf(stderr
, " -e <var>\timport environment variable\n");
1006 fprintf(stderr
, "namespace jail options:\n");
1007 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
1008 fprintf(stderr
, " -N\t\tjail has network namespace\n");
1009 fprintf(stderr
, " -f\t\tjail has user namespace\n");
1010 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
1011 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
1012 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
1013 fprintf(stderr
, " -p\t\tjail has /proc\n");
1014 fprintf(stderr
, " -s\t\tjail has /sys\n");
1015 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
1016 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
1017 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
1018 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
1019 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
1020 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
1021 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
1022 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
1023 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
1024 fprintf(stderr
, " -y\t\tprovide jail console\n");
1025 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
1026 fprintf(stderr
, " -i\t\tstart container immediately\n");
1027 fprintf(stderr
, " -P <pidfile>\tcreate <pidfile>\n");
1028 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
1029 and he has the same powers as root outside the jail,\n\
1030 thus he can escape the jail and/or break stuff.\n\
1031 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
1032 If you use none of the namespace jail options,\n\
1033 ujail will not use namespace/build a jail,\n\
1034 and will only drop capabilities/apply seccomp filter.\n\n");
1037 static int* get_namespace_fd(const unsigned int nstype
)
1041 return &opts
.setns
.pid
;
1043 return &opts
.setns
.net
;
1045 return &opts
.setns
.ns
;
1047 return &opts
.setns
.ipc
;
1049 return &opts
.setns
.uts
;
1051 return &opts
.setns
.user
;
1052 case CLONE_NEWCGROUP
:
1053 return &opts
.setns
.cgroup
;
1054 #ifdef CLONE_NEWTIME
1056 return &opts
.setns
.time
;
1063 static int setns_open(unsigned long nstype
)
1065 int *fd
= get_namespace_fd(nstype
);
1072 if (setns(*fd
, nstype
) == -1) {
1081 static int jail_running
= 0;
1082 static int jail_return_code
= 0;
1084 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1085 static struct uloop_timeout jail_process_timeout
= {
1086 .cb
= jail_process_timeout_cb
,
1088 static void poststop(void);
1089 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1091 uloop_timeout_cancel(&jail_process_timeout
);
1092 if (WIFEXITED(ret
)) {
1093 jail_return_code
= WEXITSTATUS(ret
);
1094 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1096 jail_return_code
= WTERMSIG(ret
);
1097 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1103 static struct uloop_process jail_process
= {
1104 .cb
= jail_process_handler
,
1107 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1109 DEBUG("jail process failed to stop, sending SIGKILL\n");
1110 kill(jail_process
.pid
, SIGKILL
);
1113 static void jail_handle_signal(int signo
)
1116 DEBUG("forwarding signal %d to the hook process\n", signo
);
1117 kill(hook_process
.pid
, signo
);
1118 /* set timeout to send SIGKILL hook process in case SIGTERM doesn't succeed */
1119 if (signo
== SIGTERM
)
1120 uloop_timeout_set(&hook_process_timeout
, opts
.term_timeout
* 1000);
1124 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1125 kill(jail_process
.pid
, signo
);
1126 /* set timeout to send SIGKILL jail process in case SIGTERM doesn't succeed */
1127 if (signo
== SIGTERM
)
1128 uloop_timeout_set(&jail_process_timeout
, opts
.term_timeout
* 1000);
1132 static void signals_init(void)
1137 sigfillset(&sigmask
);
1138 for (i
= 0; i
< _NSIG
; i
++) {
1139 struct sigaction s
= { 0 };
1141 if (!sigismember(&sigmask
, i
))
1143 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
) || (i
== SIGSTOP
) || (i
== SIGKILL
))
1146 s
.sa_handler
= jail_handle_signal
;
1147 sigaction(i
, &s
, NULL
);
1151 static void pre_exec_jail(struct uloop_timeout
*t
);
1152 static struct uloop_timeout pre_exec_timeout
= {
1153 .cb
= pre_exec_jail
,
1157 static int exec_jail(void *arg
)
1161 exit_from_child
= true;
1162 prctl(PR_SET_SECUREBITS
, 0);
1170 setns_open(CLONE_NEWUSER
);
1171 setns_open(CLONE_NEWNET
);
1172 setns_open(CLONE_NEWNS
);
1173 setns_open(CLONE_NEWIPC
);
1174 setns_open(CLONE_NEWUTS
);
1177 if (write(pipes
[1], buf
, 1) < 1) {
1178 ERROR("can't write to parent\n");
1179 return EXIT_FAILURE
;
1182 if (read(pipes
[2], buf
, 1) < 1) {
1183 ERROR("can't read from parent\n");
1184 return EXIT_FAILURE
;
1186 if (buf
[0] != 'O') {
1187 ERROR("parent had an error, child exiting\n");
1188 return EXIT_FAILURE
;
1191 if (opts
.namespace & CLONE_NEWCGROUP
)
1192 unshare(CLONE_NEWCGROUP
);
1194 setns_open(CLONE_NEWCGROUP
);
1196 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1197 if (setregid(0, 0) < 0) {
1199 free_and_exit(EXIT_FAILURE
);
1201 if (setreuid(0, 0) < 0) {
1203 free_and_exit(EXIT_FAILURE
);
1205 if (setgroups(0, NULL
) < 0) {
1206 ERROR("setgroups\n");
1207 free_and_exit(EXIT_FAILURE
);
1211 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1212 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1213 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1214 free_and_exit(EXIT_FAILURE
);
1217 uloop_timeout_add(&pre_exec_timeout
);
1224 static void pre_exec_jail(struct uloop_timeout
*t
)
1226 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1227 ERROR("failed to build jail fs\n");
1228 free_and_exit(EXIT_FAILURE
);
1230 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1234 static void post_start_hook(void);
1235 static void post_jail_fs(void)
1239 if (read(pipes
[2], buf
, 1) < 1) {
1240 ERROR("can't read from parent\n");
1241 free_and_exit(EXIT_FAILURE
);
1243 if (buf
[0] != '!') {
1244 ERROR("parent had an error, child exiting\n");
1245 free_and_exit(EXIT_FAILURE
);
1249 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1252 static void post_start_hook(void)
1254 int pw_uid
, pw_gid
, gr_gid
;
1257 * make sure setuid/setgid won't drop capabilities in case capabilities
1258 * have been specified explicitely.
1260 if (opts
.capset
.apply
) {
1261 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1262 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1263 free_and_exit(EXIT_FAILURE
);
1267 /* drop capabilities, retain those still needed to further setup jail */
1268 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1269 free_and_exit(EXIT_FAILURE
);
1271 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1272 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1273 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1275 if (opts
.additional_gids
&&
1276 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1277 ERROR("setgroups failed: %m\n");
1278 free_and_exit(EXIT_FAILURE
);
1284 /* restore securebits back to normal (and lock them if not in userns) */
1285 if (opts
.capset
.apply
) {
1286 if (prctl(PR_SET_SECUREBITS
, (opts
.namespace & CLONE_NEWUSER
)?0:
1287 SECBIT_KEEP_CAPS_LOCKED
|SECBIT_NO_SETUID_FIXUP_LOCKED
|SECBIT_NOROOT_LOCKED
)) {
1288 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1289 free_and_exit(EXIT_FAILURE
);
1293 /* drop remaining capabilities to end up with specified sets */
1294 if (applyOCIcapabilities(opts
.capset
, 0))
1295 free_and_exit(EXIT_FAILURE
);
1297 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1298 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1299 free_and_exit(EXIT_FAILURE
);
1302 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1304 free_and_exit(EXIT_FAILURE
);
1306 if (opts
.cwd
&& chdir(opts
.cwd
))
1307 free_and_exit(EXIT_FAILURE
);
1309 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1310 free_and_exit(EXIT_FAILURE
);
1314 INFO("exec-ing %s\n", *opts
.jail_argv
);
1315 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1316 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1318 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1320 /* we get there only if execve fails */
1321 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1325 int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1327 char pid_pid_path
[PATH_MAX
];
1329 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1331 return open(pid_pid_path
, O_RDONLY
);
1334 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1336 struct blob_attr
*cur
;
1339 blobmsg_for_each_attr(cur
, msg
, rem
)
1343 *envp
= calloc(1 + sz
, sizeof(char*));
1352 blobmsg_for_each_attr(cur
, msg
, rem
)
1353 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1367 static const struct blobmsg_policy oci_root_policy
[] = {
1368 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1369 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1372 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1374 char extroot
[PATH_MAX
] = { 0 };
1375 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1379 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1381 if (!tb
[OCI_ROOT_PATH
])
1384 root_path
= blobmsg_get_string(tb
[OCI_ROOT_PATH
]);
1386 /* prepend bundle directory in case of relative paths */
1387 if (root_path
[0] != '/') {
1388 strncpy(extroot
, jsonfile
, PATH_MAX
- 1);
1390 cur
= strrchr(extroot
, '/');
1398 strncat(extroot
, root_path
, PATH_MAX
- (strlen(extroot
) + 1));
1400 /* follow symbolic link(s) */
1401 opts
.extroot
= realpath(extroot
, NULL
);
1405 if (tb
[OCI_ROOT_READONLY
])
1406 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1420 static const struct blobmsg_policy oci_hook_policy
[] = {
1421 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1422 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1423 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1424 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1428 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1430 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1431 struct blob_attr
*cur
;
1435 blobmsg_for_each_attr(cur
, msg
, rem
)
1441 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1447 blobmsg_for_each_attr(cur
, msg
, rem
) {
1448 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1450 if (!tb
[OCI_HOOK_PATH
]) {
1455 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1456 if (tb
[OCI_HOOK_ARGS
]) {
1457 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1461 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1462 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1463 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1467 if (tb
[OCI_HOOK_ENV
]) {
1468 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1473 if (tb
[OCI_HOOK_TIMEOUT
])
1474 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1476 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1481 (*hooklist
)[idx
] = NULL
;
1483 DEBUG("added %d hooks\n", idx
);
1488 free_hooklist(*hooklist
);
1497 OCI_HOOKS_CREATERUNTIME
,
1498 OCI_HOOKS_CREATECONTAINER
,
1499 OCI_HOOKS_STARTCONTAINER
,
1500 OCI_HOOKS_POSTSTART
,
1505 static const struct blobmsg_policy oci_hooks_policy
[] = {
1506 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1507 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1508 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1509 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1510 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1511 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1514 static int parseOCIhooks(struct blob_attr
*msg
)
1516 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1519 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1521 if (tb
[OCI_HOOKS_PRESTART
])
1522 INFO("warning: ignoring deprecated prestart hook\n");
1524 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1525 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1530 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1531 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1533 goto out_createruntime
;
1536 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1537 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1539 goto out_createcontainer
;
1542 if (tb
[OCI_HOOKS_POSTSTART
]) {
1543 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1545 goto out_startcontainer
;
1548 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1549 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1557 free_hooklist(opts
.hooks
.poststart
);
1559 free_hooklist(opts
.hooks
.startContainer
);
1560 out_createcontainer
:
1561 free_hooklist(opts
.hooks
.createContainer
);
1563 free_hooklist(opts
.hooks
.createRuntime
);
1570 OCI_PROCESS_USER_UID
,
1571 OCI_PROCESS_USER_GID
,
1572 OCI_PROCESS_USER_UMASK
,
1573 OCI_PROCESS_USER_ADDITIONALGIDS
,
1574 __OCI_PROCESS_USER_MAX
,
1577 static const struct blobmsg_policy oci_process_user_policy
[] = {
1578 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1579 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1580 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1581 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1584 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1585 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1586 struct blob_attr
*cur
;
1590 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1592 if (tb
[OCI_PROCESS_USER_UID
])
1593 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1595 if (tb
[OCI_PROCESS_USER_GID
]) {
1596 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1597 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1601 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1604 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1606 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1611 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1614 /* always add primary GID to set of GIDs if set */
1616 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1618 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1619 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1621 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1623 opts
.num_additional_gids
= gidcnt
;
1625 DEBUG("read %zu additional groups\n", gidcnt
);
1628 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1629 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1630 opts
.set_umask
= true;
1637 OCI_PROCESS_RLIMIT_TYPE
,
1638 OCI_PROCESS_RLIMIT_SOFT
,
1639 OCI_PROCESS_RLIMIT_HARD
,
1640 __OCI_PROCESS_RLIMIT_MAX
,
1643 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1644 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1645 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1646 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1649 /* from manpage GETRLIMIT(2) */
1650 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1652 [RLIMIT_CORE
] = "CORE",
1653 [RLIMIT_CPU
] = "CPU",
1654 [RLIMIT_DATA
] = "DATA",
1655 [RLIMIT_FSIZE
] = "FSIZE",
1656 [RLIMIT_LOCKS
] = "LOCKS",
1657 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1658 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1659 [RLIMIT_NICE
] = "NICE",
1660 [RLIMIT_NOFILE
] = "NOFILE",
1661 [RLIMIT_NPROC
] = "NPROC",
1662 [RLIMIT_RSS
] = "RSS",
1663 [RLIMIT_RTPRIO
] = "RTPRIO",
1664 [RLIMIT_RTTIME
] = "RTTIME",
1665 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1666 [RLIMIT_STACK
] = "STACK",
1669 static int resolve_rlimit(char *type
) {
1670 unsigned int rltype
;
1672 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1673 if (rlimit_names
[rltype
] &&
1674 !strncmp("RLIMIT_", type
, 7) &&
1675 !strcmp(rlimit_names
[rltype
], type
+ 7))
1682 static int parseOCIrlimit(struct blob_attr
*msg
)
1684 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1686 struct rlimit
*curlim
;
1688 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1690 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1691 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1692 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1695 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1700 if (opts
.rlimits
[limtype
])
1703 curlim
= malloc(sizeof(struct rlimit
));
1704 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1705 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1707 opts
.rlimits
[limtype
] = curlim
;
1714 OCI_PROCESS_CAPABILITIES
,
1717 OCI_PROCESS_OOMSCOREADJ
,
1718 OCI_PROCESS_NONEWPRIVILEGES
,
1719 OCI_PROCESS_RLIMITS
,
1720 OCI_PROCESS_TERMINAL
,
1725 static const struct blobmsg_policy oci_process_policy
[] = {
1726 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1727 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1728 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1729 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1730 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1731 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1732 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1733 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1734 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1738 static int parseOCIprocess(struct blob_attr
*msg
)
1740 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1743 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1745 if (!tb
[OCI_PROCESS_ARGS
])
1748 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1752 if (tb
[OCI_PROCESS_TERMINAL
])
1753 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1755 if (tb
[OCI_PROCESS_NONEWPRIVILEGES
])
1756 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1758 if (tb
[OCI_PROCESS_CWD
])
1759 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1761 if (tb
[OCI_PROCESS_ENV
]) {
1762 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1767 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1770 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1771 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1774 if (tb
[OCI_PROCESS_RLIMITS
]) {
1775 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1776 res
= parseOCIrlimit(cur
);
1782 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1783 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1784 opts
.set_oom_score_adj
= true;
1791 OCI_LINUX_NAMESPACE_TYPE
,
1792 OCI_LINUX_NAMESPACE_PATH
,
1793 __OCI_LINUX_NAMESPACE_MAX
,
1796 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1797 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1798 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1801 static int resolve_nstype(char *type
) {
1802 if (!strcmp("pid", type
))
1803 return CLONE_NEWPID
;
1804 else if (!strcmp("network", type
))
1805 return CLONE_NEWNET
;
1806 else if (!strcmp("net", type
))
1807 return CLONE_NEWNET
;
1808 else if (!strcmp("mount", type
))
1810 else if (!strcmp("ipc", type
))
1811 return CLONE_NEWIPC
;
1812 else if (!strcmp("uts", type
))
1813 return CLONE_NEWUTS
;
1814 else if (!strcmp("user", type
))
1815 return CLONE_NEWUSER
;
1816 else if (!strcmp("cgroup", type
))
1817 return CLONE_NEWCGROUP
;
1818 #ifdef CLONE_NEWTIME
1819 else if (!strcmp("time", type
))
1820 return CLONE_NEWTIME
;
1826 static int parseOCIlinuxns(struct blob_attr
*msg
)
1828 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1833 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1835 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1838 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1842 if (opts
.namespace & nstype
)
1845 setns
= get_namespace_fd(nstype
);
1853 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1854 DEBUG("opening existing %s namespace from path %s\n",
1855 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1856 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1858 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1860 return errno
?:ESTALE
;
1862 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
) {
1867 DEBUG("opened existing %s namespace got filehandler %u\n",
1868 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1873 opts
.namespace |= nstype
;
1880 * join namespace of existing PID
1881 * The string argument is the reference PID followed by ':' and a
1882 * ',' separated list of namespaces to to join.
1884 static int jail_join_ns(char *arg
)
1889 char *tmp
, *etmp
, *nspath
;
1892 tmp
= strchr(arg
, ':');
1901 etmp
= strchr(tmp
, ',');
1905 nstype
= resolve_nstype(tmp
);
1909 if (opts
.namespace & nstype
)
1912 setns
= get_namespace_fd(nstype
);
1920 if (asprintf(&nspath
, "/proc/%d/ns/%s", pid
, tmp
) < 0)
1923 fd
= open(nspath
, O_RDONLY
);
1927 return errno
?:ESTALE
;
1940 static void get_jail_root_user(bool is_gidmap
, uint32_t container_id
, uint32_t host_id
, uint32_t size
)
1942 if (container_id
== 0 && size
>= 1)
1944 opts
.root_map_uid
= host_id
;
1948 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1949 OCI_LINUX_UIDGIDMAP_HOSTID
,
1950 OCI_LINUX_UIDGIDMAP_SIZE
,
1951 __OCI_LINUX_UIDGIDMAP_MAX
,
1954 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1955 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1956 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1957 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1960 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1962 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1963 struct blob_attr
*cur
;
1966 size_t len
, pos
, totallen
= 0;
1968 blobmsg_for_each_attr(cur
, msg
, rem
) {
1969 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1971 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1972 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1973 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1977 totallen
+= snprintf(NULL
, 0, "%d %d %d\n",
1978 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1979 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1980 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1983 /* allocate combined mapping string */
1984 map
= malloc(totallen
+ 1);
1989 blobmsg_for_each_attr(cur
, msg
, rem
) {
1990 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1992 get_jail_root_user(is_gidmap
, blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1993 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1994 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1996 /* write mapping line into pre-allocated string */
1997 len
= snprintf(&map
[pos
], totallen
+ 1, "%d %d %d\n",
1998 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1999 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
2000 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
2005 assert(totallen
== 0);
2020 OCI_DEVICES_FILEMODE
,
2026 static const struct blobmsg_policy oci_devices_policy
[] = {
2027 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
2028 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
2029 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
2030 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
2031 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
2032 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
2033 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
2036 static mode_t
resolve_devtype(char *tstr
)
2038 if (!strcmp("c", tstr
) ||
2041 else if (!strcmp("b", tstr
))
2043 else if (!strcmp("p", tstr
))
2049 static int parseOCIdevices(struct blob_attr
*msg
)
2051 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
2052 struct blob_attr
*cur
;
2055 struct mknod_args
*tmp
;
2057 blobmsg_for_each_attr(cur
, msg
, rem
)
2060 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
2063 blobmsg_for_each_attr(cur
, msg
, rem
) {
2064 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
2065 if (!tb
[OCI_DEVICES_TYPE
] ||
2066 !tb
[OCI_DEVICES_PATH
])
2069 tmp
= calloc(1, sizeof(struct mknod_args
));
2073 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
2079 if (tmp
->mode
!= S_IFIFO
) {
2080 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
]) {
2085 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
2086 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
2089 if (tb
[OCI_DEVICES_FILEMODE
]) {
2090 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
])) {
2095 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
2097 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
2100 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
2102 if (tb
[OCI_DEVICES_UID
])
2103 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
2107 if (tb
[OCI_DEVICES_GID
])
2108 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
2112 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
2113 opts
.devices
[cnt
++] = tmp
;
2116 opts
.devices
[cnt
] = NULL
;
2121 static int parseOCIsysctl(struct blob_attr
*msg
)
2123 struct blob_attr
*cur
;
2128 blobmsg_for_each_attr(cur
, msg
, rem
) {
2129 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
2138 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2143 blobmsg_for_each_attr(cur
, msg
, rem
) {
2144 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2145 if (!opts
.sysctl
[cnt
])
2148 /* replace '.' with '/' in entry name */
2149 tc
= tmp
= strdup(blobmsg_name(cur
));
2150 while ((tc
= strchr(tc
, '.')))
2153 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2154 opts
.sysctl
[cnt
]->entry
= tmp
;
2159 opts
.sysctl
[cnt
] = NULL
;
2166 OCI_LINUX_CGROUPSPATH
,
2167 OCI_LINUX_RESOURCES
,
2170 OCI_LINUX_NAMESPACES
,
2172 OCI_LINUX_UIDMAPPINGS
,
2173 OCI_LINUX_GIDMAPPINGS
,
2174 OCI_LINUX_MASKEDPATHS
,
2175 OCI_LINUX_READONLYPATHS
,
2176 OCI_LINUX_ROOTFSPROPAGATION
,
2180 static const struct blobmsg_policy oci_linux_policy
[] = {
2181 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2182 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2183 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2184 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2185 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2186 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2187 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2188 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2189 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2190 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2191 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2194 static int parseOCIlinux(struct blob_attr
*msg
)
2196 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2197 struct blob_attr
*cur
;
2201 char cgfullpath
[256] = "/sys/fs/cgroup";
2203 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2205 if (tb
[OCI_LINUX_NAMESPACES
]) {
2206 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2207 res
= parseOCIlinuxns(cur
);
2213 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2214 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2219 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2220 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2225 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2226 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2227 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, 0, NULL
, 0);
2233 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2234 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2235 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, 0, NULL
, 0);
2241 if (tb
[OCI_LINUX_SYSCTL
]) {
2242 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2247 if (tb
[OCI_LINUX_SECCOMP
]) {
2248 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2249 if (!opts
.ociseccomp
)
2253 if (tb
[OCI_LINUX_DEVICES
]) {
2254 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2259 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2260 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2261 if (cgpath
[0] == '/') {
2262 if (strlen(cgpath
) + 1 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2265 strcat(cgfullpath
, cgpath
);
2267 strcat(cgfullpath
, "/containers/");
2268 if (strlen(opts
.name
) + strlen(cgpath
) + 2 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2271 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2272 strcat(cgfullpath
, "/");
2273 strcat(cgfullpath
, cgpath
);
2276 strcat(cgfullpath
, "/containers/");
2277 if (2 * strlen(opts
.name
) + 2 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2280 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2281 strcat(cgfullpath
, "/");
2282 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2285 cgroups_init(cgfullpath
);
2287 if (tb
[OCI_LINUX_RESOURCES
]) {
2288 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2308 static const struct blobmsg_policy oci_policy
[] = {
2309 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2310 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2311 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2312 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2313 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2314 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2315 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2316 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2319 static int parseOCI(const char *jsonfile
)
2321 struct blob_attr
*tb
[__OCI_MAX
];
2322 struct blob_attr
*cur
;
2326 blob_buf_init(&ocibuf
, 0);
2328 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
)) {
2333 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2335 if (!tb
[OCI_VERSION
]) {
2340 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2341 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2346 if (tb
[OCI_HOSTNAME
])
2347 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2349 if (!tb
[OCI_PROCESS
]) {
2354 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2357 if (!tb
[OCI_ROOT
]) {
2361 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2364 if (!tb
[OCI_MOUNTS
]) {
2369 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2370 if ((res
= parseOCImount(cur
)))
2373 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2376 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2379 if (tb
[OCI_ANNOTATIONS
])
2380 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2383 blob_buf_free(&ocibuf
);
2388 static int set_oom_score_adj(void)
2393 if (!opts
.set_oom_score_adj
)
2396 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2397 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2401 dprintf(f
, "%d", opts
.oom_score_adj
);
2415 static int jail_oci_state
= OCI_STATE_CREATED
;
2416 static void pipe_send_start_container(struct uloop_timeout
*t
);
2417 static struct uloop_timeout start_container_timeout
= {
2418 .cb
= pipe_send_start_container
,
2421 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2422 struct ubus_request_data
*req
, const char *method
,
2423 struct blob_attr
*msg
)
2425 if (jail_oci_state
!= OCI_STATE_CREATED
)
2426 return UBUS_STATUS_INVALID_ARGUMENT
;
2428 uloop_timeout_add(&start_container_timeout
);
2430 return UBUS_STATUS_OK
;
2433 static struct blob_buf bb
;
2434 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2435 struct ubus_request_data
*req
, const char *method
,
2436 struct blob_attr
*msg
)
2440 switch (jail_oci_state
) {
2441 case OCI_STATE_CREATING
:
2442 statusstr
= "creating";
2444 case OCI_STATE_CREATED
:
2445 statusstr
= "created";
2447 case OCI_STATE_RUNNING
:
2448 statusstr
= "running";
2450 case OCI_STATE_STOPPED
:
2451 statusstr
= "stopped";
2454 statusstr
= "unknown";
2457 blob_buf_init(&bb
, 0);
2458 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2459 blobmsg_add_string(&bb
, "id", opts
.name
);
2460 blobmsg_add_string(&bb
, "status", statusstr
);
2461 if (jail_oci_state
== OCI_STATE_CREATED
||
2462 jail_oci_state
== OCI_STATE_RUNNING
)
2463 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2465 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2467 if (opts
.annotations
)
2468 blobmsg_add_blob(&bb
, opts
.annotations
);
2470 ubus_send_reply(ctx
, req
, bb
.head
);
2472 return UBUS_STATUS_OK
;
2476 CONTAINER_KILL_ATTR_SIGNAL
,
2477 __CONTAINER_KILL_ATTR_MAX
,
2480 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2481 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2485 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2486 struct ubus_request_data
*req
, const char *method
,
2487 struct blob_attr
*msg
)
2489 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2492 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2494 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2496 sig
= blobmsg_get_u32(cur
);
2498 if (jail_oci_state
== OCI_STATE_CREATING
)
2499 return UBUS_STATUS_NOT_FOUND
;
2501 if (kill(jail_process
.pid
, sig
) == 0)
2505 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2506 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2507 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2510 return UBUS_STATUS_UNKNOWN_ERROR
;
2514 jail_writepid(pid_t pid
)
2521 _pidfile
= fopen(opts
.pidfile
, "w");
2522 if (_pidfile
== NULL
)
2525 if (fprintf(_pidfile
, "%d\n", pid
) < 0) {
2530 if (fclose(_pidfile
))
2536 static int checkpath(const char *path
)
2538 int dirfd
= open(path
, O_RDONLY
| O_DIRECTORY
| O_CLOEXEC
);
2540 ERROR("path %s open failed %m\n", path
);
2548 static struct ubus_method container_methods
[] = {
2549 UBUS_METHOD_NOARG("start", handle_start
),
2550 UBUS_METHOD_NOARG("state", handle_state
),
2551 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2554 static struct ubus_object_type container_object_type
=
2555 UBUS_OBJECT_TYPE("container", container_methods
);
2557 static struct ubus_object container_object
= {
2558 .type
= &container_object_type
,
2559 .methods
= container_methods
,
2560 .n_methods
= ARRAY_SIZE(container_methods
),
2563 static void post_main(struct uloop_timeout
*t
);
2564 static struct uloop_timeout post_main_timeout
= {
2567 static int netns_fd
;
2568 static int pidns_fd
;
2569 #ifdef CLONE_NEWTIME
2570 static int timens_fd
;
2572 static void post_create_runtime(void);
2575 struct list_head list
;
2579 int main(int argc
, char **argv
)
2581 uid_t uid
= getuid();
2582 const char log
[] = "/dev/log";
2583 const char ubus
[] = "/var/run/ubus/ubus.sock";
2584 int ret
= EXIT_FAILURE
;
2587 struct list_head envl
= LIST_HEAD_INIT(envl
);
2588 struct env_e
*enve
, *tmpenve
;
2589 unsigned short int envn
= 0, envc
= 0;
2592 ERROR("not root, aborting: %m\n");
2593 return EXIT_FAILURE
;
2596 /* those are filehandlers, so -1 indicates unused */
2597 opts
.setns
.pid
= -1;
2598 opts
.setns
.net
= -1;
2600 opts
.setns
.ipc
= -1;
2601 opts
.setns
.uts
= -1;
2602 opts
.setns
.user
= -1;
2603 opts
.setns
.cgroup
= -1;
2604 #ifdef CLONE_NEWTIME
2605 opts
.setns
.time
= -1;
2608 /* default 5 seconds timeout after SIGTERM before SIGKILL is sent */
2609 opts
.term_timeout
= 5;
2613 init_library_search();
2615 exit_from_child
= false;
2617 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2620 debug
= atoi(optarg
);
2623 enve
= calloc(1, sizeof(*enve
));
2624 enve
->envarg
= optarg
;
2625 list_add_tail(&enve
->list
, &envl
);
2628 opts
.namespace |= CLONE_NEWNS
;
2632 opts
.namespace |= CLONE_NEWNS
;
2636 opts
.namespace |= CLONE_NEWUSER
;
2639 opts
.namespace |= CLONE_NEWCGROUP
;
2642 opts
.extroot
= realpath(optarg
, NULL
);
2645 opts
.namespace |= CLONE_NEWNS
;
2649 opts
.seccomp
= optarg
;
2650 add_mount_bind(optarg
, 1, -1);
2653 opts
.capabilities
= optarg
;
2656 opts
.no_new_privs
= 1;
2662 opts
.namespace |= CLONE_NEWNET
;
2665 opts
.namespace |= CLONE_NEWUTS
;
2666 opts
.hostname
= strdup(optarg
);
2669 jail_join_ns(optarg
);
2672 opts
.namespace |= CLONE_NEWNS
;
2673 tmp
= strchr(optarg
, ':');
2676 add_2paths_and_deps(optarg
, tmp
, 1, 0, 0);
2678 add_path_and_deps(optarg
, 1, 0, 0);
2682 opts
.namespace |= CLONE_NEWNS
;
2683 tmp
= strchr(optarg
, ':');
2686 add_2paths_and_deps(optarg
, tmp
, 0, 0, 0);
2688 add_path_and_deps(optarg
, 0, 0, 0);
2692 opts
.namespace |= CLONE_NEWNS
;
2693 add_mount_bind(ubus
, 0, -1);
2696 opts
.namespace |= CLONE_NEWNS
;
2697 add_mount_bind(log
, 0, -1);
2703 opts
.group
= optarg
;
2706 opts
.overlaydir
= realpath(optarg
, NULL
);
2709 opts
.term_timeout
= atoi(optarg
);
2712 opts
.tmpoverlaysize
= optarg
;
2715 opts
.require_jail
= 1;
2721 opts
.ocibundle
= optarg
;
2724 opts
.immediately
= true;
2727 opts
.pidfile
= optarg
;
2732 if (opts
.namespace && !opts
.ocibundle
)
2733 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2736 * env import from cmdline is not available for OCI containers
2738 if (opts
.ocibundle
&& !list_empty(&envl
)) {
2744 * prepare list of env variables to import for slim containers
2746 if (!list_empty(&envl
)) {
2747 list_for_each_entry(enve
, &envl
, list
)
2750 opts
.envp
= calloc(1 + envn
, sizeof(char*));
2751 list_for_each_entry_safe(enve
, tmpenve
, &envl
, list
) {
2752 tmp
= getenv(enve
->envarg
);
2754 ret
= asprintf(&opts
.envp
[envc
++], "%s=%s", enve
->envarg
, tmp
);
2756 ERROR("filed to handle envargs %s\n", tmp
);
2762 list_del(&enve
->list
);
2766 opts
.envp
[envc
] = NULL
;
2770 * uid in parent user namespace representing root user in new
2771 * user namespace, defaults to nobody unless specified in uidMappings
2773 opts
.root_map_uid
= 65534;
2775 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2776 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2781 if (opts
.ocibundle
) {
2786 ERROR("OCI bundle needs a named jail\n");
2790 if (asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
) < 0) {
2794 ocires
= parseOCI(jsonfile
);
2797 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2803 if (opts
.namespace & CLONE_NEWNET
) {
2805 ERROR("netns needs a named jail\n");
2812 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2813 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2818 if (opts
.extroot
&& checkpath(opts
.extroot
)) {
2819 ERROR("invalid rootfs path '%s'", opts
.extroot
);
2824 if (opts
.overlaydir
&& checkpath(opts
.overlaydir
)) {
2825 ERROR("invalid rootfs overlay path '%s'", opts
.overlaydir
);
2830 /* no <binary> param found */
2831 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2836 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
||
2837 (opts
.setns
.net
!= -1) ||
2838 (opts
.setns
.ns
!= -1) ||
2839 (opts
.setns
.ipc
!= -1) ||
2840 (opts
.setns
.uts
!= -1) ||
2841 (opts
.setns
.user
!= -1) ||
2842 (opts
.setns
.cgroup
!= -1))) {
2843 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2848 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2851 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2856 parent_ctx
= ubus_connect(NULL
);
2857 ubus_add_uloop(parent_ctx
);
2859 if (opts
.ocibundle
) {
2861 if (asprintf(&objname
, "container.%s", opts
.name
) < 0) {
2866 container_object
.name
= objname
;
2867 ret
= ubus_add_object(parent_ctx
, &container_object
);
2869 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2875 /* deliberately not using 'else' on unrelated conditional branches */
2876 if (!opts
.ocibundle
) {
2877 /* allocate NULL-terminated array for argv */
2878 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(void *));
2879 if (!opts
.jail_argv
) {
2883 for (size_t s
= optind
; s
< argc
; s
++)
2884 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2886 if (opts
.namespace & CLONE_NEWUSER
)
2887 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2890 if (!opts
.extroot
) {
2891 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2892 ERROR("failed to load dependencies\n");
2898 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2899 ERROR("failed to load libpreload-seccomp.so\n");
2901 if (opts
.require_jail
) {
2907 uloop_timeout_add(&post_main_timeout
);
2919 static void post_main(struct uloop_timeout
*t
)
2921 if (apply_rlimits()) {
2922 ERROR("error applying resource limits\n");
2923 free_and_exit(EXIT_FAILURE
);
2927 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2929 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2932 if (has_namespaces()) {
2933 if (opts
.namespace & CLONE_NEWNS
) {
2934 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2935 add_mount_bind("/etc/passwd", 1, -1);
2936 add_mount_bind("/etc/group", 1, -1);
2939 #if defined(__GLIBC__)
2941 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2943 if (opts
.setns
.ns
== -1) {
2944 if (!(opts
.namespace & CLONE_NEWNET
)) {
2945 add_mount_bind("/etc/resolv.conf", 1, 0);
2947 /* new mount namespace to provide /dev/resolv.conf.d */
2948 char hostdir
[PATH_MAX
];
2950 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2951 mkdir_p(hostdir
, 0755);
2952 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
,
2953 MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, 0, NULL
, 0);
2956 /* default mounts */
2957 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "size=1M", -1);
2958 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2960 if (opts
.procfs
|| opts
.ocibundle
) {
2961 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0, NULL
, -1);
2964 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2965 * which cannot be expressed with OCI spec, but happends to be very useful.
2966 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2968 * If not running in a new network namespace, only make /proc/sys read-only.
2969 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2970 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2971 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2973 * This works because mounts are executed in incrementing strcmp() order and
2974 * /proc/self/net appears there before /proc/sys/net and hence the operation
2975 * succeeds as the bind-mount of /proc/self/net is performed first and then
2976 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2977 * table (and in the alphabet).
2979 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, 0, NULL
, -1))
2980 if (opts
.namespace & CLONE_NEWNET
)
2981 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0, NULL
, -1))
2982 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0, NULL
, -1);
2985 if (opts
.sysfs
|| opts
.ocibundle
)
2986 add_mount("sysfs", "/sys", "sysfs", MS_RELATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0, NULL
, -1);
2989 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, 0, "mode=1777", -1);
2993 if (opts
.setns
.pid
!= -1) {
2994 pidns_fd
= ns_open_pid("pid", getpid());
2995 setns_open(CLONE_NEWPID
);
3000 #ifdef CLONE_NEWTIME
3001 if (opts
.setns
.time
!= -1) {
3002 timens_fd
= ns_open_pid("time", getpid());
3003 setns_open(CLONE_NEWTIME
);
3009 if (opts
.namespace & CLONE_NEWUSER
) {
3010 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
3011 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
3012 free_and_exit(EXIT_FAILURE
);
3014 if (seteuid(opts
.root_map_uid
)) {
3015 ERROR("seteuid(%d) failed: %m\n", opts
.root_map_uid
);
3016 free_and_exit(EXIT_FAILURE
);
3020 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
3022 jail_process
.pid
= fork();
3025 if (jail_process
.pid
> 0) {
3026 /* parent process */
3029 uloop_process_add(&jail_process
);
3032 ERROR("seteuid(%d) failed: %m\n", opts
.root_map_uid
);
3033 free_and_exit(EXIT_FAILURE
);
3036 prctl(PR_SET_SECUREBITS
, 0);
3038 if (pidns_fd
!= -1) {
3039 setns(pidns_fd
, CLONE_NEWPID
);
3042 #ifdef CLONE_NEWTIME
3043 if (timens_fd
!= -1) {
3044 setns(timens_fd
, CLONE_NEWTIME
);
3048 if (opts
.setns
.net
!= -1)
3049 close(opts
.setns
.net
);
3050 if (opts
.setns
.ns
!= -1)
3051 close(opts
.setns
.ns
);
3052 if (opts
.setns
.ipc
!= -1)
3053 close(opts
.setns
.ipc
);
3054 if (opts
.setns
.uts
!= -1)
3055 close(opts
.setns
.uts
);
3056 if (opts
.setns
.user
!= -1)
3057 close(opts
.setns
.user
);
3058 if (opts
.setns
.cgroup
!= -1)
3059 close(opts
.setns
.cgroup
);
3062 if (read(pipes
[0], sig_buf
, 1) < 1) {
3063 ERROR("can't read from child\n");
3067 set_oom_score_adj();
3070 cgroups_apply(jail_process
.pid
);
3072 if (opts
.namespace & CLONE_NEWUSER
) {
3073 if (write_setgroups(jail_process
.pid
, true)) {
3074 ERROR("can't write setgroups\n");
3078 bool has_gr
= (opts
.gr_gid
!= -1);
3079 if (opts
.pw_uid
!= -1) {
3080 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
3081 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
3083 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
3084 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
3087 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
3089 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
3093 if (opts
.namespace & CLONE_NEWNET
)
3094 jail_network_start(parent_ctx
, opts
.name
, jail_process
.pid
);
3096 if (jail_writepid(jail_process
.pid
)) {
3097 ERROR("failed to write pidfile: %m\n");
3100 } else if (jail_process
.pid
== 0) {
3101 /* fork child process */
3102 free_and_exit(exec_jail(NULL
));
3104 ERROR("failed to clone/fork: %m\n");
3105 free_and_exit(EXIT_FAILURE
);
3107 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
3110 static void post_poststart(void);
3111 static void post_create_runtime(void)
3116 if (write(pipes
[3], sig_buf
, 1) < 0) {
3117 ERROR("can't write to child\n");
3121 jail_oci_state
= OCI_STATE_CREATED
;
3122 if (opts
.ocibundle
&& !opts
.immediately
)
3123 uloop_run(); /* wait for 'start' command via ubus */
3125 pipe_send_start_container(NULL
);
3128 static void pipe_send_start_container(struct uloop_timeout
*t
)
3132 jail_oci_state
= OCI_STATE_RUNNING
;
3134 if (write(pipes
[3], sig_buf
, 1) < 0) {
3135 ERROR("can't write to child\n");
3140 run_hooks(opts
.hooks
.poststart
, post_poststart
);
3143 static void post_poststart(void)
3145 uloop_run(); /* idle here while jail is running */
3147 DEBUG("uloop interrupted, killing jail process\n");
3148 kill(jail_process
.pid
, SIGTERM
);
3149 uloop_timeout_set(&jail_process_timeout
, 1000);
3156 static void post_poststop(void);
3157 static void poststop(void) {
3158 if (opts
.namespace & CLONE_NEWNET
) {
3159 setns(netns_fd
, CLONE_NEWNET
);
3160 jail_network_stop();
3163 run_hooks(opts
.hooks
.poststop
, post_poststop
);
3166 static void post_poststop(void)
3170 ubus_free(parent_ctx
);
3172 exit(jail_return_code
);