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/utils.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>
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
);
273 free_hooklist(opts
.hooks
.createRuntime
);
274 free_hooklist(opts
.hooks
.createContainer
);
275 free_hooklist(opts
.hooks
.startContainer
);
276 free_hooklist(opts
.hooks
.poststart
);
277 free_hooklist(opts
.hooks
.poststop
);
280 static int mount_overlay(char *jail_root
, char *overlaydir
) {
281 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
282 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
285 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
288 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
291 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
294 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
298 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
299 * this is to work-around a bug in overlayfs described in the overlayfs-userns
301 * 3. modification of a file 'hithere' which is in l but not yet
302 * in u, and which is not owned by T, is not allowed, even if
303 * writes to u are allowed. This may be a bug in overlayfs,
304 * but it is safe behavior.
306 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
309 if (mkdir_p(upperetc
, 0755))
310 goto upper_etc_printf
;
312 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
313 goto upper_etc_printf
;
315 fd
= creat(upperresolvconf
, 0644);
318 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
322 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
324 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
325 goto upper_resolvconf_printf
;
329 upper_resolvconf_printf
:
330 free(upperresolvconf
);
343 static void pass_console(int console_fd
)
345 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
346 static struct blob_buf req
;
352 blob_buf_init(&req
, 0);
353 blobmsg_add_string(&req
, "name", opts
.name
);
355 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
356 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
357 INFO("ubus request failed\n");
362 ubus_free(child_ctx
);
365 static int create_dev_console(const char *jail_root
)
368 char dev_console_path
[PATH_MAX
];
369 int slave_console_fd
;
371 /* Open UNIX/98 virtual console */
372 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
373 if (console_fd
== -1)
376 console_fname
= ptsname(console_fd
);
377 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
382 unlockpt(console_fd
);
384 /* pass PTY master to procd */
385 pass_console(console_fd
);
387 /* mount-bind PTY slave to /dev/console in jail */
388 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
389 close(creat(dev_console_path
, 0620));
391 if (mount(console_fname
, dev_console_path
, "bind", MS_BIND
, NULL
))
394 /* use PTY slave for stdio */
395 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
396 dup2(slave_console_fd
, 0);
397 dup2(slave_console_fd
, 1);
398 dup2(slave_console_fd
, 2);
399 close(slave_console_fd
);
401 INFO("using guest console %s\n", console_fname
);
410 static int hook_running
= 0;
411 static int hook_return_code
= 0;
412 static struct hook_execvpe
**current_hook
= NULL
;
413 typedef void (*hook_return_handler
)(void);
414 static hook_return_handler hook_return_cb
= NULL
;
416 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
417 static struct uloop_timeout hook_process_timeout
= {
418 .cb
= hook_process_timeout_cb
,
421 static void run_hooklist(void);
422 static void hook_process_handler(struct uloop_process
*c
, int ret
)
424 uloop_timeout_cancel(&hook_process_timeout
);
426 if (WIFEXITED(ret
)) {
427 hook_return_code
= WEXITSTATUS(ret
);
428 if (hook_return_code
)
429 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
431 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
434 hook_return_code
= WTERMSIG(ret
);
435 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
442 static struct uloop_process hook_process
= {
443 .cb
= hook_process_handler
,
446 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
448 DEBUG("hook process failed to stop, sending SIGKILL\n");
449 kill(hook_process
.pid
, SIGKILL
);
452 static void run_hooklist(void)
454 struct hook_execvpe
*hook
= *current_hook
;
460 DEBUG("executing hook %s\n", hook
->file
);
462 if (stat(hook
->file
, &s
))
463 hook_process_handler(&hook_process
, ENOENT
);
465 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
466 hook_process_handler(&hook_process
, EPERM
);
468 if (!((unsigned long)s
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
)))
469 hook_process_handler(&hook_process
, EPERM
);
472 hook_process
.pid
= fork();
473 if (hook_process
.pid
== 0) {
475 execve(hook
->file
, hook
->argv
, hook
->envp
);
476 ERROR("execve error %m\n");
478 } else if (hook_process
.pid
< 0) {
480 ERROR("hook fork error\n");
482 hook_process_handler(&hook_process
, errno
);
486 uloop_process_add(&hook_process
);
488 if (hook
->timeout
> 0)
489 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
493 DEBUG("uloop interrupted, killing jail process\n");
494 kill(hook_process
.pid
, SIGTERM
);
495 uloop_timeout_set(&hook_process_timeout
, 1000);
500 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
505 current_hook
= hooklist
;
506 hook_return_cb
= return_cb
;
511 static int apply_sysctl(const char *jail_root
)
513 struct sysctl_val
**cur
;
514 char *procdir
, *fname
;
520 asprintf(&procdir
, "%s/proc", jail_root
);
524 mkdir(procdir
, 0700);
525 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
531 asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
);
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
);
542 write(f
, (*cur
)->value
, strlen((*cur
)->value
));
555 /* glibc defines makedev calling a function. make sure it's a pure macro */
556 #if defined(__GLIBC__)
558 /* from musl's sys/sysmacros.h */
559 #define makedev(x,y) ( \
560 (((x)&0xfffff000ULL) << 32) | \
561 (((x)&0x00000fffULL) << 8) | \
562 (((y)&0xffffff00ULL) << 12) | \
563 (((y)&0x000000ffULL)) )
566 static struct mknod_args default_devices
[] = {
567 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
568 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
569 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
570 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
571 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
572 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
576 static int create_devices(void)
578 struct mknod_args
**cur
, *curdef
;
581 goto only_default_devices
;
586 DEBUG("creating %s (mode=%08o)\n", (*cur
)->path
, (*cur
)->mode
);
587 if (mknod((*cur
)->path
, (*cur
)->mode
, (*cur
)->dev
))
590 if (((*cur
)->uid
|| (*cur
)->gid
) &&
591 chown((*cur
)->path
, (*cur
)->uid
, (*cur
)->gid
))
597 only_default_devices
:
598 curdef
= default_devices
;
599 while(curdef
->path
) {
600 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
601 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
603 continue; /* may already exist, eg. due to a bind-mount */
605 if ((curdef
->uid
|| curdef
->gid
) &&
606 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
612 /* Dev symbolic links as defined in OCI spec */
613 symlink("/dev/pts/ptmx", "/dev/ptmx");
614 symlink("/proc/self/fd", "/dev/fd");
615 symlink("/proc/self/fd/0", "/dev/stdin");
616 symlink("/proc/self/fd/1", "/dev/stdout");
617 symlink("/proc/self/fd/2", "/dev/stderr");
622 static char jail_root
[] = "/tmp/ujail-XXXXXX";
623 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
624 static mode_t old_umask
;
625 static void enter_jail_fs(void);
626 static int build_jail_fs(void)
628 char *overlaydir
= NULL
;
630 old_umask
= umask(0);
632 if (mkdtemp(jail_root
) == NULL
) {
633 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
637 if (apply_sysctl(jail_root
)) {
638 ERROR("failed to apply sysctl values\n");
642 /* oldroot can't be MS_SHARED else pivot_root() fails */
643 if (mount("none", "/", "none", MS_REC
|MS_PRIVATE
, NULL
)) {
644 ERROR("private mount failed %m\n");
649 if (mount(opts
.extroot
, jail_root
, "bind", MS_BIND
, NULL
)) {
650 ERROR("extroot mount failed %m\n");
654 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
655 ERROR("tmpfs mount failed %m\n");
660 if (opts
.tmpoverlaysize
) {
661 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
663 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
664 "mode=0755,size=%s", opts
.tmpoverlaysize
);
665 if (mkdtemp(tmpovdir
) == NULL
) {
666 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
669 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
671 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
674 overlaydir
= tmpovdir
;
678 overlaydir
= opts
.overlaydir
;
681 mount_overlay(jail_root
, overlaydir
);
683 if (chdir(jail_root
)) {
684 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
688 if (mount_all(jail_root
)) {
689 ERROR("mount_all() failed\n");
694 create_dev_console(jail_root
);
696 /* make sure /etc/resolv.conf exists if in new network namespace */
697 if (opts
.namespace & CLONE_NEWNET
) {
698 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
700 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
701 mkdir_p(jailetc
, 0755);
702 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
706 symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
709 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
714 static bool exit_from_child
;
715 static void free_and_exit(int ret
)
717 if (!exit_from_child
&& opts
.ocibundle
)
720 if (!exit_from_child
&& parent_ctx
)
721 ubus_free(parent_ctx
);
723 free_opts(!exit_from_child
);
728 static void post_jail_fs(void);
729 static void enter_jail_fs(void)
731 char dirbuf
[sizeof(jail_root
) + 4];
733 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
736 if (pivot_root(jail_root
, dirbuf
) == -1) {
737 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
741 ERROR("chdir(/) (after pivot_root) failed: %m\n");
745 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
746 umount2(dirbuf
, MNT_DETACH
);
748 if (opts
.tmpoverlaysize
) {
749 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
750 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
751 umount2(tmpdirbuf
, MNT_DETACH
);
755 umount2("/old", MNT_DETACH
);
758 if (create_devices()) {
759 ERROR("create_devices() failed\n");
763 mount(NULL
, "/", "bind", MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
769 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
774 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
775 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
778 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
781 if (dprintf(map_file
, "%s", mapstr
)) {
790 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
794 const char *map_format
= "%d %d %d\n";
795 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
796 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
799 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
802 if (dprintf(map_file
, map_format
, 0, id
, 1) == -1) {
811 static int write_setgroups(pid_t child_pid
, bool allow
)
814 char setgroups_path
[64];
816 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
821 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) == -1) {
825 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
826 close(setgroups_file
);
830 close(setgroups_file
);
834 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
836 struct passwd
*p
= NULL
;
837 struct group
*g
= NULL
;
840 p
= getpwnam(opts
.user
);
842 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
843 opts
.user
, errno
, strerror(errno
));
844 free_and_exit(EXIT_FAILURE
);
847 *user_gid
= p
->pw_gid
;
854 g
= getgrnam(opts
.group
);
856 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
857 free_and_exit(EXIT_FAILURE
);
865 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
867 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
868 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
869 free_and_exit(EXIT_FAILURE
);
872 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
873 ERROR("failed to set group id %d: %m\n", gr_gid
);
874 free_and_exit(EXIT_FAILURE
);
877 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
878 ERROR("failed to set user id %d: %m\n", pw_uid
);
879 free_and_exit(EXIT_FAILURE
);
883 static int apply_rlimits(void)
887 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
888 if (opts
.rlimits
[resource
])
889 DEBUG("applying limits to resource %u\n", resource
);
891 if (opts
.rlimits
[resource
] &&
892 setrlimit(resource
, opts
.rlimits
[resource
]))
900 static char** build_envp(const char *seccomp
, char **ocienvp
)
902 static char *envp
[MAX_ENVP
];
903 static char preload_var
[PATH_MAX
];
904 static char seccomp_var
[PATH_MAX
];
905 static char seccomp_debug_var
[20];
906 static char debug_var
[] = "LD_DEBUG=all";
907 static char container_var
[] = "container=ujail";
908 const char *preload_lib
= find_lib("libpreload-seccomp.so");
913 if (seccomp
&& !preload_lib
) {
914 ERROR("failed to add preload-lib to env\n");
918 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
919 envp
[count
++] = seccomp_var
;
920 snprintf(seccomp_debug_var
, sizeof(seccomp_debug_var
), "SECCOMP_DEBUG=%2d", debug
);
921 envp
[count
++] = seccomp_debug_var
;
922 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
923 envp
[count
++] = preload_var
;
926 envp
[count
++] = container_var
;
929 envp
[count
++] = debug_var
;
932 while (addenv
&& *addenv
) {
933 envp
[count
++] = *(addenv
++);
934 if (count
>= MAX_ENVP
) {
935 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
942 static void usage(void)
944 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
945 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
946 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
947 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
948 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
949 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
950 fprintf(stderr
, "namespace jail options:\n");
951 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
952 fprintf(stderr
, " -N\t\tjail has network namespace\n");
953 fprintf(stderr
, " -f\t\tjail has user namespace\n");
954 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
955 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
956 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
957 fprintf(stderr
, " -p\t\tjail has /proc\n");
958 fprintf(stderr
, " -s\t\tjail has /sys\n");
959 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
960 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
961 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
962 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
963 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
964 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
965 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
966 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
967 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
968 fprintf(stderr
, " -y\t\tprovide jail console\n");
969 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
970 fprintf(stderr
, " -i\t\tstart container immediately\n");
971 fprintf(stderr
, " -P <pidfile>\tcreate <pidfile>\n");
972 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
973 and he has the same powers as root outside the jail,\n\
974 thus he can escape the jail and/or break stuff.\n\
975 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
976 If you use none of the namespace jail options,\n\
977 ujail will not use namespace/build a jail,\n\
978 and will only drop capabilities/apply seccomp filter.\n\n");
981 static int* get_namespace_fd(const unsigned int nstype
)
985 return &opts
.setns
.pid
;
987 return &opts
.setns
.net
;
989 return &opts
.setns
.ns
;
991 return &opts
.setns
.ipc
;
993 return &opts
.setns
.uts
;
995 return &opts
.setns
.user
;
996 case CLONE_NEWCGROUP
:
997 return &opts
.setns
.cgroup
;
1000 return &opts
.setns
.time
;
1007 static int setns_open(unsigned long nstype
)
1009 int *fd
= get_namespace_fd(nstype
);
1017 if (setns(*fd
, nstype
) == -1) {
1026 static int jail_running
= 0;
1027 static int jail_return_code
= 0;
1029 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1030 static struct uloop_timeout jail_process_timeout
= {
1031 .cb
= jail_process_timeout_cb
,
1033 static void poststop(void);
1034 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1036 uloop_timeout_cancel(&jail_process_timeout
);
1037 if (WIFEXITED(ret
)) {
1038 jail_return_code
= WEXITSTATUS(ret
);
1039 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1041 jail_return_code
= WTERMSIG(ret
);
1042 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1048 static struct uloop_process jail_process
= {
1049 .cb
= jail_process_handler
,
1052 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1054 DEBUG("jail process failed to stop, sending SIGKILL\n");
1055 kill(jail_process
.pid
, SIGKILL
);
1058 static void jail_handle_signal(int signo
)
1061 DEBUG("forwarding signal %d to the hook process\n", signo
);
1062 kill(hook_process
.pid
, signo
);
1066 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1067 kill(jail_process
.pid
, signo
);
1071 static void signals_init(void)
1076 sigfillset(&sigmask
);
1077 for (i
= 0; i
< _NSIG
; i
++) {
1078 struct sigaction s
= { 0 };
1080 if (!sigismember(&sigmask
, i
))
1082 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1085 s
.sa_handler
= jail_handle_signal
;
1086 sigaction(i
, &s
, NULL
);
1090 static void pre_exec_jail(struct uloop_timeout
*t
);
1091 static struct uloop_timeout pre_exec_timeout
= {
1092 .cb
= pre_exec_jail
,
1096 static int exec_jail(void *arg
)
1100 exit_from_child
= true;
1101 prctl(PR_SET_SECUREBITS
, 0);
1109 setns_open(CLONE_NEWUSER
);
1110 setns_open(CLONE_NEWNET
);
1111 setns_open(CLONE_NEWNS
);
1112 setns_open(CLONE_NEWIPC
);
1113 setns_open(CLONE_NEWUTS
);
1116 if (write(pipes
[1], buf
, 1) < 1) {
1117 ERROR("can't write to parent\n");
1118 return EXIT_FAILURE
;
1121 if (read(pipes
[2], buf
, 1) < 1) {
1122 ERROR("can't read from parent\n");
1123 return EXIT_FAILURE
;
1125 if (buf
[0] != 'O') {
1126 ERROR("parent had an error, child exiting\n");
1127 return EXIT_FAILURE
;
1130 if (opts
.namespace & CLONE_NEWCGROUP
)
1131 unshare(CLONE_NEWCGROUP
);
1133 setns_open(CLONE_NEWCGROUP
);
1135 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1136 if (setregid(0, 0) < 0) {
1138 free_and_exit(EXIT_FAILURE
);
1140 if (setreuid(0, 0) < 0) {
1142 free_and_exit(EXIT_FAILURE
);
1144 if (setgroups(0, NULL
) < 0) {
1145 ERROR("setgroups\n");
1146 free_and_exit(EXIT_FAILURE
);
1150 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1151 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1152 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1153 free_and_exit(EXIT_FAILURE
);
1156 uloop_timeout_add(&pre_exec_timeout
);
1163 static void pre_exec_jail(struct uloop_timeout
*t
)
1165 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1166 ERROR("failed to build jail fs\n");
1167 free_and_exit(EXIT_FAILURE
);
1169 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1173 static void post_start_hook(void);
1174 static void post_jail_fs(void)
1178 if (read(pipes
[2], buf
, 1) < 1) {
1179 ERROR("can't read from parent\n");
1180 free_and_exit(EXIT_FAILURE
);
1182 if (buf
[0] != '!') {
1183 ERROR("parent had an error, child exiting\n");
1184 free_and_exit(EXIT_FAILURE
);
1188 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1191 static void post_start_hook(void)
1193 int pw_uid
, pw_gid
, gr_gid
;
1196 * make sure setuid/setgid won't drop capabilities in case capabilities
1197 * have been specified explicitely.
1199 if (opts
.capset
.apply
) {
1200 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1201 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1202 free_and_exit(EXIT_FAILURE
);
1206 /* drop capabilities, retain those still needed to further setup jail */
1207 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1208 free_and_exit(EXIT_FAILURE
);
1210 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1211 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1212 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1214 if (opts
.additional_gids
&&
1215 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1216 ERROR("setgroups failed: %m\n");
1217 free_and_exit(EXIT_FAILURE
);
1223 /* restore securebits back to normal (and lock them if not in userns) */
1224 if (opts
.capset
.apply
) {
1225 if (prctl(PR_SET_SECUREBITS
, (opts
.namespace & CLONE_NEWUSER
)?0:
1226 SECBIT_KEEP_CAPS_LOCKED
|SECBIT_NO_SETUID_FIXUP_LOCKED
|SECBIT_NOROOT_LOCKED
)) {
1227 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1228 free_and_exit(EXIT_FAILURE
);
1232 /* drop remaining capabilities to end up with specified sets */
1233 if (applyOCIcapabilities(opts
.capset
, 0))
1234 free_and_exit(EXIT_FAILURE
);
1236 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1237 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1238 free_and_exit(EXIT_FAILURE
);
1241 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1243 free_and_exit(EXIT_FAILURE
);
1245 if (opts
.cwd
&& chdir(opts
.cwd
))
1246 free_and_exit(EXIT_FAILURE
);
1248 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1249 free_and_exit(EXIT_FAILURE
);
1253 INFO("exec-ing %s\n", *opts
.jail_argv
);
1254 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1255 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1257 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1259 /* we get there only if execve fails */
1260 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1264 static int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1266 char pid_pid_path
[PATH_MAX
];
1268 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1270 return open(pid_pid_path
, O_RDONLY
);
1273 static void netns_updown(pid_t pid
, bool start
)
1275 static struct blob_buf req
;
1281 blob_buf_init(&req
, 0);
1282 blobmsg_add_string(&req
, "jail", opts
.name
);
1283 blobmsg_add_u32(&req
, "pid", pid
);
1284 blobmsg_add_u8(&req
, "start", start
);
1286 if (ubus_lookup_id(parent_ctx
, "network", &id
) ||
1287 ubus_invoke(parent_ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1288 INFO("ubus request failed\n");
1290 blob_buf_free(&req
);
1293 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1295 struct blob_attr
*cur
;
1298 blobmsg_for_each_attr(cur
, msg
, rem
)
1302 *envp
= calloc(1 + sz
, sizeof(char*));
1311 blobmsg_for_each_attr(cur
, msg
, rem
)
1312 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1326 static const struct blobmsg_policy oci_root_policy
[] = {
1327 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1328 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1331 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1333 static char extroot
[PATH_MAX
] = { 0 };
1334 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1338 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1340 if (!tb
[OCI_ROOT_PATH
])
1343 root_path
= blobmsg_get_string(tb
[OCI_ROOT_PATH
]);
1345 /* prepend bundle directory in case of relative paths */
1346 if (root_path
[0] != '/') {
1347 strncpy(extroot
, jsonfile
, PATH_MAX
);
1348 cur
= strrchr(extroot
, '/');
1356 strncat(extroot
, root_path
, PATH_MAX
- (strlen(extroot
) + 1));
1358 opts
.extroot
= extroot
;
1360 if (tb
[OCI_ROOT_READONLY
])
1361 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1375 static const struct blobmsg_policy oci_hook_policy
[] = {
1376 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1377 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1378 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1379 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1383 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1385 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1386 struct blob_attr
*cur
;
1390 blobmsg_for_each_attr(cur
, msg
, rem
)
1396 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1402 blobmsg_for_each_attr(cur
, msg
, rem
) {
1403 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1405 if (!tb
[OCI_HOOK_PATH
]) {
1410 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1411 if (tb
[OCI_HOOK_ARGS
]) {
1412 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1416 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1417 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1418 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1422 if (tb
[OCI_HOOK_ENV
]) {
1423 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1428 if (tb
[OCI_HOOK_TIMEOUT
])
1429 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1431 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1436 (*hooklist
)[idx
] = NULL
;
1438 DEBUG("added %d hooks\n", idx
);
1443 free_hooklist(*hooklist
);
1452 OCI_HOOKS_CREATERUNTIME
,
1453 OCI_HOOKS_CREATECONTAINER
,
1454 OCI_HOOKS_STARTCONTAINER
,
1455 OCI_HOOKS_POSTSTART
,
1460 static const struct blobmsg_policy oci_hooks_policy
[] = {
1461 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1462 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1463 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1464 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1465 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1466 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1469 static int parseOCIhooks(struct blob_attr
*msg
)
1471 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1474 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1476 if (tb
[OCI_HOOKS_PRESTART
])
1477 INFO("warning: ignoring deprecated prestart hook\n");
1479 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1480 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1485 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1486 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1488 goto out_createruntime
;
1491 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1492 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1494 goto out_createcontainer
;
1497 if (tb
[OCI_HOOKS_POSTSTART
]) {
1498 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1500 goto out_startcontainer
;
1503 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1504 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1512 free_hooklist(opts
.hooks
.poststart
);
1514 free_hooklist(opts
.hooks
.startContainer
);
1515 out_createcontainer
:
1516 free_hooklist(opts
.hooks
.createContainer
);
1518 free_hooklist(opts
.hooks
.createRuntime
);
1525 OCI_PROCESS_USER_UID
,
1526 OCI_PROCESS_USER_GID
,
1527 OCI_PROCESS_USER_UMASK
,
1528 OCI_PROCESS_USER_ADDITIONALGIDS
,
1529 __OCI_PROCESS_USER_MAX
,
1532 static const struct blobmsg_policy oci_process_user_policy
[] = {
1533 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1534 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1535 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1536 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1539 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1540 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1541 struct blob_attr
*cur
;
1545 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1547 if (tb
[OCI_PROCESS_USER_UID
])
1548 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1550 if (tb
[OCI_PROCESS_USER_GID
]) {
1551 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1552 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1556 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1559 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1561 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1566 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1569 /* always add primary GID to set of GIDs if set */
1571 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1573 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1574 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1576 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1578 opts
.num_additional_gids
= gidcnt
;
1580 DEBUG("read %zu additional groups\n", gidcnt
);
1583 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1584 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1585 opts
.set_umask
= true;
1592 OCI_PROCESS_RLIMIT_TYPE
,
1593 OCI_PROCESS_RLIMIT_SOFT
,
1594 OCI_PROCESS_RLIMIT_HARD
,
1595 __OCI_PROCESS_RLIMIT_MAX
,
1598 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1599 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1600 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1601 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1604 /* from manpage GETRLIMIT(2) */
1605 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1607 [RLIMIT_CORE
] = "CORE",
1608 [RLIMIT_CPU
] = "CPU",
1609 [RLIMIT_DATA
] = "DATA",
1610 [RLIMIT_FSIZE
] = "FSIZE",
1611 [RLIMIT_LOCKS
] = "LOCKS",
1612 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1613 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1614 [RLIMIT_NICE
] = "NICE",
1615 [RLIMIT_NOFILE
] = "NOFILE",
1616 [RLIMIT_NPROC
] = "NPROC",
1617 [RLIMIT_RSS
] = "RSS",
1618 [RLIMIT_RTPRIO
] = "RTPRIO",
1619 [RLIMIT_RTTIME
] = "RTTIME",
1620 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1621 [RLIMIT_STACK
] = "STACK",
1624 static int resolve_rlimit(char *type
) {
1625 unsigned int rltype
;
1627 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1628 if (rlimit_names
[rltype
] &&
1629 !strncmp("RLIMIT_", type
, 7) &&
1630 !strcmp(rlimit_names
[rltype
], type
+ 7))
1637 static int parseOCIrlimit(struct blob_attr
*msg
)
1639 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1641 struct rlimit
*curlim
;
1643 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1645 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1646 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1647 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1650 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1655 if (opts
.rlimits
[limtype
])
1658 curlim
= malloc(sizeof(struct rlimit
));
1659 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1660 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1662 opts
.rlimits
[limtype
] = curlim
;
1669 OCI_PROCESS_CAPABILITIES
,
1672 OCI_PROCESS_OOMSCOREADJ
,
1673 OCI_PROCESS_NONEWPRIVILEGES
,
1674 OCI_PROCESS_RLIMITS
,
1675 OCI_PROCESS_TERMINAL
,
1680 static const struct blobmsg_policy oci_process_policy
[] = {
1681 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1682 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1683 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1684 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1685 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1686 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1687 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1688 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1689 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1693 static int parseOCIprocess(struct blob_attr
*msg
)
1695 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1698 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1700 if (!tb
[OCI_PROCESS_ARGS
])
1703 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1707 if (tb
[OCI_PROCESS_TERMINAL
])
1708 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1710 if (tb
[OCI_PROCESS_NONEWPRIVILEGES
])
1711 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1713 if (tb
[OCI_PROCESS_CWD
])
1714 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1716 if (tb
[OCI_PROCESS_ENV
]) {
1717 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1722 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1725 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1726 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1729 if (tb
[OCI_PROCESS_RLIMITS
]) {
1730 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1731 res
= parseOCIrlimit(cur
);
1737 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1738 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1739 opts
.set_oom_score_adj
= true;
1746 OCI_LINUX_NAMESPACE_TYPE
,
1747 OCI_LINUX_NAMESPACE_PATH
,
1748 __OCI_LINUX_NAMESPACE_MAX
,
1751 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1752 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1753 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1756 static int resolve_nstype(char *type
) {
1757 if (!strcmp("pid", type
))
1758 return CLONE_NEWPID
;
1759 else if (!strcmp("network", type
))
1760 return CLONE_NEWNET
;
1761 else if (!strcmp("mount", type
))
1763 else if (!strcmp("ipc", type
))
1764 return CLONE_NEWIPC
;
1765 else if (!strcmp("uts", type
))
1766 return CLONE_NEWUTS
;
1767 else if (!strcmp("user", type
))
1768 return CLONE_NEWUSER
;
1769 else if (!strcmp("cgroup", type
))
1770 return CLONE_NEWCGROUP
;
1771 #ifdef CLONE_NEWTIME
1772 else if (!strcmp("time", type
))
1773 return CLONE_NEWTIME
;
1779 static int parseOCIlinuxns(struct blob_attr
*msg
)
1781 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1786 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1788 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1791 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1795 if (opts
.namespace & nstype
)
1798 setns
= get_namespace_fd(nstype
);
1806 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1807 DEBUG("opening existing %s namespace from path %s\n",
1808 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1809 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1811 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1813 return errno
?:ESTALE
;
1815 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
)
1818 DEBUG("opened existing %s namespace got filehandler %u\n",
1819 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1824 opts
.namespace |= nstype
;
1830 static void get_jail_root_user(bool is_gidmap
, uint32_t container_id
, uint32_t host_id
, uint32_t size
)
1832 if (container_id
== 0 && size
>= 1)
1834 opts
.root_map_uid
= host_id
;
1838 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1839 OCI_LINUX_UIDGIDMAP_HOSTID
,
1840 OCI_LINUX_UIDGIDMAP_SIZE
,
1841 __OCI_LINUX_UIDGIDMAP_MAX
,
1844 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1845 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1846 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1847 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1850 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1852 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1853 struct blob_attr
*cur
;
1856 size_t len
, pos
, totallen
= 0;
1858 blobmsg_for_each_attr(cur
, msg
, rem
) {
1859 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1861 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1862 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1863 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1867 totallen
+= snprintf(NULL
, 0, "%d %d %d\n",
1868 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1869 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1870 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1873 /* allocate combined mapping string */
1874 map
= malloc(totallen
+ 1);
1879 blobmsg_for_each_attr(cur
, msg
, rem
) {
1880 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1882 get_jail_root_user(is_gidmap
, blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1883 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1884 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1886 /* write mapping line into pre-allocated string */
1887 len
= snprintf(&map
[pos
], totallen
+ 1, "%d %d %d\n",
1888 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1889 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1890 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1895 assert(totallen
== 0);
1910 OCI_DEVICES_FILEMODE
,
1916 static const struct blobmsg_policy oci_devices_policy
[] = {
1917 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1918 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1919 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
1920 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
1921 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
1922 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1923 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
1926 static mode_t
resolve_devtype(char *tstr
)
1928 if (!strcmp("c", tstr
) ||
1931 else if (!strcmp("b", tstr
))
1933 else if (!strcmp("p", tstr
))
1939 static int parseOCIdevices(struct blob_attr
*msg
)
1941 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
1942 struct blob_attr
*cur
;
1945 struct mknod_args
*tmp
;
1947 blobmsg_for_each_attr(cur
, msg
, rem
)
1950 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
1953 blobmsg_for_each_attr(cur
, msg
, rem
) {
1954 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1955 if (!tb
[OCI_DEVICES_TYPE
] ||
1956 !tb
[OCI_DEVICES_PATH
])
1959 tmp
= calloc(1, sizeof(struct mknod_args
));
1963 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1967 if (tmp
->mode
!= S_IFIFO
) {
1968 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
])
1971 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
1972 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
1975 if (tb
[OCI_DEVICES_FILEMODE
]) {
1976 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]))
1979 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
1981 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
1984 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
1986 if (tb
[OCI_DEVICES_UID
])
1987 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
1991 if (tb
[OCI_DEVICES_GID
])
1992 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
1996 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1997 opts
.devices
[cnt
++] = tmp
;
2000 opts
.devices
[cnt
] = NULL
;
2005 static int parseOCIsysctl(struct blob_attr
*msg
)
2007 struct blob_attr
*cur
;
2012 blobmsg_for_each_attr(cur
, msg
, rem
) {
2013 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
2022 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2027 blobmsg_for_each_attr(cur
, msg
, rem
) {
2028 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2029 if (!opts
.sysctl
[cnt
])
2032 /* replace '.' with '/' in entry name */
2033 tc
= tmp
= strdup(blobmsg_name(cur
));
2034 while ((tc
= strchr(tc
, '.')))
2037 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2038 opts
.sysctl
[cnt
]->entry
= tmp
;
2043 opts
.sysctl
[cnt
] = NULL
;
2050 OCI_LINUX_CGROUPSPATH
,
2051 OCI_LINUX_RESOURCES
,
2054 OCI_LINUX_NAMESPACES
,
2056 OCI_LINUX_UIDMAPPINGS
,
2057 OCI_LINUX_GIDMAPPINGS
,
2058 OCI_LINUX_MASKEDPATHS
,
2059 OCI_LINUX_READONLYPATHS
,
2060 OCI_LINUX_ROOTFSPROPAGATION
,
2064 static const struct blobmsg_policy oci_linux_policy
[] = {
2065 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2066 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2067 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2068 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2069 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2070 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2071 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2072 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2073 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2074 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2075 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2078 static int parseOCIlinux(struct blob_attr
*msg
)
2080 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2081 struct blob_attr
*cur
;
2085 char cgfullpath
[256] = "/sys/fs/cgroup";
2087 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2089 if (tb
[OCI_LINUX_NAMESPACES
]) {
2090 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2091 res
= parseOCIlinuxns(cur
);
2097 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2098 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2103 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2104 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2109 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2110 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2111 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, 0, NULL
, 0);
2117 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2118 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2119 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, 0, NULL
, 0);
2125 if (tb
[OCI_LINUX_SYSCTL
]) {
2126 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2131 if (tb
[OCI_LINUX_SECCOMP
]) {
2132 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2133 if (!opts
.ociseccomp
)
2137 if (tb
[OCI_LINUX_DEVICES
]) {
2138 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2143 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2144 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2145 if (cgpath
[0] == '/') {
2146 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2149 strcat(cgfullpath
, cgpath
);
2151 strcat(cgfullpath
, "/containers/");
2152 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2153 strcat(cgfullpath
, "/");
2154 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2157 strcat(cgfullpath
, cgpath
);
2160 strcat(cgfullpath
, "/containers/");
2161 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2162 strcat(cgfullpath
, "/");
2163 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2166 cgroups_init(cgfullpath
);
2168 if (tb
[OCI_LINUX_RESOURCES
]) {
2169 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2189 static const struct blobmsg_policy oci_policy
[] = {
2190 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2191 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2192 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2193 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2194 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2195 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2196 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2197 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2200 static int parseOCI(const char *jsonfile
)
2202 struct blob_attr
*tb
[__OCI_MAX
];
2203 struct blob_attr
*cur
;
2207 blob_buf_init(&ocibuf
, 0);
2209 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
)) {
2214 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2216 if (!tb
[OCI_VERSION
]) {
2221 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2222 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2227 if (tb
[OCI_HOSTNAME
])
2228 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2230 if (!tb
[OCI_PROCESS
]) {
2235 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2238 if (!tb
[OCI_ROOT
]) {
2242 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2245 if (!tb
[OCI_MOUNTS
]) {
2250 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2251 if ((res
= parseOCImount(cur
)))
2254 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2257 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2260 if (tb
[OCI_ANNOTATIONS
])
2261 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2264 blob_buf_free(&ocibuf
);
2269 static int set_oom_score_adj(void)
2274 if (!opts
.set_oom_score_adj
)
2277 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2278 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2282 dprintf(f
, "%d", opts
.oom_score_adj
);
2296 static int jail_oci_state
= OCI_STATE_CREATED
;
2297 static void pipe_send_start_container(struct uloop_timeout
*t
);
2298 static struct uloop_timeout start_container_timeout
= {
2299 .cb
= pipe_send_start_container
,
2302 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2303 struct ubus_request_data
*req
, const char *method
,
2304 struct blob_attr
*msg
)
2306 if (jail_oci_state
!= OCI_STATE_CREATED
)
2307 return UBUS_STATUS_INVALID_ARGUMENT
;
2309 uloop_timeout_add(&start_container_timeout
);
2311 return UBUS_STATUS_OK
;
2314 static struct blob_buf bb
;
2315 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2316 struct ubus_request_data
*req
, const char *method
,
2317 struct blob_attr
*msg
)
2321 switch (jail_oci_state
) {
2322 case OCI_STATE_CREATING
:
2323 statusstr
= "creating";
2325 case OCI_STATE_CREATED
:
2326 statusstr
= "created";
2328 case OCI_STATE_RUNNING
:
2329 statusstr
= "running";
2331 case OCI_STATE_STOPPED
:
2332 statusstr
= "stopped";
2335 statusstr
= "unknown";
2338 blob_buf_init(&bb
, 0);
2339 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2340 blobmsg_add_string(&bb
, "id", opts
.name
);
2341 blobmsg_add_string(&bb
, "status", statusstr
);
2342 if (jail_oci_state
== OCI_STATE_CREATED
||
2343 jail_oci_state
== OCI_STATE_RUNNING
)
2344 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2346 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2348 if (opts
.annotations
)
2349 blobmsg_add_blob(&bb
, opts
.annotations
);
2351 ubus_send_reply(ctx
, req
, bb
.head
);
2353 return UBUS_STATUS_OK
;
2357 CONTAINER_KILL_ATTR_SIGNAL
,
2358 __CONTAINER_KILL_ATTR_MAX
,
2361 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2362 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2366 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2367 struct ubus_request_data
*req
, const char *method
,
2368 struct blob_attr
*msg
)
2370 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2373 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2375 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2377 sig
= blobmsg_get_u32(cur
);
2379 if (jail_oci_state
== OCI_STATE_CREATING
)
2380 return UBUS_STATUS_NOT_FOUND
;
2382 if (kill(jail_process
.pid
, sig
) == 0)
2386 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2387 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2388 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2391 return UBUS_STATUS_UNKNOWN_ERROR
;
2395 jail_writepid(pid_t pid
)
2402 _pidfile
= fopen(opts
.pidfile
, "w");
2403 if (_pidfile
== NULL
)
2406 if (fprintf(_pidfile
, "%d\n", pid
) < 0) {
2411 if (fclose(_pidfile
))
2417 static struct ubus_method container_methods
[] = {
2418 UBUS_METHOD_NOARG("start", handle_start
),
2419 UBUS_METHOD_NOARG("state", handle_state
),
2420 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2423 static struct ubus_object_type container_object_type
=
2424 UBUS_OBJECT_TYPE("container", container_methods
);
2426 static struct ubus_object container_object
= {
2427 .type
= &container_object_type
,
2428 .methods
= container_methods
,
2429 .n_methods
= ARRAY_SIZE(container_methods
),
2432 static void post_main(struct uloop_timeout
*t
);
2433 static struct uloop_timeout post_main_timeout
= {
2436 static int netns_fd
;
2437 static int pidns_fd
;
2438 #ifdef CLONE_NEWTIME
2439 static int timens_fd
;
2441 static void post_create_runtime(void);
2442 int main(int argc
, char **argv
)
2444 uid_t uid
= getuid();
2445 const char log
[] = "/dev/log";
2446 const char ubus
[] = "/var/run/ubus/ubus.sock";
2450 ERROR("not root, aborting: %m\n");
2451 return EXIT_FAILURE
;
2456 init_library_search();
2458 exit_from_child
= false;
2460 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2463 debug
= atoi(optarg
);
2466 opts
.namespace |= CLONE_NEWNS
;
2470 opts
.namespace |= CLONE_NEWNS
;
2474 opts
.namespace |= CLONE_NEWUSER
;
2477 opts
.namespace |= CLONE_NEWCGROUP
;
2480 opts
.extroot
= optarg
;
2483 opts
.namespace |= CLONE_NEWNS
;
2487 opts
.seccomp
= optarg
;
2488 add_mount_bind(optarg
, 1, -1);
2491 opts
.capabilities
= optarg
;
2494 opts
.no_new_privs
= 1;
2500 opts
.namespace |= CLONE_NEWNET
;
2503 opts
.namespace |= CLONE_NEWUTS
;
2504 opts
.hostname
= strdup(optarg
);
2507 opts
.namespace |= CLONE_NEWNS
;
2508 add_path_and_deps(optarg
, 1, 0, 0);
2511 opts
.namespace |= CLONE_NEWNS
;
2512 add_path_and_deps(optarg
, 0, 0, 0);
2515 opts
.namespace |= CLONE_NEWNS
;
2516 add_mount_bind(ubus
, 0, -1);
2519 opts
.namespace |= CLONE_NEWNS
;
2520 add_mount_bind(log
, 0, -1);
2526 opts
.group
= optarg
;
2529 opts
.overlaydir
= optarg
;
2532 opts
.tmpoverlaysize
= optarg
;
2535 opts
.require_jail
= 1;
2541 opts
.ocibundle
= optarg
;
2544 opts
.immediately
= true;
2547 opts
.pidfile
= optarg
;
2552 if (opts
.namespace && !opts
.ocibundle
)
2553 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2555 /* those are filehandlers, so -1 indicates unused */
2556 opts
.setns
.pid
= -1;
2557 opts
.setns
.net
= -1;
2559 opts
.setns
.ipc
= -1;
2560 opts
.setns
.uts
= -1;
2561 opts
.setns
.user
= -1;
2562 opts
.setns
.cgroup
= -1;
2563 #ifdef CLONE_NEWTIME
2564 opts
.setns
.time
= -1;
2568 * uid in parent user namespace representing root user in new
2569 * user namespace, defaults to nobody unless specified in uidMappings
2571 opts
.root_map_uid
= 65534;
2573 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2574 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2579 if (opts
.ocibundle
) {
2584 ERROR("OCI bundle needs a named jail\n");
2588 asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
);
2589 ocires
= parseOCI(jsonfile
);
2592 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2598 if (opts
.namespace & CLONE_NEWNET
) {
2600 ERROR("netns needs a named jail\n");
2607 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2608 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2613 /* no <binary> param found */
2614 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2619 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
2620 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2625 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2628 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2633 parent_ctx
= ubus_connect(NULL
);
2634 ubus_add_uloop(parent_ctx
);
2636 if (opts
.ocibundle
) {
2638 if (asprintf(&objname
, "container.%s", opts
.name
) < 0) {
2643 container_object
.name
= objname
;
2644 ret
= ubus_add_object(parent_ctx
, &container_object
);
2646 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2652 /* deliberately not using 'else' on unrelated conditional branches */
2653 if (!opts
.ocibundle
) {
2654 /* allocate NULL-terminated array for argv */
2655 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(char**));
2656 if (!opts
.jail_argv
) {
2660 for (size_t s
= optind
; s
< argc
; s
++)
2661 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2663 if (opts
.namespace & CLONE_NEWUSER
)
2664 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2667 if (!opts
.extroot
) {
2668 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2669 ERROR("failed to load dependencies\n");
2675 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2676 ERROR("failed to load libpreload-seccomp.so\n");
2678 if (opts
.require_jail
) {
2684 uloop_timeout_add(&post_main_timeout
);
2696 static void post_main(struct uloop_timeout
*t
)
2698 if (apply_rlimits()) {
2699 ERROR("error applying resource limits\n");
2700 free_and_exit(EXIT_FAILURE
);
2704 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2706 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2709 if (has_namespaces()) {
2710 if (opts
.namespace & CLONE_NEWNS
) {
2711 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2712 add_mount_bind("/etc/passwd", 1, -1);
2713 add_mount_bind("/etc/group", 1, -1);
2716 #if defined(__GLIBC__)
2718 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2721 if (!(opts
.namespace & CLONE_NEWNET
)) {
2722 add_mount_bind("/etc/resolv.conf", 1, 0);
2723 } else if (opts
.setns
.net
== -1) {
2724 char hostdir
[PATH_MAX
];
2726 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2727 mkdir_p(hostdir
, 0755);
2728 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, 0, NULL
, 0);
2731 /* default mounts */
2732 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "size=1M", -1);
2733 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2735 if (opts
.procfs
|| opts
.ocibundle
) {
2736 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0, NULL
, -1);
2739 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2740 * which cannot be expressed with OCI spec, but happends to be very useful.
2741 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2743 * If not running in a new network namespace, only make /proc/sys read-only.
2744 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2745 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2746 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2748 * This works because mounts are executed in incrementing strcmp() order and
2749 * /proc/self/net appears there before /proc/sys/net and hence the operation
2750 * succeeds as the bind-mount of /proc/self/net is performed first and then
2751 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2752 * table (and in the alphabet).
2754 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, 0, NULL
, -1))
2755 if (opts
.namespace & CLONE_NEWNET
)
2756 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0, NULL
, -1))
2757 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0, NULL
, -1);
2760 if (opts
.sysfs
|| opts
.ocibundle
)
2761 add_mount("sysfs", "/sys", "sysfs", MS_RELATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0, NULL
, -1);
2764 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, 0, "mode=1777", -1);
2768 if (opts
.setns
.pid
!= -1) {
2769 pidns_fd
= ns_open_pid("pid", getpid());
2770 setns_open(CLONE_NEWPID
);
2775 #ifdef CLONE_NEWTIME
2776 if (opts
.setns
.time
!= -1) {
2777 timens_fd
= ns_open_pid("time", getpid());
2778 setns_open(CLONE_NEWTIME
);
2784 if (opts
.namespace & CLONE_NEWUSER
) {
2785 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
2786 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
2787 free_and_exit(EXIT_FAILURE
);
2789 seteuid(opts
.root_map_uid
);
2792 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
2794 jail_process
.pid
= fork();
2797 if (jail_process
.pid
> 0) {
2798 /* parent process */
2801 uloop_process_add(&jail_process
);
2804 prctl(PR_SET_SECUREBITS
, 0);
2806 if (pidns_fd
!= -1) {
2807 setns(pidns_fd
, CLONE_NEWPID
);
2810 #ifdef CLONE_NEWTIME
2811 if (timens_fd
!= -1)
2812 setns(timens_fd
, CLONE_NEWTIME
);
2816 if (opts
.setns
.net
!= -1)
2817 close(opts
.setns
.net
);
2818 if (opts
.setns
.ns
!= -1)
2819 close(opts
.setns
.ns
);
2820 if (opts
.setns
.ipc
!= -1)
2821 close(opts
.setns
.ipc
);
2822 if (opts
.setns
.uts
!= -1)
2823 close(opts
.setns
.uts
);
2824 if (opts
.setns
.user
!= -1)
2825 close(opts
.setns
.user
);
2826 if (opts
.setns
.cgroup
!= -1)
2827 close(opts
.setns
.cgroup
);
2830 if (read(pipes
[0], sig_buf
, 1) < 1) {
2831 ERROR("can't read from child\n");
2835 set_oom_score_adj();
2838 cgroups_apply(jail_process
.pid
);
2840 if (opts
.namespace & CLONE_NEWUSER
) {
2841 if (write_setgroups(jail_process
.pid
, true)) {
2842 ERROR("can't write setgroups\n");
2846 bool has_gr
= (opts
.gr_gid
!= -1);
2847 if (opts
.pw_uid
!= -1) {
2848 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2849 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2851 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2852 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2855 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2857 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2861 if (opts
.namespace & CLONE_NEWNET
) {
2862 netns_fd
= ns_open_pid("net", jail_process
.pid
);
2863 netns_updown(jail_process
.pid
, true);
2866 if (jail_writepid(jail_process
.pid
)) {
2867 ERROR("failed to write pidfile: %m\n");
2870 } else if (jail_process
.pid
== 0) {
2871 /* fork child process */
2872 free_and_exit(exec_jail(NULL
));
2874 ERROR("failed to clone/fork: %m\n");
2875 free_and_exit(EXIT_FAILURE
);
2877 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
2880 static void post_poststart(void);
2881 static void post_create_runtime(void)
2886 if (write(pipes
[3], sig_buf
, 1) < 0) {
2887 ERROR("can't write to child\n");
2891 jail_oci_state
= OCI_STATE_CREATED
;
2892 if (opts
.ocibundle
&& !opts
.immediately
)
2893 uloop_run(); /* wait for 'start' command via ubus */
2895 pipe_send_start_container(NULL
);
2898 static void pipe_send_start_container(struct uloop_timeout
*t
)
2902 jail_oci_state
= OCI_STATE_RUNNING
;
2904 if (write(pipes
[3], sig_buf
, 1) < 0) {
2905 ERROR("can't write to child\n");
2910 run_hooks(opts
.hooks
.poststart
, post_poststart
);
2913 static void post_poststart(void)
2915 uloop_run(); /* idle here while jail is running */
2917 DEBUG("uloop interrupted, killing jail process\n");
2918 kill(jail_process
.pid
, SIGTERM
);
2919 uloop_timeout_set(&jail_process_timeout
, 1000);
2926 static void post_poststop(void);
2927 static void poststop(void) {
2928 if (opts
.namespace & CLONE_NEWNET
) {
2929 setns(netns_fd
, CLONE_NEWNET
);
2930 netns_updown(getpid(), false);
2933 run_hooks(opts
.hooks
.poststop
, post_poststop
);
2936 static void post_poststop(void)
2940 ubus_free(parent_ctx
);
2942 exit(jail_return_code
);