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
42 #include <linux/filter.h>
43 #include <linux/limits.h>
44 #include <linux/nsfs.h>
48 #include "capabilities.h"
53 #include "seccomp-oci.h"
55 #include <libubox/utils.h>
56 #include <libubox/blobmsg.h>
57 #include <libubox/blobmsg_json.h>
58 #include <libubox/list.h>
59 #include <libubox/vlist.h>
60 #include <libubox/uloop.h>
63 #ifndef CLONE_NEWCGROUP
64 #define CLONE_NEWCGROUP 0x02000000
67 #define STACK_SIZE (1024 * 1024)
68 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:i"
70 #define OCI_VERSION_STRING "1.0.2"
98 struct sock_fprog
*ociseccomp
;
100 struct jail_capset capset
;
105 char *tmpoverlaysize
;
109 struct sysctl_val
**sysctl
;
131 gid_t
*additional_gids
;
132 size_t num_additional_gids
;
137 struct hook_execvpe
**createRuntime
;
138 struct hook_execvpe
**createContainer
;
139 struct hook_execvpe
**startContainer
;
140 struct hook_execvpe
**poststart
;
141 struct hook_execvpe
**poststop
;
143 struct rlimit
*rlimits
[RLIM_NLIMITS
];
145 bool set_oom_score_adj
;
146 struct mknod_args
**devices
;
149 struct blob_attr
*annotations
;
152 static struct blob_buf ocibuf
;
154 extern int pivot_root(const char *new_root
, const char *put_old
);
158 static char child_stack
[STACK_SIZE
];
160 static struct ubus_context
*parent_ctx
;
165 static inline bool has_namespaces(void)
167 return ((opts
.setns
.pid
!= -1) ||
168 (opts
.setns
.net
!= -1) ||
169 (opts
.setns
.ns
!= -1) ||
170 (opts
.setns
.ipc
!= -1) ||
171 (opts
.setns
.uts
!= -1) ||
172 (opts
.setns
.user
!= -1) ||
173 (opts
.setns
.cgroup
!= -1) ||
175 (opts
.setns
.time
!= -1) ||
180 static void free_hooklist(struct hook_execvpe
**hooklist
)
182 struct hook_execvpe
*cur
;
207 static void free_sysctl(void) {
208 struct sysctl_val
*cur
;
219 static void free_devices(void) {
220 struct mknod_args
**cur
;
234 static void free_rlimits(void) {
237 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
238 free(opts
.rlimits
[type
]);
241 static void free_opts(bool child
) {
244 /* we need to keep argv, envp and seccomp filter in child */
246 if (opts
.ociseccomp
) {
247 free(opts
.ociseccomp
->filter
);
248 free(opts
.ociseccomp
);
251 tmp
= opts
.jail_argv
;
255 free(opts
.jail_argv
);
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
);
279 static int mount_overlay(char *jail_root
, char *overlaydir
) {
280 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
281 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
284 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
287 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
290 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
293 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
297 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
298 * this is to work-around a bug in overlayfs described in the overlayfs-userns
300 * 3. modification of a file 'hithere' which is in l but not yet
301 * in u, and which is not owned by T, is not allowed, even if
302 * writes to u are allowed. This may be a bug in overlayfs,
303 * but it is safe behavior.
305 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
308 if (mkdir_p(upperetc
, 0755))
309 goto upper_etc_printf
;
311 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
312 goto upper_etc_printf
;
314 fd
= creat(upperresolvconf
, 0644);
316 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
317 goto upper_resolvconf_printf
;
321 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
323 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
328 upper_resolvconf_printf
:
329 free(upperresolvconf
);
342 static void pass_console(int console_fd
)
344 struct ubus_context
*child_ctx
= ubus_connect(NULL
);
345 static struct blob_buf req
;
351 blob_buf_init(&req
, 0);
352 blobmsg_add_string(&req
, "name", opts
.name
);
354 if (ubus_lookup_id(child_ctx
, "container", &id
) ||
355 ubus_invoke_fd(child_ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
356 INFO("ubus request failed\n");
361 ubus_free(child_ctx
);
364 static int create_dev_console(const char *jail_root
)
367 char dev_console_path
[PATH_MAX
];
368 int slave_console_fd
;
370 /* Open UNIX/98 virtual console */
371 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
372 if (console_fd
== -1)
375 console_fname
= ptsname(console_fd
);
376 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
381 unlockpt(console_fd
);
383 /* pass PTY master to procd */
384 pass_console(console_fd
);
386 /* mount-bind PTY slave to /dev/console in jail */
387 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
388 close(creat(dev_console_path
, 0620));
390 if (mount(console_fname
, dev_console_path
, NULL
, MS_BIND
, NULL
))
393 /* use PTY slave for stdio */
394 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
395 dup2(slave_console_fd
, 0);
396 dup2(slave_console_fd
, 1);
397 dup2(slave_console_fd
, 2);
398 close(slave_console_fd
);
400 INFO("using guest console %s\n", console_fname
);
409 static int hook_running
= 0;
410 static int hook_return_code
= 0;
411 static struct hook_execvpe
**current_hook
= NULL
;
412 typedef void (*hook_return_handler
)(void);
413 static hook_return_handler hook_return_cb
= NULL
;
415 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
416 static struct uloop_timeout hook_process_timeout
= {
417 .cb
= hook_process_timeout_cb
,
420 static void run_hooklist(void);
421 static void hook_process_handler(struct uloop_process
*c
, int ret
)
423 uloop_timeout_cancel(&hook_process_timeout
);
425 if (WIFEXITED(ret
)) {
426 hook_return_code
= WEXITSTATUS(ret
);
427 if (hook_return_code
)
428 ERROR("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
430 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
433 hook_return_code
= WTERMSIG(ret
);
434 ERROR("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
441 static struct uloop_process hook_process
= {
442 .cb
= hook_process_handler
,
445 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
447 DEBUG("hook process failed to stop, sending SIGKILL\n");
448 kill(hook_process
.pid
, SIGKILL
);
451 static void run_hooklist(void)
453 struct hook_execvpe
*hook
= *current_hook
;
459 DEBUG("executing hook %s\n", hook
->file
);
461 if (stat(hook
->file
, &s
))
462 hook_process_handler(&hook_process
, ENOENT
);
464 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
465 hook_process_handler(&hook_process
, EPERM
);
467 if (!((unsigned long)s
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
)))
468 hook_process_handler(&hook_process
, EPERM
);
471 hook_process
.pid
= fork();
472 if (hook_process
.pid
== 0) {
474 execve(hook
->file
, hook
->argv
, hook
->envp
);
475 ERROR("execve error %m\n");
477 } else if (hook_process
.pid
< 0) {
479 ERROR("hook fork error\n");
481 hook_process_handler(&hook_process
, errno
);
485 uloop_process_add(&hook_process
);
487 if (hook
->timeout
> 0)
488 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
492 DEBUG("uloop interrupted, killing jail process\n");
493 kill(hook_process
.pid
, SIGTERM
);
494 uloop_timeout_set(&hook_process_timeout
, 1000);
499 static void run_hooks(struct hook_execvpe
**hooklist
, hook_return_handler return_cb
)
504 current_hook
= hooklist
;
505 hook_return_cb
= return_cb
;
510 static int apply_sysctl(const char *jail_root
)
512 struct sysctl_val
**cur
;
513 char *procdir
, *fname
;
519 asprintf(&procdir
, "%s/proc", jail_root
);
523 mkdir(procdir
, 0700);
524 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
530 asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
);
534 DEBUG("sysctl: writing '%s' to %s\n", (*cur
)->value
, fname
);
536 f
= open(fname
, O_WRONLY
);
538 ERROR("sysctl: can't open %s\n", fname
);
541 write(f
, (*cur
)->value
, strlen((*cur
)->value
));
554 /* glibc defines makedev calling a function. make sure it's a pure macro */
555 #if defined(__GLIBC__)
557 /* from musl's sys/sysmacros.h */
558 #define makedev(x,y) ( \
559 (((x)&0xfffff000ULL) << 32) | \
560 (((x)&0x00000fffULL) << 8) | \
561 (((y)&0xffffff00ULL) << 12) | \
562 (((y)&0x000000ffULL)) )
565 static struct mknod_args default_devices
[] = {
566 { .path
= "/dev/null", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 3) },
567 { .path
= "/dev/zero", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 5) },
568 { .path
= "/dev/full", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 7) },
569 { .path
= "/dev/random", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 8) },
570 { .path
= "/dev/urandom", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
|S_IROTH
|S_IWOTH
), .dev
= makedev(1, 9) },
571 { .path
= "/dev/tty", .mode
= (S_IFCHR
|S_IRUSR
|S_IWUSR
|S_IRGRP
|S_IWGRP
), .dev
= makedev(5, 0), .gid
= 5 },
575 static int create_devices(void)
577 struct mknod_args
**cur
, *curdef
;
580 goto only_default_devices
;
585 DEBUG("creating %s (mode=%08o)\n", (*cur
)->path
, (*cur
)->mode
);
586 if (mknod((*cur
)->path
, (*cur
)->mode
, (*cur
)->dev
))
589 if (((*cur
)->uid
|| (*cur
)->gid
) &&
590 chown((*cur
)->path
, (*cur
)->uid
, (*cur
)->gid
))
596 only_default_devices
:
597 curdef
= default_devices
;
598 while(curdef
->path
) {
599 DEBUG("creating %s (mode=%08o)\n", curdef
->path
, curdef
->mode
);
600 if (mknod(curdef
->path
, curdef
->mode
, curdef
->dev
)) {
602 continue; /* may already exist, eg. due to a bind-mount */
604 if ((curdef
->uid
|| curdef
->gid
) &&
605 chown(curdef
->path
, curdef
->uid
, curdef
->gid
))
611 /* Dev symbolic links as defined in OCI spec */
612 symlink("/dev/pts/ptmx", "/dev/ptmx");
613 symlink("/proc/self/fd", "/dev/fd");
614 symlink("/proc/self/fd/0", "/dev/stdin");
615 symlink("/proc/self/fd/1", "/dev/stdout");
616 symlink("/proc/self/fd/2", "/dev/stderr");
621 static char jail_root
[] = "/tmp/ujail-XXXXXX";
622 static char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
623 static mode_t old_umask
;
624 static void enter_jail_fs(void);
625 static int build_jail_fs(void)
627 char *overlaydir
= NULL
;
629 old_umask
= umask(0);
631 if (mkdtemp(jail_root
) == NULL
) {
632 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
636 if (apply_sysctl(jail_root
)) {
637 ERROR("failed to apply sysctl values\n");
641 /* oldroot can't be MS_SHARED else pivot_root() fails */
642 if (mount("none", "/", NULL
, MS_REC
|MS_PRIVATE
, NULL
)) {
643 ERROR("private mount failed %m\n");
648 if (mount(opts
.extroot
, jail_root
, NULL
, MS_BIND
, NULL
)) {
649 ERROR("extroot mount failed %m\n");
653 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
654 ERROR("tmpfs mount failed %m\n");
659 if (opts
.tmpoverlaysize
) {
660 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
662 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
663 "mode=0755,size=%s", opts
.tmpoverlaysize
);
664 if (mkdtemp(tmpovdir
) == NULL
) {
665 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
668 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
670 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
673 overlaydir
= tmpovdir
;
677 overlaydir
= opts
.overlaydir
;
680 mount_overlay(jail_root
, overlaydir
);
682 if (chdir(jail_root
)) {
683 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
687 if (mount_all(jail_root
)) {
688 ERROR("mount_all() failed\n");
693 create_dev_console(jail_root
);
695 /* make sure /etc/resolv.conf exists if in new network namespace */
696 if (opts
.namespace & CLONE_NEWNET
) {
697 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
699 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
700 mkdir_p(jailetc
, 0755);
701 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
705 symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink
);
708 run_hooks(opts
.hooks
.createContainer
, enter_jail_fs
);
713 static void post_jail_fs(void);
714 static void enter_jail_fs(void)
716 char dirbuf
[sizeof(jail_root
) + 4];
718 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
721 if (pivot_root(jail_root
, dirbuf
) == -1) {
722 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
726 ERROR("chdir(/) (after pivot_root) failed: %m\n");
730 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
731 umount2(dirbuf
, MNT_DETACH
);
733 if (opts
.tmpoverlaysize
) {
734 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
735 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
736 umount2(tmpdirbuf
, MNT_DETACH
);
740 umount2("/old", MNT_DETACH
);
743 if (create_devices()) {
744 ERROR("create_devices() failed\n");
748 mount(NULL
, "/", NULL
, MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
754 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
759 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
760 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
763 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
766 if (dprintf(map_file
, "%s", mapstr
)) {
776 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
780 const char *map_format
= "%d %d %d\n";
781 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
782 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
785 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
788 if (dprintf(map_file
, map_format
, 0, id
, 1) == -1) {
797 static int write_setgroups(pid_t child_pid
, bool allow
)
800 char setgroups_path
[64];
802 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
807 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) == -1) {
811 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
812 close(setgroups_file
);
816 close(setgroups_file
);
820 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
822 struct passwd
*p
= NULL
;
823 struct group
*g
= NULL
;
826 p
= getpwnam(opts
.user
);
828 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
829 opts
.user
, errno
, strerror(errno
));
833 *user_gid
= p
->pw_gid
;
840 g
= getgrnam(opts
.group
);
842 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
851 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
853 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
854 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
858 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
859 ERROR("failed to set group id %d: %m\n", gr_gid
);
863 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
864 ERROR("failed to set user id %d: %m\n", pw_uid
);
869 static int apply_rlimits(void)
873 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
874 if (opts
.rlimits
[resource
])
875 DEBUG("applying limits to resource %u\n", resource
);
877 if (opts
.rlimits
[resource
] &&
878 setrlimit(resource
, opts
.rlimits
[resource
]))
886 static char** build_envp(const char *seccomp
, char **ocienvp
)
888 static char *envp
[MAX_ENVP
];
889 static char preload_var
[PATH_MAX
];
890 static char seccomp_var
[PATH_MAX
];
891 static char debug_var
[] = "LD_DEBUG=all";
892 static char container_var
[] = "container=ujail";
893 const char *preload_lib
= find_lib("libpreload-seccomp.so");
898 if (seccomp
&& !preload_lib
) {
899 ERROR("failed to add preload-lib to env\n");
903 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
904 envp
[count
++] = seccomp_var
;
905 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
906 envp
[count
++] = preload_var
;
909 envp
[count
++] = container_var
;
912 envp
[count
++] = debug_var
;
915 while (addenv
&& *addenv
) {
916 envp
[count
++] = *(addenv
++);
917 if (count
>= MAX_ENVP
) {
918 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
925 static void usage(void)
927 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
928 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
929 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
930 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
931 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
932 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
933 fprintf(stderr
, "namespace jail options:\n");
934 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
935 fprintf(stderr
, " -N\t\tjail has network namespace\n");
936 fprintf(stderr
, " -f\t\tjail has user namespace\n");
937 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
938 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
939 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
940 fprintf(stderr
, " -p\t\tjail has /proc\n");
941 fprintf(stderr
, " -s\t\tjail has /sys\n");
942 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
943 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
944 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
945 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
946 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
947 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
948 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
949 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
950 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
951 fprintf(stderr
, " -y\t\tprovide jail console\n");
952 fprintf(stderr
, " -J <dir>\tcreate container from OCI bundle\n");
953 fprintf(stderr
, " -j\t\tstart container immediately\n");
954 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
955 and he has the same powers as root outside the jail,\n\
956 thus he can escape the jail and/or break stuff.\n\
957 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
958 If you use none of the namespace jail options,\n\
959 ujail will not use namespace/build a jail,\n\
960 and will only drop capabilities/apply seccomp filter.\n\n");
963 static int* get_namespace_fd(const unsigned int nstype
)
967 return &opts
.setns
.pid
;
969 return &opts
.setns
.net
;
971 return &opts
.setns
.ns
;
973 return &opts
.setns
.ipc
;
975 return &opts
.setns
.uts
;
977 return &opts
.setns
.user
;
978 case CLONE_NEWCGROUP
:
979 return &opts
.setns
.cgroup
;
982 return &opts
.setns
.time
;
989 static int setns_open(unsigned long nstype
)
991 int *fd
= get_namespace_fd(nstype
);
999 if (setns(*fd
, nstype
) == -1) {
1008 static int jail_running
= 0;
1009 static int jail_return_code
= 0;
1011 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
1012 static struct uloop_timeout jail_process_timeout
= {
1013 .cb
= jail_process_timeout_cb
,
1015 static void poststop(void);
1016 static void jail_process_handler(struct uloop_process
*c
, int ret
)
1018 uloop_timeout_cancel(&jail_process_timeout
);
1019 if (WIFEXITED(ret
)) {
1020 jail_return_code
= WEXITSTATUS(ret
);
1021 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
1023 jail_return_code
= WTERMSIG(ret
);
1024 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
1030 static struct uloop_process jail_process
= {
1031 .cb
= jail_process_handler
,
1034 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
1036 DEBUG("jail process failed to stop, sending SIGKILL\n");
1037 kill(jail_process
.pid
, SIGKILL
);
1040 static void jail_handle_signal(int signo
)
1043 DEBUG("forwarding signal %d to the hook process\n", signo
);
1044 kill(hook_process
.pid
, signo
);
1048 DEBUG("forwarding signal %d to the jailed process\n", signo
);
1049 kill(jail_process
.pid
, signo
);
1053 static void signals_init(void)
1058 sigfillset(&sigmask
);
1059 for (i
= 0; i
< _NSIG
; i
++) {
1060 struct sigaction s
= { 0 };
1062 if (!sigismember(&sigmask
, i
))
1064 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
1067 s
.sa_handler
= jail_handle_signal
;
1068 sigaction(i
, &s
, NULL
);
1072 static void pre_exec_jail(struct uloop_timeout
*t
);
1073 static struct uloop_timeout pre_exec_timeout
= {
1074 .cb
= pre_exec_jail
,
1078 static int exec_jail(void *arg
)
1088 setns_open(CLONE_NEWUSER
);
1089 setns_open(CLONE_NEWNET
);
1090 setns_open(CLONE_NEWNS
);
1091 setns_open(CLONE_NEWIPC
);
1092 setns_open(CLONE_NEWUTS
);
1095 if (write(pipes
[1], buf
, 1) < 1) {
1096 ERROR("can't write to parent\n");
1097 return EXIT_FAILURE
;
1100 if (read(pipes
[2], buf
, 1) < 1) {
1101 ERROR("can't read from parent\n");
1102 return EXIT_FAILURE
;
1104 if (buf
[0] != 'O') {
1105 ERROR("parent had an error, child exiting\n");
1106 return EXIT_FAILURE
;
1108 if ((opts
.namespace & CLONE_NEWUSER
) || (opts
.setns
.user
!= -1)) {
1109 if (setregid(0, 0) < 0) {
1113 if (setreuid(0, 0) < 0) {
1117 if (setgroups(0, NULL
) < 0) {
1118 ERROR("setgroups\n");
1123 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
1124 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
1125 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
1129 uloop_timeout_add(&pre_exec_timeout
);
1135 static void pre_exec_jail(struct uloop_timeout
*t
)
1137 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
1138 ERROR("failed to build jail fs\n");
1141 run_hooks(opts
.hooks
.createContainer
, post_jail_fs
);
1145 static void post_start_hook(void);
1146 static void post_jail_fs(void)
1150 if (read(pipes
[2], buf
, 1) < 1) {
1151 ERROR("can't read from parent\n");
1154 if (buf
[0] != '!') {
1155 ERROR("parent had an error, child exiting\n");
1160 run_hooks(opts
.hooks
.startContainer
, post_start_hook
);
1163 static void post_start_hook(void)
1165 if (!(opts
.namespace & CLONE_NEWUSER
) && (opts
.setns
.user
== -1)) {
1166 int pw_uid
, pw_gid
, gr_gid
;
1167 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
1169 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
1172 if (opts
.additional_gids
&&
1173 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
1174 ERROR("setgroups failed: %m\n");
1181 if (applyOCIcapabilities(opts
.capset
))
1184 if (opts
.capabilities
&& drop_capabilities(opts
.capabilities
))
1187 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
1188 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
1192 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
1196 if (opts
.cwd
&& chdir(opts
.cwd
))
1199 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
1204 INFO("exec-ing %s\n", *opts
.jail_argv
);
1205 if (opts
.envp
) /* respect PATH if potentially set in ENV */
1206 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1208 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
1210 /* we get there only if execve fails */
1211 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
1215 static int ns_open_pid(const char *nstype
, const pid_t target_ns
)
1217 char pid_pid_path
[PATH_MAX
];
1219 snprintf(pid_pid_path
, sizeof(pid_pid_path
), "/proc/%u/ns/%s", target_ns
, nstype
);
1221 return open(pid_pid_path
, O_RDONLY
);
1224 static void netns_updown(pid_t pid
, bool start
)
1226 static struct blob_buf req
;
1232 blob_buf_init(&req
, 0);
1233 blobmsg_add_string(&req
, "jail", opts
.name
);
1234 blobmsg_add_u32(&req
, "pid", pid
);
1235 blobmsg_add_u8(&req
, "start", start
);
1237 if (ubus_lookup_id(parent_ctx
, "network", &id
) ||
1238 ubus_invoke(parent_ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1239 INFO("ubus request failed\n");
1241 blob_buf_free(&req
);
1244 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1246 struct blob_attr
*cur
;
1249 blobmsg_for_each_attr(cur
, msg
, rem
)
1253 *envp
= calloc(1 + sz
, sizeof(char*));
1262 blobmsg_for_each_attr(cur
, msg
, rem
)
1263 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1277 static const struct blobmsg_policy oci_root_policy
[] = {
1278 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1279 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1282 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1284 static char rootpath
[PATH_MAX
] = { 0 };
1285 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1288 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1290 if (!tb
[OCI_ROOT_PATH
])
1293 strncpy(rootpath
, jsonfile
, PATH_MAX
);
1294 cur
= strrchr(rootpath
, '/');
1300 strncat(rootpath
, blobmsg_get_string(tb
[OCI_ROOT_PATH
]), PATH_MAX
- (strlen(rootpath
) + 1));
1302 opts
.extroot
= rootpath
;
1304 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1318 static const struct blobmsg_policy oci_hook_policy
[] = {
1319 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1320 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1321 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1322 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1326 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1328 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1329 struct blob_attr
*cur
;
1333 blobmsg_for_each_attr(cur
, msg
, rem
)
1339 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1345 blobmsg_for_each_attr(cur
, msg
, rem
) {
1346 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1348 if (!tb
[OCI_HOOK_PATH
]) {
1353 (*hooklist
)[idx
] = calloc(1, sizeof(struct hook_execvpe
));
1354 if (tb
[OCI_HOOK_ARGS
]) {
1355 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1359 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1360 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1361 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1365 if (tb
[OCI_HOOK_ENV
]) {
1366 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1371 if (tb
[OCI_HOOK_TIMEOUT
])
1372 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1374 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1379 (*hooklist
)[idx
] = NULL
;
1381 DEBUG("added %d hooks\n", idx
);
1386 free_hooklist(*hooklist
);
1395 OCI_HOOKS_CREATERUNTIME
,
1396 OCI_HOOKS_CREATECONTAINER
,
1397 OCI_HOOKS_STARTCONTAINER
,
1398 OCI_HOOKS_POSTSTART
,
1403 static const struct blobmsg_policy oci_hooks_policy
[] = {
1404 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1405 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1406 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1407 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1408 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1409 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1412 static int parseOCIhooks(struct blob_attr
*msg
)
1414 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1417 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1419 if (tb
[OCI_HOOKS_PRESTART
])
1420 INFO("warning: ignoring deprecated prestart hook\n");
1422 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1423 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1428 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1429 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1431 goto out_createruntime
;
1434 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1435 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1437 goto out_createcontainer
;
1440 if (tb
[OCI_HOOKS_POSTSTART
]) {
1441 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1443 goto out_startcontainer
;
1446 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1447 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1455 free_hooklist(opts
.hooks
.poststart
);
1457 free_hooklist(opts
.hooks
.startContainer
);
1458 out_createcontainer
:
1459 free_hooklist(opts
.hooks
.createContainer
);
1461 free_hooklist(opts
.hooks
.createRuntime
);
1468 OCI_PROCESS_USER_UID
,
1469 OCI_PROCESS_USER_GID
,
1470 OCI_PROCESS_USER_UMASK
,
1471 OCI_PROCESS_USER_ADDITIONALGIDS
,
1472 __OCI_PROCESS_USER_MAX
,
1475 static const struct blobmsg_policy oci_process_user_policy
[] = {
1476 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1477 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1478 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1479 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1482 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1483 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1484 struct blob_attr
*cur
;
1488 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1490 if (tb
[OCI_PROCESS_USER_UID
])
1491 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1493 if (tb
[OCI_PROCESS_USER_GID
]) {
1494 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1495 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1499 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1502 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1504 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1509 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1512 /* always add primary GID to set of GIDs if set */
1514 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1516 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1517 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1519 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1521 opts
.num_additional_gids
= gidcnt
;
1523 DEBUG("read %zu additional groups\n", gidcnt
);
1526 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1527 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1528 opts
.set_umask
= true;
1535 OCI_PROCESS_RLIMIT_TYPE
,
1536 OCI_PROCESS_RLIMIT_SOFT
,
1537 OCI_PROCESS_RLIMIT_HARD
,
1538 __OCI_PROCESS_RLIMIT_MAX
,
1541 static const struct blobmsg_policy oci_process_rlimit_policy
[] = {
1542 [OCI_PROCESS_RLIMIT_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1543 [OCI_PROCESS_RLIMIT_SOFT
] = { "soft", BLOBMSG_CAST_INT64
},
1544 [OCI_PROCESS_RLIMIT_HARD
] = { "hard", BLOBMSG_CAST_INT64
},
1547 /* from manpage GETRLIMIT(2) */
1548 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1550 [RLIMIT_CORE
] = "CORE",
1551 [RLIMIT_CPU
] = "CPU",
1552 [RLIMIT_DATA
] = "DATA",
1553 [RLIMIT_FSIZE
] = "FSIZE",
1554 [RLIMIT_LOCKS
] = "LOCKS",
1555 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1556 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1557 [RLIMIT_NICE
] = "NICE",
1558 [RLIMIT_NOFILE
] = "NOFILE",
1559 [RLIMIT_NPROC
] = "NPROC",
1560 [RLIMIT_RSS
] = "RSS",
1561 [RLIMIT_RTPRIO
] = "RTPRIO",
1562 [RLIMIT_RTTIME
] = "RTTIME",
1563 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1564 [RLIMIT_STACK
] = "STACK",
1567 static int resolve_rlimit(char *type
) {
1568 unsigned int rltype
;
1570 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1571 if (rlimit_names
[rltype
] &&
1572 !strncmp("RLIMIT_", type
, 7) &&
1573 !strcmp(rlimit_names
[rltype
], type
+ 7))
1580 static int parseOCIrlimit(struct blob_attr
*msg
)
1582 struct blob_attr
*tb
[__OCI_PROCESS_RLIMIT_MAX
];
1584 struct rlimit
*curlim
;
1586 blobmsg_parse(oci_process_rlimit_policy
, __OCI_PROCESS_RLIMIT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1588 if (!tb
[OCI_PROCESS_RLIMIT_TYPE
] ||
1589 !tb
[OCI_PROCESS_RLIMIT_SOFT
] ||
1590 !tb
[OCI_PROCESS_RLIMIT_HARD
])
1593 limtype
= resolve_rlimit(blobmsg_get_string(tb
[OCI_PROCESS_RLIMIT_TYPE
]));
1598 if (opts
.rlimits
[limtype
])
1601 curlim
= malloc(sizeof(struct rlimit
));
1602 curlim
->rlim_cur
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_SOFT
]);
1603 curlim
->rlim_max
= blobmsg_cast_u64(tb
[OCI_PROCESS_RLIMIT_HARD
]);
1605 opts
.rlimits
[limtype
] = curlim
;
1612 OCI_PROCESS_CAPABILITIES
,
1615 OCI_PROCESS_OOMSCOREADJ
,
1616 OCI_PROCESS_NONEWPRIVILEGES
,
1617 OCI_PROCESS_RLIMITS
,
1618 OCI_PROCESS_TERMINAL
,
1623 static const struct blobmsg_policy oci_process_policy
[] = {
1624 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1625 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1626 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1627 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1628 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1629 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1630 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1631 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1632 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1636 static int parseOCIprocess(struct blob_attr
*msg
)
1638 struct blob_attr
*tb
[__OCI_PROCESS_MAX
], *cur
;
1641 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1643 if (!tb
[OCI_PROCESS_ARGS
])
1646 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1650 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1651 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1653 if (tb
[OCI_PROCESS_CWD
])
1654 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1656 if (tb
[OCI_PROCESS_ENV
]) {
1657 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1662 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1665 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1666 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1669 if (tb
[OCI_PROCESS_RLIMITS
]) {
1670 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_RLIMITS
], rem
) {
1671 res
= parseOCIrlimit(cur
);
1677 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1678 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1679 opts
.set_oom_score_adj
= true;
1686 OCI_LINUX_NAMESPACE_TYPE
,
1687 OCI_LINUX_NAMESPACE_PATH
,
1688 __OCI_LINUX_NAMESPACE_MAX
,
1691 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1692 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1693 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1696 static int resolve_nstype(char *type
) {
1697 if (!strcmp("pid", type
))
1698 return CLONE_NEWPID
;
1699 else if (!strcmp("network", type
))
1700 return CLONE_NEWNET
;
1701 else if (!strcmp("mount", type
))
1703 else if (!strcmp("ipc", type
))
1704 return CLONE_NEWIPC
;
1705 else if (!strcmp("uts", type
))
1706 return CLONE_NEWUTS
;
1707 else if (!strcmp("user", type
))
1708 return CLONE_NEWUSER
;
1709 else if (!strcmp("cgroup", type
))
1710 return CLONE_NEWCGROUP
;
1711 #ifdef CLONE_NEWTIME
1712 else if (!strcmp("time", type
))
1713 return CLONE_NEWTIME
;
1719 static int parseOCIlinuxns(struct blob_attr
*msg
)
1721 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1726 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1728 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1731 nstype
= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1735 if (opts
.namespace & nstype
)
1738 setns
= get_namespace_fd(nstype
);
1746 if (tb
[OCI_LINUX_NAMESPACE_PATH
]) {
1747 DEBUG("opening existing %s namespace from path %s\n",
1748 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1749 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]));
1751 fd
= open(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_PATH
]), O_RDONLY
);
1753 return errno
?:ESTALE
;
1755 if (ioctl(fd
, NS_GET_NSTYPE
) != nstype
)
1758 DEBUG("opened existing %s namespace got filehandler %u\n",
1759 blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]),
1764 opts
.namespace |= nstype
;
1772 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1773 OCI_LINUX_UIDGIDMAP_HOSTID
,
1774 OCI_LINUX_UIDGIDMAP_SIZE
,
1775 __OCI_LINUX_UIDGIDMAP_MAX
,
1778 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1779 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1780 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1781 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1784 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1786 const char *map_format
= "%d %d %d\n";
1787 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1788 struct blob_attr
*cur
;
1792 unsigned int cnt
= 0;
1793 size_t totallen
= 0;
1795 /* count number of mappings */
1796 blobmsg_for_each_attr(cur
, msg
, rem
)
1802 /* allocate array for mappings */
1803 mappings
= calloc(1 + cnt
, sizeof(char*));
1807 mappings
[cnt
] = NULL
;
1810 blobmsg_for_each_attr(cur
, msg
, rem
) {
1811 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1813 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1814 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1815 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1818 /* write mapping line into allocated string */
1819 len
= asprintf(&mappings
[cnt
++], map_format
,
1820 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1821 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1822 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1830 /* allocate combined mapping string */
1831 map
= calloc(1 + totallen
, sizeof(char));
1837 /* concatenate mapping strings into combined string */
1838 curstr
= mappings
[0];
1840 strcat(map
, curstr
);
1858 OCI_DEVICES_FILEMODE
,
1864 static const struct blobmsg_policy oci_devices_policy
[] = {
1865 [OCI_DEVICES_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1866 [OCI_DEVICES_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1867 [OCI_DEVICES_MAJOR
] = { "major", BLOBMSG_TYPE_INT32
},
1868 [OCI_DEVICES_MINOR
] = { "minor", BLOBMSG_TYPE_INT32
},
1869 [OCI_DEVICES_FILEMODE
] = { "fileMode", BLOBMSG_TYPE_INT32
},
1870 [OCI_DEVICES_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1871 [OCI_DEVICES_GID
] = { "uid", BLOBMSG_TYPE_INT32
},
1874 static mode_t
resolve_devtype(char *tstr
)
1876 if (!strcmp("c", tstr
) ||
1879 else if (!strcmp("b", tstr
))
1881 else if (!strcmp("p", tstr
))
1887 static int parseOCIdevices(struct blob_attr
*msg
)
1889 struct blob_attr
*tb
[__OCI_DEVICES_MAX
];
1890 struct blob_attr
*cur
;
1893 struct mknod_args
*tmp
;
1895 blobmsg_for_each_attr(cur
, msg
, rem
)
1898 opts
.devices
= calloc(cnt
+ 1, sizeof(struct mknod_args
*));
1901 blobmsg_for_each_attr(cur
, msg
, rem
) {
1902 blobmsg_parse(oci_devices_policy
, __OCI_DEVICES_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1903 if (!tb
[OCI_DEVICES_TYPE
] ||
1904 !tb
[OCI_DEVICES_PATH
])
1907 tmp
= calloc(1, sizeof(struct mknod_args
));
1911 tmp
->mode
= resolve_devtype(blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1915 if (tmp
->mode
!= S_IFIFO
) {
1916 if (!tb
[OCI_DEVICES_MAJOR
] || !tb
[OCI_DEVICES_MINOR
])
1919 tmp
->dev
= makedev(blobmsg_get_u32(tb
[OCI_DEVICES_MAJOR
]),
1920 blobmsg_get_u32(tb
[OCI_DEVICES_MINOR
]));
1923 if (tb
[OCI_DEVICES_FILEMODE
]) {
1924 if (~(S_IRWXU
|S_IRWXG
|S_IRWXO
) & blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]))
1927 tmp
->mode
|= blobmsg_get_u32(tb
[OCI_DEVICES_FILEMODE
]);
1929 tmp
->mode
|= (S_IRUSR
|S_IWUSR
); /* 0600 */
1932 tmp
->path
= strdup(blobmsg_get_string(tb
[OCI_DEVICES_PATH
]));
1934 if (tb
[OCI_DEVICES_UID
])
1935 tmp
->uid
= blobmsg_get_u32(tb
[OCI_DEVICES_UID
]);
1939 if (tb
[OCI_DEVICES_GID
])
1940 tmp
->gid
= blobmsg_get_u32(tb
[OCI_DEVICES_GID
]);
1944 DEBUG("read device %s (%s)\n", blobmsg_get_string(tb
[OCI_DEVICES_PATH
]), blobmsg_get_string(tb
[OCI_DEVICES_TYPE
]));
1945 opts
.devices
[cnt
++] = tmp
;
1948 opts
.devices
[cnt
] = NULL
;
1954 OCI_LINUX_RESOURCES
,
1957 OCI_LINUX_NAMESPACES
,
1959 OCI_LINUX_UIDMAPPINGS
,
1960 OCI_LINUX_GIDMAPPINGS
,
1961 OCI_LINUX_MASKEDPATHS
,
1962 OCI_LINUX_READONLYPATHS
,
1963 OCI_LINUX_ROOTFSPROPAGATION
,
1967 static const struct blobmsg_policy oci_linux_policy
[] = {
1968 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
1969 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
1970 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
1971 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
1972 [OCI_LINUX_DEVICES
] = { "devices", BLOBMSG_TYPE_ARRAY
},
1973 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
1974 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
1975 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
1976 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
1977 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
1980 static int parseOCIsysctl(struct blob_attr
*msg
)
1982 struct blob_attr
*cur
;
1987 blobmsg_for_each_attr(cur
, msg
, rem
) {
1988 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
1997 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
2002 blobmsg_for_each_attr(cur
, msg
, rem
) {
2003 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
2004 if (!opts
.sysctl
[cnt
])
2007 /* replace '.' with '/' in entry name */
2008 tc
= tmp
= strdup(blobmsg_name(cur
));
2009 while ((tc
= strchr(tc
, '.')))
2012 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
2013 opts
.sysctl
[cnt
]->entry
= tmp
;
2018 opts
.sysctl
[cnt
] = NULL
;
2023 static int parseOCIlinux(struct blob_attr
*msg
)
2025 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
2026 struct blob_attr
*cur
;
2030 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
2032 if (tb
[OCI_LINUX_NAMESPACES
]) {
2033 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
2034 res
= parseOCIlinuxns(cur
);
2040 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
2041 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
2046 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
2047 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
2052 if (tb
[OCI_LINUX_READONLYPATHS
]) {
2053 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
2054 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, NULL
, 0);
2060 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
2061 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
2062 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, NULL
, 1);
2068 if (tb
[OCI_LINUX_SYSCTL
]) {
2069 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
2074 if (tb
[OCI_LINUX_SECCOMP
]) {
2075 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
2076 if (!opts
.ociseccomp
)
2080 if (tb
[OCI_LINUX_DEVICES
]) {
2081 res
= parseOCIdevices(tb
[OCI_LINUX_DEVICES
]);
2101 static const struct blobmsg_policy oci_policy
[] = {
2102 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
2103 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
2104 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
2105 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
2106 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
2107 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
2108 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
2109 [OCI_ANNOTATIONS
] = { "annotations", BLOBMSG_TYPE_TABLE
},
2112 static int parseOCI(const char *jsonfile
)
2114 struct blob_attr
*tb
[__OCI_MAX
];
2115 struct blob_attr
*cur
;
2119 blob_buf_init(&ocibuf
, 0);
2120 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
))
2123 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
2125 if (!tb
[OCI_VERSION
])
2128 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
2129 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
2133 if (tb
[OCI_HOSTNAME
])
2134 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
2136 if (!tb
[OCI_PROCESS
])
2139 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
2145 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
2148 if (!tb
[OCI_MOUNTS
])
2151 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
2152 if ((res
= parseOCImount(cur
)))
2155 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
2158 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
2161 if (tb
[OCI_ANNOTATIONS
])
2162 opts
.annotations
= blob_memdup(tb
[OCI_ANNOTATIONS
]);
2164 blob_buf_free(&ocibuf
);
2169 static int set_oom_score_adj(void)
2174 if (!opts
.set_oom_score_adj
)
2177 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
2178 f
= open(fname
, O_WRONLY
| O_TRUNC
);
2182 dprintf(f
, "%d", opts
.oom_score_adj
);
2196 static int jail_oci_state
= OCI_STATE_CREATED
;
2197 static void pipe_send_start_container(struct uloop_timeout
*t
);
2198 static struct uloop_timeout start_container_timeout
= {
2199 .cb
= pipe_send_start_container
,
2202 static int handle_start(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2203 struct ubus_request_data
*req
, const char *method
,
2204 struct blob_attr
*msg
)
2206 if (jail_oci_state
!= OCI_STATE_CREATED
)
2207 return UBUS_STATUS_INVALID_ARGUMENT
;
2209 uloop_timeout_add(&start_container_timeout
);
2211 return UBUS_STATUS_OK
;
2214 static struct blob_buf bb
;
2215 static int handle_state(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2216 struct ubus_request_data
*req
, const char *method
,
2217 struct blob_attr
*msg
)
2221 switch (jail_oci_state
) {
2222 case OCI_STATE_CREATING
:
2223 statusstr
= "creating";
2225 case OCI_STATE_CREATED
:
2226 statusstr
= "created";
2228 case OCI_STATE_RUNNING
:
2229 statusstr
= "running";
2231 case OCI_STATE_STOPPED
:
2232 statusstr
= "stopped";
2235 statusstr
= "unknown";
2238 blob_buf_init(&bb
, 0);
2239 blobmsg_add_string(&bb
, "ociVersion", OCI_VERSION_STRING
);
2240 blobmsg_add_string(&bb
, "id", opts
.name
);
2241 blobmsg_add_string(&bb
, "status", statusstr
);
2242 if (jail_oci_state
== OCI_STATE_CREATED
||
2243 jail_oci_state
== OCI_STATE_RUNNING
)
2244 blobmsg_add_u32(&bb
, "pid", jail_process
.pid
);
2246 blobmsg_add_string(&bb
, "bundle", opts
.ocibundle
);
2248 if (opts
.annotations
)
2249 blobmsg_add_blob(&bb
, opts
.annotations
);
2251 ubus_send_reply(ctx
, req
, bb
.head
);
2253 return UBUS_STATUS_OK
;
2257 CONTAINER_KILL_ATTR_SIGNAL
,
2258 __CONTAINER_KILL_ATTR_MAX
,
2261 static const struct blobmsg_policy container_kill_attrs
[__CONTAINER_KILL_ATTR_MAX
] = {
2262 [CONTAINER_KILL_ATTR_SIGNAL
] = { "signal", BLOBMSG_TYPE_INT32
},
2266 container_handle_kill(struct ubus_context
*ctx
, struct ubus_object
*obj
,
2267 struct ubus_request_data
*req
, const char *method
,
2268 struct blob_attr
*msg
)
2270 struct blob_attr
*tb
[__CONTAINER_KILL_ATTR_MAX
], *cur
;
2273 blobmsg_parse(container_kill_attrs
, __CONTAINER_KILL_ATTR_MAX
, tb
, blobmsg_data(msg
), blobmsg_data_len(msg
));
2275 cur
= tb
[CONTAINER_KILL_ATTR_SIGNAL
];
2277 sig
= blobmsg_get_u32(cur
);
2279 if (jail_oci_state
== OCI_STATE_CREATING
)
2280 return UBUS_STATUS_NOT_FOUND
;
2282 if (kill(jail_process
.pid
, sig
) == 0)
2286 case EINVAL
: return UBUS_STATUS_INVALID_ARGUMENT
;
2287 case EPERM
: return UBUS_STATUS_PERMISSION_DENIED
;
2288 case ESRCH
: return UBUS_STATUS_NOT_FOUND
;
2291 return UBUS_STATUS_UNKNOWN_ERROR
;
2294 static struct ubus_method container_methods
[] = {
2295 UBUS_METHOD_NOARG("start", handle_start
),
2296 UBUS_METHOD_NOARG("state", handle_state
),
2297 UBUS_METHOD("kill", container_handle_kill
, container_kill_attrs
),
2300 static struct ubus_object_type container_object_type
=
2301 UBUS_OBJECT_TYPE("container", container_methods
);
2303 static struct ubus_object container_object
= {
2304 .type
= &container_object_type
,
2305 .methods
= container_methods
,
2306 .n_methods
= ARRAY_SIZE(container_methods
),
2309 static void post_main(struct uloop_timeout
*t
);
2310 static struct uloop_timeout post_main_timeout
= {
2313 static int netns_fd
;
2314 static int pidns_fd
;
2315 #ifdef CLONE_NEWTIME
2316 static int timens_fd
;
2318 static void post_create_runtime(void);
2319 int main(int argc
, char **argv
)
2321 uid_t uid
= getuid();
2322 const char log
[] = "/dev/log";
2323 const char ubus
[] = "/var/run/ubus.sock";
2327 ERROR("not root, aborting: %m\n");
2328 return EXIT_FAILURE
;
2333 init_library_search();
2335 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
2338 debug
= atoi(optarg
);
2341 opts
.namespace |= CLONE_NEWNS
;
2345 opts
.namespace |= CLONE_NEWNS
;
2349 opts
.namespace |= CLONE_NEWUSER
;
2352 opts
.namespace |= CLONE_NEWCGROUP
;
2355 opts
.extroot
= strdup(optarg
);
2358 opts
.namespace |= CLONE_NEWNS
;
2362 opts
.seccomp
= optarg
;
2363 add_mount_bind(optarg
, 1, -1);
2366 opts
.capabilities
= optarg
;
2369 opts
.no_new_privs
= 1;
2375 opts
.namespace |= CLONE_NEWNET
;
2378 opts
.namespace |= CLONE_NEWUTS
;
2379 opts
.hostname
= strdup(optarg
);
2382 opts
.namespace |= CLONE_NEWNS
;
2383 add_path_and_deps(optarg
, 1, 0, 0);
2386 opts
.namespace |= CLONE_NEWNS
;
2387 add_path_and_deps(optarg
, 0, 0, 0);
2390 opts
.namespace |= CLONE_NEWNS
;
2391 add_mount_bind(ubus
, 0, -1);
2394 opts
.namespace |= CLONE_NEWNS
;
2395 add_mount_bind(log
, 0, -1);
2401 opts
.group
= optarg
;
2404 opts
.overlaydir
= optarg
;
2407 opts
.tmpoverlaysize
= optarg
;
2410 opts
.require_jail
= 1;
2416 opts
.ocibundle
= strdup(optarg
);
2419 opts
.immediately
= true;
2424 if (opts
.namespace && !opts
.ocibundle
)
2425 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
2427 /* those are filehandlers, so -1 indicates unused */
2428 opts
.setns
.pid
= -1;
2429 opts
.setns
.net
= -1;
2431 opts
.setns
.ipc
= -1;
2432 opts
.setns
.uts
= -1;
2433 opts
.setns
.user
= -1;
2434 opts
.setns
.cgroup
= -1;
2435 #ifdef CLONE_NEWTIME
2436 opts
.setns
.time
= -1;
2439 if (opts
.ocibundle
) {
2443 asprintf(&jsonfile
, "%s/config.json", opts
.ocibundle
);
2444 ocires
= parseOCI(jsonfile
);
2447 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
2452 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
2453 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
2457 /* no <binary> param found */
2458 if (!opts
.ocibundle
&& (argc
- optind
< 1)) {
2460 return EXIT_FAILURE
;
2462 if (!(opts
.ocibundle
||opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
2463 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
2465 return EXIT_FAILURE
;
2467 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
2469 opts
.capabilities
!= 0 || opts
.capset
.apply
,
2470 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
2475 parent_ctx
= ubus_connect(NULL
);
2476 ubus_add_uloop(parent_ctx
);
2478 if (opts
.ocibundle
) {
2480 if (asprintf(&objname
, "container.%s", opts
.name
) < 0)
2483 container_object
.name
= objname
;
2484 ret
= ubus_add_object(parent_ctx
, &container_object
);
2486 ERROR("Failed to add object: %s\n", ubus_strerror(ret
));
2491 /* deliberately not using 'else' on unrelated conditional branches */
2492 if (!opts
.ocibundle
) {
2493 /* allocate NULL-terminated array for argv */
2494 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(char**));
2495 if (!opts
.jail_argv
)
2496 return EXIT_FAILURE
;
2498 for (size_t s
= optind
; s
< argc
; s
++)
2499 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
2501 if (opts
.namespace & CLONE_NEWUSER
)
2502 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
2505 if (!opts
.extroot
) {
2506 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
2507 ERROR("failed to load dependencies\n");
2512 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2513 ERROR("failed to load libpreload-seccomp.so\n");
2515 if (opts
.require_jail
)
2519 uloop_timeout_add(&post_main_timeout
);
2526 static void post_main(struct uloop_timeout
*t
)
2528 if (apply_rlimits()) {
2529 ERROR("error applying resource limits\n");
2534 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2536 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2539 if (has_namespaces()) {
2540 if (opts
.namespace & CLONE_NEWNS
) {
2541 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2542 add_mount_bind("/etc/passwd", 0, -1);
2543 add_mount_bind("/etc/group", 0, -1);
2546 #if defined(__GLIBC__)
2548 add_mount_bind("/etc/nsswitch.conf", 0, -1);
2551 if (!(opts
.namespace & CLONE_NEWNET
)) {
2552 add_mount_bind("/etc/resolv.conf", 0, -1);
2553 } else if (opts
.setns
.net
== -1) {
2554 char hostdir
[PATH_MAX
];
2556 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2557 mkdir_p(hostdir
, 0755);
2558 add_mount(hostdir
, "/dev/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, NULL
, -1);
2561 /* default mounts */
2562 add_mount(NULL
, "/dev", "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, "size=1M", -1);
2563 add_mount(NULL
, "/dev/pts", "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
2565 if (opts
.procfs
|| opts
.ocibundle
) {
2566 add_mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, NULL
, -1);
2569 * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
2570 * which cannot be expressed with OCI spec, but happends to be very useful.
2571 * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
2573 * If not running in a new network namespace, only make /proc/sys read-only.
2574 * If running in a new network namespace, temporarily stash (ie. mount-bind)
2575 * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
2576 * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
2578 * This works because mounts are executed in incrementing strcmp() order and
2579 * /proc/self/net appears there before /proc/sys/net and hence the operation
2580 * succeeds as the bind-mount of /proc/self/net is performed first and then
2581 * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
2582 * table (and in the alphabet).
2584 if (!add_mount(NULL
, "/proc/sys", NULL
, MS_BIND
| MS_RDONLY
, NULL
, -1))
2585 if (opts
.namespace & CLONE_NEWNET
)
2586 if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, NULL
, -1))
2587 add_mount_inner("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, NULL
, -1);
2590 if (opts
.sysfs
|| opts
.ocibundle
)
2591 add_mount("sysfs", "/sys", "sysfs", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, NULL
, -1);
2594 add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID
| MS_NOEXEC
| MS_NODEV
, "mode=1777", -1);
2598 if (opts
.setns
.pid
!= -1) {
2599 pidns_fd
= ns_open_pid("pid", getpid());
2600 setns_open(CLONE_NEWPID
);
2605 #ifdef CLONE_NEWTIME
2606 if (opts
.setns
.time
!= -1) {
2607 timens_fd
= ns_open_pid("time", getpid());
2608 setns_open(CLONE_NEWTIME
);
2612 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| opts
.namespace, NULL
);
2614 jail_process
.pid
= fork();
2617 if (jail_process
.pid
> 0) {
2618 /* parent process */
2621 uloop_process_add(&jail_process
);
2624 if (pidns_fd
!= -1) {
2625 setns(pidns_fd
, CLONE_NEWPID
);
2628 #ifdef CLONE_NEWTIME
2629 if (timens_fd
!= -1)
2630 setns(timens_fd
, CLONE_NEWTIME
);
2634 if (opts
.setns
.net
!= -1)
2635 close(opts
.setns
.net
);
2636 if (opts
.setns
.ns
!= -1)
2637 close(opts
.setns
.ns
);
2638 if (opts
.setns
.ipc
!= -1)
2639 close(opts
.setns
.ipc
);
2640 if (opts
.setns
.uts
!= -1)
2641 close(opts
.setns
.uts
);
2642 if (opts
.setns
.user
!= -1)
2643 close(opts
.setns
.user
);
2644 if (opts
.setns
.cgroup
!= -1)
2645 close(opts
.setns
.cgroup
);
2648 if (read(pipes
[0], sig_buf
, 1) < 1) {
2649 ERROR("can't read from child\n");
2653 set_oom_score_adj();
2655 if (opts
.namespace & CLONE_NEWUSER
) {
2656 if (write_setgroups(jail_process
.pid
, true)) {
2657 ERROR("can't write setgroups\n");
2661 bool has_gr
= (opts
.gr_gid
!= -1);
2662 if (opts
.pw_uid
!= -1) {
2663 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2664 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2666 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2667 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2670 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2672 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2676 if (opts
.namespace & CLONE_NEWNET
) {
2678 ERROR("netns needs a named jail\n");
2681 netns_fd
= ns_open_pid("net", jail_process
.pid
);
2682 netns_updown(jail_process
.pid
, true);
2684 } else if (jail_process
.pid
== 0) {
2685 /* fork child process */
2686 exit(exec_jail(NULL
));
2688 ERROR("failed to clone/fork: %m\n");
2691 run_hooks(opts
.hooks
.createRuntime
, post_create_runtime
);
2694 static void post_poststart(void);
2695 static void post_create_runtime(void)
2700 if (write(pipes
[3], sig_buf
, 1) < 0) {
2701 ERROR("can't write to child\n");
2705 jail_oci_state
= OCI_STATE_CREATED
;
2706 if (opts
.ocibundle
&& !opts
.immediately
)
2707 uloop_run(); /* wait for 'start' command via ubus */
2709 pipe_send_start_container(NULL
);
2712 static void pipe_send_start_container(struct uloop_timeout
*t
)
2716 jail_oci_state
= OCI_STATE_RUNNING
;
2718 if (write(pipes
[3], sig_buf
, 1) < 0) {
2719 ERROR("can't write to child\n");
2724 run_hooks(opts
.hooks
.poststart
, post_poststart
);
2727 static void post_poststart(void)
2729 uloop_run(); /* idle here while jail is running */
2731 DEBUG("uloop interrupted, killing jail process\n");
2732 kill(jail_process
.pid
, SIGTERM
);
2733 uloop_timeout_set(&jail_process_timeout
, 1000);
2740 static void post_poststop(void);
2741 static void poststop(void) {
2742 if (opts
.namespace & CLONE_NEWNET
) {
2743 setns(netns_fd
, CLONE_NEWNET
);
2744 netns_updown(getpid(), false);
2747 run_hooks(opts
.hooks
.poststop
, post_poststop
);
2750 static void post_poststop(void)
2754 ubus_free(parent_ctx
);
2756 exit(jail_return_code
);