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>
24 /* musl only defined 15 limit types, make sure all 16 are supported */
26 #define RLIMIT_RTTIME 15
28 #define RLIMIT_NLIMITS 16
30 #define RLIM_NLIMITS 16
41 #include <linux/limits.h>
42 #include <linux/filter.h>
46 #include "capabilities.h"
51 #include "seccomp-oci.h"
53 #include <libubox/utils.h>
54 #include <libubox/blobmsg.h>
55 #include <libubox/blobmsg_json.h>
56 #include <libubox/list.h>
57 #include <libubox/vlist.h>
58 #include <libubox/uloop.h>
61 #ifndef CLONE_NEWCGROUP
62 #define CLONE_NEWCGROUP 0x02000000
65 #define STACK_SIZE (1024 * 1024)
66 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:"
86 struct sock_fprog
*ociseccomp
;
88 struct jail_capset capset
;
97 struct sysctl_val
**sysctl
;
107 gid_t
*additional_gids
;
108 size_t num_additional_gids
;
113 struct hook_execvpe
**createRuntime
;
114 struct hook_execvpe
**createContainer
;
115 struct hook_execvpe
**startContainer
;
116 struct hook_execvpe
**poststart
;
117 struct hook_execvpe
**poststop
;
119 struct rlimit
*rlimits
[RLIM_NLIMITS
];
121 bool set_oom_score_adj
;
124 static void free_hooklist(struct hook_execvpe
**hooklist
)
126 struct hook_execvpe
*cur
;
151 static void free_sysctl(void) {
152 struct sysctl_val
*cur
;
163 static void free_rlimits(void) {
166 for (type
= 0; type
< RLIM_NLIMITS
; ++type
)
167 free(opts
.rlimits
[type
]);
170 static void free_opts(bool child
) {
173 /* we need to keep argv, envp and seccomp filter in child */
175 if (opts
.ociseccomp
) {
176 free(opts
.ociseccomp
->filter
);
177 free(opts
.ociseccomp
);
180 tmp
= opts
.jail_argv
;
184 free(opts
.jail_argv
);
200 free_hooklist(opts
.hooks
.createRuntime
);
201 free_hooklist(opts
.hooks
.createContainer
);
202 free_hooklist(opts
.hooks
.startContainer
);
203 free_hooklist(opts
.hooks
.poststart
);
204 free_hooklist(opts
.hooks
.poststop
);
207 static struct blob_buf ocibuf
;
209 extern int pivot_root(const char *new_root
, const char *put_old
);
213 static char child_stack
[STACK_SIZE
];
217 static int mount_overlay(char *jail_root
, char *overlaydir
) {
218 char *upperdir
, *workdir
, *optsstr
, *upperetc
, *upperresolvconf
;
219 const char mountoptsformat
[] = "lowerdir=%s,upperdir=%s,workdir=%s";
222 if (asprintf(&upperdir
, "%s%s", overlaydir
, "/upper") < 0)
225 if (asprintf(&workdir
, "%s%s", overlaydir
, "/work") < 0)
228 if (asprintf(&optsstr
, mountoptsformat
, jail_root
, upperdir
, workdir
) < 0)
231 if (mkdir_p(upperdir
, 0755) || mkdir_p(workdir
, 0755))
235 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
236 * this is to work-around a bug in overlayfs described in the overlayfs-userns
238 * 3. modification of a file 'hithere' which is in l but not yet
239 * in u, and which is not owned by T, is not allowed, even if
240 * writes to u are allowed. This may be a bug in overlayfs,
241 * but it is safe behavior.
243 if (asprintf(&upperetc
, "%s/etc", upperdir
) < 0)
246 if (mkdir_p(upperetc
, 0755))
247 goto upper_etc_printf
;
249 if (asprintf(&upperresolvconf
, "%s/resolv.conf", upperetc
) < 0)
250 goto upper_etc_printf
;
252 fd
= creat(upperresolvconf
, 0644);
254 ERROR("creat(%s) failed: %m\n", upperresolvconf
);
255 goto upper_resolvconf_printf
;
259 DEBUG("mount -t overlay %s %s (%s)\n", jail_root
, jail_root
, optsstr
);
261 if (mount(jail_root
, jail_root
, "overlay", MS_NOATIME
, optsstr
))
266 upper_resolvconf_printf
:
267 free(upperresolvconf
);
280 static void pass_console(int console_fd
)
282 struct ubus_context
*ctx
= ubus_connect(NULL
);
283 static struct blob_buf req
;
289 blob_buf_init(&req
, 0);
290 blobmsg_add_string(&req
, "name", opts
.name
);
292 if (ubus_lookup_id(ctx
, "container", &id
) ||
293 ubus_invoke_fd(ctx
, id
, "console_set", req
.head
, NULL
, NULL
, 3000, console_fd
))
294 INFO("ubus request failed\n");
302 static int create_dev_console(const char *jail_root
)
305 char dev_console_path
[PATH_MAX
];
306 int slave_console_fd
;
308 /* Open UNIX/98 virtual console */
309 console_fd
= posix_openpt(O_RDWR
| O_NOCTTY
);
310 if (console_fd
== -1)
313 console_fname
= ptsname(console_fd
);
314 DEBUG("got console fd %d and PTS client name %s\n", console_fd
, console_fname
);
319 unlockpt(console_fd
);
321 /* pass PTY master to procd */
322 pass_console(console_fd
);
324 /* mount-bind PTY slave to /dev/console in jail */
325 snprintf(dev_console_path
, sizeof(dev_console_path
), "%s/dev/console", jail_root
);
326 close(creat(dev_console_path
, 0620));
328 if (mount(console_fname
, dev_console_path
, NULL
, MS_BIND
, NULL
))
331 /* use PTY slave for stdio */
332 slave_console_fd
= open(console_fname
, O_RDWR
); /* | O_NOCTTY */
333 dup2(slave_console_fd
, 0);
334 dup2(slave_console_fd
, 1);
335 dup2(slave_console_fd
, 2);
336 close(slave_console_fd
);
338 INFO("using guest console %s\n", console_fname
);
347 static int hook_running
= 0;
348 static int hook_return_code
= 0;
350 static void hook_process_timeout_cb(struct uloop_timeout
*t
);
351 static struct uloop_timeout hook_process_timeout
= {
352 .cb
= hook_process_timeout_cb
,
355 static void hook_process_handler(struct uloop_process
*c
, int ret
)
357 uloop_timeout_cancel(&hook_process_timeout
);
358 if (WIFEXITED(ret
)) {
359 hook_return_code
= WEXITSTATUS(ret
);
360 DEBUG("hook (%d) exited with exit: %d\n", c
->pid
, hook_return_code
);
362 hook_return_code
= WTERMSIG(ret
);
363 DEBUG("hook (%d) exited with signal: %d\n", c
->pid
, hook_return_code
);
369 static struct uloop_process hook_process
= {
370 .cb
= hook_process_handler
,
373 static void hook_process_timeout_cb(struct uloop_timeout
*t
)
375 DEBUG("hook process failed to stop, sending SIGKILL\n");
376 kill(hook_process
.pid
, SIGKILL
);
379 static int run_hook(struct hook_execvpe
*hook
)
383 DEBUG("executing hook %s\n", hook
->file
);
385 if (stat(hook
->file
, &s
))
388 if (!((unsigned long)s
.st_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)))
391 if (!((unsigned long)s
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
)))
397 hook_process
.pid
= fork();
398 if (hook_process
.pid
> 0) {
400 uloop_process_add(&hook_process
);
402 if (hook
->timeout
> 0)
403 uloop_timeout_set(&hook_process_timeout
, 1000 * hook
->timeout
);
407 DEBUG("uloop interrupted, killing hook process\n");
408 kill(hook_process
.pid
, SIGTERM
);
409 uloop_timeout_set(&hook_process_timeout
, 1000);
414 waitpid(hook_process
.pid
, NULL
, WCONTINUED
);
416 return hook_return_code
;
417 } else if (hook_process
.pid
== 0) {
419 execvpe(hook
->file
, hook
->argv
, hook
->envp
);
429 static int run_hooks(struct hook_execvpe
**hooklist
)
431 struct hook_execvpe
**cur
;
435 return 0; /* Nothing to do */
440 res
= run_hook(*cur
);
442 DEBUG(" error running hook %s\n", (*cur
)->file
);
444 DEBUG(" success running hook %s\n", (*cur
)->file
);
452 static int apply_sysctl(const char *jail_root
)
454 struct sysctl_val
**cur
;
455 char *procdir
, *fname
;
461 asprintf(&procdir
, "%s/proc", jail_root
);
465 mkdir(procdir
, 0700);
466 if (mount("proc", procdir
, "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0))
472 asprintf(&fname
, "%s/sys/%s", procdir
, (*cur
)->entry
);
476 DEBUG("sysctl: writing '%s' to %s\n", (*cur
)->value
, fname
);
478 f
= open(fname
, O_WRONLY
);
480 ERROR("sysctl: can't open %s\n", fname
);
483 write(f
, (*cur
)->value
, strlen((*cur
)->value
));
496 static int build_jail_fs(void)
498 char jail_root
[] = "/tmp/ujail-XXXXXX";
499 char tmpovdir
[] = "/tmp/ujail-overlay-XXXXXX";
500 char tmpdevdir
[] = "/tmp/ujail-XXXXXX/dev";
501 char tmpdevptsdir
[] = "/tmp/ujail-XXXXXX/dev/pts";
502 char *overlaydir
= NULL
;
504 if (mkdtemp(jail_root
) == NULL
) {
505 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
509 if (apply_sysctl(jail_root
)) {
510 ERROR("failed to apply sysctl values\n");
514 /* oldroot can't be MS_SHARED else pivot_root() fails */
515 if (mount("none", "/", NULL
, MS_REC
|MS_PRIVATE
, NULL
)) {
516 ERROR("private mount failed %m\n");
521 if (mount(opts
.extroot
, jail_root
, NULL
, MS_BIND
, NULL
)) {
522 ERROR("extroot mount failed %m\n");
526 if (mount("tmpfs", jail_root
, "tmpfs", MS_NOATIME
, "mode=0755")) {
527 ERROR("tmpfs mount failed %m\n");
532 if (opts
.tmpoverlaysize
) {
533 char mountoptsstr
[] = "mode=0755,size=XXXXXXXX";
535 snprintf(mountoptsstr
, sizeof(mountoptsstr
),
536 "mode=0755,size=%s", opts
.tmpoverlaysize
);
537 if (mkdtemp(tmpovdir
) == NULL
) {
538 ERROR("mkdtemp(%s) failed: %m\n", jail_root
);
541 if (mount("tmpfs", tmpovdir
, "tmpfs", MS_NOATIME
,
543 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts
.tmpoverlaysize
);
546 overlaydir
= tmpovdir
;
550 overlaydir
= opts
.overlaydir
;
553 mount_overlay(jail_root
, overlaydir
);
555 if (chdir(jail_root
)) {
556 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root
);
560 snprintf(tmpdevdir
, sizeof(tmpdevdir
), "%s/dev", jail_root
);
561 mkdir_p(tmpdevdir
, 0755);
562 if (mount(NULL
, tmpdevdir
, "tmpfs", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, "size=1M"))
565 snprintf(tmpdevptsdir
, sizeof(tmpdevptsdir
), "%s/dev/pts", jail_root
);
566 mkdir_p(tmpdevptsdir
, 0755);
567 if (mount(NULL
, tmpdevptsdir
, "devpts", MS_NOATIME
| MS_NOEXEC
| MS_NOSUID
, NULL
))
571 create_dev_console(jail_root
);
573 if (mount_all(jail_root
)) {
574 ERROR("mount_all() failed\n");
578 /* make sure /etc/resolv.conf exists if in new network namespace */
579 if (opts
.namespace & CLONE_NEWNET
) {
580 char jailetc
[PATH_MAX
], jaillink
[PATH_MAX
];
582 snprintf(jailetc
, PATH_MAX
, "%s/etc", jail_root
);
583 mkdir_p(jailetc
, 0755);
584 snprintf(jaillink
, PATH_MAX
, "%s/etc/resolv.conf", jail_root
);
588 symlink("../tmp/resolv.conf.d/resolv.conf.auto", jaillink
);
591 run_hooks(opts
.hooks
.createContainer
);
593 char dirbuf
[sizeof(jail_root
) + 4];
594 snprintf(dirbuf
, sizeof(dirbuf
), "%s/old", jail_root
);
597 if (pivot_root(jail_root
, dirbuf
) == -1) {
598 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root
, dirbuf
);
602 ERROR("chdir(/) (after pivot_root) failed: %m\n");
606 snprintf(dirbuf
, sizeof(dirbuf
), "/old%s", jail_root
);
607 umount2(dirbuf
, MNT_DETACH
);
609 if (opts
.tmpoverlaysize
) {
610 char tmpdirbuf
[sizeof(tmpovdir
) + 4];
611 snprintf(tmpdirbuf
, sizeof(tmpdirbuf
), "/old%s", tmpovdir
);
612 umount2(tmpdirbuf
, MNT_DETACH
);
616 umount2("/old", MNT_DETACH
);
620 mkdir("/proc", 0755);
621 mount("proc", "/proc", "proc", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
, 0);
623 * make /proc/sys read-only while keeping read-write to
624 * /proc/sys/net if CLONE_NEWNET is set.
626 if (opts
.namespace & CLONE_NEWNET
)
627 mount("/proc/sys/net", "/proc/self/net", NULL
, MS_BIND
, 0);
629 mount("/proc/sys", "/proc/sys", NULL
, MS_BIND
, 0);
630 mount(NULL
, "/proc/sys", NULL
, MS_REMOUNT
| MS_RDONLY
, 0);
631 mount(NULL
, "/proc", NULL
, MS_REMOUNT
, 0);
633 if (opts
.namespace & CLONE_NEWNET
)
634 mount("/proc/self/net", "/proc/sys/net", NULL
, MS_MOVE
, 0);
638 mount("sysfs", "/sys", "sysfs", MS_NOATIME
| MS_NODEV
| MS_NOEXEC
| MS_NOSUID
| MS_RDONLY
, 0);
641 mount(NULL
, "/", NULL
, MS_REMOUNT
| MS_BIND
| MS_RDONLY
, 0);
646 static int write_uid_gid_map(pid_t child_pid
, bool gidmap
, char *mapstr
)
651 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
652 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
655 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
658 if (dprintf(map_file
, "%s", mapstr
)) {
668 static int write_single_uid_gid_map(pid_t child_pid
, bool gidmap
, int id
)
672 const char *map_format
= "%d %d %d\n";
673 if (snprintf(map_path
, sizeof(map_path
), "/proc/%d/%s",
674 child_pid
, gidmap
?"gid_map":"uid_map") < 0)
677 if ((map_file
= open(map_path
, O_WRONLY
)) == -1)
680 if (dprintf(map_file
, map_format
, 0, id
, 1) == -1) {
689 static int write_setgroups(pid_t child_pid
, bool allow
)
692 char setgroups_path
[64];
694 if (snprintf(setgroups_path
, sizeof(setgroups_path
), "/proc/%d/setgroups",
699 if ((setgroups_file
= open(setgroups_path
, O_WRONLY
)) == -1) {
703 if (dprintf(setgroups_file
, "%s", allow
?"allow":"deny") == -1) {
704 close(setgroups_file
);
708 close(setgroups_file
);
712 static void get_jail_user(int *user
, int *user_gid
, int *gr_gid
)
714 struct passwd
*p
= NULL
;
715 struct group
*g
= NULL
;
718 p
= getpwnam(opts
.user
);
720 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
721 opts
.user
, errno
, strerror(errno
));
725 *user_gid
= p
->pw_gid
;
732 g
= getgrnam(opts
.group
);
734 ERROR("failed to get gid for group %s: %m\n", opts
.group
);
743 static void set_jail_user(int pw_uid
, int user_gid
, int gr_gid
)
745 if (opts
.user
&& (user_gid
!= -1) && initgroups(opts
.user
, user_gid
)) {
746 ERROR("failed to initgroups() for user %s: %m\n", opts
.user
);
750 if ((gr_gid
!= -1) && setregid(gr_gid
, gr_gid
)) {
751 ERROR("failed to set group id %d: %m\n", gr_gid
);
755 if ((pw_uid
!= -1) && setreuid(pw_uid
, pw_uid
)) {
756 ERROR("failed to set user id %d: %m\n", pw_uid
);
761 static int apply_rlimits(void)
765 for (resource
= 0; resource
< RLIM_NLIMITS
; ++resource
) {
766 if (opts
.rlimits
[resource
])
767 DEBUG("applying limits to resource %u\n", resource
);
769 if (opts
.rlimits
[resource
] &&
770 setrlimit(resource
, opts
.rlimits
[resource
]))
778 static char** build_envp(const char *seccomp
, char **ocienvp
)
780 static char *envp
[MAX_ENVP
];
781 static char preload_var
[PATH_MAX
];
782 static char seccomp_var
[PATH_MAX
];
783 static char debug_var
[] = "LD_DEBUG=all";
784 static char container_var
[] = "container=ujail";
785 const char *preload_lib
= find_lib("libpreload-seccomp.so");
790 if (seccomp
&& !preload_lib
) {
791 ERROR("failed to add preload-lib to env\n");
795 snprintf(seccomp_var
, sizeof(seccomp_var
), "SECCOMP_FILE=%s", seccomp
);
796 envp
[count
++] = seccomp_var
;
797 snprintf(preload_var
, sizeof(preload_var
), "LD_PRELOAD=%s", preload_lib
);
798 envp
[count
++] = preload_var
;
801 envp
[count
++] = container_var
;
804 envp
[count
++] = debug_var
;
807 while (addenv
&& *addenv
) {
808 envp
[count
++] = *(addenv
++);
809 if (count
>= MAX_ENVP
) {
810 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP
);
817 static void usage(void)
819 fprintf(stderr
, "ujail <options> -- <binary> <params ...>\n");
820 fprintf(stderr
, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
821 fprintf(stderr
, " -S <file>\tseccomp filter config\n");
822 fprintf(stderr
, " -C <file>\tcapabilities drop config\n");
823 fprintf(stderr
, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
824 fprintf(stderr
, " -n <name>\tthe name of the jail\n");
825 fprintf(stderr
, "namespace jail options:\n");
826 fprintf(stderr
, " -h <hostname>\tchange the hostname of the jail\n");
827 fprintf(stderr
, " -N\t\tjail has network namespace\n");
828 fprintf(stderr
, " -f\t\tjail has user namespace\n");
829 fprintf(stderr
, " -F\t\tjail has cgroups namespace\n");
830 fprintf(stderr
, " -r <file>\treadonly files that should be staged\n");
831 fprintf(stderr
, " -w <file>\twriteable files that should be staged\n");
832 fprintf(stderr
, " -p\t\tjail has /proc\n");
833 fprintf(stderr
, " -s\t\tjail has /sys\n");
834 fprintf(stderr
, " -l\t\tjail has /dev/log\n");
835 fprintf(stderr
, " -u\t\tjail has a ubus socket\n");
836 fprintf(stderr
, " -U <name>\tuser to run jailed process\n");
837 fprintf(stderr
, " -G <name>\tgroup to run jailed process\n");
838 fprintf(stderr
, " -o\t\tremont jail root (/) read only\n");
839 fprintf(stderr
, " -R <dir>\texternal jail rootfs (system container)\n");
840 fprintf(stderr
, " -O <dir>\tdirectory for r/w overlayfs\n");
841 fprintf(stderr
, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
842 fprintf(stderr
, " -E\t\tfail if jail cannot be setup\n");
843 fprintf(stderr
, " -y\t\tprovide jail console\n");
844 fprintf(stderr
, " -J <dir>\tstart OCI bundle\n");
845 fprintf(stderr
, "\nWarning: by default root inside the jail is the same\n\
846 and he has the same powers as root outside the jail,\n\
847 thus he can escape the jail and/or break stuff.\n\
848 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
849 If you use none of the namespace jail options,\n\
850 ujail will not use namespace/build a jail,\n\
851 and will only drop capabilities/apply seccomp filter.\n\n");
854 static int exec_jail(void *pipes_ptr
)
856 int *pipes
= (int*)pipes_ptr
;
858 int pw_uid
, pw_gid
, gr_gid
;
864 if (write(pipes
[1], buf
, 1) < 1) {
865 ERROR("can't write to parent\n");
868 if (read(pipes
[2], buf
, 1) < 1) {
869 ERROR("can't read from parent\n");
873 ERROR("parent had an error, child exiting\n");
880 if (opts
.namespace & CLONE_NEWUSER
) {
881 if (setregid(0, 0) < 0) {
885 if (setreuid(0, 0) < 0) {
889 if (setgroups(0, NULL
) < 0) {
890 ERROR("setgroups\n");
895 if (opts
.namespace && opts
.hostname
&& strlen(opts
.hostname
) > 0
896 && sethostname(opts
.hostname
, strlen(opts
.hostname
))) {
897 ERROR("sethostname(%s) failed: %m\n", opts
.hostname
);
901 if ((opts
.namespace & CLONE_NEWNS
) && build_jail_fs()) {
902 ERROR("failed to build jail fs\n");
905 run_hooks(opts
.hooks
.startContainer
);
907 if (!(opts
.namespace & CLONE_NEWUSER
)) {
908 get_jail_user(&pw_uid
, &pw_gid
, &gr_gid
);
910 set_jail_user(opts
.pw_uid
?:pw_uid
, opts
.pw_gid
?:pw_gid
, opts
.gr_gid
?:gr_gid
);
913 if (opts
.additional_gids
&&
914 (setgroups(opts
.num_additional_gids
, opts
.additional_gids
) < 0)) {
915 ERROR("setgroups failed: %m\n");
922 if (applyOCIcapabilities(opts
.capset
))
925 if (opts
.capabilities
&& drop_capabilities(opts
.capabilities
))
928 if (opts
.no_new_privs
&& prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0)) {
929 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
933 char **envp
= build_envp(opts
.seccomp
, opts
.envp
);
937 if (opts
.cwd
&& chdir(opts
.cwd
))
940 if (opts
.ociseccomp
&& applyOCIlinuxseccomp(opts
.ociseccomp
))
945 INFO("exec-ing %s\n", *opts
.jail_argv
);
946 if (opts
.envp
) /* respect PATH if potentially set in ENV */
947 execvpe(*opts
.jail_argv
, opts
.jail_argv
, envp
);
949 execve(*opts
.jail_argv
, opts
.jail_argv
, envp
);
951 /* we get there only if execve fails */
952 ERROR("failed to execve %s: %m\n", *opts
.jail_argv
);
956 static int jail_running
= 0;
957 static int jail_return_code
= 0;
959 static void jail_process_timeout_cb(struct uloop_timeout
*t
);
960 static struct uloop_timeout jail_process_timeout
= {
961 .cb
= jail_process_timeout_cb
,
964 static void jail_process_handler(struct uloop_process
*c
, int ret
)
966 uloop_timeout_cancel(&jail_process_timeout
);
967 if (WIFEXITED(ret
)) {
968 jail_return_code
= WEXITSTATUS(ret
);
969 INFO("jail (%d) exited with exit: %d\n", c
->pid
, jail_return_code
);
971 jail_return_code
= WTERMSIG(ret
);
972 INFO("jail (%d) exited with signal: %d\n", c
->pid
, jail_return_code
);
978 static struct uloop_process jail_process
= {
979 .cb
= jail_process_handler
,
982 static void jail_process_timeout_cb(struct uloop_timeout
*t
)
984 DEBUG("jail process failed to stop, sending SIGKILL\n");
985 kill(jail_process
.pid
, SIGKILL
);
988 static void jail_handle_signal(int signo
)
991 DEBUG("forwarding signal %d to the hook process\n", signo
);
992 kill(hook_process
.pid
, signo
);
996 DEBUG("forwarding signal %d to the jailed process\n", signo
);
997 kill(jail_process
.pid
, signo
);
1001 static int netns_open_pid(const pid_t target_ns
)
1003 char pid_net_path
[PATH_MAX
];
1005 snprintf(pid_net_path
, sizeof(pid_net_path
), "/proc/%u/ns/net", target_ns
);
1007 return open(pid_net_path
, O_RDONLY
);
1010 static void netns_updown(pid_t pid
, bool start
)
1012 struct ubus_context
*ctx
= ubus_connect(NULL
);
1013 static struct blob_buf req
;
1019 blob_buf_init(&req
, 0);
1020 blobmsg_add_string(&req
, "jail", opts
.name
);
1021 blobmsg_add_u32(&req
, "pid", pid
);
1022 blobmsg_add_u8(&req
, "start", start
);
1024 if (ubus_lookup_id(ctx
, "network", &id
) ||
1025 ubus_invoke(ctx
, id
, "netns_updown", req
.head
, NULL
, NULL
, 3000))
1026 INFO("ubus request failed\n");
1028 blob_buf_free(&req
);
1032 static int parseOCIenvarray(struct blob_attr
*msg
, char ***envp
)
1034 struct blob_attr
*cur
;
1037 blobmsg_for_each_attr(cur
, msg
, rem
)
1041 *envp
= calloc(1 + sz
, sizeof(char*));
1050 blobmsg_for_each_attr(cur
, msg
, rem
)
1051 (*envp
)[sz
++] = strdup(blobmsg_get_string(cur
));
1065 static const struct blobmsg_policy oci_root_policy
[] = {
1066 [OCI_ROOT_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1067 [OCI_ROOT_READONLY
] = { "readonly", BLOBMSG_TYPE_BOOL
},
1070 static int parseOCIroot(const char *jsonfile
, struct blob_attr
*msg
)
1072 static char rootpath
[PATH_MAX
] = { 0 };
1073 struct blob_attr
*tb
[__OCI_ROOT_MAX
];
1076 blobmsg_parse(oci_root_policy
, __OCI_ROOT_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1078 if (!tb
[OCI_ROOT_PATH
])
1081 strncpy(rootpath
, jsonfile
, PATH_MAX
);
1082 cur
= strrchr(rootpath
, '/');
1088 strncat(rootpath
, blobmsg_get_string(tb
[OCI_ROOT_PATH
]), PATH_MAX
- (strlen(rootpath
) + 1));
1090 opts
.extroot
= rootpath
;
1092 opts
.ronly
= blobmsg_get_bool(tb
[OCI_ROOT_READONLY
]);
1106 static const struct blobmsg_policy oci_hook_policy
[] = {
1107 [OCI_HOOK_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1108 [OCI_HOOK_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1109 [OCI_HOOK_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1110 [OCI_HOOK_TIMEOUT
] = { "timeout", BLOBMSG_TYPE_INT32
},
1114 static int parseOCIhook(struct hook_execvpe
***hooklist
, struct blob_attr
*msg
)
1116 struct blob_attr
*tb
[__OCI_HOOK_MAX
];
1117 struct blob_attr
*cur
;
1121 blobmsg_for_each_attr(cur
, msg
, rem
)
1127 *hooklist
= calloc(idx
+ 1, sizeof(struct hook_execvpe
*));
1133 blobmsg_for_each_attr(cur
, msg
, rem
) {
1134 blobmsg_parse(oci_hook_policy
, __OCI_HOOK_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1136 if (!tb
[OCI_HOOK_PATH
]) {
1141 (*hooklist
)[idx
] = malloc(sizeof(struct hook_execvpe
));
1142 if (tb
[OCI_HOOK_ARGS
]) {
1143 ret
= parseOCIenvarray(tb
[OCI_HOOK_ARGS
], &((*hooklist
)[idx
]->argv
));
1147 (*hooklist
)[idx
]->argv
= calloc(2, sizeof(char *));
1148 ((*hooklist
)[idx
]->argv
)[0] = strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1149 ((*hooklist
)[idx
]->argv
)[1] = NULL
;
1153 if (tb
[OCI_HOOK_ENV
]) {
1154 ret
= parseOCIenvarray(tb
[OCI_HOOK_ENV
], &((*hooklist
)[idx
]->envp
));
1159 if (tb
[OCI_HOOK_TIMEOUT
])
1160 (*hooklist
)[idx
]->timeout
= blobmsg_get_u32(tb
[OCI_HOOK_TIMEOUT
]);
1162 (*hooklist
)[idx
]->file
= strdup(blobmsg_get_string(tb
[OCI_HOOK_PATH
]));
1167 (*hooklist
)[idx
] = NULL
;
1169 DEBUG("added %d hooks\n", idx
);
1174 free_hooklist(*hooklist
);
1183 OCI_HOOKS_CREATERUNTIME
,
1184 OCI_HOOKS_CREATECONTAINER
,
1185 OCI_HOOKS_STARTCONTAINER
,
1186 OCI_HOOKS_POSTSTART
,
1191 static const struct blobmsg_policy oci_hooks_policy
[] = {
1192 [OCI_HOOKS_PRESTART
] = { "prestart", BLOBMSG_TYPE_ARRAY
},
1193 [OCI_HOOKS_CREATERUNTIME
] = { "createRuntime", BLOBMSG_TYPE_ARRAY
},
1194 [OCI_HOOKS_CREATECONTAINER
] = { "createContainer", BLOBMSG_TYPE_ARRAY
},
1195 [OCI_HOOKS_STARTCONTAINER
] = { "startContainer", BLOBMSG_TYPE_ARRAY
},
1196 [OCI_HOOKS_POSTSTART
] = { "poststart", BLOBMSG_TYPE_ARRAY
},
1197 [OCI_HOOKS_POSTSTOP
] = { "poststop", BLOBMSG_TYPE_ARRAY
},
1200 static int parseOCIhooks(struct blob_attr
*msg
)
1202 struct blob_attr
*tb
[__OCI_HOOKS_MAX
];
1205 blobmsg_parse(oci_hooks_policy
, __OCI_HOOKS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1207 if (tb
[OCI_HOOKS_PRESTART
])
1208 INFO("warning: ignoring deprecated prestart hook\n");
1210 if (tb
[OCI_HOOKS_CREATERUNTIME
]) {
1211 ret
= parseOCIhook(&opts
.hooks
.createRuntime
, tb
[OCI_HOOKS_CREATERUNTIME
]);
1216 if (tb
[OCI_HOOKS_CREATECONTAINER
]) {
1217 ret
= parseOCIhook(&opts
.hooks
.createContainer
, tb
[OCI_HOOKS_CREATECONTAINER
]);
1219 goto out_createruntime
;
1222 if (tb
[OCI_HOOKS_STARTCONTAINER
]) {
1223 ret
= parseOCIhook(&opts
.hooks
.startContainer
, tb
[OCI_HOOKS_STARTCONTAINER
]);
1225 goto out_createcontainer
;
1228 if (tb
[OCI_HOOKS_POSTSTART
]) {
1229 ret
= parseOCIhook(&opts
.hooks
.poststart
, tb
[OCI_HOOKS_POSTSTART
]);
1231 goto out_startcontainer
;
1234 if (tb
[OCI_HOOKS_POSTSTOP
]) {
1235 ret
= parseOCIhook(&opts
.hooks
.poststop
, tb
[OCI_HOOKS_POSTSTOP
]);
1243 free_hooklist(opts
.hooks
.poststart
);
1245 free_hooklist(opts
.hooks
.startContainer
);
1246 out_createcontainer
:
1247 free_hooklist(opts
.hooks
.createContainer
);
1249 free_hooklist(opts
.hooks
.createRuntime
);
1256 OCI_PROCESS_USER_UID
,
1257 OCI_PROCESS_USER_GID
,
1258 OCI_PROCESS_USER_UMASK
,
1259 OCI_PROCESS_USER_ADDITIONALGIDS
,
1260 __OCI_PROCESS_USER_MAX
,
1263 static const struct blobmsg_policy oci_process_user_policy
[] = {
1264 [OCI_PROCESS_USER_UID
] = { "uid", BLOBMSG_TYPE_INT32
},
1265 [OCI_PROCESS_USER_GID
] = { "gid", BLOBMSG_TYPE_INT32
},
1266 [OCI_PROCESS_USER_UMASK
] = { "umask", BLOBMSG_TYPE_INT32
},
1267 [OCI_PROCESS_USER_ADDITIONALGIDS
] = { "additionalGids", BLOBMSG_TYPE_ARRAY
},
1270 static int parseOCIprocessuser(struct blob_attr
*msg
) {
1271 struct blob_attr
*tb
[__OCI_PROCESS_USER_MAX
];
1272 struct blob_attr
*cur
;
1276 blobmsg_parse(oci_process_user_policy
, __OCI_PROCESS_USER_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1278 if (tb
[OCI_PROCESS_USER_UID
])
1279 opts
.pw_uid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UID
]);
1281 if (tb
[OCI_PROCESS_USER_GID
]) {
1282 opts
.pw_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1283 opts
.gr_gid
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_GID
]);
1287 if (tb
[OCI_PROCESS_USER_ADDITIONALGIDS
]) {
1290 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1292 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1297 opts
.additional_gids
= calloc(gidcnt
+ has_gid
, sizeof(gid_t
));
1300 /* always add primary GID to set of GIDs if set */
1302 opts
.additional_gids
[gidcnt
++] = opts
.gr_gid
;
1304 blobmsg_for_each_attr(cur
, tb
[OCI_PROCESS_USER_ADDITIONALGIDS
], rem
) {
1305 if (has_gid
&& (blobmsg_get_u32(cur
) == opts
.gr_gid
))
1307 opts
.additional_gids
[gidcnt
++] = blobmsg_get_u32(cur
);
1309 opts
.num_additional_gids
= gidcnt
;
1311 DEBUG("read %lu additional groups\n", gidcnt
);
1314 if (tb
[OCI_PROCESS_USER_UMASK
]) {
1315 opts
.umask
= blobmsg_get_u32(tb
[OCI_PROCESS_USER_UMASK
]);
1316 opts
.set_umask
= true;
1322 /* from manpage GETRLIMIT(2) */
1323 static const char* const rlimit_names
[RLIM_NLIMITS
] = {
1325 [RLIMIT_CORE
] = "CORE",
1326 [RLIMIT_CPU
] = "CPU",
1327 [RLIMIT_DATA
] = "DATA",
1328 [RLIMIT_FSIZE
] = "FSIZE",
1329 [RLIMIT_LOCKS
] = "LOCKS",
1330 [RLIMIT_MEMLOCK
] = "MEMLOCK",
1331 [RLIMIT_MSGQUEUE
] = "MSGQUEUE",
1332 [RLIMIT_NICE
] = "NICE",
1333 [RLIMIT_NOFILE
] = "NOFILE",
1334 [RLIMIT_NPROC
] = "NPROC",
1335 [RLIMIT_RSS
] = "RSS",
1336 [RLIMIT_RTPRIO
] = "RTPRIO",
1337 [RLIMIT_RTTIME
] = "RTTIME",
1338 [RLIMIT_SIGPENDING
] = "SIGPENDING",
1339 [RLIMIT_STACK
] = "STACK",
1342 static int resolve_rlimit(char *type
) {
1343 unsigned int rltype
;
1345 for (rltype
= 0; rltype
< RLIM_NLIMITS
; ++rltype
)
1346 if (rlimit_names
[rltype
] &&
1347 !strncmp("RLIMIT_", type
, 7) &&
1348 !strcmp(rlimit_names
[rltype
], type
+ 7))
1355 static int parseOCIrlimits(struct blob_attr
*msg
)
1357 struct blob_attr
*cur
, *cure
;
1360 struct rlimit
*curlim
;
1362 bool sethard
= false, setsoft
= false;
1364 blobmsg_for_each_attr(cur
, msg
, rem
) {
1365 blobmsg_for_each_attr(cure
, cur
, reme
) {
1366 if (!strcmp(blobmsg_name(cure
), "type") && (blobmsg_type(cure
) == BLOBMSG_TYPE_STRING
)) {
1367 limtype
= resolve_rlimit(blobmsg_get_string(cure
));
1368 } else if (!strcmp(blobmsg_name(cure
), "soft")) {
1369 switch (blobmsg_type(cure
)) {
1370 case BLOBMSG_TYPE_INT32
:
1371 soft
= blobmsg_get_u32(cure
);
1373 case BLOBMSG_TYPE_INT64
:
1374 soft
= blobmsg_get_u64(cure
);
1380 } else if (!strcmp(blobmsg_name(cure
), "hard")) {
1381 switch (blobmsg_type(cure
)) {
1382 case BLOBMSG_TYPE_INT32
:
1383 hard
= blobmsg_get_u32(cure
);
1385 case BLOBMSG_TYPE_INT64
:
1386 hard
= blobmsg_get_u64(cure
);
1400 if (opts
.rlimits
[limtype
])
1403 if (!sethard
|| !setsoft
)
1406 curlim
= malloc(sizeof(struct rlimit
));
1407 curlim
->rlim_cur
= soft
;
1408 curlim
->rlim_max
= hard
;
1410 opts
.rlimits
[limtype
] = curlim
;
1418 OCI_PROCESS_CAPABILITIES
,
1421 OCI_PROCESS_OOMSCOREADJ
,
1422 OCI_PROCESS_NONEWPRIVILEGES
,
1423 OCI_PROCESS_RLIMITS
,
1424 OCI_PROCESS_TERMINAL
,
1429 static const struct blobmsg_policy oci_process_policy
[] = {
1430 [OCI_PROCESS_ARGS
] = { "args", BLOBMSG_TYPE_ARRAY
},
1431 [OCI_PROCESS_CAPABILITIES
] = { "capabilities", BLOBMSG_TYPE_TABLE
},
1432 [OCI_PROCESS_CWD
] = { "cwd", BLOBMSG_TYPE_STRING
},
1433 [OCI_PROCESS_ENV
] = { "env", BLOBMSG_TYPE_ARRAY
},
1434 [OCI_PROCESS_OOMSCOREADJ
] = { "oomScoreAdj", BLOBMSG_TYPE_INT32
},
1435 [OCI_PROCESS_NONEWPRIVILEGES
] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL
},
1436 [OCI_PROCESS_RLIMITS
] = { "rlimits", BLOBMSG_TYPE_ARRAY
},
1437 [OCI_PROCESS_TERMINAL
] = { "terminal", BLOBMSG_TYPE_BOOL
},
1438 [OCI_PROCESS_USER
] = { "user", BLOBMSG_TYPE_TABLE
},
1442 static int parseOCIprocess(struct blob_attr
*msg
)
1444 struct blob_attr
*tb
[__OCI_PROCESS_MAX
];
1447 blobmsg_parse(oci_process_policy
, __OCI_PROCESS_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1449 if (!tb
[OCI_PROCESS_ARGS
])
1452 res
= parseOCIenvarray(tb
[OCI_PROCESS_ARGS
], &opts
.jail_argv
);
1456 opts
.console
= blobmsg_get_bool(tb
[OCI_PROCESS_TERMINAL
]);
1457 opts
.no_new_privs
= blobmsg_get_bool(tb
[OCI_PROCESS_NONEWPRIVILEGES
]);
1459 if (tb
[OCI_PROCESS_CWD
])
1460 opts
.cwd
= strdup(blobmsg_get_string(tb
[OCI_PROCESS_CWD
]));
1462 if (tb
[OCI_PROCESS_ENV
]) {
1463 res
= parseOCIenvarray(tb
[OCI_PROCESS_ENV
], &opts
.envp
);
1468 if (tb
[OCI_PROCESS_USER
] && (res
= parseOCIprocessuser(tb
[OCI_PROCESS_USER
])))
1471 if (tb
[OCI_PROCESS_CAPABILITIES
] &&
1472 (res
= parseOCIcapabilities(&opts
.capset
, tb
[OCI_PROCESS_CAPABILITIES
])))
1475 if (tb
[OCI_PROCESS_RLIMITS
] &&
1476 (res
= parseOCIrlimits(tb
[OCI_PROCESS_RLIMITS
])))
1479 if (tb
[OCI_PROCESS_OOMSCOREADJ
]) {
1480 opts
.oom_score_adj
= blobmsg_get_u32(tb
[OCI_PROCESS_OOMSCOREADJ
]);
1481 opts
.set_oom_score_adj
= true;
1488 OCI_LINUX_NAMESPACE_TYPE
,
1489 OCI_LINUX_NAMESPACE_PATH
,
1490 __OCI_LINUX_NAMESPACE_MAX
,
1493 static const struct blobmsg_policy oci_linux_namespace_policy
[] = {
1494 [OCI_LINUX_NAMESPACE_TYPE
] = { "type", BLOBMSG_TYPE_STRING
},
1495 [OCI_LINUX_NAMESPACE_PATH
] = { "path", BLOBMSG_TYPE_STRING
},
1498 static unsigned int resolve_nstype(char *type
) {
1499 if (!strcmp("pid", type
))
1500 return CLONE_NEWPID
;
1501 else if (!strcmp("network", type
))
1502 return CLONE_NEWNET
;
1503 else if (!strcmp("mount", type
))
1505 else if (!strcmp("ipc", type
))
1506 return CLONE_NEWIPC
;
1507 else if (!strcmp("uts", type
))
1508 return CLONE_NEWUTS
;
1509 else if (!strcmp("user", type
))
1510 return CLONE_NEWUSER
;
1511 else if (!strcmp("cgroup", type
))
1512 return CLONE_NEWCGROUP
;
1517 static int parseOCIlinuxns(struct blob_attr
*msg
)
1519 struct blob_attr
*tb
[__OCI_LINUX_NAMESPACE_MAX
];
1521 blobmsg_parse(oci_linux_namespace_policy
, __OCI_LINUX_NAMESPACE_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1523 if (!tb
[OCI_LINUX_NAMESPACE_TYPE
])
1526 if (tb
[OCI_LINUX_NAMESPACE_PATH
])
1527 return ENOTSUP
; /* ToDo */
1529 opts
.namespace |= resolve_nstype(blobmsg_get_string(tb
[OCI_LINUX_NAMESPACE_TYPE
]));
1536 OCI_LINUX_UIDGIDMAP_CONTAINERID
,
1537 OCI_LINUX_UIDGIDMAP_HOSTID
,
1538 OCI_LINUX_UIDGIDMAP_SIZE
,
1539 __OCI_LINUX_UIDGIDMAP_MAX
,
1542 static const struct blobmsg_policy oci_linux_uidgidmap_policy
[] = {
1543 [OCI_LINUX_UIDGIDMAP_CONTAINERID
] = { "containerID", BLOBMSG_TYPE_INT32
},
1544 [OCI_LINUX_UIDGIDMAP_HOSTID
] = { "hostID", BLOBMSG_TYPE_INT32
},
1545 [OCI_LINUX_UIDGIDMAP_SIZE
] = { "size", BLOBMSG_TYPE_INT32
},
1548 static int parseOCIuidgidmappings(struct blob_attr
*msg
, bool is_gidmap
)
1550 const char *map_format
= "%d %d %d\n";
1551 struct blob_attr
*tb
[__OCI_LINUX_UIDGIDMAP_MAX
];
1552 struct blob_attr
*cur
;
1556 unsigned int cnt
= 0;
1557 size_t totallen
= 0;
1559 /* count number of mappings */
1560 blobmsg_for_each_attr(cur
, msg
, rem
)
1566 /* allocate array for mappings */
1567 mappings
= calloc(1 + cnt
, sizeof(char*));
1571 mappings
[cnt
] = NULL
;
1574 blobmsg_for_each_attr(cur
, msg
, rem
) {
1575 blobmsg_parse(oci_linux_uidgidmap_policy
, __OCI_LINUX_UIDGIDMAP_MAX
, tb
, blobmsg_data(cur
), blobmsg_len(cur
));
1577 if (!tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
] ||
1578 !tb
[OCI_LINUX_UIDGIDMAP_HOSTID
] ||
1579 !tb
[OCI_LINUX_UIDGIDMAP_SIZE
])
1582 /* write mapping line into allocated string */
1583 len
= asprintf(&mappings
[cnt
++], map_format
,
1584 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_CONTAINERID
]),
1585 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_HOSTID
]),
1586 blobmsg_get_u32(tb
[OCI_LINUX_UIDGIDMAP_SIZE
]));
1594 /* allocate combined mapping string */
1595 map
= calloc(1 + totallen
, sizeof(char));
1601 /* concatenate mapping strings into combined string */
1602 curstr
= mappings
[0];
1604 strcat(map
, curstr
);
1618 OCI_LINUX_RESOURCES
,
1621 OCI_LINUX_NAMESPACES
,
1622 OCI_LINUX_UIDMAPPINGS
,
1623 OCI_LINUX_GIDMAPPINGS
,
1624 OCI_LINUX_MASKEDPATHS
,
1625 OCI_LINUX_READONLYPATHS
,
1626 OCI_LINUX_ROOTFSPROPAGATION
,
1630 static const struct blobmsg_policy oci_linux_policy
[] = {
1631 [OCI_LINUX_RESOURCES
] = { "resources", BLOBMSG_TYPE_TABLE
},
1632 [OCI_LINUX_SECCOMP
] = { "seccomp", BLOBMSG_TYPE_TABLE
},
1633 [OCI_LINUX_SYSCTL
] = { "sysctl", BLOBMSG_TYPE_TABLE
},
1634 [OCI_LINUX_NAMESPACES
] = { "namespaces", BLOBMSG_TYPE_ARRAY
},
1635 [OCI_LINUX_UIDMAPPINGS
] = { "uidMappings", BLOBMSG_TYPE_ARRAY
},
1636 [OCI_LINUX_GIDMAPPINGS
] = { "gidMappings", BLOBMSG_TYPE_ARRAY
},
1637 [OCI_LINUX_MASKEDPATHS
] = { "maskedPaths", BLOBMSG_TYPE_ARRAY
},
1638 [OCI_LINUX_READONLYPATHS
] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY
},
1639 [OCI_LINUX_ROOTFSPROPAGATION
] = { "rootfsPropagation", BLOBMSG_TYPE_STRING
},
1642 static int parseOCIsysctl(struct blob_attr
*msg
)
1644 struct blob_attr
*cur
;
1649 blobmsg_for_each_attr(cur
, msg
, rem
) {
1650 if (!blobmsg_name(cur
) || !blobmsg_get_string(cur
))
1659 opts
.sysctl
= calloc(cnt
+ 1, sizeof(struct sysctl_val
*));
1664 blobmsg_for_each_attr(cur
, msg
, rem
) {
1665 opts
.sysctl
[cnt
] = malloc(sizeof(struct sysctl_val
));
1666 if (!opts
.sysctl
[cnt
])
1669 /* replace '.' with '/' in entry name */
1670 tc
= tmp
= strdup(blobmsg_name(cur
));
1671 while ((tc
= strchr(tc
, '.')))
1674 opts
.sysctl
[cnt
]->value
= strdup(blobmsg_get_string(cur
));
1675 opts
.sysctl
[cnt
]->entry
= tmp
;
1680 opts
.sysctl
[cnt
] = NULL
;
1685 static int parseOCIlinux(struct blob_attr
*msg
)
1687 struct blob_attr
*tb
[__OCI_LINUX_MAX
];
1688 struct blob_attr
*cur
;
1692 blobmsg_parse(oci_linux_policy
, __OCI_LINUX_MAX
, tb
, blobmsg_data(msg
), blobmsg_len(msg
));
1694 if (tb
[OCI_LINUX_NAMESPACES
]) {
1695 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_NAMESPACES
], rem
) {
1696 res
= parseOCIlinuxns(cur
);
1702 if (tb
[OCI_LINUX_UIDMAPPINGS
]) {
1703 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 0);
1708 if (tb
[OCI_LINUX_GIDMAPPINGS
]) {
1709 res
= parseOCIuidgidmappings(tb
[OCI_LINUX_GIDMAPPINGS
], 1);
1714 if (tb
[OCI_LINUX_READONLYPATHS
]) {
1715 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_READONLYPATHS
], rem
) {
1716 res
= add_mount(NULL
, blobmsg_get_string(cur
), NULL
, MS_BIND
| MS_REC
| MS_RDONLY
, NULL
, 0);
1722 if (tb
[OCI_LINUX_MASKEDPATHS
]) {
1723 blobmsg_for_each_attr(cur
, tb
[OCI_LINUX_MASKEDPATHS
], rem
) {
1724 res
= add_mount((void *)(-1), blobmsg_get_string(cur
), NULL
, 0, NULL
, 1);
1730 if (tb
[OCI_LINUX_SYSCTL
]) {
1731 res
= parseOCIsysctl(tb
[OCI_LINUX_SYSCTL
]);
1736 if (tb
[OCI_LINUX_SECCOMP
]) {
1737 opts
.ociseccomp
= parseOCIlinuxseccomp(tb
[OCI_LINUX_SECCOMP
]);
1738 if (!opts
.ociseccomp
)
1756 static const struct blobmsg_policy oci_policy
[] = {
1757 [OCI_VERSION
] = { "ociVersion", BLOBMSG_TYPE_STRING
},
1758 [OCI_HOSTNAME
] = { "hostname", BLOBMSG_TYPE_STRING
},
1759 [OCI_PROCESS
] = { "process", BLOBMSG_TYPE_TABLE
},
1760 [OCI_ROOT
] = { "root", BLOBMSG_TYPE_TABLE
},
1761 [OCI_MOUNTS
] = { "mounts", BLOBMSG_TYPE_ARRAY
},
1762 [OCI_HOOKS
] = { "hooks", BLOBMSG_TYPE_TABLE
},
1763 [OCI_LINUX
] = { "linux", BLOBMSG_TYPE_TABLE
},
1766 static int parseOCI(const char *jsonfile
)
1768 struct blob_attr
*tb
[__OCI_MAX
];
1769 struct blob_attr
*cur
;
1773 blob_buf_init(&ocibuf
, 0);
1774 if (!blobmsg_add_json_from_file(&ocibuf
, jsonfile
))
1777 blobmsg_parse(oci_policy
, __OCI_MAX
, tb
, blob_data(ocibuf
.head
), blob_len(ocibuf
.head
));
1779 if (!tb
[OCI_VERSION
])
1782 if (strncmp("1.0", blobmsg_get_string(tb
[OCI_VERSION
]), 3)) {
1783 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb
[OCI_VERSION
]));
1787 if (tb
[OCI_HOSTNAME
])
1788 opts
.hostname
= strdup(blobmsg_get_string(tb
[OCI_HOSTNAME
]));
1790 if (!tb
[OCI_PROCESS
])
1793 if ((res
= parseOCIprocess(tb
[OCI_PROCESS
])))
1799 if ((res
= parseOCIroot(jsonfile
, tb
[OCI_ROOT
])))
1802 if (!tb
[OCI_MOUNTS
])
1805 blobmsg_for_each_attr(cur
, tb
[OCI_MOUNTS
], rem
)
1806 if ((res
= parseOCImount(cur
)))
1809 if (tb
[OCI_LINUX
] && (res
= parseOCIlinux(tb
[OCI_LINUX
])))
1812 if (tb
[OCI_HOOKS
] && (res
= parseOCIhooks(tb
[OCI_HOOKS
])))
1815 blob_buf_free(&ocibuf
);
1820 static int set_oom_score_adj(void)
1825 if (!opts
.set_oom_score_adj
)
1828 snprintf(fname
, sizeof(fname
), "/proc/%u/oom_score_adj", jail_process
.pid
);
1829 f
= open(fname
, O_WRONLY
| O_TRUNC
);
1833 dprintf(f
, "%d", opts
.oom_score_adj
);
1839 int main(int argc
, char **argv
)
1842 uid_t uid
= getuid();
1843 const char log
[] = "/dev/log";
1844 const char ubus
[] = "/var/run/ubus.sock";
1845 char *jsonfile
= NULL
;
1852 ERROR("not root, aborting: %m\n");
1853 return EXIT_FAILURE
;
1858 init_library_search();
1860 while ((ch
= getopt(argc
, argv
, OPT_ARGS
)) != -1) {
1863 debug
= atoi(optarg
);
1866 opts
.namespace |= CLONE_NEWNS
;
1870 opts
.namespace |= CLONE_NEWNS
;
1874 opts
.namespace |= CLONE_NEWUSER
;
1877 opts
.namespace |= CLONE_NEWCGROUP
;
1880 opts
.extroot
= strdup(optarg
);
1883 opts
.namespace |= CLONE_NEWNS
;
1887 opts
.seccomp
= optarg
;
1888 add_mount_bind(optarg
, 1, -1);
1891 opts
.capabilities
= optarg
;
1894 opts
.no_new_privs
= 1;
1900 opts
.namespace |= CLONE_NEWNET
;
1903 opts
.namespace |= CLONE_NEWUTS
;
1904 opts
.hostname
= strdup(optarg
);
1907 opts
.namespace |= CLONE_NEWNS
;
1908 add_path_and_deps(optarg
, 1, 0, 0);
1911 opts
.namespace |= CLONE_NEWNS
;
1912 add_path_and_deps(optarg
, 0, 0, 0);
1915 opts
.namespace |= CLONE_NEWNS
;
1916 add_mount_bind(ubus
, 0, -1);
1919 opts
.namespace |= CLONE_NEWNS
;
1920 add_mount_bind(log
, 0, -1);
1926 opts
.group
= optarg
;
1929 opts
.overlaydir
= optarg
;
1932 opts
.tmpoverlaysize
= optarg
;
1935 opts
.require_jail
= 1;
1941 asprintf(&jsonfile
, "%s/config.json", optarg
);
1947 opts
.namespace |= CLONE_NEWIPC
| CLONE_NEWPID
;
1951 ocires
= parseOCI(jsonfile
);
1954 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires
), ocires
);
1959 if (opts
.tmpoverlaysize
&& strlen(opts
.tmpoverlaysize
) > 8) {
1960 ERROR("size parameter too long: \"%s\"\n", opts
.tmpoverlaysize
);
1964 /* no <binary> param found */
1965 if (!jsonfile
&& (argc
- optind
< 1)) {
1967 return EXIT_FAILURE
;
1969 if (!(opts
.namespace||opts
.capabilities
||opts
.seccomp
)) {
1970 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
1972 return EXIT_FAILURE
;
1974 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
1976 opts
.capabilities
!= 0 || opts
.capset
.apply
,
1977 opts
.seccomp
!= 0 || opts
.ociseccomp
!= 0);
1980 /* allocate NULL-terminated array for argv */
1981 opts
.jail_argv
= calloc(1 + argc
- optind
, sizeof(char**));
1982 if (!opts
.jail_argv
)
1983 return EXIT_FAILURE
;
1985 for (size_t s
= optind
; s
< argc
; s
++)
1986 opts
.jail_argv
[s
- optind
] = strdup(argv
[s
]);
1988 if (opts
.namespace & CLONE_NEWUSER
)
1989 get_jail_user(&opts
.pw_uid
, &opts
.pw_gid
, &opts
.gr_gid
);
1992 if (!opts
.extroot
) {
1993 if (opts
.namespace && add_path_and_deps(*opts
.jail_argv
, 1, -1, 0)) {
1994 ERROR("failed to load dependencies\n");
1999 if (opts
.namespace && opts
.seccomp
&& add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
2000 ERROR("failed to load libpreload-seccomp.so\n");
2002 if (opts
.require_jail
)
2006 if (apply_rlimits()) {
2007 ERROR("error applying resource limits\n");
2012 prctl(PR_SET_NAME
, opts
.name
, NULL
, NULL
, NULL
);
2014 sigfillset(&sigmask
);
2015 for (i
= 0; i
< _NSIG
; i
++) {
2016 struct sigaction s
= { 0 };
2018 if (!sigismember(&sigmask
, i
))
2020 if ((i
== SIGCHLD
) || (i
== SIGPIPE
) || (i
== SIGSEGV
))
2023 s
.sa_handler
= jail_handle_signal
;
2024 sigaction(i
, &s
, NULL
);
2027 if (opts
.namespace) {
2028 if (opts
.namespace & CLONE_NEWNS
) {
2029 add_mount_bind("/dev/full", 0, -1);
2030 add_mount_bind("/dev/null", 0, -1);
2031 add_mount_bind("/dev/random", 0, -1);
2032 add_mount_bind("/dev/urandom", 0, -1);
2033 add_mount_bind("/dev/zero", 0, -1);
2034 add_mount_bind("/dev/ptmx", 0, -1);
2035 add_mount_bind("/dev/tty", 0, -1);
2037 if (!opts
.extroot
&& (opts
.user
|| opts
.group
)) {
2038 add_mount_bind("/etc/passwd", 0, -1);
2039 add_mount_bind("/etc/group", 0, -1);
2042 #if defined(__GLIBC__)
2044 add_mount_bind("/etc/nsswitch.conf", 0, -1);
2047 if (!(opts
.namespace & CLONE_NEWNET
)) {
2048 add_mount_bind("/etc/resolv.conf", 0, -1);
2050 char hostdir
[PATH_MAX
];
2052 snprintf(hostdir
, PATH_MAX
, "/tmp/resolv.conf-%s.d", opts
.name
);
2053 mkdir_p(hostdir
, 0755);
2054 add_mount(hostdir
, "/tmp/resolv.conf.d", NULL
, MS_BIND
| MS_NOEXEC
| MS_NOATIME
| MS_NOSUID
| MS_NODEV
| MS_RDONLY
, NULL
, -1);
2058 if (pipe(&pipes
[0]) < 0 || pipe(&pipes
[2]) < 0)
2061 jail_process
.pid
= clone(exec_jail
, child_stack
+ STACK_SIZE
, SIGCHLD
| opts
.namespace, &pipes
);
2063 jail_process
.pid
= fork();
2066 if (jail_process
.pid
> 0) {
2069 /* parent process */
2072 run_hooks(opts
.hooks
.createRuntime
);
2073 if (read(pipes
[0], sig_buf
, 1) < 1) {
2074 ERROR("can't read from child\n");
2078 set_oom_score_adj();
2080 if (opts
.namespace & CLONE_NEWUSER
) {
2081 if (write_setgroups(jail_process
.pid
, true)) {
2082 ERROR("can't write setgroups\n");
2086 bool has_gr
= (opts
.gr_gid
!= -1);
2087 if (opts
.pw_uid
!= -1) {
2088 write_single_uid_gid_map(jail_process
.pid
, 0, opts
.pw_uid
);
2089 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:opts
.pw_gid
);
2091 write_single_uid_gid_map(jail_process
.pid
, 0, 65534);
2092 write_single_uid_gid_map(jail_process
.pid
, 1, has_gr
?opts
.gr_gid
:65534);
2095 write_uid_gid_map(jail_process
.pid
, 0, opts
.uidmap
);
2097 write_uid_gid_map(jail_process
.pid
, 1, opts
.gidmap
);
2101 if (opts
.namespace & CLONE_NEWNET
) {
2103 ERROR("netns needs a named jail\n");
2106 netns_fd
= netns_open_pid(jail_process
.pid
);
2107 netns_updown(jail_process
.pid
, true);
2111 if (write(pipes
[3], sig_buf
, 1) < 0) {
2112 ERROR("can't write to child\n");
2116 run_hooks(opts
.hooks
.poststart
);
2119 uloop_process_add(&jail_process
);
2122 DEBUG("uloop interrupted, killing jail process\n");
2123 kill(jail_process
.pid
, SIGTERM
);
2124 uloop_timeout_set(&jail_process_timeout
, 1000);
2128 if (opts
.namespace & CLONE_NEWNET
) {
2129 setns(netns_fd
, CLONE_NEWNET
);
2130 netns_updown(getpid(), false);
2133 run_hooks(opts
.hooks
.poststop
);
2135 return jail_return_code
;
2136 } else if (jail_process
.pid
== 0) {
2137 /* fork child process */
2138 return exec_jail(NULL
);
2140 ERROR("failed to clone/fork: %m\n");
2141 return EXIT_FAILURE
;