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"
58 #include <libubox/blobmsg.h>
59 #include <libubox/blobmsg_json.h>
60 #include <libubox/list.h>
61 #include <libubox/vlist.h>
62 #include <libubox/uloop.h>
63 #include <libubox/utils.h>
66 #ifndef CLONE_NEWCGROUP
67 #define CLONE_NEWCGROUP 0x02000000
70 #define STACK_SIZE (1024 * 1024)
71 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:iP:"
73 #define OCI_VERSION_STRING "1.0.2"
101 struct sock_fprog
*ociseccomp
;
103 struct jail_capset capset
;
108 char *tmpoverlaysize
;
113 struct sysctl_val
**sysctl
;
136 gid_t
*additional_gids
;
137 size_t num_additional_gids
;
142 struct hook_execvpe
**createRuntime
;
143 struct hook_execvpe
**createContainer
;
144 struct hook_execvpe
**startContainer
;
145 struct hook_execvpe
**poststart
;
146 struct hook_execvpe
**poststop
;
148 struct rlimit
*rlimits
[RLIM_NLIMITS
];
150 bool set_oom_score_adj
;
151 struct mknod_args
**devices
;
154 struct blob_attr
*annotations
;
157 static struct blob_buf ocibuf
;
159 extern int pivot_root(const char *new_root
, const char *put_old
);
163 static char child_stack
[STACK_SIZE
];
165 static struct ubus_context
*parent_ctx
;
170 static inline bool has_namespaces(void)
172 return ((opts
.setns
.pid
!= -1) ||
173 (opts
.setns
.net
!= -1) ||
174 (opts
.setns
.ns
!= -1) ||
175 (opts
.setns
.ipc
!= -1) ||
176 (opts
.setns
.uts
!= -1) ||
177 (opts
.setns
.user
!= -1) ||
178 (opts
.setns
.cgroup
!= -1) ||
180 (opts
.setns
.time
!= -1) ||
185 static void free_oci_envp(char **p
) {
197 static void free_hooklist(struct hook_execvpe
**hooklist
)
199 struct hook_execvpe
*cur
;
206 free_oci_envp(cur
->argv
);
207 free_oci_envp(cur
->envp
);
214 static void free_sysctl(void) {
215 struct sysctl_val
*cur
;
226 static void free_devices(void) {
227 struct mknod_args
**cur
;
241 static void free_rlimits(void) {
244 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
245 free(opts
.rlimits
[type
]);
248 static void free_opts(bool parent
) {
250 free_library_search();
254 /* we need to keep argv, envp and seccomp filter in child */
255 if (parent
) { /* parent-only */
256 if (opts
.ociseccomp
) {
257 free(opts
.ociseccomp
->filter
);
258 free(opts
.ociseccomp
);
261 free_oci_envp(opts
.jail_argv
);
262 free_oci_envp(opts
.envp
);
272 free(opts
.annotations
);
274 free(opts
.overlaydir
);
275 free_hooklist(opts
.hooks
.createRuntime
);
276 free_hooklist(opts
.hooks
.createContainer
);
277 free_hooklist(opts
.hooks
.startContainer
);
278 free_hooklist(opts
.hooks
.poststart
);
279 free_hooklist(opts
.hooks
.poststop
);
282 static int mount_overlay(char *jail_root
, char *overlaydir
) {
283 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
284 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
287 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
290 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
293 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
296 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
300 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
301 * this is to work-around a bug in overlayfs described in the overlayfs-userns
303 * 3. modification of a file 'hithere' which is in l but not yet
304 * in u, and which is not owned by T, is not allowed, even if
305 * writes to u are allowed. This may be a bug in overlayfs,
306 * but it is safe behavior.
308 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
311 if (mkdir_p(upperetc
, 0755))
312 goto upper_etc_printf
;
314 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
315 goto upper_etc_printf
;
317 fd
= creat(upperresolvconf
, 0644);
320 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
324 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
326 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
327 goto upper_resolvconf_printf
;
331 upper_resolvconf_printf
:
332 free(upperresolvconf
);
345 static void pass_console(int console_fd
)
347 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
348 static struct blob_buf req
;
354 blob_buf_init(&req
, 0);
355 blobmsg_add_string(&req
, "name", opts
.name
);
357 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
358 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
359 INFO("ubus request failed\n");
364 ubus_free(child_ctx
);
367 static int create_dev_console(const char *jail_root
)
370 char dev_console_path
[PATH_MAX
];
371 int slave_console_fd
;
373 /* Open UNIX/98 virtual console */
374 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
378 console_fname
= ptsname(console_fd
);
379 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
384 unlockpt(console_fd
);
386 /* pass PTY master to procd */
387 pass_console(console_fd
);
389 /* mount-bind PTY slave to /dev/console in jail */
390 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
391 close(creat(dev_console_path
, 0620));
393 if (mount(console_fname
, dev_console_path
, "bind", MS_BIND
, NULL
))
396 /* use PTY slave for stdio */
397 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
398 if (slave_console_fd
< 0)
401 dup2(slave_console_fd
, 0);
402 dup2(slave_console_fd
, 1);
403 dup2(slave_console_fd
, 2);
404 close(slave_console_fd
);
406 INFO("using guest console %s\n", console_fname
);
415 static int hook_running
= 0;
416 static int hook_return_code
= 0;
417 static struct hook_execvpe
**current_hook
= NULL
;
418 typedef void (*hook_return_handler
)(void);
419 static hook_return_handler hook_return_cb
= NULL
;
421 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
422 static struct uloop_timeout hook_process_timeout
= {
423 .cb
= hook_process_timeout_cb
,
426 static void run_hooklist(void);
427 static void hook_process_handler(struct uloop_process
*c
, int ret
)
429 uloop_timeout_cancel(&hook_process_timeout
);
431 if (WIFEXITED(ret
)) {
432 hook_return_code
= WEXITSTATUS(ret
);
433 if (hook_return_code
)
434 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
436 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
439 hook_return_code
= WTERMSIG(ret
);
440 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
447 static struct uloop_process hook_process
= {
448 .cb
= hook_process_handler
,
451 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
453 DEBUG("hook process failed to stop, sending SIGKILL\n");
454 kill(hook_process
.pid
, SIGKILL
);
457 static void run_hooklist(void)
459 struct hook_execvpe
*hook
= *current_hook
;
463 return hook_return_cb();
465 DEBUG("executing hook %s\n", hook
->file
);
467 if (stat(hook
->file
, &s
))
468 hook_process_handler(&hook_process
, ENOENT
);
470 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
471 hook_process_handler(&hook_process
, EPERM
);
474 hook_process
.pid
= fork();
475 if (hook_process
.pid
== 0) {
477 execve(hook
->file
, hook
->argv
, hook
->envp
);
478 ERROR("execve error %m\n");
480 } else if (hook_process
.pid
< 0) {
482 ERROR("hook fork error\n");
484 hook_process_handler(&hook_process
, errno
);
488 uloop_process_add(&hook_process
);
490 if (hook
->timeout
> 0)
491 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
495 DEBUG("uloop interrupted, killing jail process\n");
496 kill(hook_process
.pid
, SIGTERM
);
497 uloop_timeout_set(&hook_process_timeout
, 1000);
502 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
507 current_hook
= hooklist
;
508 hook_return_cb
= return_cb
;
513 static int apply_sysctl(const char *jail_root
)
515 struct sysctl_val
**cur
;
516 char *procdir
, *fname
;
522 if (asprintf(&procdir
, "%s/proc", jail_root
) < 0)
525 mkdir(procdir
, 0700);
526 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
532 if (asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
) < 0)
535 DEBUG("sysctl: writing '%s' to %s\n", (*cur
)->value
, fname
);
537 f
= open(fname
, O_WRONLY
);
539 ERROR("sysctl: can't open %s\n", fname
);
543 if (write(f
, (*cur
)->value
, strlen((*cur
)->value
)) < 0) {
544 ERROR("sysctl: write to %s\n", fname
);
561 /* glibc defines makedev calling a function. make sure it's a pure macro */
562 #if defined(__GLIBC__)
564 /* from musl's sys/sysmacros.h */
565 #define makedev(x,y) ( \
566 (((x)&0xfffff000ULL) << 32) | \
567 (((x)&0x00000fffULL) << 8) | \
568 (((y)&0xffffff00ULL) << 12) | \
569 (((y)&0x000000ffULL)) )
572 static struct mknod_args default_devices
[] = {
573 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
574 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
575 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
576 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
577 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
578 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
582 static int create_devices(void)
584 struct mknod_args
**cur
, *curdef
;
588 goto only_default_devices
;
594 /* don't allow devices outside of /dev */
595 if (strncmp(path
, "/dev", 4))
598 /* make sure parent folder exists */
599 tmp
= strrchr(path
, '/');
604 if (strcmp(path
, "/dev")) {
605 DEBUG("creating directory %s\n", path
);
611 DEBUG("creating %s (mode=%08o)\n", path
, (*cur
)->mode
);
614 if (mknod(path
, (*cur
)->mode
, (*cur
)->dev
))
617 /* change owner, if needed */
618 if (((*cur
)->uid
|| (*cur
)->gid
) &&
619 chown(path
, (*cur
)->uid
, (*cur
)->gid
))
625 only_default_devices
:
626 curdef
= default_devices
;
627 while(curdef
->path
) {
628 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
629 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
631 continue; /* may already exist, eg. due to a bind-mount */
633 if ((curdef
->uid
|| curdef
->gid
) &&
634 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
640 /* Dev symbolic links as defined in OCI spec */
641 (void) symlink("/dev/pts/ptmx", "/dev/ptmx");
642 (void) symlink("/proc/self/fd", "/dev/fd");
643 (void) symlink("/proc/self/fd/0", "/dev/stdin");
644 (void) symlink("/proc/self/fd/1", "/dev/stdout");
645 (void) symlink("/proc/self/fd/2", "/dev/stderr");
650 static char jail_root
[] = "/tmp/ujail-XXXXXX";
651 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
652 static mode_t old_umask
;
653 static void enter_jail_fs(void);
654 static int build_jail_fs(void)
656 char *overlaydir
= NULL
;
659 old_umask
= umask(0);
661 if (mkdtemp(jail_root
) == NULL
) {
662 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
666 if (apply_sysctl(jail_root
)) {
667 ERROR("failed to apply sysctl values\n");
671 /* oldroot can't be MS_SHARED else pivot_root() fails */
672 if (mount("none", "/", "none", MS_REC
|MS_PRIVATE
, NULL
)) {
673 ERROR("private mount failed %m\n");
678 if (mount(opts
.extroot
, jail_root
, "bind", MS_BIND
, NULL
)) {
679 ERROR("extroot mount failed %m\n");
683 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
684 ERROR("tmpfs mount failed %m\n");
689 if (opts
.tmpoverlaysize
) {
690 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
692 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
693 "mode=0755,size=%s", opts
.tmpoverlaysize
);
694 if (mkdtemp(tmpovdir
) == NULL
) {
695 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
698 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
700 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
703 overlaydir
= tmpovdir
;
707 overlaydir
= opts
.overlaydir
;
710 ret
= mount_overlay(jail_root
, overlaydir
);
715 if (chdir(jail_root
)) {
716 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
720 if (mount_all(jail_root
)) {
721 ERROR("mount_all() failed\n");
726 create_dev_console(jail_root
);
728 /* make sure /etc/resolv.conf exists if in new network namespace */
729 if (!opts
.extroot
&& opts
.namespace & CLONE_NEWNET
) {
730 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
732 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
733 mkdir_p(jailetc
, 0755);
734 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
738 (void) symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
741 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
746 static bool exit_from_child
;
747 static void free_and_exit(int ret
)
749 if (!exit_from_child
&& opts
.ocibundle
)
752 if (!exit_from_child
&& parent_ctx
)
753 ubus_free(parent_ctx
);
755 free_opts(!exit_from_child
);
760 static void post_jail_fs(void);
761 static void enter_jail_fs(void)
763 char dirbuf
[sizeof(jail_root
) + 4];
765 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
768 if (pivot_root(jail_root
, dirbuf
) == -1) {
769 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
773 ERROR("chdir(/) (after pivot_root) failed: %m\n");
777 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
778 umount2(dirbuf
, MNT_DETACH
);
780 if (opts
.tmpoverlaysize
) {
781 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
782 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
783 umount2(tmpdirbuf
, MNT_DETACH
);
787 umount2("/old", MNT_DETACH
);
790 if (create_devices()) {
791 ERROR("create_devices() failed\n");
795 mount(NULL
, "/", "bind", MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
801 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
806 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
807 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
810 if ((map_file
= open(map_path
, O_WRONLY
)) < 0)
813 if (dprintf(map_file
, "%s", mapstr
)) {
822 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
826 const char *map_format
= "%d %d %d\n";
827 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
828 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
831 if ((map_file
= open(map_path
, O_WRONLY
)) < 0)
834 if (dprintf(map_file
, map_format
, 0, id
, 1) < 0) {
843 static int write_setgroups(pid_t child_pid
, bool allow
)
846 char setgroups_path
[64];
848 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
853 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) < 0) {
857 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
858 close(setgroups_file
);
862 close(setgroups_file
);
866 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
868 struct passwd
*p
= NULL
;
869 struct group
*g
= NULL
;
872 p
= getpwnam(opts
.user
);
874 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
875 opts
.user
, errno
, strerror(errno
));
876 free_and_exit(EXIT_FAILURE
);
879 *user_gid
= p
->pw_gid
;
886 g
= getgrnam(opts
.group
);
888 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
889 free_and_exit(EXIT_FAILURE
);
897 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
899 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
900 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
901 free_and_exit(EXIT_FAILURE
);
904 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
905 ERROR("failed to set group id %d: %m\n", gr_gid
);
906 free_and_exit(EXIT_FAILURE
);
909 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
910 ERROR("failed to set user id %d: %m\n", pw_uid
);
911 free_and_exit(EXIT_FAILURE
);
915 static int apply_rlimits(void)
919 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
920 if (opts
.rlimits
[resource
])
921 DEBUG("applying limits to resource %u\n", resource
);
923 if (opts
.rlimits
[resource
] &&
924 setrlimit(resource
, opts
.rlimits
[resource
]))
932 static char** build_envp(const char *seccomp
, char **ocienvp
)
934 static char *envp
[MAX_ENVP
];
935 static char preload_var
[PATH_MAX
];
936 static char seccomp_var
[PATH_MAX
];
937 static char seccomp_debug_var
[20];
938 static char debug_var
[] = "LD_DEBUG=all";
939 static char container_var
[] = "container=ujail";
940 const char *preload_lib
= find_lib("libpreload-seccomp.so");
945 if (seccomp
&& !preload_lib
) {
946 ERROR("failed to add preload-lib to env\n");
950 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
951 envp
[count
++] = seccomp_var
;
952 snprintf(seccomp_debug_var
, sizeof(seccomp_debug_var
), "SECCOMP_DEBUG=%2d", debug
);
953 envp
[count
++] = seccomp_debug_var
;
954 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
955 envp
[count
++] = preload_var
;
958 envp
[count
++] = container_var
;
961 envp
[count
++] = debug_var
;
964 while (addenv
&& *addenv
) {
965 envp
[count
++] = *(addenv
++);
966 if (count
>= MAX_ENVP
) {
967 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
974 static void usage(void)
976 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
977 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
978 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
979 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
980 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
981 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
982 fprintf(stderr
, "namespace jail options:\n");
983 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
984 fprintf(stderr
, " -N\t\tjail has network namespace\n");
985 fprintf(stderr
, " -f\t\tjail has user namespace\n");
986 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
987 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
988 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
989 fprintf(stderr
, " -p\t\tjail has /proc\n");
990 fprintf(stderr
, " -s\t\tjail has /sys\n");
991 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
992 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
993 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
994 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
995 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
996 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
997 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
998 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
999 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
1000 fprintf(stderr
, " -y\t\tprovide jail console\n");
1001 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
1002 fprintf(stderr
, " -i\t\tstart container immediately\n");
1003 fprintf(stderr
, " -P <pidfile>\tcreate <pidfile>\n");
1004 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
1005 and he has the same powers as root outside the jail,\n\
1006 thus he can escape the jail and/or break stuff.\n\
1007 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
1008 If you use none of the namespace jail options,\n\
1009 ujail will not use namespace/build a jail,\n\
1010 and will only drop capabilities/apply seccomp filter.\n\n");
1013 static int* get_namespace_fd(const unsigned int nstype
)
1017 return &opts
.setns
.pid
;
1019 return &opts
.setns
.net
;
1021 return &opts
.setns
.ns
;
1023 return &opts
.setns
.ipc
;
1025 return &opts
.setns
.uts
;
1027 return &opts
.setns
.user
;
1028 case CLONE_NEWCGROUP
:
1029 return &opts
.setns
.cgroup
;
1030 #ifdef CLONE_NEWTIME
1032 return &opts
.setns
.time
;
1039 static int setns_open(unsigned long nstype
)
1041 int *fd
= get_namespace_fd(nstype
);
1048 if (setns(*fd
, nstype
) == -1) {
1057 static int jail_running
= 0;
1058 static int jail_return_code
= 0;
1060 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1061 static struct uloop_timeout jail_process_timeout
= {
1062 .cb
= jail_process_timeout_cb
,
1064 static void poststop(void);
1065 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1067 uloop_timeout_cancel(&jail_process_timeout
);
1068 if (WIFEXITED(ret
)) {
1069 jail_return_code
= WEXITSTATUS(ret
);
1070 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1072 jail_return_code
= WTERMSIG(ret
);
1073 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1079 static struct uloop_process jail_process
= {
1080 .cb
= jail_process_handler
,
1083 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1085 DEBUG("jail process failed to stop, sending SIGKILL\n");
1086 kill(jail_process
.pid
, SIGKILL
);
1089 static void jail_handle_signal(int signo
)
1092 DEBUG("forwarding signal %d to the hook process\n", signo
);
1093 kill(hook_process
.pid
, signo
);
1097 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1098 kill(jail_process
.pid
, signo
);
1102 static void signals_init(void)
1107 sigfillset(&sigmask
);
1108 for (i
= 0; i
< _NSIG
; i
++) {
1109 struct sigaction s
= { 0 };
1111 if (!sigismember(&sigmask
, i
))
1113 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1116 s
.sa_handler
= jail_handle_signal
;
1117 sigaction(i
, &s
, NULL
);
1121 static void pre_exec_jail(struct uloop_timeout
*t
);
1122 static struct uloop_timeout pre_exec_timeout
= {
1123 .cb
= pre_exec_jail
,
1127 static int exec_jail(void *arg
)
1131 exit_from_child
= true;
1132 prctl(PR_SET_SECUREBITS
, 0);
1140 setns_open(CLONE_NEWUSER
);
1141 setns_open(CLONE_NEWNET
);
1142 setns_open(CLONE_NEWNS
);
1143 setns_open(CLONE_NEWIPC
);
1144 setns_open(CLONE_NEWUTS
);
1147 if (write(pipes
[1], buf
, 1) < 1) {
1148 ERROR("can't write to parent\n");
1149 return EXIT_FAILURE
;
1152 if (read(pipes
[2], buf
, 1) < 1) {
1153 ERROR("can't read from parent\n");
1154 return EXIT_FAILURE
;
1156 if (buf
[0] != 'O') {
1157 ERROR("parent had an error, child exiting\n");
1158 return EXIT_FAILURE
;
1161 if (opts
.namespace & CLONE_NEWCGROUP
)
1162 unshare(CLONE_NEWCGROUP
);
1164 setns_open(CLONE_NEWCGROUP
);
1166 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1167 if (setregid(0, 0) < 0) {
1169 free_and_exit(EXIT_FAILURE
);
1171 if (setreuid(0, 0) < 0) {
1173 free_and_exit(EXIT_FAILURE
);
1175 if (setgroups(0, NULL
) < 0) {
1176 ERROR("setgroups\n");
1177 free_and_exit(EXIT_FAILURE
);
1181 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1182 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1183 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1184 free_and_exit(EXIT_FAILURE
);
1187 uloop_timeout_add(&pre_exec_timeout
);
1194 static void pre_exec_jail(struct uloop_timeout
*t
)
1196 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1197 ERROR("failed to build jail fs\n");
1198 free_and_exit(EXIT_FAILURE
);
1200 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1204 static void post_start_hook(void);
1205 static void post_jail_fs(void)
1209 if (read(pipes
[2], buf
, 1) < 1) {
1210 ERROR("can't read from parent\n");
1211 free_and_exit(EXIT_FAILURE
);
1213 if (buf
[0] != '!') {
1214 ERROR("parent had an error, child exiting\n");
1215 free_and_exit(EXIT_FAILURE
);
1219 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1222 static void post_start_hook(void)
1224 int pw_uid
, pw_gid
, gr_gid
;
1227 * make sure setuid/setgid won't drop capabilities in case capabilities
1228 * have been specified explicitely.
1230 if (opts
.capset
.apply
) {
1231 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1232 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1233 free_and_exit(EXIT_FAILURE
);
1237 /* drop capabilities, retain those still needed to further setup jail */
1238 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1239 free_and_exit(EXIT_FAILURE
);
1241 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1242 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1243 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1245 if (opts
.additional_gids
&&
1246 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1247 ERROR("setgroups failed: %m\n");
1248 free_and_exit(EXIT_FAILURE
);
1254 /* restore securebits back to normal (and lock them if not in userns) */
1255 if (opts
.capset
.apply
) {
1256 if (prctl(PR_SET_SECUREBITS
, (opts
.namespace & CLONE_NEWUSER
)?0:
1257 SECBIT_KEEP_CAPS_LOCKED
|SECBIT_NO_SETUID_FIXUP_LOCKED
|SECBIT_NOROOT_LOCKED
)) {
1258 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1259 free_and_exit(EXIT_FAILURE
);
1263 /* drop remaining capabilities to end up with specified sets */
1264 if (applyOCIcapabilities(opts
.capset
, 0))
1265 free_and_exit(EXIT_FAILURE
);
1267 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1268 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1269 free_and_exit(EXIT_FAILURE
);
1272 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1274 free_and_exit(EXIT_FAILURE
);
1276 if (opts
.cwd
&& chdir(opts
.cwd
))
1277 free_and_exit(EXIT_FAILURE
);
1279 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1280 free_and_exit(EXIT_FAILURE
);
1284 INFO("exec-ing %s\n", *opts
.jail_argv
);
1285 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1286 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1288 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1290 /* we get there only if execve fails */
1291 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1295 static int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1297 char pid_pid_path
[PATH_MAX
];
1299 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1301 return open(pid_pid_path
, O_RDONLY
);
1304 static void netns_updown(pid_t pid
, bool start
)
1306 static struct blob_buf req
;
1312 blob_buf_init(&req
, 0);
1313 blobmsg_add_string(&req
, "jail", opts
.name
);
1314 blobmsg_add_u32(&req
, "pid", pid
);
1315 blobmsg_add_u8(&req
, "start", start
);
1317 if (ubus_lookup_id(parent_ctx
, "network", &id
) ||
1318 ubus_invoke(parent_ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1319 INFO("ubus request failed\n");
1321 blob_buf_free(&req
);
1324 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1326 struct blob_attr
*cur
;
1329 blobmsg_for_each_attr(cur
, msg
, rem
)
1333 *envp
= calloc(1 + sz
, sizeof(char*));
1342 blobmsg_for_each_attr(cur
, msg
, rem
)
1343 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1357 static const struct blobmsg_policy oci_root_policy
[] = {
1358 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1359 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1362 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1364 char extroot
[PATH_MAX
] = { 0 };
1365 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1369 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1371 if (!tb
[OCI_ROOT_PATH
])
1374 root_path
= blobmsg_get_string(tb
[OCI_ROOT_PATH
]);
1376 /* prepend bundle directory in case of relative paths */
1377 if (root_path
[0] != '/') {
1378 strncpy(extroot
, jsonfile
, PATH_MAX
- 1);
1380 cur
= strrchr(extroot
, '/');
1388 strncat(extroot
, root_path
, PATH_MAX
- (strlen(extroot
) + 1));
1390 /* follow symbolic link(s) */
1391 opts
.extroot
= realpath(extroot
, NULL
);
1395 if (tb
[OCI_ROOT_READONLY
])
1396 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1410 static const struct blobmsg_policy oci_hook_policy
[] = {
1411 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1412 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1413 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1414 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1418 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1420 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1421 struct blob_attr
*cur
;
1425 blobmsg_for_each_attr(cur
, msg
, rem
)
1431 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1437 blobmsg_for_each_attr(cur
, msg
, rem
) {
1438 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1440 if (!tb
[OCI_HOOK_PATH
]) {
1445 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1446 if (tb
[OCI_HOOK_ARGS
]) {
1447 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1451 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1452 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1453 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1457 if (tb
[OCI_HOOK_ENV
]) {
1458 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1463 if (tb
[OCI_HOOK_TIMEOUT
])
1464 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1466 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1471 (*hooklist
)[idx
] = NULL
;
1473 DEBUG("added %d hooks\n", idx
);
1478 free_hooklist(*hooklist
);
1487 OCI_HOOKS_CREATERUNTIME
,
1488 OCI_HOOKS_CREATECONTAINER
,
1489 OCI_HOOKS_STARTCONTAINER
,
1490 OCI_HOOKS_POSTSTART
,
1495 static const struct blobmsg_policy oci_hooks_policy
[] = {
1496 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1497 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1498 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1499 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1500 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1501 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1504 static int parseOCIhooks(struct blob_attr
*msg
)
1506 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1509 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1511 if (tb
[OCI_HOOKS_PRESTART
])
1512 INFO("warning: ignoring deprecated prestart hook\n");
1514 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1515 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1520 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1521 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1523 goto out_createruntime
;
1526 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1527 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1529 goto out_createcontainer
;
1532 if (tb
[OCI_HOOKS_POSTSTART
]) {
1533 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1535 goto out_startcontainer
;
1538 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1539 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1547 free_hooklist(opts
.hooks
.poststart
);
1549 free_hooklist(opts
.hooks
.startContainer
);
1550 out_createcontainer
:
1551 free_hooklist(opts
.hooks
.createContainer
);
1553 free_hooklist(opts
.hooks
.createRuntime
);
1560 OCI_PROCESS_USER_UID
,
1561 OCI_PROCESS_USER_GID
,
1562 OCI_PROCESS_USER_UMASK
,
1563 OCI_PROCESS_USER_ADDITIONALGIDS
,
1564 __OCI_PROCESS_USER_MAX
,
1567 static const struct blobmsg_policy oci_process_user_policy
[] = {
1568 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1569 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1570 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1571 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1574 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1575 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1576 struct blob_attr
*cur
;
1580 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1582 if (tb
[OCI_PROCESS_USER_UID
])
1583 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1585 if (tb
[OCI_PROCESS_USER_GID
]) {
1586 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1587 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1591 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1594 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1596 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1601 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1604 /* always add primary GID to set of GIDs if set */
1606 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1608 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1609 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1611 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1613 opts
.num_additional_gids
= gidcnt
;
1615 DEBUG("read %zu additional groups\n", gidcnt
);
1618 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1619 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1620 opts
.set_umask
= true;
1627 OCI_PROCESS_RLIMIT_TYPE
,
1628 OCI_PROCESS_RLIMIT_SOFT
,
1629 OCI_PROCESS_RLIMIT_HARD
,
1630 __OCI_PROCESS_RLIMIT_MAX
,
1633 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1634 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1635 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1636 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1639 /* from manpage GETRLIMIT(2) */
1640 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1642 [RLIMIT_CORE
] = "CORE",
1643 [RLIMIT_CPU
] = "CPU",
1644 [RLIMIT_DATA
] = "DATA",
1645 [RLIMIT_FSIZE
] = "FSIZE",
1646 [RLIMIT_LOCKS
] = "LOCKS",
1647 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1648 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1649 [RLIMIT_NICE
] = "NICE",
1650 [RLIMIT_NOFILE
] = "NOFILE",
1651 [RLIMIT_NPROC
] = "NPROC",
1652 [RLIMIT_RSS
] = "RSS",
1653 [RLIMIT_RTPRIO
] = "RTPRIO",
1654 [RLIMIT_RTTIME
] = "RTTIME",
1655 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1656 [RLIMIT_STACK
] = "STACK",
1659 static int resolve_rlimit(char *type
) {
1660 unsigned int rltype
;
1662 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1663 if (rlimit_names
[rltype
] &&
1664 !strncmp("RLIMIT_", type
, 7) &&
1665 !strcmp(rlimit_names
[rltype
], type
+ 7))
1672 static int parseOCIrlimit(struct blob_attr
*msg
)
1674 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1676 struct rlimit
*curlim
;
1678 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1680 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1681 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1682 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1685 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1690 if (opts
.rlimits
[limtype
])
1693 curlim
= malloc(sizeof(struct rlimit
));
1694 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1695 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1697 opts
.rlimits
[limtype
] = curlim
;
1704 OCI_PROCESS_CAPABILITIES
,
1707 OCI_PROCESS_OOMSCOREADJ
,
1708 OCI_PROCESS_NONEWPRIVILEGES
,
1709 OCI_PROCESS_RLIMITS
,
1710 OCI_PROCESS_TERMINAL
,
1715 static const struct blobmsg_policy oci_process_policy
[] = {
1716 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1717 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1718 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1719 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1720 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1721 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1722 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1723 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1724 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1728 static int parseOCIprocess(struct blob_attr
*msg
)
1730 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1733 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1735 if (!tb
[OCI_PROCESS_ARGS
])
1738 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1742 if (tb
[OCI_PROCESS_TERMINAL
])
1743 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1745 if (tb
[OCI_PROCESS_NONEWPRIVILEGES
])
1746 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1748 if (tb
[OCI_PROCESS_CWD
])
1749 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1751 if (tb
[OCI_PROCESS_ENV
]) {
1752 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1757 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1760 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1761 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1764 if (tb
[OCI_PROCESS_RLIMITS
]) {
1765 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1766 res
= parseOCIrlimit(cur
);
1772 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1773 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1774 opts
.set_oom_score_adj
= true;
1781 OCI_LINUX_NAMESPACE_TYPE
,
1782 OCI_LINUX_NAMESPACE_PATH
,
1783 __OCI_LINUX_NAMESPACE_MAX
,
1786 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1787 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1788 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1791 static int resolve_nstype(char *type
) {
1792 if (!strcmp("pid", type
))
1793 return CLONE_NEWPID
;
1794 else if (!strcmp("network", type
))
1795 return CLONE_NEWNET
;
1796 else if (!strcmp("mount", type
))
1798 else if (!strcmp("ipc", type
))
1799 return CLONE_NEWIPC
;
1800 else if (!strcmp("uts", type
))
1801 return CLONE_NEWUTS
;
1802 else if (!strcmp("user", type
))
1803 return CLONE_NEWUSER
;
1804 else if (!strcmp("cgroup", type
))
1805 return CLONE_NEWCGROUP
;
1806 #ifdef CLONE_NEWTIME
1807 else if (!strcmp("time", type
))
1808 return CLONE_NEWTIME
;
1814 static int parseOCIlinuxns(struct blob_attr
*msg
)
1816 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1821 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1823 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1826 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1830 if (opts
.namespace & nstype
)
1833 setns
= get_namespace_fd(nstype
);
1841 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1842 DEBUG("opening existing %s namespace from path %s\n",
1843 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1844 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1846 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1848 return errno
?:ESTALE
;
1850 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
) {
1855 DEBUG("opened existing %s namespace got filehandler %u\n",
1856 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1861 opts
.namespace |= nstype
;
1867 static void get_jail_root_user(bool is_gidmap
, uint32_t container_id
, uint32_t host_id
, uint32_t size
)
1869 if (container_id
== 0 && size
>= 1)
1871 opts
.root_map_uid
= host_id
;
1875 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1876 OCI_LINUX_UIDGIDMAP_HOSTID
,
1877 OCI_LINUX_UIDGIDMAP_SIZE
,
1878 __OCI_LINUX_UIDGIDMAP_MAX
,
1881 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1882 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1883 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1884 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1887 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1889 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1890 struct blob_attr
*cur
;
1893 size_t len
, pos
, totallen
= 0;
1895 blobmsg_for_each_attr(cur
, msg
, rem
) {
1896 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1898 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1899 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1900 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1904 totallen
+= snprintf(NULL
, 0, "%d %d %d\n",
1905 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1906 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1907 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1910 /* allocate combined mapping string */
1911 map
= malloc(totallen
+ 1);
1916 blobmsg_for_each_attr(cur
, msg
, rem
) {
1917 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1919 get_jail_root_user(is_gidmap
, blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1920 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1921 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1923 /* write mapping line into pre-allocated string */
1924 len
= snprintf(&map
[pos
], totallen
+ 1, "%d %d %d\n",
1925 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1926 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1927 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1932 assert(totallen
== 0);
1947 OCI_DEVICES_FILEMODE
,
1953 static const struct blobmsg_policy oci_devices_policy
[] = {
1954 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1955 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1956 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
1957 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
1958 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
1959 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1960 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
1963 static mode_t
resolve_devtype(char *tstr
)
1965 if (!strcmp("c", tstr
) ||
1968 else if (!strcmp("b", tstr
))
1970 else if (!strcmp("p", tstr
))
1976 static int parseOCIdevices(struct blob_attr
*msg
)
1978 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
1979 struct blob_attr
*cur
;
1982 struct mknod_args
*tmp
;
1984 blobmsg_for_each_attr(cur
, msg
, rem
)
1987 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
1990 blobmsg_for_each_attr(cur
, msg
, rem
) {
1991 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1992 if (!tb
[OCI_DEVICES_TYPE
] ||
1993 !tb
[OCI_DEVICES_PATH
])
1996 tmp
= calloc(1, sizeof(struct mknod_args
));
2000 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
2006 if (tmp
->mode
!= S_IFIFO
) {
2007 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
]) {
2012 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
2013 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
2016 if (tb
[OCI_DEVICES_FILEMODE
]) {
2017 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
])) {
2022 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
2024 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
2027 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
2029 if (tb
[OCI_DEVICES_UID
])
2030 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
2034 if (tb
[OCI_DEVICES_GID
])
2035 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
2039 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
2040 opts
.devices
[cnt
++] = tmp
;
2043 opts
.devices
[cnt
] = NULL
;
2048 static int parseOCIsysctl(struct blob_attr
*msg
)
2050 struct blob_attr
*cur
;
2055 blobmsg_for_each_attr(cur
, msg
, rem
) {
2056 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
2065 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2070 blobmsg_for_each_attr(cur
, msg
, rem
) {
2071 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2072 if (!opts
.sysctl
[cnt
])
2075 /* replace '.' with '/' in entry name */
2076 tc
= tmp
= strdup(blobmsg_name(cur
));
2077 while ((tc
= strchr(tc
, '.')))
2080 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2081 opts
.sysctl
[cnt
]->entry
= tmp
;
2086 opts
.sysctl
[cnt
] = NULL
;
2093 OCI_LINUX_CGROUPSPATH
,
2094 OCI_LINUX_RESOURCES
,
2097 OCI_LINUX_NAMESPACES
,
2099 OCI_LINUX_UIDMAPPINGS
,
2100 OCI_LINUX_GIDMAPPINGS
,
2101 OCI_LINUX_MASKEDPATHS
,
2102 OCI_LINUX_READONLYPATHS
,
2103 OCI_LINUX_ROOTFSPROPAGATION
,
2107 static const struct blobmsg_policy oci_linux_policy
[] = {
2108 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2109 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2110 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2111 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2112 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2113 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2114 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2115 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2116 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2117 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2118 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2121 static int parseOCIlinux(struct blob_attr
*msg
)
2123 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2124 struct blob_attr
*cur
;
2128 char cgfullpath
[256] = "/sys/fs/cgroup";
2130 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2132 if (tb
[OCI_LINUX_NAMESPACES
]) {
2133 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2134 res
= parseOCIlinuxns(cur
);
2140 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2141 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2146 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2147 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2152 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2153 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2154 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, 0, NULL
, 0);
2160 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2161 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2162 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, 0, NULL
, 0);
2168 if (tb
[OCI_LINUX_SYSCTL
]) {
2169 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2174 if (tb
[OCI_LINUX_SECCOMP
]) {
2175 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2176 if (!opts
.ociseccomp
)
2180 if (tb
[OCI_LINUX_DEVICES
]) {
2181 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2186 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2187 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2188 if (cgpath
[0] == '/') {
2189 if (strlen(cgpath
) + 1 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2192 strcat(cgfullpath
, cgpath
);
2194 strcat(cgfullpath
, "/containers/");
2195 if (strlen(opts
.name
) + strlen(cgpath
) + 2 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2198 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2199 strcat(cgfullpath
, "/");
2200 strcat(cgfullpath
, cgpath
);
2203 strcat(cgfullpath
, "/containers/");
2204 if (2 * strlen(opts
.name
) + 2 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2207 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2208 strcat(cgfullpath
, "/");
2209 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2212 cgroups_init(cgfullpath
);
2214 if (tb
[OCI_LINUX_RESOURCES
]) {
2215 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2235 static const struct blobmsg_policy oci_policy
[] = {
2236 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2237 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2238 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2239 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2240 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2241 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2242 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2243 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2246 static int parseOCI(const char *jsonfile
)
2248 struct blob_attr
*tb
[__OCI_MAX
];
2249 struct blob_attr
*cur
;
2253 blob_buf_init(&ocibuf
, 0);
2255 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
)) {
2260 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2262 if (!tb
[OCI_VERSION
]) {
2267 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2268 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2273 if (tb
[OCI_HOSTNAME
])
2274 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2276 if (!tb
[OCI_PROCESS
]) {
2281 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2284 if (!tb
[OCI_ROOT
]) {
2288 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2291 if (!tb
[OCI_MOUNTS
]) {
2296 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2297 if ((res
= parseOCImount(cur
)))
2300 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2303 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2306 if (tb
[OCI_ANNOTATIONS
])
2307 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2310 blob_buf_free(&ocibuf
);
2315 static int set_oom_score_adj(void)
2320 if (!opts
.set_oom_score_adj
)
2323 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2324 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2328 dprintf(f
, "%d", opts
.oom_score_adj
);
2342 static int jail_oci_state
= OCI_STATE_CREATED
;
2343 static void pipe_send_start_container(struct uloop_timeout
*t
);
2344 static struct uloop_timeout start_container_timeout
= {
2345 .cb
= pipe_send_start_container
,
2348 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2349 struct ubus_request_data
*req
, const char *method
,
2350 struct blob_attr
*msg
)
2352 if (jail_oci_state
!= OCI_STATE_CREATED
)
2353 return UBUS_STATUS_INVALID_ARGUMENT
;
2355 uloop_timeout_add(&start_container_timeout
);
2357 return UBUS_STATUS_OK
;
2360 static struct blob_buf bb
;
2361 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2362 struct ubus_request_data
*req
, const char *method
,
2363 struct blob_attr
*msg
)
2367 switch (jail_oci_state
) {
2368 case OCI_STATE_CREATING
:
2369 statusstr
= "creating";
2371 case OCI_STATE_CREATED
:
2372 statusstr
= "created";
2374 case OCI_STATE_RUNNING
:
2375 statusstr
= "running";
2377 case OCI_STATE_STOPPED
:
2378 statusstr
= "stopped";
2381 statusstr
= "unknown";
2384 blob_buf_init(&bb
, 0);
2385 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2386 blobmsg_add_string(&bb
, "id", opts
.name
);
2387 blobmsg_add_string(&bb
, "status", statusstr
);
2388 if (jail_oci_state
== OCI_STATE_CREATED
||
2389 jail_oci_state
== OCI_STATE_RUNNING
)
2390 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2392 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2394 if (opts
.annotations
)
2395 blobmsg_add_blob(&bb
, opts
.annotations
);
2397 ubus_send_reply(ctx
, req
, bb
.head
);
2399 return UBUS_STATUS_OK
;
2403 CONTAINER_KILL_ATTR_SIGNAL
,
2404 __CONTAINER_KILL_ATTR_MAX
,
2407 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2408 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2412 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2413 struct ubus_request_data
*req
, const char *method
,
2414 struct blob_attr
*msg
)
2416 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2419 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2421 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2423 sig
= blobmsg_get_u32(cur
);
2425 if (jail_oci_state
== OCI_STATE_CREATING
)
2426 return UBUS_STATUS_NOT_FOUND
;
2428 if (kill(jail_process
.pid
, sig
) == 0)
2432 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2433 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2434 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2437 return UBUS_STATUS_UNKNOWN_ERROR
;
2441 jail_writepid(pid_t pid
)
2448 _pidfile
= fopen(opts
.pidfile
, "w");
2449 if (_pidfile
== NULL
)
2452 if (fprintf(_pidfile
, "%d\n", pid
) < 0) {
2457 if (fclose(_pidfile
))
2463 static int checkpath(const char *path
)
2465 int dirfd
= open(path
, O_RDONLY
| O_DIRECTORY
| O_CLOEXEC
);
2467 ERROR("path %s open failed %m\n", path
);
2475 static struct ubus_method container_methods
[] = {
2476 UBUS_METHOD_NOARG("start", handle_start
),
2477 UBUS_METHOD_NOARG("state", handle_state
),
2478 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2481 static struct ubus_object_type container_object_type
=
2482 UBUS_OBJECT_TYPE("container", container_methods
);
2484 static struct ubus_object container_object
= {
2485 .type
= &container_object_type
,
2486 .methods
= container_methods
,
2487 .n_methods
= ARRAY_SIZE(container_methods
),
2490 static void post_main(struct uloop_timeout
*t
);
2491 static struct uloop_timeout post_main_timeout
= {
2494 static int netns_fd
;
2495 static int pidns_fd
;
2496 #ifdef CLONE_NEWTIME
2497 static int timens_fd
;
2499 static void post_create_runtime(void);
2500 int main(int argc
, char **argv
)
2502 uid_t uid
= getuid();
2503 const char log
[] = "/dev/log";
2504 const char ubus
[] = "/var/run/ubus/ubus.sock";
2505 int ret
= EXIT_FAILURE
;
2509 ERROR("not root, aborting: %m\n");
2510 return EXIT_FAILURE
;
2515 init_library_search();
2517 exit_from_child
= false;
2519 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2522 debug
= atoi(optarg
);
2525 opts
.namespace |= CLONE_NEWNS
;
2529 opts
.namespace |= CLONE_NEWNS
;
2533 opts
.namespace |= CLONE_NEWUSER
;
2536 opts
.namespace |= CLONE_NEWCGROUP
;
2539 opts
.extroot
= realpath(optarg
, NULL
);
2542 opts
.namespace |= CLONE_NEWNS
;
2546 opts
.seccomp
= optarg
;
2547 add_mount_bind(optarg
, 1, -1);
2550 opts
.capabilities
= optarg
;
2553 opts
.no_new_privs
= 1;
2559 opts
.namespace |= CLONE_NEWNET
;
2562 opts
.namespace |= CLONE_NEWUTS
;
2563 opts
.hostname
= strdup(optarg
);
2566 opts
.namespace |= CLONE_NEWNS
;
2567 add_path_and_deps(optarg
, 1, 0, 0);
2570 opts
.namespace |= CLONE_NEWNS
;
2571 add_path_and_deps(optarg
, 0, 0, 0);
2574 opts
.namespace |= CLONE_NEWNS
;
2575 add_mount_bind(ubus
, 0, -1);
2578 opts
.namespace |= CLONE_NEWNS
;
2579 add_mount_bind(log
, 0, -1);
2585 opts
.group
= optarg
;
2588 opts
.overlaydir
= realpath(optarg
, NULL
);
2591 opts
.tmpoverlaysize
= optarg
;
2594 opts
.require_jail
= 1;
2600 opts
.ocibundle
= optarg
;
2603 opts
.immediately
= true;
2606 opts
.pidfile
= optarg
;
2611 if (opts
.namespace && !opts
.ocibundle
)
2612 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2614 /* those are filehandlers, so -1 indicates unused */
2615 opts
.setns
.pid
= -1;
2616 opts
.setns
.net
= -1;
2618 opts
.setns
.ipc
= -1;
2619 opts
.setns
.uts
= -1;
2620 opts
.setns
.user
= -1;
2621 opts
.setns
.cgroup
= -1;
2622 #ifdef CLONE_NEWTIME
2623 opts
.setns
.time
= -1;
2627 * uid in parent user namespace representing root user in new
2628 * user namespace, defaults to nobody unless specified in uidMappings
2630 opts
.root_map_uid
= 65534;
2632 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2633 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2638 if (opts
.ocibundle
) {
2643 ERROR("OCI bundle needs a named jail\n");
2647 if (asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
) < 0) {
2651 ocires
= parseOCI(jsonfile
);
2654 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2660 if (opts
.namespace & CLONE_NEWNET
) {
2662 ERROR("netns needs a named jail\n");
2669 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2670 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2675 if (opts
.extroot
&& checkpath(opts
.extroot
)) {
2676 ERROR("invalid rootfs path '%s'", opts
.extroot
);
2681 if (opts
.overlaydir
&& checkpath(opts
.overlaydir
)) {
2682 ERROR("invalid rootfs overlay path '%s'", opts
.overlaydir
);
2687 /* no <binary> param found */
2688 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2693 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
2694 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2699 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2702 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2707 parent_ctx
= ubus_connect(NULL
);
2708 ubus_add_uloop(parent_ctx
);
2710 if (opts
.ocibundle
) {
2712 if (asprintf(&objname
, "container.%s", opts
.name
) < 0) {
2717 container_object
.name
= objname
;
2718 ret
= ubus_add_object(parent_ctx
, &container_object
);
2720 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2726 /* deliberately not using 'else' on unrelated conditional branches */
2727 if (!opts
.ocibundle
) {
2728 /* allocate NULL-terminated array for argv */
2729 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(void *));
2730 if (!opts
.jail_argv
) {
2734 for (size_t s
= optind
; s
< argc
; s
++)
2735 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2737 if (opts
.namespace & CLONE_NEWUSER
)
2738 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2741 if (!opts
.extroot
) {
2742 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2743 ERROR("failed to load dependencies\n");
2749 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2750 ERROR("failed to load libpreload-seccomp.so\n");
2752 if (opts
.require_jail
) {
2758 uloop_timeout_add(&post_main_timeout
);
2770 static void post_main(struct uloop_timeout
*t
)
2772 if (apply_rlimits()) {
2773 ERROR("error applying resource limits\n");
2774 free_and_exit(EXIT_FAILURE
);
2778 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2780 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2783 if (has_namespaces()) {
2784 if (opts
.namespace & CLONE_NEWNS
) {
2785 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2786 add_mount_bind("/etc/passwd", 1, -1);
2787 add_mount_bind("/etc/group", 1, -1);
2790 #if defined(__GLIBC__)
2792 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2795 if (!(opts
.namespace & CLONE_NEWNET
)) {
2796 add_mount_bind("/etc/resolv.conf", 1, 0);
2797 } else if (opts
.setns
.ns
== -1) {
2798 /* new mount namespace to provide /dev/resolv.conf.d */
2799 char hostdir
[PATH_MAX
];
2801 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2802 mkdir_p(hostdir
, 0755);
2803 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, 0, NULL
, 0);
2806 /* default mounts */
2807 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "size=1M", -1);
2808 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2810 if (opts
.procfs
|| opts
.ocibundle
) {
2811 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0, NULL
, -1);
2814 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2815 * which cannot be expressed with OCI spec, but happends to be very useful.
2816 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2818 * If not running in a new network namespace, only make /proc/sys read-only.
2819 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2820 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2821 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2823 * This works because mounts are executed in incrementing strcmp() order and
2824 * /proc/self/net appears there before /proc/sys/net and hence the operation
2825 * succeeds as the bind-mount of /proc/self/net is performed first and then
2826 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2827 * table (and in the alphabet).
2829 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, 0, NULL
, -1))
2830 if (opts
.namespace & CLONE_NEWNET
)
2831 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0, NULL
, -1))
2832 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0, NULL
, -1);
2835 if (opts
.sysfs
|| opts
.ocibundle
)
2836 add_mount("sysfs", "/sys", "sysfs", MS_RELATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0, NULL
, -1);
2839 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, 0, "mode=1777", -1);
2843 if (opts
.setns
.pid
!= -1) {
2844 pidns_fd
= ns_open_pid("pid", getpid());
2845 setns_open(CLONE_NEWPID
);
2850 #ifdef CLONE_NEWTIME
2851 if (opts
.setns
.time
!= -1) {
2852 timens_fd
= ns_open_pid("time", getpid());
2853 setns_open(CLONE_NEWTIME
);
2859 if (opts
.namespace & CLONE_NEWUSER
) {
2860 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
2861 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
2862 free_and_exit(EXIT_FAILURE
);
2864 if (seteuid(opts
.root_map_uid
)) {
2865 ERROR("seteuid(%d) failed: %m\n", opts
.root_map_uid
);
2866 free_and_exit(EXIT_FAILURE
);
2870 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
2872 jail_process
.pid
= fork();
2875 if (jail_process
.pid
> 0) {
2876 /* parent process */
2879 uloop_process_add(&jail_process
);
2882 ERROR("seteuid(%d) failed: %m\n", opts
.root_map_uid
);
2883 free_and_exit(EXIT_FAILURE
);
2886 prctl(PR_SET_SECUREBITS
, 0);
2888 if (pidns_fd
!= -1) {
2889 setns(pidns_fd
, CLONE_NEWPID
);
2892 #ifdef CLONE_NEWTIME
2893 if (timens_fd
!= -1) {
2894 setns(timens_fd
, CLONE_NEWTIME
);
2898 if (opts
.setns
.net
!= -1)
2899 close(opts
.setns
.net
);
2900 if (opts
.setns
.ns
!= -1)
2901 close(opts
.setns
.ns
);
2902 if (opts
.setns
.ipc
!= -1)
2903 close(opts
.setns
.ipc
);
2904 if (opts
.setns
.uts
!= -1)
2905 close(opts
.setns
.uts
);
2906 if (opts
.setns
.user
!= -1)
2907 close(opts
.setns
.user
);
2908 if (opts
.setns
.cgroup
!= -1)
2909 close(opts
.setns
.cgroup
);
2912 if (read(pipes
[0], sig_buf
, 1) < 1) {
2913 ERROR("can't read from child\n");
2917 set_oom_score_adj();
2920 cgroups_apply(jail_process
.pid
);
2922 if (opts
.namespace & CLONE_NEWUSER
) {
2923 if (write_setgroups(jail_process
.pid
, true)) {
2924 ERROR("can't write setgroups\n");
2928 bool has_gr
= (opts
.gr_gid
!= -1);
2929 if (opts
.pw_uid
!= -1) {
2930 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2931 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2933 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2934 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2937 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2939 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2943 if (opts
.namespace & CLONE_NEWNET
) {
2944 netns_fd
= ns_open_pid("net", jail_process
.pid
);
2945 netns_updown(jail_process
.pid
, true);
2948 if (jail_writepid(jail_process
.pid
)) {
2949 ERROR("failed to write pidfile: %m\n");
2952 } else if (jail_process
.pid
== 0) {
2953 /* fork child process */
2954 free_and_exit(exec_jail(NULL
));
2956 ERROR("failed to clone/fork: %m\n");
2957 free_and_exit(EXIT_FAILURE
);
2959 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
2962 static void post_poststart(void);
2963 static void post_create_runtime(void)
2968 if (write(pipes
[3], sig_buf
, 1) < 0) {
2969 ERROR("can't write to child\n");
2973 jail_oci_state
= OCI_STATE_CREATED
;
2974 if (opts
.ocibundle
&& !opts
.immediately
)
2975 uloop_run(); /* wait for 'start' command via ubus */
2977 pipe_send_start_container(NULL
);
2980 static void pipe_send_start_container(struct uloop_timeout
*t
)
2984 jail_oci_state
= OCI_STATE_RUNNING
;
2986 if (write(pipes
[3], sig_buf
, 1) < 0) {
2987 ERROR("can't write to child\n");
2992 run_hooks(opts
.hooks
.poststart
, post_poststart
);
2995 static void post_poststart(void)
2997 uloop_run(); /* idle here while jail is running */
2999 DEBUG("uloop interrupted, killing jail process\n");
3000 kill(jail_process
.pid
, SIGTERM
);
3001 uloop_timeout_set(&jail_process_timeout
, 1000);
3008 static void post_poststop(void);
3009 static void poststop(void) {
3010 if (opts
.namespace & CLONE_NEWNET
) {
3011 setns(netns_fd
, CLONE_NEWNET
);
3012 netns_updown(getpid(), false);
3015 run_hooks(opts
.hooks
.poststop
, post_poststop
);
3018 static void post_poststop(void)
3022 ubus_free(parent_ctx
);
3024 exit(jail_return_code
);