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