2 * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 2.1
6 * as published by the Free Software Foundation
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
15 #include <sys/mount.h>
16 #include <sys/prctl.h>
18 #include <sys/types.h>
30 #include <linux/limits.h>
33 #include "capabilities.h"
39 #include <libubox/uloop.h>
42 #define STACK_SIZE (1024 * 1024)
43 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:"
67 extern int pivot_root(const char *new_root, const char *put_old);
71 static char child_stack[STACK_SIZE];
73 static int mkdir_p(char *dir, mode_t mask)
75 char *l = strrchr(dir, '/');
83 if (mkdir_p(dir, mask))
88 ret = mkdir(dir, mask);
89 if (ret && errno == EEXIST)
93 ERROR("mkdir(%s, %d) failed: %m\n", dir, mask);
98 static int _mount_bind(const char *root, const char *path, const char *target, int readonly, int strict, int error)
103 int remount_flags = MS_BIND | MS_REMOUNT;
105 if (stat(path, &s)) {
106 ERROR("stat(%s) failed: %m\n", path);
110 snprintf(new, sizeof(new), "%s%s", root, target?target:path);
112 if (S_ISDIR(s.st_mode)) {
115 mkdir_p(dirname(new), 0755);
116 snprintf(new, sizeof(new), "%s%s", root, target?target:path);
117 fd = creat(new, 0644);
119 ERROR("creat(%s) failed: %m\n", new);
125 if (mount(path, new, NULL, MS_BIND, NULL)) {
126 ERROR("failed to mount -B %s %s: %m\n", path, new);
131 remount_flags |= MS_RDONLY;
134 remount_flags |= MS_NOEXEC | MS_NOSUID | MS_NODEV;
136 if ((strict || readonly) && mount(NULL, new, NULL, remount_flags, NULL)) {
137 ERROR("failed to remount (%s%s%s) %s: %m\n", readonly?"ro":"rw",
138 (readonly && strict)?", ":"", strict?"strict":"", new);
142 DEBUG("mount -B %s %s (%s%s%s)\n", path, new,
143 readonly?"ro":"rw", (readonly && strict)?", ":"", strict?"strict":"");
148 int mount_bind(const char *root, const char *path, int readonly, int error) {
149 return _mount_bind(root, path, NULL, readonly, 0, error);
152 static int mount_overlay(char *jail_root, char *overlaydir) {
153 char *upperdir, *workdir, *optsstr;
154 const char mountoptsformat[] = "lowerdir=%s,upperdir=%s,workdir=%s";
157 if (asprintf(&upperdir, "%s%s", overlaydir, "/upper") < 0)
160 if (asprintf(&workdir, "%s%s", overlaydir, "/work") < 0)
163 if (asprintf(&optsstr, mountoptsformat, jail_root, upperdir, workdir) < 0)
166 if (mkdir_p(upperdir, 0755) || mkdir_p(workdir, 0755))
169 DEBUG("mount -t overlay %s %s (%s)\n", jail_root, jail_root, optsstr);
171 if (mount(jail_root, jail_root, "overlay", MS_NOATIME, optsstr))
186 static int build_jail_fs(void)
188 char jail_root[] = "/tmp/ujail-XXXXXX";
189 char tmpovdir[] = "/tmp/ujail-overlay-XXXXXX";
190 char *overlaydir = NULL;
192 if (mkdtemp(jail_root) == NULL) {
193 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
197 /* oldroot can't be MS_SHARED else pivot_root() fails */
198 if (mount("none", "/", NULL, MS_REC|MS_PRIVATE, NULL)) {
199 ERROR("private mount failed %m\n");
204 if (mount(opts.extroot, jail_root, NULL, MS_BIND, NULL)) {
205 ERROR("extroot mount failed %m\n");
209 if (mount("tmpfs", jail_root, "tmpfs", MS_NOATIME, "mode=0755")) {
210 ERROR("tmpfs mount failed %m\n");
215 if (opts.tmpoverlaysize) {
216 char mountoptsstr[] = "mode=0755,size=XXXXXXXX";
218 snprintf(mountoptsstr, sizeof(mountoptsstr),
219 "mode=0755,size=%s", opts.tmpoverlaysize);
220 if (mkdtemp(tmpovdir) == NULL) {
221 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
224 if (mount("tmpfs", tmpovdir, "tmpfs", MS_NOATIME,
226 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts.tmpoverlaysize);
229 overlaydir = tmpovdir;
233 overlaydir = opts.overlaydir;
236 mount_overlay(jail_root, overlaydir);
238 if (chdir(jail_root)) {
239 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root);
243 if (mount_all(jail_root)) {
244 ERROR("mount_all() failed\n");
248 if (opts.namespace & CLONE_NEWNET) {
249 char hostdir[PATH_MAX], jailetc[PATH_MAX], jaillink[PATH_MAX];
251 snprintf(hostdir, PATH_MAX, "/tmp/resolv.conf-%s.d", opts.name);
252 mkdir_p(hostdir, 0755);
253 _mount_bind(jail_root, hostdir, "/tmp/resolv.conf.d", 1, 1, -1);
254 snprintf(jailetc, PATH_MAX, "%s/etc", jail_root);
255 mkdir_p(jailetc, 0755);
256 snprintf(jaillink, PATH_MAX, "%s/etc/resolv.conf", jail_root);
257 symlink("../tmp/resolv.conf.d/resolv.conf.auto", jaillink);
260 char dirbuf[sizeof(jail_root) + 4];
261 snprintf(dirbuf, sizeof(dirbuf), "%s/old", jail_root);
264 if (pivot_root(jail_root, dirbuf) == -1) {
265 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root, dirbuf);
269 ERROR("chdir(/) (after pivot_root) failed: %m\n");
273 snprintf(dirbuf, sizeof(dirbuf), "/old%s", jail_root);
274 umount2(dirbuf, MNT_DETACH);
276 if (opts.tmpoverlaysize) {
277 char tmpdirbuf[sizeof(tmpovdir) + 4];
278 snprintf(tmpdirbuf, sizeof(tmpdirbuf), "/old%s", tmpovdir);
279 umount2(tmpdirbuf, MNT_DETACH);
283 umount2("/old", MNT_DETACH);
287 mkdir("/proc", 0755);
288 mount("proc", "/proc", "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
292 mount("sysfs", "/sys", "sysfs", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
295 mount(NULL, "/", NULL, MS_RDONLY | MS_REMOUNT, 0);
300 static int write_uid_gid_map(pid_t child_pid, bool gidmap, int id)
304 const char *map_format = "%d %d %d\n";
305 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
306 child_pid, gidmap?"gid_map":"uid_map") < 0)
309 if ((map_file = open(map_path, O_WRONLY)) == -1)
312 if (dprintf(map_file, map_format, 0, id, 1) == -1) {
321 static int write_setgroups(pid_t child_pid, bool allow)
324 char setgroups_path[64];
326 if (snprintf(setgroups_path, sizeof(setgroups_path), "/proc/%d/setgroups",
331 if ((setgroups_file = open(setgroups_path, O_WRONLY)) == -1) {
335 if (dprintf(setgroups_file, allow?"allow":"deny") == -1) {
336 close(setgroups_file);
340 close(setgroups_file);
344 static void get_jail_user(int *user, int *user_gid, int *gr_gid)
346 struct passwd *p = NULL;
347 struct group *g = NULL;
350 p = getpwnam(opts.user);
352 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
353 opts.user, errno, strerror(errno));
357 *user_gid = p->pw_gid;
364 g = getgrnam(opts.group);
366 ERROR("failed to get gid for group %s: %m\n", opts.group);
375 static void set_jail_user(int pw_uid, int user_gid, int gr_gid)
377 if ((user_gid != -1) && initgroups(opts.user, user_gid)) {
378 ERROR("failed to initgroups() for user %s: %m\n", opts.user);
382 if ((gr_gid != -1) && setregid(gr_gid, gr_gid)) {
383 ERROR("failed to set group id %d: %m\n", gr_gid);
387 if ((pw_uid != -1) && setreuid(pw_uid, pw_uid)) {
388 ERROR("failed to set user id %d: %m\n", pw_uid);
394 static char** build_envp(const char *seccomp)
396 static char *envp[MAX_ENVP];
397 static char preload_var[PATH_MAX];
398 static char seccomp_var[PATH_MAX];
399 static char debug_var[] = "LD_DEBUG=all";
400 static char container_var[] = "container=ujail";
401 const char *preload_lib = find_lib("libpreload-seccomp.so");
404 if (seccomp && !preload_lib) {
405 ERROR("failed to add preload-lib to env\n");
409 snprintf(seccomp_var, sizeof(seccomp_var), "SECCOMP_FILE=%s", seccomp);
410 envp[count++] = seccomp_var;
411 snprintf(preload_var, sizeof(preload_var), "LD_PRELOAD=%s", preload_lib);
412 envp[count++] = preload_var;
415 envp[count++] = container_var;
418 envp[count++] = debug_var;
423 static void usage(void)
425 fprintf(stderr, "ujail <options> -- <binary> <params ...>\n");
426 fprintf(stderr, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
427 fprintf(stderr, " -S <file>\tseccomp filter config\n");
428 fprintf(stderr, " -C <file>\tcapabilities drop config\n");
429 fprintf(stderr, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
430 fprintf(stderr, " -n <name>\tthe name of the jail\n");
431 fprintf(stderr, "namespace jail options:\n");
432 fprintf(stderr, " -h <hostname>\tchange the hostname of the jail\n");
433 fprintf(stderr, " -N\t\tjail has network namespace\n");
434 fprintf(stderr, " -f\t\tjail has user namespace\n");
435 fprintf(stderr, " -F\t\tjail has cgroups namespace\n");
436 fprintf(stderr, " -r <file>\treadonly files that should be staged\n");
437 fprintf(stderr, " -w <file>\twriteable files that should be staged\n");
438 fprintf(stderr, " -p\t\tjail has /proc\n");
439 fprintf(stderr, " -s\t\tjail has /sys\n");
440 fprintf(stderr, " -l\t\tjail has /dev/log\n");
441 fprintf(stderr, " -u\t\tjail has a ubus socket\n");
442 fprintf(stderr, " -U <name>\tuser to run jailed process\n");
443 fprintf(stderr, " -G <name>\tgroup to run jailed process\n");
444 fprintf(stderr, " -o\t\tremont jail root (/) read only\n");
445 fprintf(stderr, " -R <dir>\texternal jail rootfs (system container)\n");
446 fprintf(stderr, " -O <dir>\tdirectory for r/w overlayfs\n");
447 fprintf(stderr, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
448 fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
449 and he has the same powers as root outside the jail,\n\
450 thus he can escape the jail and/or break stuff.\n\
451 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
452 If you use none of the namespace jail options,\n\
453 ujail will not use namespace/build a jail,\n\
454 and will only drop capabilities/apply seccomp filter.\n\n");
457 static int exec_jail(void *pipes_ptr)
459 int *pipes = (int*)pipes_ptr;
461 int pw_uid, pw_gid, gr_gid;
468 if (write(pipes[1], buf, 1) < 1) {
469 ERROR("can't write to parent\n");
472 if (read(pipes[2], buf, 1) < 1) {
473 ERROR("can't read from parent\n");
477 ERROR("parent had an error, child exiting\n");
484 if (opts.namespace & CLONE_NEWUSER) {
493 // if (setgroups(0, NULL) < 0) {
494 // ERROR("setgroups\n");
495 // exit(EXIT_FAILURE);
499 if (opts.namespace && opts.hostname && strlen(opts.hostname) > 0
500 && sethostname(opts.hostname, strlen(opts.hostname))) {
501 ERROR("sethostname(%s) failed: %m\n", opts.hostname);
505 if ((opts.namespace & CLONE_NEWNS) && build_jail_fs()) {
506 ERROR("failed to build jail fs\n");
510 if (opts.capabilities && drop_capabilities(opts.capabilities))
513 if (opts.no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
514 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
518 if (!(opts.namespace & CLONE_NEWUSER)) {
519 get_jail_user(&pw_uid, &pw_gid, &gr_gid);
520 set_jail_user(pw_uid, pw_gid, gr_gid);
523 char **envp = build_envp(opts.seccomp);
527 INFO("exec-ing %s\n", *opts.jail_argv);
528 execve(*opts.jail_argv, opts.jail_argv, envp);
529 /* we get there only if execve fails */
530 ERROR("failed to execve %s: %m\n", *opts.jail_argv);
534 static int jail_running = 1;
535 static int jail_return_code = 0;
537 static void jail_process_timeout_cb(struct uloop_timeout *t);
538 static struct uloop_timeout jail_process_timeout = {
539 .cb = jail_process_timeout_cb,
542 static void jail_process_handler(struct uloop_process *c, int ret)
544 uloop_timeout_cancel(&jail_process_timeout);
545 if (WIFEXITED(ret)) {
546 jail_return_code = WEXITSTATUS(ret);
547 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
549 jail_return_code = WTERMSIG(ret);
550 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
556 static struct uloop_process jail_process = {
557 .cb = jail_process_handler,
560 static void jail_process_timeout_cb(struct uloop_timeout *t)
562 DEBUG("jail process failed to stop, sending SIGKILL\n");
563 kill(jail_process.pid, SIGKILL);
566 static void jail_handle_signal(int signo)
568 DEBUG("forwarding signal %d to the jailed process\n", signo);
569 kill(jail_process.pid, signo);
572 static int netns_open_pid(const pid_t target_ns)
574 char pid_net_path[PATH_MAX];
576 snprintf(pid_net_path, sizeof(pid_net_path), "/proc/%u/ns/net", target_ns);
578 return open(pid_net_path, O_RDONLY);
581 static void netns_updown(pid_t pid, bool start)
583 struct ubus_context *ctx = ubus_connect(NULL);
584 static struct blob_buf req;
590 blob_buf_init(&req, 0);
591 blobmsg_add_string(&req, "jail", opts.name);
592 blobmsg_add_u32(&req, "pid", pid);
593 blobmsg_add_u8(&req, "start", start);
595 if (ubus_lookup_id(ctx, "network", &id) ||
596 ubus_invoke(ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
597 INFO("ubus request failed\n");
603 int main(int argc, char **argv)
606 uid_t uid = getuid();
607 char log[] = "/dev/log";
608 char ubus[] = "/var/run/ubus.sock";
615 ERROR("not root, aborting: %m\n");
621 init_library_search();
623 while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
626 debug = atoi(optarg);
629 opts.namespace |= CLONE_NEWNS;
633 opts.namespace |= CLONE_NEWNS;
637 opts.namespace |= CLONE_NEWUSER;
640 opts.namespace |= CLONE_NEWCGROUP;
643 opts.extroot = optarg;
646 opts.namespace |= CLONE_NEWNS;
650 opts.seccomp = optarg;
651 add_mount(optarg, 1, -1);
654 opts.capabilities = optarg;
657 opts.no_new_privs = 1;
663 opts.namespace |= CLONE_NEWNET;
666 opts.namespace |= CLONE_NEWUTS;
667 opts.hostname = optarg;
670 opts.namespace |= CLONE_NEWNS;
671 add_path_and_deps(optarg, 1, 0, 0);
674 opts.namespace |= CLONE_NEWNS;
675 add_path_and_deps(optarg, 0, 0, 0);
678 opts.namespace |= CLONE_NEWNS;
679 add_mount(ubus, 0, -1);
682 opts.namespace |= CLONE_NEWNS;
683 add_mount(log, 0, -1);
692 opts.overlaydir = optarg;
695 opts.tmpoverlaysize = optarg;
701 opts.namespace |= CLONE_NEWIPC | CLONE_NEWPID;
703 if (opts.tmpoverlaysize && strlen(opts.tmpoverlaysize) > 8) {
704 ERROR("size parameter too long: \"%s\"\n", opts.tmpoverlaysize);
708 /* no <binary> param found */
709 if (argc - optind < 1) {
713 if (!(opts.namespace||opts.capabilities||opts.seccomp)) {
714 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
718 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
720 opts.capabilities != 0,
723 opts.jail_argv = &argv[optind];
725 get_jail_user(&opts.pw_uid, &opts.pw_gid, &opts.gr_gid);
728 if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
729 ERROR("failed to load dependencies\n");
734 if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
735 ERROR("failed to load libpreload-seccomp.so\n");
740 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
744 sigfillset(&sigmask);
745 for (i = 0; i < _NSIG; i++) {
746 struct sigaction s = { 0 };
748 if (!sigismember(&sigmask, i))
750 if ((i == SIGCHLD) || (i == SIGPIPE))
753 s.sa_handler = jail_handle_signal;
754 sigaction(i, &s, NULL);
757 if (opts.namespace) {
758 if (opts.namespace & CLONE_NEWNS) {
759 add_mount("/dev/full", 0, -1);
760 add_mount("/dev/null", 0, -1);
761 add_mount("/dev/random", 0, -1);
762 add_mount("/dev/urandom", 0, -1);
763 add_mount("/dev/tty", 0, -1);
764 add_mount("/dev/zero", 0, -1);
765 add_mount("/dev/console", 0, -1);
767 if (!opts.extroot && (opts.user || opts.group)) {
768 add_mount("/etc/passwd", 0, -1);
769 add_mount("/etc/group", 0, -1);
772 if (!(opts.namespace & CLONE_NEWNET)) {
773 add_mount("/etc/resolv.conf", 0, -1);
777 if (pipe(&pipes[0]) < 0 || pipe(&pipes[2]) < 0)
780 jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, SIGCHLD | opts.namespace, &pipes);
782 jail_process.pid = fork();
785 if (jail_process.pid > 0) {
790 if (read(pipes[0], sig_buf, 1) < 1) {
791 ERROR("can't read from child\n");
795 if (opts.namespace & CLONE_NEWUSER) {
796 bool has_gr = (opts.gr_gid != -1);
797 if (write_setgroups(jail_process.pid, false)) {
798 ERROR("can't write setgroups\n");
801 if (opts.pw_uid != -1) {
802 write_uid_gid_map(jail_process.pid, 0, opts.pw_uid);
803 write_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:opts.pw_gid);
805 write_uid_gid_map(jail_process.pid, 0, 65534);
806 write_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:65534);
810 if (opts.namespace & CLONE_NEWNET) {
811 netns_fd = netns_open_pid(jail_process.pid);
812 netns_updown(jail_process.pid, true);
816 if (write(pipes[3], sig_buf, 1) < 0) {
817 ERROR("can't write to child\n");
821 uloop_process_add(&jail_process);
824 DEBUG("uloop interrupted, killing jail process\n");
825 kill(jail_process.pid, SIGTERM);
826 uloop_timeout_set(&jail_process_timeout, 1000);
830 if (opts.namespace & CLONE_NEWNET) {
831 setns(netns_fd, CLONE_NEWNET);
832 netns_updown(getpid(), false);
835 return jail_return_code;
836 } else if (jail_process.pid == 0) {
837 /* fork child process */
838 return exec_jail(NULL);
840 ERROR("failed to clone/fork: %m\n");