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
;
135 gid_t
*additional_gids
;
136 size_t num_additional_gids
;
141 struct hook_execvpe
**createRuntime
;
142 struct hook_execvpe
**createContainer
;
143 struct hook_execvpe
**startContainer
;
144 struct hook_execvpe
**poststart
;
145 struct hook_execvpe
**poststop
;
147 struct rlimit
*rlimits
[RLIM_NLIMITS
];
149 bool set_oom_score_adj
;
150 struct mknod_args
**devices
;
153 struct blob_attr
*annotations
;
156 static struct blob_buf ocibuf
;
158 extern int pivot_root(const char *new_root
, const char *put_old
);
162 static char child_stack
[STACK_SIZE
];
164 static struct ubus_context
*parent_ctx
;
169 static inline bool has_namespaces(void)
171 return ((opts
.setns
.pid
!= -1) ||
172 (opts
.setns
.net
!= -1) ||
173 (opts
.setns
.ns
!= -1) ||
174 (opts
.setns
.ipc
!= -1) ||
175 (opts
.setns
.uts
!= -1) ||
176 (opts
.setns
.user
!= -1) ||
177 (opts
.setns
.cgroup
!= -1) ||
179 (opts
.setns
.time
!= -1) ||
184 static void free_oci_envp(char **p
) {
196 static void free_hooklist(struct hook_execvpe
**hooklist
)
198 struct hook_execvpe
*cur
;
205 free_oci_envp(cur
->argv
);
206 free_oci_envp(cur
->envp
);
213 static void free_sysctl(void) {
214 struct sysctl_val
*cur
;
225 static void free_devices(void) {
226 struct mknod_args
**cur
;
240 static void free_rlimits(void) {
243 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
244 free(opts
.rlimits
[type
]);
247 static void free_opts(bool parent
) {
249 free_library_search();
252 /* we need to keep argv, envp and seccomp filter in child */
253 if (parent
) { /* parent-only */
254 if (opts
.ociseccomp
) {
255 free(opts
.ociseccomp
->filter
);
256 free(opts
.ociseccomp
);
259 free_oci_envp(opts
.jail_argv
);
260 free_oci_envp(opts
.envp
);
261 } else { /* child-only */
273 free(opts
.annotations
);
274 free_hooklist(opts
.hooks
.createRuntime
);
275 free_hooklist(opts
.hooks
.createContainer
);
276 free_hooklist(opts
.hooks
.startContainer
);
277 free_hooklist(opts
.hooks
.poststart
);
278 free_hooklist(opts
.hooks
.poststop
);
281 static int mount_overlay(char *jail_root
, char *overlaydir
) {
282 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
283 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
286 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
289 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
292 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
295 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
299 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
300 * this is to work-around a bug in overlayfs described in the overlayfs-userns
302 * 3. modification of a file 'hithere' which is in l but not yet
303 * in u, and which is not owned by T, is not allowed, even if
304 * writes to u are allowed. This may be a bug in overlayfs,
305 * but it is safe behavior.
307 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
310 if (mkdir_p(upperetc
, 0755))
311 goto upper_etc_printf
;
313 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
314 goto upper_etc_printf
;
316 fd
= creat(upperresolvconf
, 0644);
319 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
323 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
325 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
326 goto upper_resolvconf_printf
;
330 upper_resolvconf_printf
:
331 free(upperresolvconf
);
344 static void pass_console(int console_fd
)
346 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
347 static struct blob_buf req
;
353 blob_buf_init(&req
, 0);
354 blobmsg_add_string(&req
, "name", opts
.name
);
356 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
357 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
358 INFO("ubus request failed\n");
363 ubus_free(child_ctx
);
366 static int create_dev_console(const char *jail_root
)
369 char dev_console_path
[PATH_MAX
];
370 int slave_console_fd
;
372 /* Open UNIX/98 virtual console */
373 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
374 if (console_fd
== -1)
377 console_fname
= ptsname(console_fd
);
378 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
383 unlockpt(console_fd
);
385 /* pass PTY master to procd */
386 pass_console(console_fd
);
388 /* mount-bind PTY slave to /dev/console in jail */
389 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
390 close(creat(dev_console_path
, 0620));
392 if (mount(console_fname
, dev_console_path
, NULL
, MS_BIND
, NULL
))
395 /* use PTY slave for stdio */
396 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
397 dup2(slave_console_fd
, 0);
398 dup2(slave_console_fd
, 1);
399 dup2(slave_console_fd
, 2);
400 close(slave_console_fd
);
402 INFO("using guest console %s\n", console_fname
);
411 static int hook_running
= 0;
412 static int hook_return_code
= 0;
413 static struct hook_execvpe
**current_hook
= NULL
;
414 typedef void (*hook_return_handler
)(void);
415 static hook_return_handler hook_return_cb
= NULL
;
417 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
418 static struct uloop_timeout hook_process_timeout
= {
419 .cb
= hook_process_timeout_cb
,
422 static void run_hooklist(void);
423 static void hook_process_handler(struct uloop_process
*c
, int ret
)
425 uloop_timeout_cancel(&hook_process_timeout
);
427 if (WIFEXITED(ret
)) {
428 hook_return_code
= WEXITSTATUS(ret
);
429 if (hook_return_code
)
430 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
432 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
435 hook_return_code
= WTERMSIG(ret
);
436 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
443 static struct uloop_process hook_process
= {
444 .cb
= hook_process_handler
,
447 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
449 DEBUG("hook process failed to stop, sending SIGKILL\n");
450 kill(hook_process
.pid
, SIGKILL
);
453 static void run_hooklist(void)
455 struct hook_execvpe
*hook
= *current_hook
;
461 DEBUG("executing hook %s\n", hook
->file
);
463 if (stat(hook
->file
, &s
))
464 hook_process_handler(&hook_process
, ENOENT
);
466 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
467 hook_process_handler(&hook_process
, EPERM
);
469 if (!((unsigned long)s
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
)))
470 hook_process_handler(&hook_process
, EPERM
);
473 hook_process
.pid
= fork();
474 if (hook_process
.pid
== 0) {
476 execve(hook
->file
, hook
->argv
, hook
->envp
);
477 ERROR("execve error %m\n");
479 } else if (hook_process
.pid
< 0) {
481 ERROR("hook fork error\n");
483 hook_process_handler(&hook_process
, errno
);
487 uloop_process_add(&hook_process
);
489 if (hook
->timeout
> 0)
490 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
494 DEBUG("uloop interrupted, killing jail process\n");
495 kill(hook_process
.pid
, SIGTERM
);
496 uloop_timeout_set(&hook_process_timeout
, 1000);
501 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
506 current_hook
= hooklist
;
507 hook_return_cb
= return_cb
;
512 static int apply_sysctl(const char *jail_root
)
514 struct sysctl_val
**cur
;
515 char *procdir
, *fname
;
521 asprintf(&procdir
, "%s/proc", jail_root
);
525 mkdir(procdir
, 0700);
526 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
532 asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
);
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
);
543 write(f
, (*cur
)->value
, strlen((*cur
)->value
));
556 /* glibc defines makedev calling a function. make sure it's a pure macro */
557 #if defined(__GLIBC__)
559 /* from musl's sys/sysmacros.h */
560 #define makedev(x,y) ( \
561 (((x)&0xfffff000ULL) << 32) | \
562 (((x)&0x00000fffULL) << 8) | \
563 (((y)&0xffffff00ULL) << 12) | \
564 (((y)&0x000000ffULL)) )
567 static struct mknod_args default_devices
[] = {
568 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
569 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
570 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
571 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
572 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
573 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
577 static int create_devices(void)
579 struct mknod_args
**cur
, *curdef
;
582 goto only_default_devices
;
587 DEBUG("creating %s (mode=%08o)\n", (*cur
)->path
, (*cur
)->mode
);
588 if (mknod((*cur
)->path
, (*cur
)->mode
, (*cur
)->dev
))
591 if (((*cur
)->uid
|| (*cur
)->gid
) &&
592 chown((*cur
)->path
, (*cur
)->uid
, (*cur
)->gid
))
598 only_default_devices
:
599 curdef
= default_devices
;
600 while(curdef
->path
) {
601 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
602 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
604 continue; /* may already exist, eg. due to a bind-mount */
606 if ((curdef
->uid
|| curdef
->gid
) &&
607 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
613 /* Dev symbolic links as defined in OCI spec */
614 symlink("/dev/pts/ptmx", "/dev/ptmx");
615 symlink("/proc/self/fd", "/dev/fd");
616 symlink("/proc/self/fd/0", "/dev/stdin");
617 symlink("/proc/self/fd/1", "/dev/stdout");
618 symlink("/proc/self/fd/2", "/dev/stderr");
623 static char jail_root
[] = "/tmp/ujail-XXXXXX";
624 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
625 static mode_t old_umask
;
626 static void enter_jail_fs(void);
627 static int build_jail_fs(void)
629 char *overlaydir
= NULL
;
631 old_umask
= umask(0);
633 if (mkdtemp(jail_root
) == NULL
) {
634 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
638 if (apply_sysctl(jail_root
)) {
639 ERROR("failed to apply sysctl values\n");
643 /* oldroot can't be MS_SHARED else pivot_root() fails */
644 if (mount("none", "/", NULL
, MS_REC
|MS_PRIVATE
, NULL
)) {
645 ERROR("private mount failed %m\n");
650 if (mount(opts
.extroot
, jail_root
, NULL
, MS_BIND
, NULL
)) {
651 ERROR("extroot mount failed %m\n");
655 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
656 ERROR("tmpfs mount failed %m\n");
661 if (opts
.tmpoverlaysize
) {
662 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
664 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
665 "mode=0755,size=%s", opts
.tmpoverlaysize
);
666 if (mkdtemp(tmpovdir
) == NULL
) {
667 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
670 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
672 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
675 overlaydir
= tmpovdir
;
679 overlaydir
= opts
.overlaydir
;
682 mount_overlay(jail_root
, overlaydir
);
684 if (chdir(jail_root
)) {
685 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
689 if (mount_all(jail_root
)) {
690 ERROR("mount_all() failed\n");
695 create_dev_console(jail_root
);
697 /* make sure /etc/resolv.conf exists if in new network namespace */
698 if (opts
.namespace & CLONE_NEWNET
) {
699 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
701 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
702 mkdir_p(jailetc
, 0755);
703 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
707 symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
710 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
715 static bool exit_from_child
;
716 static void free_and_exit(int ret
)
718 if (!exit_from_child
&& opts
.ocibundle
)
721 if (!exit_from_child
&& parent_ctx
)
722 ubus_free(parent_ctx
);
724 free_opts(!exit_from_child
);
729 static void post_jail_fs(void);
730 static void enter_jail_fs(void)
732 char dirbuf
[sizeof(jail_root
) + 4];
734 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
737 if (pivot_root(jail_root
, dirbuf
) == -1) {
738 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
742 ERROR("chdir(/) (after pivot_root) failed: %m\n");
746 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
747 umount2(dirbuf
, MNT_DETACH
);
749 if (opts
.tmpoverlaysize
) {
750 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
751 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
752 umount2(tmpdirbuf
, MNT_DETACH
);
756 umount2("/old", MNT_DETACH
);
759 if (create_devices()) {
760 ERROR("create_devices() failed\n");
764 mount(NULL
, "/", NULL
, MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
770 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
775 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
776 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
779 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
782 if (dprintf(map_file
, "%s", mapstr
)) {
791 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
795 const char *map_format
= "%d %d %d\n";
796 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
797 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
800 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
803 if (dprintf(map_file
, map_format
, 0, id
, 1) == -1) {
812 static int write_setgroups(pid_t child_pid
, bool allow
)
815 char setgroups_path
[64];
817 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
822 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) == -1) {
826 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
827 close(setgroups_file
);
831 close(setgroups_file
);
835 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
837 struct passwd
*p
= NULL
;
838 struct group
*g
= NULL
;
841 p
= getpwnam(opts
.user
);
843 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
844 opts
.user
, errno
, strerror(errno
));
845 free_and_exit(EXIT_FAILURE
);
848 *user_gid
= p
->pw_gid
;
855 g
= getgrnam(opts
.group
);
857 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
858 free_and_exit(EXIT_FAILURE
);
866 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
868 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
869 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
870 free_and_exit(EXIT_FAILURE
);
873 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
874 ERROR("failed to set group id %d: %m\n", gr_gid
);
875 free_and_exit(EXIT_FAILURE
);
878 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
879 ERROR("failed to set user id %d: %m\n", pw_uid
);
880 free_and_exit(EXIT_FAILURE
);
884 static int apply_rlimits(void)
888 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
889 if (opts
.rlimits
[resource
])
890 DEBUG("applying limits to resource %u\n", resource
);
892 if (opts
.rlimits
[resource
] &&
893 setrlimit(resource
, opts
.rlimits
[resource
]))
901 static char** build_envp(const char *seccomp
, char **ocienvp
)
903 static char *envp
[MAX_ENVP
];
904 static char preload_var
[PATH_MAX
];
905 static char seccomp_var
[PATH_MAX
];
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(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
921 envp
[count
++] = preload_var
;
924 envp
[count
++] = container_var
;
927 envp
[count
++] = debug_var
;
930 while (addenv
&& *addenv
) {
931 envp
[count
++] = *(addenv
++);
932 if (count
>= MAX_ENVP
) {
933 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
940 static void usage(void)
942 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
943 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
944 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
945 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
946 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
947 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
948 fprintf(stderr
, "namespace jail options:\n");
949 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
950 fprintf(stderr
, " -N\t\tjail has network namespace\n");
951 fprintf(stderr
, " -f\t\tjail has user namespace\n");
952 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
953 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
954 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
955 fprintf(stderr
, " -p\t\tjail has /proc\n");
956 fprintf(stderr
, " -s\t\tjail has /sys\n");
957 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
958 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
959 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
960 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
961 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
962 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
963 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
964 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
965 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
966 fprintf(stderr
, " -y\t\tprovide jail console\n");
967 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
968 fprintf(stderr
, " -j\t\tstart container immediately\n");
969 fprintf(stderr
, " -P <pidfile>\tcreate <pidfile>\n");
970 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
971 and he has the same powers as root outside the jail,\n\
972 thus he can escape the jail and/or break stuff.\n\
973 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
974 If you use none of the namespace jail options,\n\
975 ujail will not use namespace/build a jail,\n\
976 and will only drop capabilities/apply seccomp filter.\n\n");
979 static int* get_namespace_fd(const unsigned int nstype
)
983 return &opts
.setns
.pid
;
985 return &opts
.setns
.net
;
987 return &opts
.setns
.ns
;
989 return &opts
.setns
.ipc
;
991 return &opts
.setns
.uts
;
993 return &opts
.setns
.user
;
994 case CLONE_NEWCGROUP
:
995 return &opts
.setns
.cgroup
;
998 return &opts
.setns
.time
;
1005 static int setns_open(unsigned long nstype
)
1007 int *fd
= get_namespace_fd(nstype
);
1015 if (setns(*fd
, nstype
) == -1) {
1024 static int jail_running
= 0;
1025 static int jail_return_code
= 0;
1027 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1028 static struct uloop_timeout jail_process_timeout
= {
1029 .cb
= jail_process_timeout_cb
,
1031 static void poststop(void);
1032 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1034 uloop_timeout_cancel(&jail_process_timeout
);
1035 if (WIFEXITED(ret
)) {
1036 jail_return_code
= WEXITSTATUS(ret
);
1037 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1039 jail_return_code
= WTERMSIG(ret
);
1040 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1046 static struct uloop_process jail_process
= {
1047 .cb
= jail_process_handler
,
1050 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1052 DEBUG("jail process failed to stop, sending SIGKILL\n");
1053 kill(jail_process
.pid
, SIGKILL
);
1056 static void jail_handle_signal(int signo
)
1059 DEBUG("forwarding signal %d to the hook process\n", signo
);
1060 kill(hook_process
.pid
, signo
);
1064 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1065 kill(jail_process
.pid
, signo
);
1069 static void signals_init(void)
1074 sigfillset(&sigmask
);
1075 for (i
= 0; i
< _NSIG
; i
++) {
1076 struct sigaction s
= { 0 };
1078 if (!sigismember(&sigmask
, i
))
1080 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1083 s
.sa_handler
= jail_handle_signal
;
1084 sigaction(i
, &s
, NULL
);
1088 static void pre_exec_jail(struct uloop_timeout
*t
);
1089 static struct uloop_timeout pre_exec_timeout
= {
1090 .cb
= pre_exec_jail
,
1094 static int exec_jail(void *arg
)
1098 exit_from_child
= true;
1105 setns_open(CLONE_NEWUSER
);
1106 setns_open(CLONE_NEWNET
);
1107 setns_open(CLONE_NEWNS
);
1108 setns_open(CLONE_NEWIPC
);
1109 setns_open(CLONE_NEWUTS
);
1112 if (write(pipes
[1], buf
, 1) < 1) {
1113 ERROR("can't write to parent\n");
1114 return EXIT_FAILURE
;
1117 if (read(pipes
[2], buf
, 1) < 1) {
1118 ERROR("can't read from parent\n");
1119 return EXIT_FAILURE
;
1121 if (buf
[0] != 'O') {
1122 ERROR("parent had an error, child exiting\n");
1123 return EXIT_FAILURE
;
1126 if (opts
.namespace & CLONE_NEWCGROUP
)
1127 unshare(CLONE_NEWCGROUP
);
1129 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1130 if (setregid(0, 0) < 0) {
1132 free_and_exit(EXIT_FAILURE
);
1134 if (setreuid(0, 0) < 0) {
1136 free_and_exit(EXIT_FAILURE
);
1138 if (setgroups(0, NULL
) < 0) {
1139 ERROR("setgroups\n");
1140 free_and_exit(EXIT_FAILURE
);
1144 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1145 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1146 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1147 free_and_exit(EXIT_FAILURE
);
1150 uloop_timeout_add(&pre_exec_timeout
);
1157 static void pre_exec_jail(struct uloop_timeout
*t
)
1159 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1160 ERROR("failed to build jail fs\n");
1161 free_and_exit(EXIT_FAILURE
);
1163 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1167 static void post_start_hook(void);
1168 static void post_jail_fs(void)
1172 if (read(pipes
[2], buf
, 1) < 1) {
1173 ERROR("can't read from parent\n");
1174 free_and_exit(EXIT_FAILURE
);
1176 if (buf
[0] != '!') {
1177 ERROR("parent had an error, child exiting\n");
1178 free_and_exit(EXIT_FAILURE
);
1182 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1185 static void post_start_hook(void)
1187 int pw_uid
, pw_gid
, gr_gid
;
1190 * make sure setuid/setgid won't drop capabilities in case capabilities
1191 * have been specified explicitely.
1193 if (opts
.capset
.apply
) {
1194 if (prctl(PR_SET_SECUREBITS
, SECBIT_NO_SETUID_FIXUP
)) {
1195 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1196 free_and_exit(EXIT_FAILURE
);
1200 /* drop capabilities, retain those still needed to further setup jail */
1201 if (applyOCIcapabilities(opts
.capset
, (1LLU << CAP_SETGID
) | (1LLU << CAP_SETUID
) | (1LLU << CAP_SETPCAP
)))
1202 free_and_exit(EXIT_FAILURE
);
1204 /* use either cmdline-supplied user/group or uid/gid from OCI spec */
1205 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1206 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1208 if (opts
.additional_gids
&&
1209 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1210 ERROR("setgroups failed: %m\n");
1211 free_and_exit(EXIT_FAILURE
);
1217 /* restore securebits back to normal */
1218 if (opts
.capset
.apply
) {
1219 if (prctl(PR_SET_SECUREBITS
, 0)) {
1220 ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
1221 free_and_exit(EXIT_FAILURE
);
1225 /* drop remaining capabilities to end up with specified sets */
1226 if (applyOCIcapabilities(opts
.capset
, 0))
1227 free_and_exit(EXIT_FAILURE
);
1229 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1230 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1231 free_and_exit(EXIT_FAILURE
);
1234 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1236 free_and_exit(EXIT_FAILURE
);
1238 if (opts
.cwd
&& chdir(opts
.cwd
))
1239 free_and_exit(EXIT_FAILURE
);
1241 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1242 free_and_exit(EXIT_FAILURE
);
1246 INFO("exec-ing %s\n", *opts
.jail_argv
);
1247 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1248 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1250 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1252 /* we get there only if execve fails */
1253 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1257 static int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1259 char pid_pid_path
[PATH_MAX
];
1261 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1263 return open(pid_pid_path
, O_RDONLY
);
1266 static void netns_updown(pid_t pid
, bool start
)
1268 static struct blob_buf req
;
1274 blob_buf_init(&req
, 0);
1275 blobmsg_add_string(&req
, "jail", opts
.name
);
1276 blobmsg_add_u32(&req
, "pid", pid
);
1277 blobmsg_add_u8(&req
, "start", start
);
1279 if (ubus_lookup_id(parent_ctx
, "network", &id
) ||
1280 ubus_invoke(parent_ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1281 INFO("ubus request failed\n");
1283 blob_buf_free(&req
);
1286 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1288 struct blob_attr
*cur
;
1291 blobmsg_for_each_attr(cur
, msg
, rem
)
1295 *envp
= calloc(1 + sz
, sizeof(char*));
1304 blobmsg_for_each_attr(cur
, msg
, rem
)
1305 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1319 static const struct blobmsg_policy oci_root_policy
[] = {
1320 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1321 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1324 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1326 static char extroot
[PATH_MAX
] = { 0 };
1327 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1331 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1333 if (!tb
[OCI_ROOT_PATH
])
1336 root_path
= blobmsg_get_string(tb
[OCI_ROOT_PATH
]);
1338 /* prepend bundle directory in case of relative paths */
1339 if (root_path
[0] != '/') {
1340 strncpy(extroot
, jsonfile
, PATH_MAX
);
1341 cur
= strrchr(extroot
, '/');
1349 strncat(extroot
, root_path
, PATH_MAX
- (strlen(extroot
) + 1));
1351 opts
.extroot
= extroot
;
1353 if (tb
[OCI_ROOT_READONLY
])
1354 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1368 static const struct blobmsg_policy oci_hook_policy
[] = {
1369 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1370 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1371 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1372 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1376 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1378 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1379 struct blob_attr
*cur
;
1383 blobmsg_for_each_attr(cur
, msg
, rem
)
1389 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1395 blobmsg_for_each_attr(cur
, msg
, rem
) {
1396 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1398 if (!tb
[OCI_HOOK_PATH
]) {
1403 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1404 if (tb
[OCI_HOOK_ARGS
]) {
1405 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1409 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1410 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1411 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1415 if (tb
[OCI_HOOK_ENV
]) {
1416 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1421 if (tb
[OCI_HOOK_TIMEOUT
])
1422 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1424 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1429 (*hooklist
)[idx
] = NULL
;
1431 DEBUG("added %d hooks\n", idx
);
1436 free_hooklist(*hooklist
);
1445 OCI_HOOKS_CREATERUNTIME
,
1446 OCI_HOOKS_CREATECONTAINER
,
1447 OCI_HOOKS_STARTCONTAINER
,
1448 OCI_HOOKS_POSTSTART
,
1453 static const struct blobmsg_policy oci_hooks_policy
[] = {
1454 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1455 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1456 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1457 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1458 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1459 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1462 static int parseOCIhooks(struct blob_attr
*msg
)
1464 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1467 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1469 if (tb
[OCI_HOOKS_PRESTART
])
1470 INFO("warning: ignoring deprecated prestart hook\n");
1472 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1473 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1478 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1479 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1481 goto out_createruntime
;
1484 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1485 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1487 goto out_createcontainer
;
1490 if (tb
[OCI_HOOKS_POSTSTART
]) {
1491 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1493 goto out_startcontainer
;
1496 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1497 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1505 free_hooklist(opts
.hooks
.poststart
);
1507 free_hooklist(opts
.hooks
.startContainer
);
1508 out_createcontainer
:
1509 free_hooklist(opts
.hooks
.createContainer
);
1511 free_hooklist(opts
.hooks
.createRuntime
);
1518 OCI_PROCESS_USER_UID
,
1519 OCI_PROCESS_USER_GID
,
1520 OCI_PROCESS_USER_UMASK
,
1521 OCI_PROCESS_USER_ADDITIONALGIDS
,
1522 __OCI_PROCESS_USER_MAX
,
1525 static const struct blobmsg_policy oci_process_user_policy
[] = {
1526 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1527 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1528 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1529 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1532 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1533 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1534 struct blob_attr
*cur
;
1538 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1540 if (tb
[OCI_PROCESS_USER_UID
])
1541 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1543 if (tb
[OCI_PROCESS_USER_GID
]) {
1544 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1545 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1549 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1552 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1554 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1559 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1562 /* always add primary GID to set of GIDs if set */
1564 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1566 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1567 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1569 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1571 opts
.num_additional_gids
= gidcnt
;
1573 DEBUG("read %zu additional groups\n", gidcnt
);
1576 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1577 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1578 opts
.set_umask
= true;
1585 OCI_PROCESS_RLIMIT_TYPE
,
1586 OCI_PROCESS_RLIMIT_SOFT
,
1587 OCI_PROCESS_RLIMIT_HARD
,
1588 __OCI_PROCESS_RLIMIT_MAX
,
1591 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1592 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1593 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1594 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1597 /* from manpage GETRLIMIT(2) */
1598 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1600 [RLIMIT_CORE
] = "CORE",
1601 [RLIMIT_CPU
] = "CPU",
1602 [RLIMIT_DATA
] = "DATA",
1603 [RLIMIT_FSIZE
] = "FSIZE",
1604 [RLIMIT_LOCKS
] = "LOCKS",
1605 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1606 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1607 [RLIMIT_NICE
] = "NICE",
1608 [RLIMIT_NOFILE
] = "NOFILE",
1609 [RLIMIT_NPROC
] = "NPROC",
1610 [RLIMIT_RSS
] = "RSS",
1611 [RLIMIT_RTPRIO
] = "RTPRIO",
1612 [RLIMIT_RTTIME
] = "RTTIME",
1613 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1614 [RLIMIT_STACK
] = "STACK",
1617 static int resolve_rlimit(char *type
) {
1618 unsigned int rltype
;
1620 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1621 if (rlimit_names
[rltype
] &&
1622 !strncmp("RLIMIT_", type
, 7) &&
1623 !strcmp(rlimit_names
[rltype
], type
+ 7))
1630 static int parseOCIrlimit(struct blob_attr
*msg
)
1632 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1634 struct rlimit
*curlim
;
1636 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1638 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1639 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1640 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1643 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1648 if (opts
.rlimits
[limtype
])
1651 curlim
= malloc(sizeof(struct rlimit
));
1652 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1653 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1655 opts
.rlimits
[limtype
] = curlim
;
1662 OCI_PROCESS_CAPABILITIES
,
1665 OCI_PROCESS_OOMSCOREADJ
,
1666 OCI_PROCESS_NONEWPRIVILEGES
,
1667 OCI_PROCESS_RLIMITS
,
1668 OCI_PROCESS_TERMINAL
,
1673 static const struct blobmsg_policy oci_process_policy
[] = {
1674 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1675 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1676 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1677 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1678 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1679 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1680 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1681 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1682 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1686 static int parseOCIprocess(struct blob_attr
*msg
)
1688 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1691 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1693 if (!tb
[OCI_PROCESS_ARGS
])
1696 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1700 if (tb
[OCI_PROCESS_TERMINAL
])
1701 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1703 if (tb
[OCI_PROCESS_NONEWPRIVILEGES
])
1704 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1706 if (tb
[OCI_PROCESS_CWD
])
1707 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1709 if (tb
[OCI_PROCESS_ENV
]) {
1710 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1715 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1718 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1719 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1722 if (tb
[OCI_PROCESS_RLIMITS
]) {
1723 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1724 res
= parseOCIrlimit(cur
);
1730 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1731 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1732 opts
.set_oom_score_adj
= true;
1739 OCI_LINUX_NAMESPACE_TYPE
,
1740 OCI_LINUX_NAMESPACE_PATH
,
1741 __OCI_LINUX_NAMESPACE_MAX
,
1744 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1745 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1746 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1749 static int resolve_nstype(char *type
) {
1750 if (!strcmp("pid", type
))
1751 return CLONE_NEWPID
;
1752 else if (!strcmp("network", type
))
1753 return CLONE_NEWNET
;
1754 else if (!strcmp("mount", type
))
1756 else if (!strcmp("ipc", type
))
1757 return CLONE_NEWIPC
;
1758 else if (!strcmp("uts", type
))
1759 return CLONE_NEWUTS
;
1760 else if (!strcmp("user", type
))
1761 return CLONE_NEWUSER
;
1762 else if (!strcmp("cgroup", type
))
1763 return CLONE_NEWCGROUP
;
1764 #ifdef CLONE_NEWTIME
1765 else if (!strcmp("time", type
))
1766 return CLONE_NEWTIME
;
1772 static int parseOCIlinuxns(struct blob_attr
*msg
)
1774 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1779 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1781 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1784 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1788 if (opts
.namespace & nstype
)
1791 setns
= get_namespace_fd(nstype
);
1799 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1800 DEBUG("opening existing %s namespace from path %s\n",
1801 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1802 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1804 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1806 return errno
?:ESTALE
;
1808 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
)
1811 DEBUG("opened existing %s namespace got filehandler %u\n",
1812 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1817 opts
.namespace |= nstype
;
1825 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1826 OCI_LINUX_UIDGIDMAP_HOSTID
,
1827 OCI_LINUX_UIDGIDMAP_SIZE
,
1828 __OCI_LINUX_UIDGIDMAP_MAX
,
1831 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1832 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1833 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1834 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1837 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1839 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1840 struct blob_attr
*cur
;
1843 size_t len
, pos
, totallen
= 0;
1845 blobmsg_for_each_attr(cur
, msg
, rem
) {
1846 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1848 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1849 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1850 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1854 totallen
+= snprintf(NULL
, 0, "%d %d %d\n",
1855 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1856 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1857 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1860 /* allocate combined mapping string */
1861 map
= malloc(totallen
+ 1);
1866 blobmsg_for_each_attr(cur
, msg
, rem
) {
1867 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1869 /* write mapping line into pre-allocated string */
1870 len
= snprintf(&map
[pos
], totallen
+ 1, "%d %d %d\n",
1871 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1872 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1873 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1878 assert(totallen
== 0);
1893 OCI_DEVICES_FILEMODE
,
1899 static const struct blobmsg_policy oci_devices_policy
[] = {
1900 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1901 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1902 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
1903 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
1904 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
1905 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1906 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
1909 static mode_t
resolve_devtype(char *tstr
)
1911 if (!strcmp("c", tstr
) ||
1914 else if (!strcmp("b", tstr
))
1916 else if (!strcmp("p", tstr
))
1922 static int parseOCIdevices(struct blob_attr
*msg
)
1924 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
1925 struct blob_attr
*cur
;
1928 struct mknod_args
*tmp
;
1930 blobmsg_for_each_attr(cur
, msg
, rem
)
1933 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
1936 blobmsg_for_each_attr(cur
, msg
, rem
) {
1937 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1938 if (!tb
[OCI_DEVICES_TYPE
] ||
1939 !tb
[OCI_DEVICES_PATH
])
1942 tmp
= calloc(1, sizeof(struct mknod_args
));
1946 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1950 if (tmp
->mode
!= S_IFIFO
) {
1951 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
])
1954 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
1955 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
1958 if (tb
[OCI_DEVICES_FILEMODE
]) {
1959 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]))
1962 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
1964 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
1967 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
1969 if (tb
[OCI_DEVICES_UID
])
1970 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
1974 if (tb
[OCI_DEVICES_GID
])
1975 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
1979 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1980 opts
.devices
[cnt
++] = tmp
;
1983 opts
.devices
[cnt
] = NULL
;
1988 static int parseOCIsysctl(struct blob_attr
*msg
)
1990 struct blob_attr
*cur
;
1995 blobmsg_for_each_attr(cur
, msg
, rem
) {
1996 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
2005 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2010 blobmsg_for_each_attr(cur
, msg
, rem
) {
2011 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2012 if (!opts
.sysctl
[cnt
])
2015 /* replace '.' with '/' in entry name */
2016 tc
= tmp
= strdup(blobmsg_name(cur
));
2017 while ((tc
= strchr(tc
, '.')))
2020 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2021 opts
.sysctl
[cnt
]->entry
= tmp
;
2026 opts
.sysctl
[cnt
] = NULL
;
2033 OCI_LINUX_CGROUPSPATH
,
2034 OCI_LINUX_RESOURCES
,
2037 OCI_LINUX_NAMESPACES
,
2039 OCI_LINUX_UIDMAPPINGS
,
2040 OCI_LINUX_GIDMAPPINGS
,
2041 OCI_LINUX_MASKEDPATHS
,
2042 OCI_LINUX_READONLYPATHS
,
2043 OCI_LINUX_ROOTFSPROPAGATION
,
2047 static const struct blobmsg_policy oci_linux_policy
[] = {
2048 [OCI_LINUX_CGROUPSPATH
] = { "cgroupsPath", BLOBMSG_TYPE_STRING
},
2049 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
2050 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
2051 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
2052 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
2053 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
2054 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
2055 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
2056 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
2057 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
2058 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
2061 static int parseOCIlinux(struct blob_attr
*msg
)
2063 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2064 struct blob_attr
*cur
;
2068 char cgfullpath
[256] = "/sys/fs/cgroup";
2070 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2072 if (tb
[OCI_LINUX_NAMESPACES
]) {
2073 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2074 res
= parseOCIlinuxns(cur
);
2080 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2081 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2086 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2087 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2092 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2093 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2094 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, 0, NULL
, 0);
2100 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2101 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2102 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, 0, NULL
, 0);
2108 if (tb
[OCI_LINUX_SYSCTL
]) {
2109 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2114 if (tb
[OCI_LINUX_SECCOMP
]) {
2115 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2116 if (!opts
.ociseccomp
)
2120 if (tb
[OCI_LINUX_DEVICES
]) {
2121 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2126 if (tb
[OCI_LINUX_CGROUPSPATH
]) {
2127 cgpath
= blobmsg_get_string(tb
[OCI_LINUX_CGROUPSPATH
]);
2128 if (cgpath
[0] == '/') {
2129 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2132 strcat(cgfullpath
, cgpath
);
2134 strcat(cgfullpath
, "/containers/");
2135 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2136 strcat(cgfullpath
, "/");
2137 if (strlen(cgpath
) >= (sizeof(cgfullpath
) - strlen(cgfullpath
)))
2140 strcat(cgfullpath
, cgpath
);
2143 strcat(cgfullpath
, "/containers/");
2144 strcat(cgfullpath
, opts
.name
); /* should be container name rather than jail name */
2145 strcat(cgfullpath
, "/");
2146 strcat(cgfullpath
, opts
.name
); /* should be container instance name rather than jail name */
2149 cgroups_init(cgfullpath
);
2151 if (tb
[OCI_LINUX_RESOURCES
]) {
2152 res
= parseOCIlinuxcgroups(tb
[OCI_LINUX_RESOURCES
]);
2172 static const struct blobmsg_policy oci_policy
[] = {
2173 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2174 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2175 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2176 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2177 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2178 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2179 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2180 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2183 static int parseOCI(const char *jsonfile
)
2185 struct blob_attr
*tb
[__OCI_MAX
];
2186 struct blob_attr
*cur
;
2190 blob_buf_init(&ocibuf
, 0);
2192 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
)) {
2197 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2199 if (!tb
[OCI_VERSION
]) {
2204 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2205 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2210 if (tb
[OCI_HOSTNAME
])
2211 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2213 if (!tb
[OCI_PROCESS
]) {
2218 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2221 if (!tb
[OCI_ROOT
]) {
2225 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2228 if (!tb
[OCI_MOUNTS
]) {
2233 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2234 if ((res
= parseOCImount(cur
)))
2237 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2240 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2243 if (tb
[OCI_ANNOTATIONS
])
2244 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2247 blob_buf_free(&ocibuf
);
2252 static int set_oom_score_adj(void)
2257 if (!opts
.set_oom_score_adj
)
2260 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2261 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2265 dprintf(f
, "%d", opts
.oom_score_adj
);
2279 static int jail_oci_state
= OCI_STATE_CREATED
;
2280 static void pipe_send_start_container(struct uloop_timeout
*t
);
2281 static struct uloop_timeout start_container_timeout
= {
2282 .cb
= pipe_send_start_container
,
2285 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2286 struct ubus_request_data
*req
, const char *method
,
2287 struct blob_attr
*msg
)
2289 if (jail_oci_state
!= OCI_STATE_CREATED
)
2290 return UBUS_STATUS_INVALID_ARGUMENT
;
2292 uloop_timeout_add(&start_container_timeout
);
2294 return UBUS_STATUS_OK
;
2297 static struct blob_buf bb
;
2298 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2299 struct ubus_request_data
*req
, const char *method
,
2300 struct blob_attr
*msg
)
2304 switch (jail_oci_state
) {
2305 case OCI_STATE_CREATING
:
2306 statusstr
= "creating";
2308 case OCI_STATE_CREATED
:
2309 statusstr
= "created";
2311 case OCI_STATE_RUNNING
:
2312 statusstr
= "running";
2314 case OCI_STATE_STOPPED
:
2315 statusstr
= "stopped";
2318 statusstr
= "unknown";
2321 blob_buf_init(&bb
, 0);
2322 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2323 blobmsg_add_string(&bb
, "id", opts
.name
);
2324 blobmsg_add_string(&bb
, "status", statusstr
);
2325 if (jail_oci_state
== OCI_STATE_CREATED
||
2326 jail_oci_state
== OCI_STATE_RUNNING
)
2327 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2329 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2331 if (opts
.annotations
)
2332 blobmsg_add_blob(&bb
, opts
.annotations
);
2334 ubus_send_reply(ctx
, req
, bb
.head
);
2336 return UBUS_STATUS_OK
;
2340 CONTAINER_KILL_ATTR_SIGNAL
,
2341 __CONTAINER_KILL_ATTR_MAX
,
2344 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2345 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2349 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2350 struct ubus_request_data
*req
, const char *method
,
2351 struct blob_attr
*msg
)
2353 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2356 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2358 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2360 sig
= blobmsg_get_u32(cur
);
2362 if (jail_oci_state
== OCI_STATE_CREATING
)
2363 return UBUS_STATUS_NOT_FOUND
;
2365 if (kill(jail_process
.pid
, sig
) == 0)
2369 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2370 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2371 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2374 return UBUS_STATUS_UNKNOWN_ERROR
;
2378 jail_writepid(pid_t pid
)
2385 _pidfile
= fopen(opts
.pidfile
, "w");
2386 if (_pidfile
== NULL
)
2389 if (fprintf(_pidfile
, "%d\n", pid
) < 0) {
2394 if (fclose(_pidfile
))
2400 static struct ubus_method container_methods
[] = {
2401 UBUS_METHOD_NOARG("start", handle_start
),
2402 UBUS_METHOD_NOARG("state", handle_state
),
2403 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2406 static struct ubus_object_type container_object_type
=
2407 UBUS_OBJECT_TYPE("container", container_methods
);
2409 static struct ubus_object container_object
= {
2410 .type
= &container_object_type
,
2411 .methods
= container_methods
,
2412 .n_methods
= ARRAY_SIZE(container_methods
),
2415 static void post_main(struct uloop_timeout
*t
);
2416 static struct uloop_timeout post_main_timeout
= {
2419 static int netns_fd
;
2420 static int pidns_fd
;
2421 #ifdef CLONE_NEWTIME
2422 static int timens_fd
;
2424 static void post_create_runtime(void);
2425 int main(int argc
, char **argv
)
2427 uid_t uid
= getuid();
2428 const char log
[] = "/dev/log";
2429 const char ubus
[] = "/var/run/ubus/ubus.sock";
2433 ERROR("not root, aborting: %m\n");
2434 return EXIT_FAILURE
;
2439 init_library_search();
2441 exit_from_child
= false;
2443 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2446 debug
= atoi(optarg
);
2449 opts
.namespace |= CLONE_NEWNS
;
2453 opts
.namespace |= CLONE_NEWNS
;
2457 opts
.namespace |= CLONE_NEWUSER
;
2460 opts
.namespace |= CLONE_NEWCGROUP
;
2463 opts
.extroot
= optarg
;
2466 opts
.namespace |= CLONE_NEWNS
;
2470 opts
.seccomp
= optarg
;
2471 add_mount_bind(optarg
, 1, -1);
2474 opts
.capabilities
= optarg
;
2477 opts
.no_new_privs
= 1;
2483 opts
.namespace |= CLONE_NEWNET
;
2486 opts
.namespace |= CLONE_NEWUTS
;
2487 opts
.hostname
= strdup(optarg
);
2490 opts
.namespace |= CLONE_NEWNS
;
2491 add_path_and_deps(optarg
, 1, 0, 0);
2494 opts
.namespace |= CLONE_NEWNS
;
2495 add_path_and_deps(optarg
, 0, 0, 0);
2498 opts
.namespace |= CLONE_NEWNS
;
2499 add_mount_bind(ubus
, 0, -1);
2502 opts
.namespace |= CLONE_NEWNS
;
2503 add_mount_bind(log
, 0, -1);
2509 opts
.group
= optarg
;
2512 opts
.overlaydir
= optarg
;
2515 opts
.tmpoverlaysize
= optarg
;
2518 opts
.require_jail
= 1;
2524 opts
.ocibundle
= optarg
;
2527 opts
.immediately
= true;
2530 opts
.pidfile
= optarg
;
2535 if (opts
.namespace && !opts
.ocibundle
)
2536 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2538 /* those are filehandlers, so -1 indicates unused */
2539 opts
.setns
.pid
= -1;
2540 opts
.setns
.net
= -1;
2542 opts
.setns
.ipc
= -1;
2543 opts
.setns
.uts
= -1;
2544 opts
.setns
.user
= -1;
2545 opts
.setns
.cgroup
= -1;
2546 #ifdef CLONE_NEWTIME
2547 opts
.setns
.time
= -1;
2550 if (opts
.capabilities
&& parseOCIcapabilities_from_file(&opts
.capset
, opts
.capabilities
)) {
2551 ERROR("failed to read capabilities from file %s\n", opts
.capabilities
);
2556 if (opts
.ocibundle
) {
2561 ERROR("OCI bundle needs a named jail\n");
2565 asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
);
2566 ocires
= parseOCI(jsonfile
);
2569 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2575 if (opts
.namespace & CLONE_NEWNET
) {
2577 ERROR("netns needs a named jail\n");
2584 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2585 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2590 /* no <binary> param found */
2591 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2596 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
2597 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2602 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2605 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2610 parent_ctx
= ubus_connect(NULL
);
2611 ubus_add_uloop(parent_ctx
);
2613 if (opts
.ocibundle
) {
2615 if (asprintf(&objname
, "container.%s", opts
.name
) < 0) {
2620 container_object
.name
= objname
;
2621 ret
= ubus_add_object(parent_ctx
, &container_object
);
2623 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2629 /* deliberately not using 'else' on unrelated conditional branches */
2630 if (!opts
.ocibundle
) {
2631 /* allocate NULL-terminated array for argv */
2632 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(char**));
2633 if (!opts
.jail_argv
) {
2637 for (size_t s
= optind
; s
< argc
; s
++)
2638 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2640 if (opts
.namespace & CLONE_NEWUSER
)
2641 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2644 if (!opts
.extroot
) {
2645 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2646 ERROR("failed to load dependencies\n");
2652 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2653 ERROR("failed to load libpreload-seccomp.so\n");
2655 if (opts
.require_jail
) {
2661 uloop_timeout_add(&post_main_timeout
);
2673 static void post_main(struct uloop_timeout
*t
)
2675 if (apply_rlimits()) {
2676 ERROR("error applying resource limits\n");
2677 free_and_exit(EXIT_FAILURE
);
2681 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2683 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2686 if (has_namespaces()) {
2687 if (opts
.namespace & CLONE_NEWNS
) {
2688 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2689 add_mount_bind("/etc/passwd", 1, -1);
2690 add_mount_bind("/etc/group", 1, -1);
2693 #if defined(__GLIBC__)
2695 add_mount_bind("/etc/nsswitch.conf", 1, -1);
2698 if (!(opts
.namespace & CLONE_NEWNET
)) {
2699 add_mount_bind("/etc/resolv.conf", 1, -1);
2700 } else if (opts
.setns
.net
== -1) {
2701 char hostdir
[PATH_MAX
];
2703 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2704 mkdir_p(hostdir
, 0755);
2705 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, 0, NULL
, -1);
2708 /* default mounts */
2709 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "size=1M", -1);
2710 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, 0, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2712 if (opts
.procfs
|| opts
.ocibundle
) {
2713 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0, NULL
, -1);
2716 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2717 * which cannot be expressed with OCI spec, but happends to be very useful.
2718 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2720 * If not running in a new network namespace, only make /proc/sys read-only.
2721 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2722 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2723 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2725 * This works because mounts are executed in incrementing strcmp() order and
2726 * /proc/self/net appears there before /proc/sys/net and hence the operation
2727 * succeeds as the bind-mount of /proc/self/net is performed first and then
2728 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2729 * table (and in the alphabet).
2731 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, 0, NULL
, -1))
2732 if (opts
.namespace & CLONE_NEWNET
)
2733 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0, NULL
, -1))
2734 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0, NULL
, -1);
2737 if (opts
.sysfs
|| opts
.ocibundle
)
2738 add_mount("sysfs", "/sys", "sysfs", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0, NULL
, -1);
2741 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, 0, "mode=1777", -1);
2745 if (opts
.setns
.pid
!= -1) {
2746 pidns_fd
= ns_open_pid("pid", getpid());
2747 setns_open(CLONE_NEWPID
);
2752 #ifdef CLONE_NEWTIME
2753 if (opts
.setns
.time
!= -1) {
2754 timens_fd
= ns_open_pid("time", getpid());
2755 setns_open(CLONE_NEWTIME
);
2759 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| (opts
.namespace & (~CLONE_NEWCGROUP
)), NULL
);
2761 jail_process
.pid
= fork();
2764 if (jail_process
.pid
> 0) {
2765 /* parent process */
2768 uloop_process_add(&jail_process
);
2771 if (pidns_fd
!= -1) {
2772 setns(pidns_fd
, CLONE_NEWPID
);
2775 #ifdef CLONE_NEWTIME
2776 if (timens_fd
!= -1)
2777 setns(timens_fd
, CLONE_NEWTIME
);
2781 if (opts
.setns
.net
!= -1)
2782 close(opts
.setns
.net
);
2783 if (opts
.setns
.ns
!= -1)
2784 close(opts
.setns
.ns
);
2785 if (opts
.setns
.ipc
!= -1)
2786 close(opts
.setns
.ipc
);
2787 if (opts
.setns
.uts
!= -1)
2788 close(opts
.setns
.uts
);
2789 if (opts
.setns
.user
!= -1)
2790 close(opts
.setns
.user
);
2791 if (opts
.setns
.cgroup
!= -1)
2792 close(opts
.setns
.cgroup
);
2795 if (read(pipes
[0], sig_buf
, 1) < 1) {
2796 ERROR("can't read from child\n");
2800 set_oom_score_adj();
2803 cgroups_apply(jail_process
.pid
);
2805 if (opts
.namespace & CLONE_NEWUSER
) {
2806 if (write_setgroups(jail_process
.pid
, true)) {
2807 ERROR("can't write setgroups\n");
2811 bool has_gr
= (opts
.gr_gid
!= -1);
2812 if (opts
.pw_uid
!= -1) {
2813 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2814 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2816 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2817 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2820 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2822 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2826 if (opts
.namespace & CLONE_NEWNET
) {
2827 netns_fd
= ns_open_pid("net", jail_process
.pid
);
2828 netns_updown(jail_process
.pid
, true);
2831 if (jail_writepid(jail_process
.pid
)) {
2832 ERROR("failed to write pidfile: %m\n");
2835 } else if (jail_process
.pid
== 0) {
2836 /* fork child process */
2837 free_and_exit(exec_jail(NULL
));
2839 ERROR("failed to clone/fork: %m\n");
2840 free_and_exit(EXIT_FAILURE
);
2842 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
2845 static void post_poststart(void);
2846 static void post_create_runtime(void)
2851 if (write(pipes
[3], sig_buf
, 1) < 0) {
2852 ERROR("can't write to child\n");
2856 jail_oci_state
= OCI_STATE_CREATED
;
2857 if (opts
.ocibundle
&& !opts
.immediately
)
2858 uloop_run(); /* wait for 'start' command via ubus */
2860 pipe_send_start_container(NULL
);
2863 static void pipe_send_start_container(struct uloop_timeout
*t
)
2867 jail_oci_state
= OCI_STATE_RUNNING
;
2869 if (write(pipes
[3], sig_buf
, 1) < 0) {
2870 ERROR("can't write to child\n");
2875 run_hooks(opts
.hooks
.poststart
, post_poststart
);
2878 static void post_poststart(void)
2880 uloop_run(); /* idle here while jail is running */
2882 DEBUG("uloop interrupted, killing jail process\n");
2883 kill(jail_process
.pid
, SIGTERM
);
2884 uloop_timeout_set(&jail_process_timeout
, 1000);
2891 static void post_poststop(void);
2892 static void poststop(void) {
2893 if (opts
.namespace & CLONE_NEWNET
) {
2894 setns(netns_fd
, CLONE_NEWNET
);
2895 netns_updown(getpid(), false);
2898 run_hooks(opts
.hooks
.poststop
, post_poststop
);
2901 static void post_poststop(void)
2905 ubus_free(parent_ctx
);
2907 exit(jail_return_code
);