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:EfFG:h:ij:J:ln:NoO:pP:r:R:sS:uU:w: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
;
158 static struct blob_buf ocibuf
;
160 extern int pivot_root(const char *new_root
, const char *put_old
);
164 static char child_stack
[STACK_SIZE
];
166 static struct ubus_context
*parent_ctx
;
171 static inline bool has_namespaces(void)
173 return ((opts
.setns
.pid
!= -1) ||
174 (opts
.setns
.net
!= -1) ||
175 (opts
.setns
.ns
!= -1) ||
176 (opts
.setns
.ipc
!= -1) ||
177 (opts
.setns
.uts
!= -1) ||
178 (opts
.setns
.user
!= -1) ||
179 (opts
.setns
.cgroup
!= -1) ||
181 (opts
.setns
.time
!= -1) ||
186 static void free_oci_envp(char **p
) {
198 static void free_hooklist(struct hook_execvpe
**hooklist
)
200 struct hook_execvpe
*cur
;
207 free_oci_envp(cur
->argv
);
208 free_oci_envp(cur
->envp
);
215 static void free_sysctl(void) {
216 struct sysctl_val
*cur
;
227 static void free_devices(void) {
228 struct mknod_args
**cur
;
242 static void free_rlimits(void) {
245 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
246 free(opts
.rlimits
[type
]);
249 static void free_opts(bool parent
) {
251 free_library_search();
255 /* we need to keep argv, envp and seccomp filter in child */
256 if (parent
) { /* parent-only */
257 if (opts
.ociseccomp
) {
258 free(opts
.ociseccomp
->filter
);
259 free(opts
.ociseccomp
);
262 free_oci_envp(opts
.jail_argv
);
263 free_oci_envp(opts
.envp
);
273 free(opts
.annotations
);
275 free(opts
.overlaydir
);
276 free_hooklist(opts
.hooks
.createRuntime
);
277 free_hooklist(opts
.hooks
.createContainer
);
278 free_hooklist(opts
.hooks
.startContainer
);
279 free_hooklist(opts
.hooks
.poststart
);
280 free_hooklist(opts
.hooks
.poststop
);
283 static int mount_overlay(char *jail_root
, char *overlaydir
) {
284 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
285 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
288 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
291 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
294 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
297 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
301 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
302 * this is to work-around a bug in overlayfs described in the overlayfs-userns
304 * 3. modification of a file 'hithere' which is in l but not yet
305 * in u, and which is not owned by T, is not allowed, even if
306 * writes to u are allowed. This may be a bug in overlayfs,
307 * but it is safe behavior.
309 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
312 if (mkdir_p(upperetc
, 0755))
313 goto upper_etc_printf
;
315 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
316 goto upper_etc_printf
;
318 fd
= creat(upperresolvconf
, 0644);
321 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
325 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
327 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
328 goto upper_resolvconf_printf
;
332 upper_resolvconf_printf
:
333 free(upperresolvconf
);
346 static void pass_console(int console_fd
)
348 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
349 static struct blob_buf req
;
355 blob_buf_init(&req
, 0);
356 blobmsg_add_string(&req
, "name", opts
.name
);
358 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
359 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
360 INFO("ubus request failed\n");
365 ubus_free(child_ctx
);
368 static int create_dev_console(const char *jail_root
)
371 char dev_console_path
[PATH_MAX
];
372 int slave_console_fd
;
374 /* Open UNIX/98 virtual console */
375 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
379 console_fname
= ptsname(console_fd
);
380 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
385 unlockpt(console_fd
);
387 /* pass PTY master to procd */
388 pass_console(console_fd
);
390 /* mount-bind PTY slave to /dev/console in jail */
391 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
392 close(creat(dev_console_path
, 0620));
394 if (mount(console_fname
, dev_console_path
, "bind", MS_BIND
, NULL
))
397 /* use PTY slave for stdio */
398 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
399 if (slave_console_fd
< 0)
402 dup2(slave_console_fd
, 0);
403 dup2(slave_console_fd
, 1);
404 dup2(slave_console_fd
, 2);
405 close(slave_console_fd
);
407 INFO("using guest console %s\n", console_fname
);
416 static int hook_running
= 0;
417 static int hook_return_code
= 0;
418 static struct hook_execvpe
**current_hook
= NULL
;
419 typedef void (*hook_return_handler
)(void);
420 static hook_return_handler hook_return_cb
= NULL
;
422 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
423 static struct uloop_timeout hook_process_timeout
= {
424 .cb
= hook_process_timeout_cb
,
427 static void run_hooklist(void);
428 static void hook_process_handler(struct uloop_process
*c
, int ret
)
430 uloop_timeout_cancel(&hook_process_timeout
);
432 if (WIFEXITED(ret
)) {
433 hook_return_code
= WEXITSTATUS(ret
);
434 if (hook_return_code
)
435 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
437 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
440 hook_return_code
= WTERMSIG(ret
);
441 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
448 static struct uloop_process hook_process
= {
449 .cb
= hook_process_handler
,
452 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
454 DEBUG("hook process failed to stop, sending SIGKILL\n");
455 kill(hook_process
.pid
, SIGKILL
);
458 static void run_hooklist(void)
460 struct hook_execvpe
*hook
= *current_hook
;
464 return hook_return_cb();
466 DEBUG("executing hook %s\n", hook
->file
);
468 if (stat(hook
->file
, &s
))
469 hook_process_handler(&hook_process
, ENOENT
);
471 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
472 hook_process_handler(&hook_process
, EPERM
);
475 hook_process
.pid
= fork();
476 if (hook_process
.pid
== 0) {
478 execve(hook
->file
, hook
->argv
, hook
->envp
);
479 ERROR("execve error %m\n");
481 } else if (hook_process
.pid
< 0) {
483 ERROR("hook fork error\n");
485 hook_process_handler(&hook_process
, errno
);
489 uloop_process_add(&hook_process
);
491 if (hook
->timeout
> 0)
492 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
496 DEBUG("uloop interrupted, killing jail process\n");
497 kill(hook_process
.pid
, SIGTERM
);
498 uloop_timeout_set(&hook_process_timeout
, 1000);
503 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
508 current_hook
= hooklist
;
509 hook_return_cb
= return_cb
;
514 static int apply_sysctl(const char *jail_root
)
516 struct sysctl_val
**cur
;
517 char *procdir
, *fname
;
523 if (asprintf(&procdir
, "%s/proc", jail_root
) < 0)
526 mkdir(procdir
, 0700);
527 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
533 if (asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
) < 0)
536 DEBUG("sysctl: writing '%s' to %s\n", (*cur
)->value
, fname
);
538 f
= open(fname
, O_WRONLY
);
540 ERROR("sysctl: can't open %s\n", fname
);
544 if (write(f
, (*cur
)->value
, strlen((*cur
)->value
)) < 0) {
545 ERROR("sysctl: write to %s\n", fname
);
562 /* glibc defines makedev calling a function. make sure it's a pure macro */
563 #if defined(__GLIBC__)
565 /* from musl's sys/sysmacros.h */
566 #define makedev(x,y) ( \
567 (((x)&0xfffff000ULL) << 32) | \
568 (((x)&0x00000fffULL) << 8) | \
569 (((y)&0xffffff00ULL) << 12) | \
570 (((y)&0x000000ffULL)) )
573 static struct mknod_args default_devices
[] = {
574 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
575 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
576 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
577 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
578 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
579 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
583 static int create_devices(void)
585 struct mknod_args
**cur
, *curdef
;
589 goto only_default_devices
;
595 /* don't allow devices outside of /dev */
596 if (strncmp(path
, "/dev", 4))
599 /* make sure parent folder exists */
600 tmp
= strrchr(path
, '/');
605 if (strcmp(path
, "/dev")) {
606 DEBUG("creating directory %s\n", path
);
612 DEBUG("creating %s (mode=%08o)\n", path
, (*cur
)->mode
);
615 if (mknod(path
, (*cur
)->mode
, (*cur
)->dev
))
618 /* change owner, if needed */
619 if (((*cur
)->uid
|| (*cur
)->gid
) &&
620 chown(path
, (*cur
)->uid
, (*cur
)->gid
))
626 only_default_devices
:
627 curdef
= default_devices
;
628 while(curdef
->path
) {
629 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
630 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
632 continue; /* may already exist, eg. due to a bind-mount */
634 if ((curdef
->uid
|| curdef
->gid
) &&
635 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
641 /* Dev symbolic links as defined in OCI spec */
642 (void) symlink("/dev/pts/ptmx", "/dev/ptmx");
643 (void) symlink("/proc/self/fd", "/dev/fd");
644 (void) symlink("/proc/self/fd/0", "/dev/stdin");
645 (void) symlink("/proc/self/fd/1", "/dev/stdout");
646 (void) symlink("/proc/self/fd/2", "/dev/stderr");
651 static char jail_root
[] = "/tmp/ujail-XXXXXX";
652 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
653 static mode_t old_umask
;
654 static void enter_jail_fs(void);
655 static int build_jail_fs(void)
657 char *overlaydir
= NULL
;
660 old_umask
= umask(0);
662 if (mkdtemp(jail_root
) == NULL
) {
663 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
667 if (apply_sysctl(jail_root
)) {
668 ERROR("failed to apply sysctl values\n");
672 /* oldroot can't be MS_SHARED else pivot_root() fails */
673 if (mount("none", "/", "none", MS_REC
|MS_PRIVATE
, NULL
)) {
674 ERROR("private mount failed %m\n");
679 if (mount(opts
.extroot
, jail_root
, "bind", MS_BIND
, NULL
)) {
680 ERROR("extroot mount failed %m\n");
684 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
685 ERROR("tmpfs mount failed %m\n");
690 if (opts
.tmpoverlaysize
) {
691 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
693 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
694 "mode=0755,size=%s", opts
.tmpoverlaysize
);
695 if (mkdtemp(tmpovdir
) == NULL
) {
696 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
699 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
701 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
704 overlaydir
= tmpovdir
;
708 overlaydir
= opts
.overlaydir
;
711 ret
= mount_overlay(jail_root
, overlaydir
);
716 if (chdir(jail_root
)) {
717 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
721 if (mount_all(jail_root
)) {
722 ERROR("mount_all() failed\n");
727 create_dev_console(jail_root
);
729 /* make sure /etc/resolv.conf exists if in new network namespace */
730 if (opts
.namespace & CLONE_NEWNET
) {
731 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
733 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
734 mkdir_p(jailetc
, 0755);
735 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
739 (void) symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
742 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
747 static bool exit_from_child
;
748 static void free_and_exit(int ret
)
750 if (!exit_from_child
&& opts
.ocibundle
)
753 if (!exit_from_child
&& parent_ctx
)
754 ubus_free(parent_ctx
);
756 free_opts(!exit_from_child
);
761 static void post_jail_fs(void);
762 static void enter_jail_fs(void)
764 char dirbuf
[sizeof(jail_root
) + 4];
766 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
769 if (pivot_root(jail_root
, dirbuf
) == -1) {
770 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
774 ERROR("chdir(/) (after pivot_root) failed: %m\n");
778 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
779 umount2(dirbuf
, MNT_DETACH
);
781 if (opts
.tmpoverlaysize
) {
782 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
783 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
784 umount2(tmpdirbuf
, MNT_DETACH
);
788 umount2("/old", MNT_DETACH
);
791 if (create_devices()) {
792 ERROR("create_devices() failed\n");
796 mount(NULL
, "/", "bind", MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
802 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
807 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
808 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
811 if ((map_file
= open(map_path
, O_WRONLY
)) < 0)
814 if (dprintf(map_file
, "%s", mapstr
)) {
823 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
827 const char *map_format
= "%d %d %d\n";
828 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
829 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
832 if ((map_file
= open(map_path
, O_WRONLY
)) < 0)
835 if (dprintf(map_file
, map_format
, 0, id
, 1) < 0) {
844 static int write_setgroups(pid_t child_pid
, bool allow
)
847 char setgroups_path
[64];
849 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
854 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) < 0) {
858 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
859 close(setgroups_file
);
863 close(setgroups_file
);
867 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
869 struct passwd
*p
= NULL
;
870 struct group
*g
= NULL
;
873 p
= getpwnam(opts
.user
);
875 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
876 opts
.user
, errno
, strerror(errno
));
877 free_and_exit(EXIT_FAILURE
);
880 *user_gid
= p
->pw_gid
;
887 g
= getgrnam(opts
.group
);
889 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
890 free_and_exit(EXIT_FAILURE
);
898 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
900 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
901 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
902 free_and_exit(EXIT_FAILURE
);
905 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
906 ERROR("failed to set group id %d: %m\n", gr_gid
);
907 free_and_exit(EXIT_FAILURE
);
910 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
911 ERROR("failed to set user id %d: %m\n", pw_uid
);
912 free_and_exit(EXIT_FAILURE
);
916 static int apply_rlimits(void)
920 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
921 if (opts
.rlimits
[resource
])
922 DEBUG("applying limits to resource %u\n", resource
);
924 if (opts
.rlimits
[resource
] &&
925 setrlimit(resource
, opts
.rlimits
[resource
]))
933 static char** build_envp(const char *seccomp
, char **ocienvp
)
935 static char *envp
[MAX_ENVP
];
936 static char preload_var
[PATH_MAX
];
937 static char seccomp_var
[PATH_MAX
];
938 static char seccomp_debug_var
[20];
939 static char debug_var
[] = "LD_DEBUG=all";
940 static char container_var
[] = "container=ujail";
941 const char *preload_lib
= find_lib("libpreload-seccomp.so");
946 if (seccomp
&& !preload_lib
) {
947 ERROR("failed to add preload-lib to env\n");
951 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
952 envp
[count
++] = seccomp_var
;
953 snprintf(seccomp_debug_var
, sizeof(seccomp_debug_var
), "SECCOMP_DEBUG=%2d", debug
);
954 envp
[count
++] = seccomp_debug_var
;
955 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
956 envp
[count
++] = preload_var
;
959 envp
[count
++] = container_var
;
962 envp
[count
++] = debug_var
;
965 while (addenv
&& *addenv
) {
966 envp
[count
++] = *(addenv
++);
967 if (count
>= MAX_ENVP
) {
968 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
975 static void usage(void)
977 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
978 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
979 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
980 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
981 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
982 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
983 fprintf(stderr
, "namespace jail options:\n");
984 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
985 fprintf(stderr
, " -N\t\tjail has network namespace\n");
986 fprintf(stderr
, " -f\t\tjail has user namespace\n");
987 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
988 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
989 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
990 fprintf(stderr
, " -p\t\tjail has /proc\n");
991 fprintf(stderr
, " -s\t\tjail has /sys\n");
992 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
993 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
994 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
995 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
996 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
997 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
998 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
999 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
1000 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
1001 fprintf(stderr
, " -y\t\tprovide jail console\n");
1002 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
1003 fprintf(stderr
, " -i\t\tstart container immediately\n");
1004 fprintf(stderr
, " -P <pidfile>\tcreate <pidfile>\n");
1005 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
1006 and he has the same powers as root outside the jail,\n\
1007 thus he can escape the jail and/or break stuff.\n\
1008 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
1009 If you use none of the namespace jail options,\n\
1010 ujail will not use namespace/build a jail,\n\
1011 and will only drop capabilities/apply seccomp filter.\n\n");
1014 static int* get_namespace_fd(const unsigned int nstype
)
1018 return &opts
.setns
.pid
;
1020 return &opts
.setns
.net
;
1022 return &opts
.setns
.ns
;
1024 return &opts
.setns
.ipc
;
1026 return &opts
.setns
.uts
;
1028 return &opts
.setns
.user
;
1029 case CLONE_NEWCGROUP
:
1030 return &opts
.setns
.cgroup
;
1031 #ifdef CLONE_NEWTIME
1033 return &opts
.setns
.time
;
1040 static int setns_open(unsigned long nstype
)
1042 int *fd
= get_namespace_fd(nstype
);
1049 if (setns(*fd
, nstype
) == -1) {
1058 static int jail_running
= 0;
1059 static int jail_return_code
= 0;
1061 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1062 static struct uloop_timeout jail_process_timeout
= {
1063 .cb
= jail_process_timeout_cb
,
1065 static void poststop(void);
1066 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1068 uloop_timeout_cancel(&jail_process_timeout
);
1069 if (WIFEXITED(ret
)) {
1070 jail_return_code
= WEXITSTATUS(ret
);
1071 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1073 jail_return_code
= WTERMSIG(ret
);
1074 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1080 static struct uloop_process jail_process
= {
1081 .cb
= jail_process_handler
,
1084 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1086 DEBUG("jail process failed to stop, sending SIGKILL\n");
1087 kill(jail_process
.pid
, SIGKILL
);
1090 static void jail_handle_signal(int signo
)
1093 DEBUG("forwarding signal %d to the hook process\n", signo
);
1094 kill(hook_process
.pid
, signo
);
1098 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1099 kill(jail_process
.pid
, signo
);
1103 static void signals_init(void)
1108 sigfillset(&sigmask
);
1109 for (i
= 0; i
< _NSIG
; i
++) {
1110 struct sigaction s
= { 0 };
1112 if (!sigismember(&sigmask
, i
))
1114 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1117 s
.sa_handler
= jail_handle_signal
;
1118 sigaction(i
, &s
, NULL
);
1122 static void pre_exec_jail(struct uloop_timeout
*t
);
1123 static struct uloop_timeout pre_exec_timeout
= {
1124 .cb
= pre_exec_jail
,
1128 static int exec_jail(void *arg
)
1132 exit_from_child
= true;
1133 prctl(PR_SET_SECUREBITS
, 0);
1141 setns_open(CLONE_NEWUSER
);
1142 setns_open(CLONE_NEWNET
);
1143 setns_open(CLONE_NEWNS
);
1144 setns_open(CLONE_NEWIPC
);
1145 setns_open(CLONE_NEWUTS
);
1148 if (write(pipes
[1], buf
, 1) < 1) {
1149 ERROR("can't write to parent\n");
1150 return EXIT_FAILURE
;
1153 if (read(pipes
[2], buf
, 1) < 1) {
1154 ERROR("can't read from parent\n");
1155 return EXIT_FAILURE
;
1157 if (buf
[0] != 'O') {
1158 ERROR("parent had an error, child exiting\n");
1159 return EXIT_FAILURE
;
1162 if (opts
.namespace & CLONE_NEWCGROUP
)
1163 unshare(CLONE_NEWCGROUP
);
1165 setns_open(CLONE_NEWCGROUP
);
1167 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1168 if (setregid(0, 0) < 0) {
1170 free_and_exit(EXIT_FAILURE
);
1172 if (setreuid(0, 0) < 0) {
1174 free_and_exit(EXIT_FAILURE
);
1176 if (setgroups(0, NULL
) < 0) {
1177 ERROR("setgroups\n");
1178 free_and_exit(EXIT_FAILURE
);
1182 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1183 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1184 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1185 free_and_exit(EXIT_FAILURE
);
1188 uloop_timeout_add(&pre_exec_timeout
);
1195 static void pre_exec_jail(struct uloop_timeout
*t
)
1197 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1198 ERROR("failed to build jail fs\n");
1199 free_and_exit(EXIT_FAILURE
);
1201 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1205 static void post_start_hook(void);
1206 static void post_jail_fs(void)
1210 if (read(pipes
[2], buf
, 1) < 1) {
1211 ERROR("can't read from parent\n");
1212 free_and_exit(EXIT_FAILURE
);
1214 if (buf
[0] != '!') {
1215 ERROR("parent had an error, child exiting\n");
1216 free_and_exit(EXIT_FAILURE
);
1220 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1223 static void post_start_hook(void)
1225 int pw_uid
, pw_gid
, gr_gid
;
1228 * make sure setuid/setgid won't drop capabilities in case capabilities
1229 * have been specified explicitely.
1231 if (opts
.capset
.apply
) {
1232 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1233 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1234 free_and_exit(EXIT_FAILURE
);
1238 /* drop capabilities, retain those still needed to further setup jail */
1239 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1240 free_and_exit(EXIT_FAILURE
);
1242 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1243 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1244 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1246 if (opts
.additional_gids
&&
1247 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1248 ERROR("setgroups failed: %m\n");
1249 free_and_exit(EXIT_FAILURE
);
1255 /* restore securebits back to normal (and lock them if not in userns) */
1256 if (opts
.capset
.apply
) {
1257 if (prctl(PR_SET_SECUREBITS
, (opts
.namespace & CLONE_NEWUSER
)?0:
1258 SECBIT_KEEP_CAPS_LOCKED
|SECBIT_NO_SETUID_FIXUP_LOCKED
|SECBIT_NOROOT_LOCKED
)) {
1259 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1260 free_and_exit(EXIT_FAILURE
);
1264 /* drop remaining capabilities to end up with specified sets */
1265 if (applyOCIcapabilities(opts
.capset
, 0))
1266 free_and_exit(EXIT_FAILURE
);
1268 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1269 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1270 free_and_exit(EXIT_FAILURE
);
1273 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1275 free_and_exit(EXIT_FAILURE
);
1277 if (opts
.cwd
&& chdir(opts
.cwd
))
1278 free_and_exit(EXIT_FAILURE
);
1280 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1281 free_and_exit(EXIT_FAILURE
);
1285 INFO("exec-ing %s\n", *opts
.jail_argv
);
1286 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1287 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1289 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1291 /* we get there only if execve fails */
1292 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1296 int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1298 char pid_pid_path
[PATH_MAX
];
1300 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1302 return open(pid_pid_path
, O_RDONLY
);
1305 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1307 struct blob_attr
*cur
;
1310 blobmsg_for_each_attr(cur
, msg
, rem
)
1314 *envp
= calloc(1 + sz
, sizeof(char*));
1323 blobmsg_for_each_attr(cur
, msg
, rem
)
1324 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1338 static const struct blobmsg_policy oci_root_policy
[] = {
1339 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1340 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1343 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1345 char extroot
[PATH_MAX
] = { 0 };
1346 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1350 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1352 if (!tb
[OCI_ROOT_PATH
])
1355 root_path
= blobmsg_get_string(tb
[OCI_ROOT_PATH
]);
1357 /* prepend bundle directory in case of relative paths */
1358 if (root_path
[0] != '/') {
1359 strncpy(extroot
, jsonfile
, PATH_MAX
- 1);
1361 cur
= strrchr(extroot
, '/');
1369 strncat(extroot
, root_path
, PATH_MAX
- (strlen(extroot
) + 1));
1371 /* follow symbolic link(s) */
1372 opts
.extroot
= realpath(extroot
, NULL
);
1376 if (tb
[OCI_ROOT_READONLY
])
1377 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1391 static const struct blobmsg_policy oci_hook_policy
[] = {
1392 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1393 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1394 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1395 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1399 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1401 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1402 struct blob_attr
*cur
;
1406 blobmsg_for_each_attr(cur
, msg
, rem
)
1412 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1418 blobmsg_for_each_attr(cur
, msg
, rem
) {
1419 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1421 if (!tb
[OCI_HOOK_PATH
]) {
1426 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1427 if (tb
[OCI_HOOK_ARGS
]) {
1428 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1432 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1433 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1434 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1438 if (tb
[OCI_HOOK_ENV
]) {
1439 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1444 if (tb
[OCI_HOOK_TIMEOUT
])
1445 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1447 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1452 (*hooklist
)[idx
] = NULL
;
1454 DEBUG("added %d hooks\n", idx
);
1459 free_hooklist(*hooklist
);
1468 OCI_HOOKS_CREATERUNTIME
,
1469 OCI_HOOKS_CREATECONTAINER
,
1470 OCI_HOOKS_STARTCONTAINER
,
1471 OCI_HOOKS_POSTSTART
,
1476 static const struct blobmsg_policy oci_hooks_policy
[] = {
1477 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1478 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1479 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1480 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1481 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1482 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1485 static int parseOCIhooks(struct blob_attr
*msg
)
1487 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1490 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1492 if (tb
[OCI_HOOKS_PRESTART
])
1493 INFO("warning: ignoring deprecated prestart hook\n");
1495 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1496 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1501 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1502 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1504 goto out_createruntime
;
1507 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1508 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1510 goto out_createcontainer
;
1513 if (tb
[OCI_HOOKS_POSTSTART
]) {
1514 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1516 goto out_startcontainer
;
1519 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1520 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1528 free_hooklist(opts
.hooks
.poststart
);
1530 free_hooklist(opts
.hooks
.startContainer
);
1531 out_createcontainer
:
1532 free_hooklist(opts
.hooks
.createContainer
);
1534 free_hooklist(opts
.hooks
.createRuntime
);
1541 OCI_PROCESS_USER_UID
,
1542 OCI_PROCESS_USER_GID
,
1543 OCI_PROCESS_USER_UMASK
,
1544 OCI_PROCESS_USER_ADDITIONALGIDS
,
1545 __OCI_PROCESS_USER_MAX
,
1548 static const struct blobmsg_policy oci_process_user_policy
[] = {
1549 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1550 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1551 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1552 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1555 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1556 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1557 struct blob_attr
*cur
;
1561 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1563 if (tb
[OCI_PROCESS_USER_UID
])
1564 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1566 if (tb
[OCI_PROCESS_USER_GID
]) {
1567 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1568 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1572 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1575 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1577 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1582 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1585 /* always add primary GID to set of GIDs if set */
1587 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1589 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1590 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1592 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1594 opts
.num_additional_gids
= gidcnt
;
1596 DEBUG("read %zu additional groups\n", gidcnt
);
1599 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1600 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1601 opts
.set_umask
= true;
1608 OCI_PROCESS_RLIMIT_TYPE
,
1609 OCI_PROCESS_RLIMIT_SOFT
,
1610 OCI_PROCESS_RLIMIT_HARD
,
1611 __OCI_PROCESS_RLIMIT_MAX
,
1614 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1615 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1616 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1617 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1620 /* from manpage GETRLIMIT(2) */
1621 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1623 [RLIMIT_CORE
] = "CORE",
1624 [RLIMIT_CPU
] = "CPU",
1625 [RLIMIT_DATA
] = "DATA",
1626 [RLIMIT_FSIZE
] = "FSIZE",
1627 [RLIMIT_LOCKS
] = "LOCKS",
1628 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1629 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1630 [RLIMIT_NICE
] = "NICE",
1631 [RLIMIT_NOFILE
] = "NOFILE",
1632 [RLIMIT_NPROC
] = "NPROC",
1633 [RLIMIT_RSS
] = "RSS",
1634 [RLIMIT_RTPRIO
] = "RTPRIO",
1635 [RLIMIT_RTTIME
] = "RTTIME",
1636 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1637 [RLIMIT_STACK
] = "STACK",
1640 static int resolve_rlimit(char *type
) {
1641 unsigned int rltype
;
1643 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1644 if (rlimit_names
[rltype
] &&
1645 !strncmp("RLIMIT_", type
, 7) &&
1646 !strcmp(rlimit_names
[rltype
], type
+ 7))
1653 static int parseOCIrlimit(struct blob_attr
*msg
)
1655 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1657 struct rlimit
*curlim
;
1659 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1661 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1662 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1663 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1666 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1671 if (opts
.rlimits
[limtype
])
1674 curlim
= malloc(sizeof(struct rlimit
));
1675 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1676 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1678 opts
.rlimits
[limtype
] = curlim
;
1685 OCI_PROCESS_CAPABILITIES
,
1688 OCI_PROCESS_OOMSCOREADJ
,
1689 OCI_PROCESS_NONEWPRIVILEGES
,
1690 OCI_PROCESS_RLIMITS
,
1691 OCI_PROCESS_TERMINAL
,
1696 static const struct blobmsg_policy oci_process_policy
[] = {
1697 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1698 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1699 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1700 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1701 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1702 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1703 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1704 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1705 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1709 static int parseOCIprocess(struct blob_attr
*msg
)
1711 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1714 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1716 if (!tb
[OCI_PROCESS_ARGS
])
1719 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1723 if (tb
[OCI_PROCESS_TERMINAL
])
1724 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1726 if (tb
[OCI_PROCESS_NONEWPRIVILEGES
])
1727 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1729 if (tb
[OCI_PROCESS_CWD
])
1730 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1732 if (tb
[OCI_PROCESS_ENV
]) {
1733 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1738 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1741 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1742 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1745 if (tb
[OCI_PROCESS_RLIMITS
]) {
1746 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1747 res
= parseOCIrlimit(cur
);
1753 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1754 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1755 opts
.set_oom_score_adj
= true;
1762 OCI_LINUX_NAMESPACE_TYPE
,
1763 OCI_LINUX_NAMESPACE_PATH
,
1764 __OCI_LINUX_NAMESPACE_MAX
,
1767 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1768 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1769 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1772 static int resolve_nstype(char *type
) {
1773 if (!strcmp("pid", type
))
1774 return CLONE_NEWPID
;
1775 else if (!strcmp("network", type
))
1776 return CLONE_NEWNET
;
1777 else if (!strcmp("net", type
))
1778 return CLONE_NEWNET
;
1779 else if (!strcmp("mount", type
))
1781 else if (!strcmp("ipc", type
))
1782 return CLONE_NEWIPC
;
1783 else if (!strcmp("uts", type
))
1784 return CLONE_NEWUTS
;
1785 else if (!strcmp("user", type
))
1786 return CLONE_NEWUSER
;
1787 else if (!strcmp("cgroup", type
))
1788 return CLONE_NEWCGROUP
;
1789 #ifdef CLONE_NEWTIME
1790 else if (!strcmp("time", type
))
1791 return CLONE_NEWTIME
;
1797 static int parseOCIlinuxns(struct blob_attr
*msg
)
1799 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1804 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1806 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1809 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1813 if (opts
.namespace & nstype
)
1816 setns
= get_namespace_fd(nstype
);
1824 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1825 DEBUG("opening existing %s namespace from path %s\n",
1826 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1827 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1829 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1831 return errno
?:ESTALE
;
1833 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
) {
1838 DEBUG("opened existing %s namespace got filehandler %u\n",
1839 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1844 opts
.namespace |= nstype
;
1851 * join namespace of existing PID
1852 * The string argument is the reference PID followed by ':' and a
1853 * ',' separated list of namespaces to to join.
1855 static int jail_join_ns(char *arg
)
1860 char *tmp
, *etmp
, *nspath
;
1863 tmp
= strchr(arg
, ':');
1872 etmp
= strchr(tmp
, ',');
1876 nstype
= resolve_nstype(tmp
);
1880 if (opts
.namespace & nstype
)
1883 setns
= get_namespace_fd(nstype
);
1891 if (asprintf(&nspath
, "/proc/%d/ns/%s", pid
, tmp
) < 0)
1894 fd
= open(nspath
, O_RDONLY
);
1898 return errno
?:ESTALE
;
1911 static void get_jail_root_user(bool is_gidmap
, uint32_t container_id
, uint32_t host_id
, uint32_t size
)
1913 if (container_id
== 0 && size
>= 1)
1915 opts
.root_map_uid
= host_id
;
1919 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1920 OCI_LINUX_UIDGIDMAP_HOSTID
,
1921 OCI_LINUX_UIDGIDMAP_SIZE
,
1922 __OCI_LINUX_UIDGIDMAP_MAX
,
1925 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1926 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1927 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1928 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1931 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1933 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1934 struct blob_attr
*cur
;
1937 size_t len
, pos
, totallen
= 0;
1939 blobmsg_for_each_attr(cur
, msg
, rem
) {
1940 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1942 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1943 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1944 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1948 totallen
+= snprintf(NULL
, 0, "%d %d %d\n",
1949 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1950 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1951 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1954 /* allocate combined mapping string */
1955 map
= malloc(totallen
+ 1);
1960 blobmsg_for_each_attr(cur
, msg
, rem
) {
1961 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1963 get_jail_root_user(is_gidmap
, blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1964 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1965 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1967 /* write mapping line into pre-allocated string */
1968 len
= snprintf(&map
[pos
], totallen
+ 1, "%d %d %d\n",
1969 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1970 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1971 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1976 assert(totallen
== 0);
1991 OCI_DEVICES_FILEMODE
,
1997 static const struct blobmsg_policy oci_devices_policy
[] = {
1998 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1999 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
2000 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
2001 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
2002 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
2003 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
2004 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
2007 static mode_t
resolve_devtype(char *tstr
)
2009 if (!strcmp("c", tstr
) ||
2012 else if (!strcmp("b", tstr
))
2014 else if (!strcmp("p", tstr
))
2020 static int parseOCIdevices(struct blob_attr
*msg
)
2022 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
2023 struct blob_attr
*cur
;
2026 struct mknod_args
*tmp
;
2028 blobmsg_for_each_attr(cur
, msg
, rem
)
2031 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
2034 blobmsg_for_each_attr(cur
, msg
, rem
) {
2035 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
2036 if (!tb
[OCI_DEVICES_TYPE
] ||
2037 !tb
[OCI_DEVICES_PATH
])
2040 tmp
= calloc(1, sizeof(struct mknod_args
));
2044 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
2050 if (tmp
->mode
!= S_IFIFO
) {
2051 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
]) {
2056 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
2057 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
2060 if (tb
[OCI_DEVICES_FILEMODE
]) {
2061 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
])) {
2066 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
2068 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
2071 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
2073 if (tb
[OCI_DEVICES_UID
])
2074 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
2078 if (tb
[OCI_DEVICES_GID
])
2079 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
2083 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
2084 opts
.devices
[cnt
++] = tmp
;
2087 opts
.devices
[cnt
] = NULL
;
2092 static int parseOCIsysctl(struct blob_attr
*msg
)
2094 struct blob_attr
*cur
;
2099 blobmsg_for_each_attr(cur
, msg
, rem
) {
2100 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
2109 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2114 blobmsg_for_each_attr(cur
, msg
, rem
) {
2115 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2116 if (!opts
.sysctl
[cnt
])
2119 /* replace '.' with '/' in entry name */
2120 tc
= tmp
= strdup(blobmsg_name(cur
));
2121 while ((tc
= strchr(tc
, '.')))
2124 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2125 opts
.sysctl
[cnt
]->entry
= tmp
;
2130 opts
.sysctl
[cnt
] = NULL
;
2137 OCI_LINUX_CGROUPSPATH
,
2138 OCI_LINUX_RESOURCES
,
2141 OCI_LINUX_NAMESPACES
,
2143 OCI_LINUX_UIDMAPPINGS
,
2144 OCI_LINUX_GIDMAPPINGS
,
2145 OCI_LINUX_MASKEDPATHS
,
2146 OCI_LINUX_READONLYPATHS
,
2147 OCI_LINUX_ROOTFSPROPAGATION
,
2151 static const struct blobmsg_policy oci_linux_policy
[] = {
2152 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2153 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2154 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2155 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2156 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2157 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2158 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2159 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2160 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2161 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2162 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2165 static int parseOCIlinux(struct blob_attr
*msg
)
2167 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2168 struct blob_attr
*cur
;
2172 char cgfullpath
[256] = "/sys/fs/cgroup";
2174 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2176 if (tb
[OCI_LINUX_NAMESPACES
]) {
2177 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2178 res
= parseOCIlinuxns(cur
);
2184 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2185 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2190 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2191 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2196 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2197 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2198 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, 0, NULL
, 0);
2204 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2205 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2206 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, 0, NULL
, 0);
2212 if (tb
[OCI_LINUX_SYSCTL
]) {
2213 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2218 if (tb
[OCI_LINUX_SECCOMP
]) {
2219 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2220 if (!opts
.ociseccomp
)
2224 if (tb
[OCI_LINUX_DEVICES
]) {
2225 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2230 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2231 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2232 if (cgpath
[0] == '/') {
2233 if (strlen(cgpath
) + 1 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2236 strcat(cgfullpath
, cgpath
);
2238 strcat(cgfullpath
, "/containers/");
2239 if (strlen(opts
.name
) + strlen(cgpath
) + 2 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2242 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2243 strcat(cgfullpath
, "/");
2244 strcat(cgfullpath
, cgpath
);
2247 strcat(cgfullpath
, "/containers/");
2248 if (2 * strlen(opts
.name
) + 2 >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2251 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2252 strcat(cgfullpath
, "/");
2253 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2256 cgroups_init(cgfullpath
);
2258 if (tb
[OCI_LINUX_RESOURCES
]) {
2259 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2279 static const struct blobmsg_policy oci_policy
[] = {
2280 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2281 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2282 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2283 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2284 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2285 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2286 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2287 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2290 static int parseOCI(const char *jsonfile
)
2292 struct blob_attr
*tb
[__OCI_MAX
];
2293 struct blob_attr
*cur
;
2297 blob_buf_init(&ocibuf
, 0);
2299 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
)) {
2304 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2306 if (!tb
[OCI_VERSION
]) {
2311 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2312 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2317 if (tb
[OCI_HOSTNAME
])
2318 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2320 if (!tb
[OCI_PROCESS
]) {
2325 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2328 if (!tb
[OCI_ROOT
]) {
2332 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2335 if (!tb
[OCI_MOUNTS
]) {
2340 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2341 if ((res
= parseOCImount(cur
)))
2344 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2347 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2350 if (tb
[OCI_ANNOTATIONS
])
2351 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2354 blob_buf_free(&ocibuf
);
2359 static int set_oom_score_adj(void)
2364 if (!opts
.set_oom_score_adj
)
2367 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2368 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2372 dprintf(f
, "%d", opts
.oom_score_adj
);
2386 static int jail_oci_state
= OCI_STATE_CREATED
;
2387 static void pipe_send_start_container(struct uloop_timeout
*t
);
2388 static struct uloop_timeout start_container_timeout
= {
2389 .cb
= pipe_send_start_container
,
2392 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2393 struct ubus_request_data
*req
, const char *method
,
2394 struct blob_attr
*msg
)
2396 if (jail_oci_state
!= OCI_STATE_CREATED
)
2397 return UBUS_STATUS_INVALID_ARGUMENT
;
2399 uloop_timeout_add(&start_container_timeout
);
2401 return UBUS_STATUS_OK
;
2404 static struct blob_buf bb
;
2405 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2406 struct ubus_request_data
*req
, const char *method
,
2407 struct blob_attr
*msg
)
2411 switch (jail_oci_state
) {
2412 case OCI_STATE_CREATING
:
2413 statusstr
= "creating";
2415 case OCI_STATE_CREATED
:
2416 statusstr
= "created";
2418 case OCI_STATE_RUNNING
:
2419 statusstr
= "running";
2421 case OCI_STATE_STOPPED
:
2422 statusstr
= "stopped";
2425 statusstr
= "unknown";
2428 blob_buf_init(&bb
, 0);
2429 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2430 blobmsg_add_string(&bb
, "id", opts
.name
);
2431 blobmsg_add_string(&bb
, "status", statusstr
);
2432 if (jail_oci_state
== OCI_STATE_CREATED
||
2433 jail_oci_state
== OCI_STATE_RUNNING
)
2434 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2436 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2438 if (opts
.annotations
)
2439 blobmsg_add_blob(&bb
, opts
.annotations
);
2441 ubus_send_reply(ctx
, req
, bb
.head
);
2443 return UBUS_STATUS_OK
;
2447 CONTAINER_KILL_ATTR_SIGNAL
,
2448 __CONTAINER_KILL_ATTR_MAX
,
2451 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2452 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2456 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2457 struct ubus_request_data
*req
, const char *method
,
2458 struct blob_attr
*msg
)
2460 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2463 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2465 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2467 sig
= blobmsg_get_u32(cur
);
2469 if (jail_oci_state
== OCI_STATE_CREATING
)
2470 return UBUS_STATUS_NOT_FOUND
;
2472 if (kill(jail_process
.pid
, sig
) == 0)
2476 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2477 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2478 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2481 return UBUS_STATUS_UNKNOWN_ERROR
;
2485 jail_writepid(pid_t pid
)
2492 _pidfile
= fopen(opts
.pidfile
, "w");
2493 if (_pidfile
== NULL
)
2496 if (fprintf(_pidfile
, "%d\n", pid
) < 0) {
2501 if (fclose(_pidfile
))
2507 static int checkpath(const char *path
)
2509 int dirfd
= open(path
, O_RDONLY
| O_DIRECTORY
| O_CLOEXEC
);
2511 ERROR("path %s open failed %m\n", path
);
2519 static struct ubus_method container_methods
[] = {
2520 UBUS_METHOD_NOARG("start", handle_start
),
2521 UBUS_METHOD_NOARG("state", handle_state
),
2522 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2525 static struct ubus_object_type container_object_type
=
2526 UBUS_OBJECT_TYPE("container", container_methods
);
2528 static struct ubus_object container_object
= {
2529 .type
= &container_object_type
,
2530 .methods
= container_methods
,
2531 .n_methods
= ARRAY_SIZE(container_methods
),
2534 static void post_main(struct uloop_timeout
*t
);
2535 static struct uloop_timeout post_main_timeout
= {
2538 static int netns_fd
;
2539 static int pidns_fd
;
2540 #ifdef CLONE_NEWTIME
2541 static int timens_fd
;
2543 static void post_create_runtime(void);
2544 int main(int argc
, char **argv
)
2546 uid_t uid
= getuid();
2547 const char log
[] = "/dev/log";
2548 const char ubus
[] = "/var/run/ubus/ubus.sock";
2549 int ret
= EXIT_FAILURE
;
2554 ERROR("not root, aborting: %m\n");
2555 return EXIT_FAILURE
;
2558 /* those are filehandlers, so -1 indicates unused */
2559 opts
.setns
.pid
= -1;
2560 opts
.setns
.net
= -1;
2562 opts
.setns
.ipc
= -1;
2563 opts
.setns
.uts
= -1;
2564 opts
.setns
.user
= -1;
2565 opts
.setns
.cgroup
= -1;
2566 #ifdef CLONE_NEWTIME
2567 opts
.setns
.time
= -1;
2572 init_library_search();
2574 exit_from_child
= false;
2576 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2579 debug
= atoi(optarg
);
2582 opts
.namespace |= CLONE_NEWNS
;
2586 opts
.namespace |= CLONE_NEWNS
;
2590 opts
.namespace |= CLONE_NEWUSER
;
2593 opts
.namespace |= CLONE_NEWCGROUP
;
2596 opts
.extroot
= realpath(optarg
, NULL
);
2599 opts
.namespace |= CLONE_NEWNS
;
2603 opts
.seccomp
= optarg
;
2604 add_mount_bind(optarg
, 1, -1);
2607 opts
.capabilities
= optarg
;
2610 opts
.no_new_privs
= 1;
2616 opts
.namespace |= CLONE_NEWNET
;
2619 opts
.namespace |= CLONE_NEWUTS
;
2620 opts
.hostname
= strdup(optarg
);
2623 jail_join_ns(optarg
);
2626 opts
.namespace |= CLONE_NEWNS
;
2627 tmp
= strchr(optarg
, ':');
2630 add_2paths_and_deps(optarg
, tmp
, 1, 0, 0);
2632 add_path_and_deps(optarg
, 1, 0, 0);
2636 opts
.namespace |= CLONE_NEWNS
;
2637 tmp
= strchr(optarg
, ':');
2640 add_2paths_and_deps(optarg
, tmp
, 0, 0, 0);
2642 add_path_and_deps(optarg
, 0, 0, 0);
2646 opts
.namespace |= CLONE_NEWNS
;
2647 add_mount_bind(ubus
, 0, -1);
2650 opts
.namespace |= CLONE_NEWNS
;
2651 add_mount_bind(log
, 0, -1);
2657 opts
.group
= optarg
;
2660 opts
.overlaydir
= realpath(optarg
, NULL
);
2663 opts
.tmpoverlaysize
= optarg
;
2666 opts
.require_jail
= 1;
2672 opts
.ocibundle
= optarg
;
2675 opts
.immediately
= true;
2678 opts
.pidfile
= optarg
;
2683 if (opts
.namespace && !opts
.ocibundle
)
2684 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2687 * uid in parent user namespace representing root user in new
2688 * user namespace, defaults to nobody unless specified in uidMappings
2690 opts
.root_map_uid
= 65534;
2692 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2693 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2698 if (opts
.ocibundle
) {
2703 ERROR("OCI bundle needs a named jail\n");
2707 if (asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
) < 0) {
2711 ocires
= parseOCI(jsonfile
);
2714 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2720 if (opts
.namespace & CLONE_NEWNET
) {
2722 ERROR("netns needs a named jail\n");
2729 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2730 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2735 if (opts
.extroot
&& checkpath(opts
.extroot
)) {
2736 ERROR("invalid rootfs path '%s'", opts
.extroot
);
2741 if (opts
.overlaydir
&& checkpath(opts
.overlaydir
)) {
2742 ERROR("invalid rootfs overlay path '%s'", opts
.overlaydir
);
2747 /* no <binary> param found */
2748 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2753 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
||
2754 (opts
.setns
.net
!= -1) ||
2755 (opts
.setns
.ns
!= -1) ||
2756 (opts
.setns
.ipc
!= -1) ||
2757 (opts
.setns
.uts
!= -1) ||
2758 (opts
.setns
.user
!= -1) ||
2759 (opts
.setns
.cgroup
!= -1))) {
2760 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2765 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2768 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2773 parent_ctx
= ubus_connect(NULL
);
2774 ubus_add_uloop(parent_ctx
);
2776 if (opts
.ocibundle
) {
2778 if (asprintf(&objname
, "container.%s", opts
.name
) < 0) {
2783 container_object
.name
= objname
;
2784 ret
= ubus_add_object(parent_ctx
, &container_object
);
2786 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2792 /* deliberately not using 'else' on unrelated conditional branches */
2793 if (!opts
.ocibundle
) {
2794 /* allocate NULL-terminated array for argv */
2795 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(void *));
2796 if (!opts
.jail_argv
) {
2800 for (size_t s
= optind
; s
< argc
; s
++)
2801 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2803 if (opts
.namespace & CLONE_NEWUSER
)
2804 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2807 if (!opts
.extroot
) {
2808 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2809 ERROR("failed to load dependencies\n");
2815 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2816 ERROR("failed to load libpreload-seccomp.so\n");
2818 if (opts
.require_jail
) {
2824 uloop_timeout_add(&post_main_timeout
);
2836 static void post_main(struct uloop_timeout
*t
)
2838 if (apply_rlimits()) {
2839 ERROR("error applying resource limits\n");
2840 free_and_exit(EXIT_FAILURE
);
2844 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2846 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2849 if (has_namespaces()) {
2850 if (opts
.namespace & CLONE_NEWNS
) {
2851 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2852 add_mount_bind("/etc/passwd", 1, -1);
2853 add_mount_bind("/etc/group", 1, -1);
2856 #if defined(__GLIBC__)
2858 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2860 if (opts
.setns
.ns
== -1) {
2861 if (!(opts
.namespace & CLONE_NEWNET
)) {
2862 add_mount_bind("/etc/resolv.conf", 1, 0);
2864 /* new mount namespace to provide /dev/resolv.conf.d */
2865 char hostdir
[PATH_MAX
];
2867 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2868 mkdir_p(hostdir
, 0755);
2869 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
,
2870 MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, 0, NULL
, 0);
2873 /* default mounts */
2874 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "size=1M", -1);
2875 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2877 if (opts
.procfs
|| opts
.ocibundle
) {
2878 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0, NULL
, -1);
2881 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2882 * which cannot be expressed with OCI spec, but happends to be very useful.
2883 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2885 * If not running in a new network namespace, only make /proc/sys read-only.
2886 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2887 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2888 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2890 * This works because mounts are executed in incrementing strcmp() order and
2891 * /proc/self/net appears there before /proc/sys/net and hence the operation
2892 * succeeds as the bind-mount of /proc/self/net is performed first and then
2893 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2894 * table (and in the alphabet).
2896 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, 0, NULL
, -1))
2897 if (opts
.namespace & CLONE_NEWNET
)
2898 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0, NULL
, -1))
2899 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0, NULL
, -1);
2902 if (opts
.sysfs
|| opts
.ocibundle
)
2903 add_mount("sysfs", "/sys", "sysfs", MS_RELATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0, NULL
, -1);
2906 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, 0, "mode=1777", -1);
2910 if (opts
.setns
.pid
!= -1) {
2911 pidns_fd
= ns_open_pid("pid", getpid());
2912 setns_open(CLONE_NEWPID
);
2917 #ifdef CLONE_NEWTIME
2918 if (opts
.setns
.time
!= -1) {
2919 timens_fd
= ns_open_pid("time", getpid());
2920 setns_open(CLONE_NEWTIME
);
2926 if (opts
.namespace & CLONE_NEWUSER
) {
2927 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
2928 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
2929 free_and_exit(EXIT_FAILURE
);
2931 if (seteuid(opts
.root_map_uid
)) {
2932 ERROR("seteuid(%d) failed: %m\n", opts
.root_map_uid
);
2933 free_and_exit(EXIT_FAILURE
);
2937 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
2939 jail_process
.pid
= fork();
2942 if (jail_process
.pid
> 0) {
2943 /* parent process */
2946 uloop_process_add(&jail_process
);
2949 ERROR("seteuid(%d) failed: %m\n", opts
.root_map_uid
);
2950 free_and_exit(EXIT_FAILURE
);
2953 prctl(PR_SET_SECUREBITS
, 0);
2955 if (pidns_fd
!= -1) {
2956 setns(pidns_fd
, CLONE_NEWPID
);
2959 #ifdef CLONE_NEWTIME
2960 if (timens_fd
!= -1) {
2961 setns(timens_fd
, CLONE_NEWTIME
);
2965 if (opts
.setns
.net
!= -1)
2966 close(opts
.setns
.net
);
2967 if (opts
.setns
.ns
!= -1)
2968 close(opts
.setns
.ns
);
2969 if (opts
.setns
.ipc
!= -1)
2970 close(opts
.setns
.ipc
);
2971 if (opts
.setns
.uts
!= -1)
2972 close(opts
.setns
.uts
);
2973 if (opts
.setns
.user
!= -1)
2974 close(opts
.setns
.user
);
2975 if (opts
.setns
.cgroup
!= -1)
2976 close(opts
.setns
.cgroup
);
2979 if (read(pipes
[0], sig_buf
, 1) < 1) {
2980 ERROR("can't read from child\n");
2984 set_oom_score_adj();
2987 cgroups_apply(jail_process
.pid
);
2989 if (opts
.namespace & CLONE_NEWUSER
) {
2990 if (write_setgroups(jail_process
.pid
, true)) {
2991 ERROR("can't write setgroups\n");
2995 bool has_gr
= (opts
.gr_gid
!= -1);
2996 if (opts
.pw_uid
!= -1) {
2997 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2998 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
3000 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
3001 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
3004 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
3006 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
3010 if (opts
.namespace & CLONE_NEWNET
)
3011 jail_network_start(parent_ctx
, opts
.name
, jail_process
.pid
);
3013 if (jail_writepid(jail_process
.pid
)) {
3014 ERROR("failed to write pidfile: %m\n");
3017 } else if (jail_process
.pid
== 0) {
3018 /* fork child process */
3019 free_and_exit(exec_jail(NULL
));
3021 ERROR("failed to clone/fork: %m\n");
3022 free_and_exit(EXIT_FAILURE
);
3024 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
3027 static void post_poststart(void);
3028 static void post_create_runtime(void)
3033 if (write(pipes
[3], sig_buf
, 1) < 0) {
3034 ERROR("can't write to child\n");
3038 jail_oci_state
= OCI_STATE_CREATED
;
3039 if (opts
.ocibundle
&& !opts
.immediately
)
3040 uloop_run(); /* wait for 'start' command via ubus */
3042 pipe_send_start_container(NULL
);
3045 static void pipe_send_start_container(struct uloop_timeout
*t
)
3049 jail_oci_state
= OCI_STATE_RUNNING
;
3051 if (write(pipes
[3], sig_buf
, 1) < 0) {
3052 ERROR("can't write to child\n");
3057 run_hooks(opts
.hooks
.poststart
, post_poststart
);
3060 static void post_poststart(void)
3062 uloop_run(); /* idle here while jail is running */
3064 DEBUG("uloop interrupted, killing jail process\n");
3065 kill(jail_process
.pid
, SIGTERM
);
3066 uloop_timeout_set(&jail_process_timeout
, 1000);
3073 static void post_poststop(void);
3074 static void poststop(void) {
3075 if (opts
.namespace & CLONE_NEWNET
) {
3076 setns(netns_fd
, CLONE_NEWNET
);
3077 jail_network_stop();
3080 run_hooks(opts
.hooks
.poststop
, post_poststop
);
3083 static void post_poststop(void)
3087 ubus_free(parent_ctx
);
3089 exit(jail_return_code
);