df1bda7666e3535d47c53a6ebfbb00949f84f5fb
[project/procd.git] / jail / jail.c
1 /*
2 * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
3 *
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
7 *
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.
12 */
13
14 #define _GNU_SOURCE
15 #include <sys/mount.h>
16 #include <sys/prctl.h>
17 #include <sys/wait.h>
18 #include <sys/types.h>
19
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <errno.h>
23 #include <pwd.h>
24 #include <grp.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <libgen.h>
29 #include <sched.h>
30 #include <linux/limits.h>
31 #include <signal.h>
32
33 #include "capabilities.h"
34 #include "elf.h"
35 #include "fs.h"
36 #include "jail.h"
37 #include "log.h"
38
39 #include <libubox/uloop.h>
40 #include <libubus.h>
41
42 #define STACK_SIZE (1024 * 1024)
43 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:"
44
45 #define NAMESPACE_MOUNT (1U << 0)
46 #define NAMESPACE_IPC (1U << 1)
47 #define NAMESPACE_NET (1U << 2)
48 #define NAMESPACE_PID (1U << 3)
49 #define NAMESPACE_USER (1U << 4)
50 #define NAMESPACE_UTS (1U << 5)
51 #define NAMESPACE_CGROUP (1U << 6)
52
53 static struct {
54 char *name;
55 char *hostname;
56 char **jail_argv;
57 char *seccomp;
58 char *capabilities;
59 char *user;
60 char *group;
61 char *extroot;
62 int no_new_privs;
63 int namespace;
64 int procfs;
65 int ronly;
66 int sysfs;
67 } opts;
68
69 extern int pivot_root(const char *new_root, const char *put_old);
70
71 int debug = 0;
72
73 static char child_stack[STACK_SIZE];
74
75 static int mkdir_p(char *dir, mode_t mask)
76 {
77 char *l = strrchr(dir, '/');
78 int ret;
79
80 if (!l)
81 return 0;
82
83 *l = '\0';
84
85 if (mkdir_p(dir, mask))
86 return -1;
87
88 *l = '/';
89
90 ret = mkdir(dir, mask);
91 if (ret && errno == EEXIST)
92 return 0;
93
94 if (ret)
95 ERROR("mkdir(%s, %d) failed: %m\n", dir, mask);
96
97 return ret;
98 }
99
100 static int _mount_bind(const char *root, const char *path, const char *target, int readonly, int strict, int error)
101 {
102 struct stat s;
103 char new[PATH_MAX];
104 int fd;
105 int remount_flags = MS_BIND | MS_REMOUNT;
106
107 if (stat(path, &s)) {
108 ERROR("stat(%s) failed: %m\n", path);
109 return error;
110 }
111
112 snprintf(new, sizeof(new), "%s%s", root, target?target:path);
113
114 if (S_ISDIR(s.st_mode)) {
115 mkdir_p(new, 0755);
116 } else {
117 mkdir_p(dirname(new), 0755);
118 snprintf(new, sizeof(new), "%s%s", root, target?target:path);
119 fd = creat(new, 0644);
120 if (fd == -1) {
121 ERROR("creat(%s) failed: %m\n", new);
122 return -1;
123 }
124 close(fd);
125 }
126
127 if (mount(path, new, NULL, MS_BIND, NULL)) {
128 ERROR("failed to mount -B %s %s: %m\n", path, new);
129 return -1;
130 }
131
132 if (readonly)
133 remount_flags |= MS_RDONLY;
134
135 if (strict)
136 remount_flags |= MS_NOEXEC | MS_NOSUID | MS_NODEV;
137
138 if ((strict || readonly) && mount(NULL, new, NULL, remount_flags, NULL)) {
139 ERROR("failed to remount (%s%s%s) %s: %m\n", readonly?"ro":"rw",
140 (readonly && strict)?", ":"", strict?"strict":"", new);
141 return -1;
142 }
143
144 DEBUG("mount -B %s %s (%s%s%s)\n", path, new,
145 readonly?"ro":"rw", (readonly && strict)?", ":"", strict?"strict":"");
146
147 return 0;
148 }
149
150 int mount_bind(const char *root, const char *path, int readonly, int error) {
151 return _mount_bind(root, path, NULL, readonly, 0, error);
152 }
153
154 static int build_jail_fs(void)
155 {
156 char jail_root[] = "/tmp/ujail-XXXXXX";
157 if (mkdtemp(jail_root) == NULL) {
158 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
159 return -1;
160 }
161
162 /* oldroot can't be MS_SHARED else pivot_root() fails */
163 if (mount("none", "/", NULL, MS_REC|MS_PRIVATE, NULL)) {
164 ERROR("private mount failed %m\n");
165 return -1;
166 }
167
168 if (opts.extroot) {
169 if (mount(opts.extroot, jail_root, NULL, MS_BIND | MS_REC, NULL)) {
170 ERROR("extroot mount failed %m\n");
171 return -1;
172 }
173 } else {
174 if (mount("tmpfs", jail_root, "tmpfs", MS_NOATIME, "mode=0755")) {
175 ERROR("tmpfs mount failed %m\n");
176 return -1;
177 }
178 }
179
180 if (chdir(jail_root)) {
181 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root);
182 return -1;
183 }
184
185 if (mount_all(jail_root)) {
186 ERROR("mount_all() failed\n");
187 return -1;
188 }
189
190 if (opts.namespace & NAMESPACE_NET) {
191 char hostdir[PATH_MAX], jailetc[PATH_MAX], jaillink[PATH_MAX];
192
193 snprintf(hostdir, PATH_MAX, "/tmp/resolv.conf-%s.d", opts.name);
194 mkdir_p(hostdir, 0755);
195 _mount_bind(jail_root, hostdir, "/tmp/resolv.conf.d", 1, 1, -1);
196 snprintf(jailetc, PATH_MAX, "%s/etc", jail_root);
197 mkdir_p(jailetc, 0755);
198 snprintf(jaillink, PATH_MAX, "%s/etc/resolv.conf", jail_root);
199 symlink("../tmp/resolv.conf.d/resolv.conf.auto", jaillink);
200 }
201
202 char dirbuf[sizeof(jail_root) + 4];
203 snprintf(dirbuf, sizeof(dirbuf), "%s/old", jail_root);
204 mkdir(dirbuf, 0755);
205
206 if (pivot_root(jail_root, dirbuf) == -1) {
207 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root, dirbuf);
208 return -1;
209 }
210 if (chdir("/")) {
211 ERROR("chdir(/) (after pivot_root) failed: %m\n");
212 return -1;
213 }
214
215 snprintf(dirbuf, sizeof(dirbuf), "/old%s", jail_root);
216 rmdir(dirbuf);
217 umount2("/old", MNT_DETACH);
218 rmdir("/old");
219
220 if (opts.procfs) {
221 mkdir("/proc", 0755);
222 mount("proc", "/proc", "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
223 }
224 if (opts.sysfs) {
225 mkdir("/sys", 0755);
226 mount("sysfs", "/sys", "sysfs", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
227 }
228 if (opts.ronly)
229 mount(NULL, "/", NULL, MS_RDONLY | MS_REMOUNT, 0);
230
231 return 0;
232 }
233
234 #define MAX_ENVP 8
235 static char** build_envp(const char *seccomp)
236 {
237 static char *envp[MAX_ENVP];
238 static char preload_var[PATH_MAX];
239 static char seccomp_var[PATH_MAX];
240 static char debug_var[] = "LD_DEBUG=all";
241 static char container_var[] = "container=ujail";
242 const char *preload_lib = find_lib("libpreload-seccomp.so");
243 int count = 0;
244
245 if (seccomp && !preload_lib) {
246 ERROR("failed to add preload-lib to env\n");
247 return NULL;
248 }
249 if (seccomp) {
250 snprintf(seccomp_var, sizeof(seccomp_var), "SECCOMP_FILE=%s", seccomp);
251 envp[count++] = seccomp_var;
252 snprintf(preload_var, sizeof(preload_var), "LD_PRELOAD=%s", preload_lib);
253 envp[count++] = preload_var;
254 }
255
256 if (is_extroot)
257 envp[count++] = container_var;
258
259 if (debug > 1)
260 envp[count++] = debug_var;
261
262 return envp;
263 }
264
265 static void usage(void)
266 {
267 fprintf(stderr, "ujail <options> -- <binary> <params ...>\n");
268 fprintf(stderr, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
269 fprintf(stderr, " -S <file>\tseccomp filter config\n");
270 fprintf(stderr, " -C <file>\tcapabilities drop config\n");
271 fprintf(stderr, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
272 fprintf(stderr, " -n <name>\tthe name of the jail\n");
273 fprintf(stderr, "namespace jail options:\n");
274 fprintf(stderr, " -h <hostname>\tchange the hostname of the jail\n");
275 fprintf(stderr, " -N\t\tjail has network namespace\n");
276 fprintf(stderr, " -r <file>\treadonly files that should be staged\n");
277 fprintf(stderr, " -w <file>\twriteable files that should be staged\n");
278 fprintf(stderr, " -p\t\tjail has /proc\n");
279 fprintf(stderr, " -s\t\tjail has /sys\n");
280 fprintf(stderr, " -l\t\tjail has /dev/log\n");
281 fprintf(stderr, " -u\t\tjail has a ubus socket\n");
282 fprintf(stderr, " -U <name>\tuser to run jailed process\n");
283 fprintf(stderr, " -G <name>\tgroup to run jailed process\n");
284 fprintf(stderr, " -o\t\tremont jail root (/) read only\n");
285 fprintf(stderr, " -R <dir>\texternal jail rootfs (system container)\n");
286 fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
287 and he has the same powers as root outside the jail,\n\
288 thus he can escape the jail and/or break stuff.\n\
289 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
290 If you use none of the namespace jail options,\n\
291 ujail will not use namespace/build a jail,\n\
292 and will only drop capabilities/apply seccomp filter.\n\n");
293 }
294
295 static int exec_jail(void *_notused)
296 {
297 struct passwd *p = NULL;
298 struct group *g = NULL;
299
300 if (opts.capabilities && drop_capabilities(opts.capabilities))
301 exit(EXIT_FAILURE);
302
303 if (opts.no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
304 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
305 exit(EXIT_FAILURE);
306 }
307
308 if (opts.namespace && opts.hostname && strlen(opts.hostname) > 0
309 && sethostname(opts.hostname, strlen(opts.hostname))) {
310 ERROR("sethostname(%s) failed: %m\n", opts.hostname);
311 exit(EXIT_FAILURE);
312 }
313
314 if (opts.namespace && build_jail_fs()) {
315 ERROR("failed to build jail fs\n");
316 exit(EXIT_FAILURE);
317 }
318
319 if (opts.user) {
320 p = getpwnam(opts.user);
321 if (!p) {
322 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
323 opts.user, errno, strerror(errno));
324 exit(EXIT_FAILURE);
325 }
326 }
327
328 if (opts.group) {
329 g = getgrnam(opts.group);
330 if (!g) {
331 ERROR("failed to get gid for group %s: %m\n", opts.group);
332 exit(EXIT_FAILURE);
333 }
334 }
335
336 if (p && p->pw_gid && initgroups(opts.user, p->pw_gid)) {
337 ERROR("failed to initgroups() for user %s: %m\n", opts.user);
338 exit(EXIT_FAILURE);
339 }
340
341 if (g && g->gr_gid && setgid(g->gr_gid)) {
342 ERROR("failed to set group id %d: %m\n", g?g->gr_gid:p->pw_gid);
343 exit(EXIT_FAILURE);
344 }
345
346 if (p && p->pw_uid && setuid(p->pw_uid)) {
347 ERROR("failed to set user id %d: %m\n", p->pw_uid);
348 exit(EXIT_FAILURE);
349 }
350
351
352 char **envp = build_envp(opts.seccomp);
353 if (!envp)
354 exit(EXIT_FAILURE);
355
356 INFO("exec-ing %s\n", *opts.jail_argv);
357 execve(*opts.jail_argv, opts.jail_argv, envp);
358 /* we get there only if execve fails */
359 ERROR("failed to execve %s: %m\n", *opts.jail_argv);
360 exit(EXIT_FAILURE);
361 }
362
363 static int jail_running = 1;
364 static int jail_return_code = 0;
365
366 static void jail_process_timeout_cb(struct uloop_timeout *t);
367 static struct uloop_timeout jail_process_timeout = {
368 .cb = jail_process_timeout_cb,
369 };
370
371 static void jail_process_handler(struct uloop_process *c, int ret)
372 {
373 uloop_timeout_cancel(&jail_process_timeout);
374 if (WIFEXITED(ret)) {
375 jail_return_code = WEXITSTATUS(ret);
376 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
377 } else {
378 jail_return_code = WTERMSIG(ret);
379 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
380 }
381 jail_running = 0;
382 uloop_end();
383 }
384
385 static struct uloop_process jail_process = {
386 .cb = jail_process_handler,
387 };
388
389 static void jail_process_timeout_cb(struct uloop_timeout *t)
390 {
391 DEBUG("jail process failed to stop, sending SIGKILL\n");
392 kill(jail_process.pid, SIGKILL);
393 }
394
395 static void jail_handle_signal(int signo)
396 {
397 DEBUG("forwarding signal %d to the jailed process\n", signo);
398 kill(jail_process.pid, signo);
399 }
400
401 static void netns_updown(bool start)
402 {
403 struct ubus_context *ctx = ubus_connect(NULL);
404 static struct blob_buf req;
405 uint32_t id;
406 pid_t pid = getpid();
407
408 if (!ctx)
409 return;
410
411 blob_buf_init(&req, 0);
412 blobmsg_add_string(&req, "jail", opts.name);
413 blobmsg_add_u32(&req, "pid", pid);
414 blobmsg_add_u8(&req, "start", start);
415
416 if (ubus_lookup_id(ctx, "network", &id) ||
417 ubus_invoke(ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
418 INFO("ubus request failed\n");
419
420 blob_buf_free(&req);
421 ubus_free(ctx);
422 }
423
424 int main(int argc, char **argv)
425 {
426 sigset_t sigmask;
427 uid_t uid = getuid();
428 char log[] = "/dev/log";
429 char ubus[] = "/var/run/ubus.sock";
430 int ch, i;
431
432 if (uid) {
433 ERROR("not root, aborting: %m\n");
434 return EXIT_FAILURE;
435 }
436
437 umask(022);
438 mount_list_init();
439 init_library_search();
440
441 while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
442 switch (ch) {
443 case 'd':
444 debug = atoi(optarg);
445 break;
446 case 'p':
447 opts.namespace |= NAMESPACE_MOUNT;
448 opts.procfs = 1;
449 break;
450 case 'o':
451 opts.namespace |= NAMESPACE_MOUNT;
452 opts.ronly = 1;
453 break;
454 case 'R':
455 opts.namespace |= NAMESPACE_MOUNT | NAMESPACE_UTS;
456 opts.extroot = optarg;
457 break;
458 case 's':
459 opts.namespace |= NAMESPACE_MOUNT;
460 opts.sysfs = 1;
461 break;
462 case 'S':
463 opts.seccomp = optarg;
464 add_mount(optarg, 1, -1);
465 break;
466 case 'C':
467 opts.capabilities = optarg;
468 break;
469 case 'c':
470 opts.no_new_privs = 1;
471 break;
472 case 'n':
473 opts.name = optarg;
474 break;
475 case 'N':
476 opts.namespace |= NAMESPACE_NET;
477 break;
478 case 'h':
479 opts.hostname = optarg;
480 break;
481 case 'r':
482 opts.namespace |= NAMESPACE_MOUNT;
483 add_path_and_deps(optarg, 1, 0, 0);
484 break;
485 case 'w':
486 opts.namespace |= NAMESPACE_MOUNT;
487 add_path_and_deps(optarg, 0, 0, 0);
488 break;
489 case 'u':
490 opts.namespace |= NAMESPACE_MOUNT;
491 add_mount(ubus, 0, -1);
492 break;
493 case 'l':
494 opts.namespace |= NAMESPACE_MOUNT;
495 add_mount(log, 0, -1);
496 break;
497 case 'U':
498 opts.user = optarg;
499 break;
500 case 'G':
501 opts.group = optarg;
502 break;
503 }
504 }
505
506 /* no <binary> param found */
507 if (argc - optind < 1) {
508 usage();
509 return EXIT_FAILURE;
510 }
511 if (!(opts.namespace||opts.capabilities||opts.seccomp)) {
512 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
513 usage();
514 return EXIT_FAILURE;
515 }
516 DEBUG("Using namespaces(%d), capabilities(%d), seccomp(%d)\n",
517 opts.namespace,
518 opts.capabilities != 0,
519 opts.seccomp != 0);
520
521 opts.jail_argv = &argv[optind];
522
523 if (!opts.extroot) {
524 if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
525 ERROR("failed to load dependencies\n");
526 return -1;
527 }
528
529 if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
530 ERROR("failed to load libpreload-seccomp.so\n");
531 return -1;
532 }
533 }
534
535 if (opts.name)
536 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
537
538 uloop_init();
539
540 sigfillset(&sigmask);
541 for (i = 0; i < _NSIG; i++) {
542 struct sigaction s = { 0 };
543
544 if (!sigismember(&sigmask, i))
545 continue;
546 if ((i == SIGCHLD) || (i == SIGPIPE))
547 continue;
548
549 s.sa_handler = jail_handle_signal;
550 sigaction(i, &s, NULL);
551 }
552
553 if (opts.namespace) {
554 int flags = SIGCHLD | CLONE_NEWPID | CLONE_NEWIPC;
555
556 if (opts.namespace & NAMESPACE_MOUNT) {
557 flags |= CLONE_NEWNS;
558 add_mount("/dev/full", 0, -1);
559 add_mount("/dev/null", 0, -1);
560 add_mount("/dev/random", 0, -1);
561 add_mount("/dev/urandom", 0, -1);
562 add_mount("/dev/tty", 0, -1);
563 add_mount("/dev/zero", 0, -1);
564 add_mount("/dev/console", 0, -1);
565
566 if (opts.user || opts.group) {
567 add_mount("/etc/passwd", 0, -1);
568 add_mount("/etc/group", 0, -1);
569 }
570
571 if (!(opts.namespace & CLONE_NEWNET)) {
572 add_mount("/etc/resolv.conf", 0, -1);
573 }
574 }
575
576 if (opts.hostname)
577 flags |= CLONE_NEWUTS;
578
579 if (opts.namespace & NAMESPACE_NET) {
580 unshare(CLONE_NEWNET);
581 netns_updown(true);
582 };
583
584 jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, flags, NULL);
585 } else {
586 jail_process.pid = fork();
587 }
588
589 if (jail_process.pid > 0) {
590 /* parent process */
591 uloop_process_add(&jail_process);
592 uloop_run();
593 if (jail_running) {
594 DEBUG("uloop interrupted, killing jail process\n");
595 kill(jail_process.pid, SIGTERM);
596 uloop_timeout_set(&jail_process_timeout, 1000);
597 uloop_run();
598 }
599 uloop_done();
600 if (opts.namespace & NAMESPACE_NET)
601 netns_updown(false);
602
603 return jail_return_code;
604 } else if (jail_process.pid == 0) {
605 /* fork child process */
606 return exec_jail(NULL);
607 } else {
608 ERROR("failed to clone/fork: %m\n");
609 return EXIT_FAILURE;
610 }
611 }