aa9285c88dc896743a11583fc0dd20a71c59ef56
[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 <linux/filter.h>
32 #include <signal.h>
33
34 #include "capabilities.h"
35 #include "elf.h"
36 #include "fs.h"
37 #include "jail.h"
38 #include "log.h"
39 #include "seccomp-oci.h"
40
41 #include <libubox/utils.h>
42 #include <libubox/blobmsg.h>
43 #include <libubox/blobmsg_json.h>
44 #include <libubox/list.h>
45 #include <libubox/vlist.h>
46 #include <libubox/uloop.h>
47 #include <libubus.h>
48
49 #ifndef CLONE_NEWCGROUP
50 #define CLONE_NEWCGROUP 0x02000000
51 #endif
52
53 #define STACK_SIZE (1024 * 1024)
54 #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:"
55
56 static struct {
57 char *name;
58 char *hostname;
59 char **jail_argv;
60 char *cwd;
61 char *seccomp;
62 struct sock_fprog *ociseccomp;
63 char *capabilities;
64 struct jail_capset capset;
65 char *user;
66 char *group;
67 char *extroot;
68 char *overlaydir;
69 char *tmpoverlaysize;
70 char **envp;
71 char *uidmap;
72 char *gidmap;
73 int no_new_privs;
74 int namespace;
75 int procfs;
76 int ronly;
77 int sysfs;
78 int console;
79 int pw_uid;
80 int pw_gid;
81 int gr_gid;
82 int require_jail;
83 } opts;
84
85 static struct blob_buf ocibuf;
86
87 extern int pivot_root(const char *new_root, const char *put_old);
88
89 int debug = 0;
90
91 static char child_stack[STACK_SIZE];
92
93 int console_fd;
94
95 static int mkdir_p(char *dir, mode_t mask)
96 {
97 char *l = strrchr(dir, '/');
98 int ret;
99
100 if (!l)
101 return 0;
102
103 *l = '\0';
104
105 if (mkdir_p(dir, mask))
106 return -1;
107
108 *l = '/';
109
110 ret = mkdir(dir, mask);
111 if (ret && errno == EEXIST)
112 return 0;
113
114 if (ret)
115 ERROR("mkdir(%s, %d) failed: %m\n", dir, mask);
116
117 return ret;
118 }
119
120 static int _mount_bind(const char *root, const char *path, const char *target, int readonly, int strict, int error)
121 {
122 struct stat s;
123 char new[PATH_MAX];
124 int fd;
125 int remount_flags = MS_BIND | MS_REMOUNT;
126
127 if (stat(path, &s)) {
128 ERROR("stat(%s) failed: %m\n", path);
129 return error;
130 }
131
132 snprintf(new, sizeof(new), "%s%s", root, target?target:path);
133
134 if (S_ISDIR(s.st_mode)) {
135 mkdir_p(new, 0755);
136 } else {
137 mkdir_p(dirname(new), 0755);
138 snprintf(new, sizeof(new), "%s%s", root, target?target:path);
139 fd = creat(new, 0644);
140 if (fd == -1) {
141 ERROR("creat(%s) failed: %m\n", new);
142 return -1;
143 }
144 close(fd);
145 }
146
147 if (mount(path, new, NULL, MS_BIND, NULL)) {
148 ERROR("failed to mount -B %s %s: %m\n", path, new);
149 return -1;
150 }
151
152 if (readonly)
153 remount_flags |= MS_RDONLY;
154
155 if (strict)
156 remount_flags |= MS_NOEXEC | MS_NOSUID | MS_NODEV;
157
158 if ((strict || readonly) && mount(NULL, new, NULL, remount_flags, NULL)) {
159 ERROR("failed to remount (%s%s%s) %s: %m\n", readonly?"ro":"rw",
160 (readonly && strict)?", ":"", strict?"strict":"", new);
161 return -1;
162 }
163
164 DEBUG("mount -B %s %s (%s%s%s)\n", path, new,
165 readonly?"ro":"rw", (readonly && strict)?", ":"", strict?"strict":"");
166
167 return 0;
168 }
169
170 int mount_bind(const char *root, const char *path, int readonly, int error) {
171 return _mount_bind(root, path, NULL, readonly, 0, error);
172 }
173
174 static int mount_overlay(char *jail_root, char *overlaydir) {
175 char *upperdir, *workdir, *optsstr, *upperetc, *upperresolvconf;
176 const char mountoptsformat[] = "lowerdir=%s,upperdir=%s,workdir=%s";
177 int ret = -1, fd;
178
179 if (asprintf(&upperdir, "%s%s", overlaydir, "/upper") < 0)
180 goto out;
181
182 if (asprintf(&workdir, "%s%s", overlaydir, "/work") < 0)
183 goto upper_printf;
184
185 if (asprintf(&optsstr, mountoptsformat, jail_root, upperdir, workdir) < 0)
186 goto work_printf;
187
188 if (mkdir_p(upperdir, 0755) || mkdir_p(workdir, 0755))
189 goto opts_printf;
190
191 /*
192 * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
193 * this is to work-around a bug in overlayfs described in the overlayfs-userns
194 * patch:
195 * 3. modification of a file 'hithere' which is in l but not yet
196 * in u, and which is not owned by T, is not allowed, even if
197 * writes to u are allowed. This may be a bug in overlayfs,
198 * but it is safe behavior.
199 */
200 if (asprintf(&upperetc, "%s/etc", upperdir) < 0)
201 goto opts_printf;
202
203 if (mkdir_p(upperetc, 0755))
204 goto upper_etc_printf;
205
206 if (asprintf(&upperresolvconf, "%s/resolv.conf", upperetc) < 0)
207 goto upper_etc_printf;
208
209 fd = creat(upperresolvconf, 0644);
210 if (fd == -1) {
211 ERROR("creat(%s) failed: %m\n", upperresolvconf);
212 goto upper_resolvconf_printf;
213 }
214 close(fd);
215
216 DEBUG("mount -t overlay %s %s (%s)\n", jail_root, jail_root, optsstr);
217
218 if (mount(jail_root, jail_root, "overlay", MS_NOATIME, optsstr))
219 goto opts_printf;
220
221 ret = 0;
222
223 upper_resolvconf_printf:
224 free(upperresolvconf);
225 upper_etc_printf:
226 free(upperetc);
227 opts_printf:
228 free(optsstr);
229 work_printf:
230 free(workdir);
231 upper_printf:
232 free(upperdir);
233 out:
234 return ret;
235 }
236
237 static void pass_console(int console_fd)
238 {
239 struct ubus_context *ctx = ubus_connect(NULL);
240 static struct blob_buf req;
241 uint32_t id;
242
243 if (!ctx)
244 return;
245
246 blob_buf_init(&req, 0);
247 blobmsg_add_string(&req, "name", opts.name);
248
249 if (ubus_lookup_id(ctx, "container", &id) ||
250 ubus_invoke_fd(ctx, id, "console_set", req.head, NULL, NULL, 3000, console_fd))
251 INFO("ubus request failed\n");
252 else
253 close(console_fd);
254
255 blob_buf_free(&req);
256 ubus_free(ctx);
257 }
258
259 static int create_dev_console(const char *jail_root)
260 {
261 char *console_fname;
262 char dev_console_path[PATH_MAX];
263 int slave_console_fd;
264
265 /* Open UNIX/98 virtual console */
266 console_fd = posix_openpt(O_RDWR | O_NOCTTY);
267 if (console_fd == -1)
268 return -1;
269
270 console_fname = ptsname(console_fd);
271 DEBUG("got console fd %d and PTS client name %s\n", console_fd, console_fname);
272 if (!console_fname)
273 goto no_console;
274
275 grantpt(console_fd);
276 unlockpt(console_fd);
277
278 /* pass PTY master to procd */
279 pass_console(console_fd);
280
281 /* mount-bind PTY slave to /dev/console in jail */
282 snprintf(dev_console_path, sizeof(dev_console_path), "%s/dev/console", jail_root);
283 close(creat(dev_console_path, 0620));
284
285 if (mount(console_fname, dev_console_path, NULL, MS_BIND, NULL))
286 goto no_console;
287
288 /* use PTY slave for stdio */
289 slave_console_fd = open(console_fname, O_RDWR); /* | O_NOCTTY */
290 dup2(slave_console_fd, 0);
291 dup2(slave_console_fd, 1);
292 dup2(slave_console_fd, 2);
293 close(slave_console_fd);
294
295 INFO("using guest console %s\n", console_fname);
296
297 return 0;
298
299 no_console:
300 close(console_fd);
301 return 1;
302 }
303
304 static int build_jail_fs(void)
305 {
306 char jail_root[] = "/tmp/ujail-XXXXXX";
307 char tmpovdir[] = "/tmp/ujail-overlay-XXXXXX";
308 char tmpdevdir[] = "/tmp/ujail-XXXXXX/dev";
309 char tmpdevptsdir[] = "/tmp/ujail-XXXXXX/dev/pts";
310 char *overlaydir = NULL;
311
312 if (mkdtemp(jail_root) == NULL) {
313 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
314 return -1;
315 }
316
317 /* oldroot can't be MS_SHARED else pivot_root() fails */
318 if (mount("none", "/", NULL, MS_REC|MS_PRIVATE, NULL)) {
319 ERROR("private mount failed %m\n");
320 return -1;
321 }
322
323 if (opts.extroot) {
324 if (mount(opts.extroot, jail_root, NULL, MS_BIND, NULL)) {
325 ERROR("extroot mount failed %m\n");
326 return -1;
327 }
328 } else {
329 if (mount("tmpfs", jail_root, "tmpfs", MS_NOATIME, "mode=0755")) {
330 ERROR("tmpfs mount failed %m\n");
331 return -1;
332 }
333 }
334
335 if (opts.tmpoverlaysize) {
336 char mountoptsstr[] = "mode=0755,size=XXXXXXXX";
337
338 snprintf(mountoptsstr, sizeof(mountoptsstr),
339 "mode=0755,size=%s", opts.tmpoverlaysize);
340 if (mkdtemp(tmpovdir) == NULL) {
341 ERROR("mkdtemp(%s) failed: %m\n", jail_root);
342 return -1;
343 }
344 if (mount("tmpfs", tmpovdir, "tmpfs", MS_NOATIME,
345 mountoptsstr)) {
346 ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts.tmpoverlaysize);
347 return -1;
348 }
349 overlaydir = tmpovdir;
350 }
351
352 if (opts.overlaydir)
353 overlaydir = opts.overlaydir;
354
355 if (overlaydir)
356 mount_overlay(jail_root, overlaydir);
357
358 if (chdir(jail_root)) {
359 ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root);
360 return -1;
361 }
362
363 snprintf(tmpdevdir, sizeof(tmpdevdir), "%s/dev", jail_root);
364 mkdir_p(tmpdevdir, 0755);
365 if (mount(NULL, tmpdevdir, "tmpfs", MS_NOATIME | MS_NOEXEC | MS_NOSUID, "size=1M"))
366 return -1;
367
368 snprintf(tmpdevptsdir, sizeof(tmpdevptsdir), "%s/dev/pts", jail_root);
369 mkdir_p(tmpdevptsdir, 0755);
370 if (mount(NULL, tmpdevptsdir, "devpts", MS_NOATIME | MS_NOEXEC | MS_NOSUID, NULL))
371 return -1;
372
373 if (opts.console)
374 create_dev_console(jail_root);
375
376 if (mount_all(jail_root)) {
377 ERROR("mount_all() failed\n");
378 return -1;
379 }
380
381 if (opts.namespace & CLONE_NEWNET) {
382 char hostdir[PATH_MAX], jailetc[PATH_MAX], jaillink[PATH_MAX];
383
384 snprintf(hostdir, PATH_MAX, "/tmp/resolv.conf-%s.d", opts.name);
385 mkdir_p(hostdir, 0755);
386 _mount_bind(jail_root, hostdir, "/tmp/resolv.conf.d", 1, 1, -1);
387 snprintf(jailetc, PATH_MAX, "%s/etc", jail_root);
388 mkdir_p(jailetc, 0755);
389 snprintf(jaillink, PATH_MAX, "%s/etc/resolv.conf", jail_root);
390 if (overlaydir)
391 unlink(jaillink);
392 symlink("../tmp/resolv.conf.d/resolv.conf.auto", jaillink);
393 }
394
395 char dirbuf[sizeof(jail_root) + 4];
396 snprintf(dirbuf, sizeof(dirbuf), "%s/old", jail_root);
397 mkdir(dirbuf, 0755);
398
399 if (pivot_root(jail_root, dirbuf) == -1) {
400 ERROR("pivot_root(%s, %s) failed: %m\n", jail_root, dirbuf);
401 return -1;
402 }
403 if (chdir("/")) {
404 ERROR("chdir(/) (after pivot_root) failed: %m\n");
405 return -1;
406 }
407
408 snprintf(dirbuf, sizeof(dirbuf), "/old%s", jail_root);
409 umount2(dirbuf, MNT_DETACH);
410 rmdir(dirbuf);
411 if (opts.tmpoverlaysize) {
412 char tmpdirbuf[sizeof(tmpovdir) + 4];
413 snprintf(tmpdirbuf, sizeof(tmpdirbuf), "/old%s", tmpovdir);
414 umount2(tmpdirbuf, MNT_DETACH);
415 rmdir(tmpdirbuf);
416 }
417
418 umount2("/old", MNT_DETACH);
419 rmdir("/old");
420
421 if (opts.procfs) {
422 mkdir("/proc", 0755);
423 mount("proc", "/proc", "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
424 /*
425 * make /proc/sys read-only while keeping read-write to
426 * /proc/sys/net if CLONE_NEWNET is set.
427 */
428 if (opts.namespace & CLONE_NEWNET)
429 mount("/proc/sys/net", "/proc/self/net", NULL, MS_BIND, 0);
430
431 mount("/proc/sys", "/proc/sys", NULL, MS_BIND, 0);
432 mount(NULL, "/proc/sys", NULL, MS_REMOUNT | MS_RDONLY, 0);
433 mount(NULL, "/proc", NULL, MS_REMOUNT, 0);
434
435 if (opts.namespace & CLONE_NEWNET)
436 mount("/proc/self/net", "/proc/sys/net", NULL, MS_MOVE, 0);
437 }
438 if (opts.sysfs) {
439 mkdir("/sys", 0755);
440 mount("sysfs", "/sys", "sysfs", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RDONLY, 0);
441 }
442 if (opts.ronly)
443 mount(NULL, "/", NULL, MS_RDONLY | MS_REMOUNT, 0);
444
445 return 0;
446 }
447
448 static int write_uid_gid_map(pid_t child_pid, bool gidmap, char *mapstr)
449 {
450 int map_file;
451 char map_path[64];
452
453 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
454 child_pid, gidmap?"gid_map":"uid_map") < 0)
455 return -1;
456
457 if ((map_file = open(map_path, O_WRONLY)) == -1)
458 return -1;
459
460 if (dprintf(map_file, "%s", mapstr)) {
461 close(map_file);
462 return -1;
463 }
464
465 close(map_file);
466 free(mapstr);
467 return 0;
468 }
469
470 static int write_single_uid_gid_map(pid_t child_pid, bool gidmap, int id)
471 {
472 int map_file;
473 char map_path[64];
474 const char *map_format = "%d %d %d\n";
475 if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
476 child_pid, gidmap?"gid_map":"uid_map") < 0)
477 return -1;
478
479 if ((map_file = open(map_path, O_WRONLY)) == -1)
480 return -1;
481
482 if (dprintf(map_file, map_format, 0, id, 1) == -1) {
483 close(map_file);
484 return -1;
485 }
486
487 close(map_file);
488 return 0;
489 }
490
491 static int write_setgroups(pid_t child_pid, bool allow)
492 {
493 int setgroups_file;
494 char setgroups_path[64];
495
496 if (snprintf(setgroups_path, sizeof(setgroups_path), "/proc/%d/setgroups",
497 child_pid) < 0) {
498 return -1;
499 }
500
501 if ((setgroups_file = open(setgroups_path, O_WRONLY)) == -1) {
502 return -1;
503 }
504
505 if (dprintf(setgroups_file, "%s", allow?"allow":"deny") == -1) {
506 close(setgroups_file);
507 return -1;
508 }
509
510 close(setgroups_file);
511 return 0;
512 }
513
514 static void get_jail_user(int *user, int *user_gid, int *gr_gid)
515 {
516 struct passwd *p = NULL;
517 struct group *g = NULL;
518
519 if (opts.user) {
520 p = getpwnam(opts.user);
521 if (!p) {
522 ERROR("failed to get uid/gid for user %s: %d (%s)\n",
523 opts.user, errno, strerror(errno));
524 exit(EXIT_FAILURE);
525 }
526 *user = p->pw_uid;
527 *user_gid = p->pw_gid;
528 } else {
529 *user = -1;
530 *user_gid = -1;
531 }
532
533 if (opts.group) {
534 g = getgrnam(opts.group);
535 if (!g) {
536 ERROR("failed to get gid for group %s: %m\n", opts.group);
537 exit(EXIT_FAILURE);
538 }
539 *gr_gid = g->gr_gid;
540 } else {
541 *gr_gid = -1;
542 }
543 };
544
545 static void set_jail_user(int pw_uid, int user_gid, int gr_gid)
546 {
547 if (opts.user && (user_gid != -1) && initgroups(opts.user, user_gid)) {
548 ERROR("failed to initgroups() for user %s: %m\n", opts.user);
549 exit(EXIT_FAILURE);
550 }
551
552 if ((gr_gid != -1) && setregid(gr_gid, gr_gid)) {
553 ERROR("failed to set group id %d: %m\n", gr_gid);
554 exit(EXIT_FAILURE);
555 }
556
557 if ((pw_uid != -1) && setreuid(pw_uid, pw_uid)) {
558 ERROR("failed to set user id %d: %m\n", pw_uid);
559 exit(EXIT_FAILURE);
560 }
561 }
562
563 #define MAX_ENVP 8
564 static char** build_envp(const char *seccomp, char **ocienvp)
565 {
566 static char *envp[MAX_ENVP];
567 static char preload_var[PATH_MAX];
568 static char seccomp_var[PATH_MAX];
569 static char debug_var[] = "LD_DEBUG=all";
570 static char container_var[] = "container=ujail";
571 const char *preload_lib = find_lib("libpreload-seccomp.so");
572 char **addenv;
573
574 int count = 0;
575
576 if (seccomp && !preload_lib) {
577 ERROR("failed to add preload-lib to env\n");
578 return NULL;
579 }
580 if (seccomp) {
581 snprintf(seccomp_var, sizeof(seccomp_var), "SECCOMP_FILE=%s", seccomp);
582 envp[count++] = seccomp_var;
583 snprintf(preload_var, sizeof(preload_var), "LD_PRELOAD=%s", preload_lib);
584 envp[count++] = preload_var;
585 }
586
587 envp[count++] = container_var;
588
589 if (debug > 1)
590 envp[count++] = debug_var;
591
592 addenv = ocienvp;
593 while (addenv && *addenv) {
594 envp[count++] = *(addenv++);
595 if (count >= MAX_ENVP) {
596 ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP);
597 break;
598 }
599 }
600 return envp;
601 }
602
603 static void usage(void)
604 {
605 fprintf(stderr, "ujail <options> -- <binary> <params ...>\n");
606 fprintf(stderr, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
607 fprintf(stderr, " -S <file>\tseccomp filter config\n");
608 fprintf(stderr, " -C <file>\tcapabilities drop config\n");
609 fprintf(stderr, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
610 fprintf(stderr, " -n <name>\tthe name of the jail\n");
611 fprintf(stderr, "namespace jail options:\n");
612 fprintf(stderr, " -h <hostname>\tchange the hostname of the jail\n");
613 fprintf(stderr, " -N\t\tjail has network namespace\n");
614 fprintf(stderr, " -f\t\tjail has user namespace\n");
615 fprintf(stderr, " -F\t\tjail has cgroups namespace\n");
616 fprintf(stderr, " -r <file>\treadonly files that should be staged\n");
617 fprintf(stderr, " -w <file>\twriteable files that should be staged\n");
618 fprintf(stderr, " -p\t\tjail has /proc\n");
619 fprintf(stderr, " -s\t\tjail has /sys\n");
620 fprintf(stderr, " -l\t\tjail has /dev/log\n");
621 fprintf(stderr, " -u\t\tjail has a ubus socket\n");
622 fprintf(stderr, " -U <name>\tuser to run jailed process\n");
623 fprintf(stderr, " -G <name>\tgroup to run jailed process\n");
624 fprintf(stderr, " -o\t\tremont jail root (/) read only\n");
625 fprintf(stderr, " -R <dir>\texternal jail rootfs (system container)\n");
626 fprintf(stderr, " -O <dir>\tdirectory for r/w overlayfs\n");
627 fprintf(stderr, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
628 fprintf(stderr, " -E\t\tfail if jail cannot be setup\n");
629 fprintf(stderr, " -y\t\tprovide jail console\n");
630 fprintf(stderr, " -J <dir>\tstart OCI bundle\n");
631 fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
632 and he has the same powers as root outside the jail,\n\
633 thus he can escape the jail and/or break stuff.\n\
634 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
635 If you use none of the namespace jail options,\n\
636 ujail will not use namespace/build a jail,\n\
637 and will only drop capabilities/apply seccomp filter.\n\n");
638 }
639
640 static int exec_jail(void *pipes_ptr)
641 {
642 int *pipes = (int*)pipes_ptr;
643 char buf[1];
644 int pw_uid, pw_gid, gr_gid;
645
646 close(pipes[0]);
647 close(pipes[3]);
648
649 buf[0] = 'i';
650 if (write(pipes[1], buf, 1) < 1) {
651 ERROR("can't write to parent\n");
652 exit(EXIT_FAILURE);
653 }
654 if (read(pipes[2], buf, 1) < 1) {
655 ERROR("can't read from parent\n");
656 exit(EXIT_FAILURE);
657 }
658 if (buf[0] != 'O') {
659 ERROR("parent had an error, child exiting\n");
660 exit(EXIT_FAILURE);
661 }
662
663 close(pipes[1]);
664 close(pipes[2]);
665
666 if (opts.namespace & CLONE_NEWUSER) {
667 if (setregid(0, 0) < 0) {
668 ERROR("setgid\n");
669 exit(EXIT_FAILURE);
670 }
671 if (setreuid(0, 0) < 0) {
672 ERROR("setuid\n");
673 exit(EXIT_FAILURE);
674 }
675 if (setgroups(0, NULL) < 0) {
676 ERROR("setgroups\n");
677 exit(EXIT_FAILURE);
678 }
679 }
680
681 if (opts.namespace && opts.hostname && strlen(opts.hostname) > 0
682 && sethostname(opts.hostname, strlen(opts.hostname))) {
683 ERROR("sethostname(%s) failed: %m\n", opts.hostname);
684 exit(EXIT_FAILURE);
685 }
686
687 if ((opts.namespace & CLONE_NEWNS) && build_jail_fs()) {
688 ERROR("failed to build jail fs\n");
689 exit(EXIT_FAILURE);
690 }
691
692 if (applyOCIcapabilities(opts.capset))
693 exit(EXIT_FAILURE);
694
695 if (opts.capabilities && drop_capabilities(opts.capabilities))
696 exit(EXIT_FAILURE);
697
698 if (opts.no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
699 ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
700 exit(EXIT_FAILURE);
701 }
702
703 if (!(opts.namespace & CLONE_NEWUSER)) {
704 get_jail_user(&pw_uid, &pw_gid, &gr_gid);
705
706 set_jail_user(opts.pw_uid?:pw_uid, opts.pw_gid?:pw_gid, opts.gr_gid?:gr_gid);
707 }
708
709 char **envp = build_envp(opts.seccomp, opts.envp);
710 if (!envp)
711 exit(EXIT_FAILURE);
712
713 if (opts.ociseccomp && applyOCIlinuxseccomp(opts.ociseccomp))
714 exit(EXIT_FAILURE);
715
716 INFO("exec-ing %s\n", *opts.jail_argv);
717 execve(*opts.jail_argv, opts.jail_argv, envp);
718 /* we get there only if execve fails */
719 ERROR("failed to execve %s: %m\n", *opts.jail_argv);
720 exit(EXIT_FAILURE);
721 }
722
723 static int jail_running = 1;
724 static int jail_return_code = 0;
725
726 static void jail_process_timeout_cb(struct uloop_timeout *t);
727 static struct uloop_timeout jail_process_timeout = {
728 .cb = jail_process_timeout_cb,
729 };
730
731 static void jail_process_handler(struct uloop_process *c, int ret)
732 {
733 uloop_timeout_cancel(&jail_process_timeout);
734 if (WIFEXITED(ret)) {
735 jail_return_code = WEXITSTATUS(ret);
736 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
737 } else {
738 jail_return_code = WTERMSIG(ret);
739 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
740 }
741 jail_running = 0;
742 uloop_end();
743 }
744
745 static struct uloop_process jail_process = {
746 .cb = jail_process_handler,
747 };
748
749 static void jail_process_timeout_cb(struct uloop_timeout *t)
750 {
751 DEBUG("jail process failed to stop, sending SIGKILL\n");
752 kill(jail_process.pid, SIGKILL);
753 }
754
755 static void jail_handle_signal(int signo)
756 {
757 DEBUG("forwarding signal %d to the jailed process\n", signo);
758 kill(jail_process.pid, signo);
759 }
760
761 static int netns_open_pid(const pid_t target_ns)
762 {
763 char pid_net_path[PATH_MAX];
764
765 snprintf(pid_net_path, sizeof(pid_net_path), "/proc/%u/ns/net", target_ns);
766
767 return open(pid_net_path, O_RDONLY);
768 }
769
770 static void netns_updown(pid_t pid, bool start)
771 {
772 struct ubus_context *ctx = ubus_connect(NULL);
773 static struct blob_buf req;
774 uint32_t id;
775
776 if (!ctx)
777 return;
778
779 blob_buf_init(&req, 0);
780 blobmsg_add_string(&req, "jail", opts.name);
781 blobmsg_add_u32(&req, "pid", pid);
782 blobmsg_add_u8(&req, "start", start);
783
784 if (ubus_lookup_id(ctx, "network", &id) ||
785 ubus_invoke(ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
786 INFO("ubus request failed\n");
787
788 blob_buf_free(&req);
789 ubus_free(ctx);
790 }
791
792
793 enum {
794 OCI_ROOT_PATH,
795 OCI_ROOT_READONLY,
796 __OCI_ROOT_MAX,
797 };
798
799 static const struct blobmsg_policy oci_root_policy[] = {
800 [OCI_ROOT_PATH] = { "path", BLOBMSG_TYPE_STRING },
801 [OCI_ROOT_READONLY] = { "readonly", BLOBMSG_TYPE_BOOL },
802 };
803
804 static int parseOCIroot(const char *jsonfile, struct blob_attr *msg)
805 {
806 static char rootpath[PATH_MAX] = { 0 };
807 struct blob_attr *tb[__OCI_ROOT_MAX];
808 char *cur;
809
810 blobmsg_parse(oci_root_policy, __OCI_ROOT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
811
812 if (!tb[OCI_ROOT_PATH])
813 return ENODATA;
814
815 strncpy(rootpath, jsonfile, PATH_MAX);
816 cur = strrchr(rootpath, '/');
817
818 if (!cur)
819 return ENOTDIR;
820
821 *(++cur) = '\0';
822 strncat(rootpath, blobmsg_get_string(tb[OCI_ROOT_PATH]), PATH_MAX - (strlen(rootpath) + 1));
823
824 opts.extroot = rootpath;
825
826 opts.ronly = blobmsg_get_bool(tb[OCI_ROOT_READONLY]);
827
828 return 0;
829 }
830
831
832 enum {
833 OCI_MOUNT_SOURCE,
834 OCI_MOUNT_DESTINATION,
835 OCI_MOUNT_TYPE,
836 OCI_MOUNT_OPTIONS,
837 __OCI_MOUNT_MAX,
838 };
839
840 static const struct blobmsg_policy oci_mount_policy[] = {
841 [OCI_MOUNT_SOURCE] = { "source", BLOBMSG_TYPE_STRING },
842 [OCI_MOUNT_DESTINATION] = { "destination", BLOBMSG_TYPE_STRING },
843 [OCI_MOUNT_TYPE] = { "type", BLOBMSG_TYPE_STRING },
844 [OCI_MOUNT_OPTIONS] = { "options", BLOBMSG_TYPE_ARRAY },
845 };
846
847 static int parseOCImount(struct blob_attr *msg)
848 {
849 struct blob_attr *tb[__OCI_MOUNT_MAX];
850
851 blobmsg_parse(oci_mount_policy, __OCI_MOUNT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
852
853 if (!tb[OCI_MOUNT_DESTINATION])
854 return EINVAL;
855
856 if (!strcmp("proc", blobmsg_get_string(tb[OCI_MOUNT_TYPE])) &&
857 !strcmp("/proc", blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]))) {
858 opts.procfs = true;
859 return 0;
860 }
861
862 if (!strcmp("sysfs", blobmsg_get_string(tb[OCI_MOUNT_TYPE])) &&
863 !strcmp("/sys", blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]))) {
864 opts.sysfs = true;
865 return 0;
866 }
867
868 if (!strcmp("tmpfs", blobmsg_get_string(tb[OCI_MOUNT_TYPE])) &&
869 !strcmp("/dev", blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]))) {
870 /* we always mount a small tmpfs on /dev */
871 return 0;
872 }
873
874 INFO("ignoring unsupported mount %s %s -t %s -o %s\n",
875 blobmsg_get_string(tb[OCI_MOUNT_SOURCE]),
876 blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]),
877 blobmsg_get_string(tb[OCI_MOUNT_TYPE]),
878 blobmsg_format_json(tb[OCI_MOUNT_OPTIONS], true));
879
880 return 0;
881 };
882
883
884 enum {
885 OCI_PROCESS_USER_UID,
886 OCI_PROCESS_USER_GID,
887 OCI_PROCESS_USER_UMASK,
888 OCI_PROCESS_USER_ADDITIONALGIDS,
889 __OCI_PROCESS_USER_MAX,
890 };
891
892 static const struct blobmsg_policy oci_process_user_policy[] = {
893 [OCI_PROCESS_USER_UID] = { "uid", BLOBMSG_TYPE_INT32 },
894 [OCI_PROCESS_USER_GID] = { "gid", BLOBMSG_TYPE_INT32 },
895 [OCI_PROCESS_USER_UMASK] = { "umask", BLOBMSG_TYPE_INT32 },
896 [OCI_PROCESS_USER_ADDITIONALGIDS] = { "additionalGids", BLOBMSG_TYPE_ARRAY },
897 };
898
899 static int parseOCIprocessuser(struct blob_attr *msg) {
900 struct blob_attr *tb[__OCI_PROCESS_USER_MAX];
901
902 blobmsg_parse(oci_process_user_policy, __OCI_PROCESS_USER_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
903
904 if (tb[OCI_PROCESS_USER_UID])
905 opts.pw_uid = blobmsg_get_u32(tb[OCI_PROCESS_USER_UID]);
906
907 if (tb[OCI_PROCESS_USER_GID]) {
908 opts.pw_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
909 opts.gr_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
910 }
911
912 /* ToDo: umask, additional GIDs */
913
914 return 0;
915 }
916
917 enum {
918 OCI_PROCESS_ARGS,
919 OCI_PROCESS_CAPABILITIES,
920 OCI_PROCESS_CWD,
921 OCI_PROCESS_ENV,
922 OCI_PROCESS_NONEWPRIVILEGES,
923 OCI_PROCESS_RLIMITS,
924 OCI_PROCESS_TERMINAL,
925 OCI_PROCESS_USER,
926 __OCI_PROCESS_MAX,
927 };
928
929 static const struct blobmsg_policy oci_process_policy[] = {
930 [OCI_PROCESS_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
931 [OCI_PROCESS_CAPABILITIES] = { "capabilities", BLOBMSG_TYPE_TABLE },
932 [OCI_PROCESS_CWD] = { "cwd", BLOBMSG_TYPE_STRING },
933 [OCI_PROCESS_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
934 [OCI_PROCESS_NONEWPRIVILEGES] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL },
935 [OCI_PROCESS_RLIMITS] = { "rlimits", BLOBMSG_TYPE_ARRAY },
936 [OCI_PROCESS_TERMINAL] = { "terminal", BLOBMSG_TYPE_BOOL },
937 [OCI_PROCESS_USER] = { "user", BLOBMSG_TYPE_TABLE },
938 };
939
940 static int parseOCIprocess(struct blob_attr *msg)
941 {
942 struct blob_attr *tb[__OCI_PROCESS_MAX];
943 struct blob_attr *cur;
944 unsigned int sz = 0;
945 int rem;
946 int res;
947
948 blobmsg_parse(oci_process_policy, __OCI_PROCESS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
949
950 if (!tb[OCI_PROCESS_ARGS])
951 return ENOENT;
952
953 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ARGS], rem)
954 ++sz;
955
956 if (!sz)
957 return ENODATA;
958
959 opts.jail_argv = calloc(1 + sz, sizeof(char*));
960 if (!opts.jail_argv)
961 return ENOMEM;
962
963 sz = 0;
964 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ARGS], rem)
965 opts.jail_argv[sz++] = blobmsg_get_string(cur);
966
967 opts.console = blobmsg_get_bool(tb[OCI_PROCESS_TERMINAL]);
968 opts.no_new_privs = blobmsg_get_bool(tb[OCI_PROCESS_NONEWPRIVILEGES]);
969
970 if (tb[OCI_PROCESS_CWD])
971 opts.cwd = blobmsg_get_string(tb[OCI_PROCESS_CWD]);
972
973 sz = 0;
974 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ENV], rem)
975 ++sz;
976
977 if (sz > 0) {
978 opts.envp = calloc(1 + sz, sizeof(char*));
979 if (!opts.envp)
980 return ENOMEM;
981 }
982
983 sz = 0;
984 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ENV], rem)
985 opts.envp[sz++] = strdup(blobmsg_get_string(cur));
986
987 if (tb[OCI_PROCESS_USER] && (res = parseOCIprocessuser(tb[OCI_PROCESS_USER])))
988 return res;
989
990 if (tb[OCI_PROCESS_CAPABILITIES] &&
991 (res = parseOCIcapabilities(&opts.capset, tb[OCI_PROCESS_CAPABILITIES])))
992 return res;
993
994 /* ToDo: rlimits, capabilities */
995
996 return 0;
997 }
998
999 enum {
1000 OCI_LINUX_NAMESPACE_TYPE,
1001 OCI_LINUX_NAMESPACE_PATH,
1002 __OCI_LINUX_NAMESPACE_MAX,
1003 };
1004
1005 static const struct blobmsg_policy oci_linux_namespace_policy[] = {
1006 [OCI_LINUX_NAMESPACE_TYPE] = { "type", BLOBMSG_TYPE_STRING },
1007 [OCI_LINUX_NAMESPACE_PATH] = { "path", BLOBMSG_TYPE_STRING },
1008 };
1009
1010 static unsigned int resolve_nstype(char *type) {
1011 if (!strcmp("pid", type))
1012 return CLONE_NEWPID;
1013 else if (!strcmp("network", type))
1014 return CLONE_NEWNET;
1015 else if (!strcmp("mount", type))
1016 return CLONE_NEWNS;
1017 else if (!strcmp("ipc", type))
1018 return CLONE_NEWIPC;
1019 else if (!strcmp("uts", type))
1020 return CLONE_NEWUTS;
1021 else if (!strcmp("user", type))
1022 return CLONE_NEWUSER;
1023 else if (!strcmp("cgroup", type))
1024 return CLONE_NEWCGROUP;
1025 else
1026 return 0;
1027 }
1028
1029 static int parseOCIlinuxns(struct blob_attr *msg)
1030 {
1031 struct blob_attr *tb[__OCI_LINUX_NAMESPACE_MAX];
1032
1033
1034 blobmsg_parse(oci_linux_namespace_policy, __OCI_LINUX_NAMESPACE_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1035
1036 if (!tb[OCI_LINUX_NAMESPACE_TYPE])
1037 return EINVAL;
1038
1039 if (tb[OCI_LINUX_NAMESPACE_PATH])
1040 return ENOTSUP; /* ToDo */
1041
1042 opts.namespace |= resolve_nstype(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]));
1043
1044 return 0;
1045 };
1046
1047
1048 enum {
1049 OCI_LINUX_UIDGIDMAP_CONTAINERID,
1050 OCI_LINUX_UIDGIDMAP_HOSTID,
1051 OCI_LINUX_UIDGIDMAP_SIZE,
1052 __OCI_LINUX_UIDGIDMAP_MAX,
1053 };
1054
1055 static const struct blobmsg_policy oci_linux_uidgidmap_policy[] = {
1056 [OCI_LINUX_UIDGIDMAP_CONTAINERID] = { "containerID", BLOBMSG_TYPE_INT32 },
1057 [OCI_LINUX_UIDGIDMAP_HOSTID] = { "hostID", BLOBMSG_TYPE_INT32 },
1058 [OCI_LINUX_UIDGIDMAP_SIZE] = { "size", BLOBMSG_TYPE_INT32 },
1059 };
1060
1061 static int parseOCIuidgidmappings(struct blob_attr *msg, bool is_gidmap)
1062 {
1063 const char *map_format = "%d %d %d\n";
1064 struct blob_attr *tb[__OCI_LINUX_UIDGIDMAP_MAX];
1065 struct blob_attr *cur;
1066 int rem, len;
1067 char **mappings;
1068 char *map, *curstr;
1069 unsigned int cnt = 0;
1070 size_t totallen = 0;
1071
1072 /* count number of mappings */
1073 blobmsg_for_each_attr(cur, msg, rem)
1074 cnt++;
1075
1076 if (!cnt)
1077 return 0;
1078
1079 /* allocate array for mappings */
1080 mappings = calloc(1 + cnt, sizeof(char*));
1081 if (!mappings)
1082 return ENOMEM;
1083
1084 mappings[cnt] = NULL;
1085
1086 cnt = 0;
1087 blobmsg_for_each_attr(cur, msg, rem) {
1088 blobmsg_parse(oci_linux_uidgidmap_policy, __OCI_LINUX_UIDGIDMAP_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1089
1090 if (!tb[OCI_LINUX_UIDGIDMAP_CONTAINERID] ||
1091 !tb[OCI_LINUX_UIDGIDMAP_HOSTID] ||
1092 !tb[OCI_LINUX_UIDGIDMAP_SIZE])
1093 return EINVAL;
1094
1095 /* write mapping line into allocated string */
1096 len = asprintf(&mappings[cnt++], map_format,
1097 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
1098 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
1099 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
1100
1101 if (len < 0)
1102 return ENOMEM;
1103
1104 totallen += len;
1105 }
1106
1107 /* allocate combined mapping string */
1108 map = calloc(1 + totallen, sizeof(char));
1109 if (!map)
1110 return ENOMEM;
1111
1112 map[0] = '\0';
1113
1114 /* concatenate mapping strings into combined string */
1115 curstr = mappings[0];
1116 while (curstr) {
1117 strcat(map, curstr);
1118 free(curstr++);
1119 }
1120 free(mappings);
1121
1122 if (is_gidmap)
1123 opts.gidmap = map;
1124 else
1125 opts.uidmap = map;
1126
1127 return 0;
1128 }
1129
1130 enum {
1131 OCI_LINUX_RESOURCES,
1132 OCI_LINUX_SECCOMP,
1133 OCI_LINUX_SYSCTL,
1134 OCI_LINUX_NAMESPACES,
1135 OCI_LINUX_UIDMAPPINGS,
1136 OCI_LINUX_GIDMAPPINGS,
1137 OCI_LINUX_MASKEDPATHS,
1138 OCI_LINUX_READONLYPATHS,
1139 OCI_LINUX_ROOTFSPROPAGATION,
1140 __OCI_LINUX_MAX,
1141 };
1142
1143 static const struct blobmsg_policy oci_linux_policy[] = {
1144 [OCI_LINUX_RESOURCES] = { "resources", BLOBMSG_TYPE_TABLE },
1145 [OCI_LINUX_SECCOMP] = { "seccomp", BLOBMSG_TYPE_TABLE },
1146 [OCI_LINUX_SYSCTL] = { "sysctl", BLOBMSG_TYPE_TABLE },
1147 [OCI_LINUX_NAMESPACES] = { "namespaces", BLOBMSG_TYPE_ARRAY },
1148 [OCI_LINUX_UIDMAPPINGS] = { "uidMappings", BLOBMSG_TYPE_ARRAY },
1149 [OCI_LINUX_GIDMAPPINGS] = { "gidMappings", BLOBMSG_TYPE_ARRAY },
1150 [OCI_LINUX_MASKEDPATHS] = { "maskedPaths", BLOBMSG_TYPE_ARRAY },
1151 [OCI_LINUX_READONLYPATHS] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY },
1152 [OCI_LINUX_ROOTFSPROPAGATION] = { "rootfsPropagation", BLOBMSG_TYPE_STRING },
1153 };
1154
1155 static int parseOCIlinux(struct blob_attr *msg)
1156 {
1157 struct blob_attr *tb[__OCI_LINUX_MAX];
1158 struct blob_attr *cur;
1159 int rem;
1160 int res = 0;
1161
1162 blobmsg_parse(oci_linux_policy, __OCI_LINUX_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1163
1164 if (tb[OCI_LINUX_NAMESPACES]) {
1165 blobmsg_for_each_attr(cur, tb[OCI_LINUX_NAMESPACES], rem) {
1166 res = parseOCIlinuxns(cur);
1167 if (res)
1168 return res;
1169 }
1170 }
1171
1172 if (tb[OCI_LINUX_UIDMAPPINGS]) {
1173 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 0);
1174 if (res)
1175 return res;
1176 }
1177
1178 if (tb[OCI_LINUX_GIDMAPPINGS]) {
1179 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 1);
1180 if (res)
1181 return res;
1182 }
1183
1184 if (tb[OCI_LINUX_SECCOMP]) {
1185 opts.ociseccomp = parseOCIlinuxseccomp(tb[OCI_LINUX_SECCOMP]);
1186 if (!opts.ociseccomp)
1187 return EINVAL;
1188 }
1189
1190 return 0;
1191 }
1192
1193 enum {
1194 OCI_VERSION,
1195 OCI_HOSTNAME,
1196 OCI_PROCESS,
1197 OCI_ROOT,
1198 OCI_MOUNTS,
1199 OCI_LINUX,
1200 __OCI_MAX,
1201 };
1202
1203 static const struct blobmsg_policy oci_policy[] = {
1204 [OCI_VERSION] = { "ociVersion", BLOBMSG_TYPE_STRING },
1205 [OCI_HOSTNAME] = { "hostname", BLOBMSG_TYPE_STRING },
1206 [OCI_PROCESS] = { "process", BLOBMSG_TYPE_TABLE },
1207 [OCI_ROOT] = { "root", BLOBMSG_TYPE_TABLE },
1208 [OCI_MOUNTS] = { "mounts", BLOBMSG_TYPE_ARRAY },
1209 [OCI_LINUX] = { "linux", BLOBMSG_TYPE_TABLE },
1210 };
1211
1212 static int parseOCI(const char *jsonfile)
1213 {
1214 struct blob_attr *tb[__OCI_MAX];
1215 struct blob_attr *cur;
1216 int rem;
1217 int res;
1218
1219 blob_buf_init(&ocibuf, 0);
1220 if (!blobmsg_add_json_from_file(&ocibuf, jsonfile))
1221 return ENOENT;
1222
1223 blobmsg_parse(oci_policy, __OCI_MAX, tb, blob_data(ocibuf.head), blob_len(ocibuf.head));
1224
1225 if (!tb[OCI_VERSION])
1226 return ENOMSG;
1227
1228 if (strncmp("1.0", blobmsg_get_string(tb[OCI_VERSION]), 3)) {
1229 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb[OCI_VERSION]));
1230 return ENOTSUP;
1231 }
1232
1233 if (tb[OCI_HOSTNAME])
1234 opts.hostname = blobmsg_get_string(tb[OCI_HOSTNAME]);
1235
1236 if (!tb[OCI_PROCESS])
1237 return ENODATA;
1238
1239 if ((res = parseOCIprocess(tb[OCI_PROCESS])))
1240 return res;
1241
1242 if (!tb[OCI_ROOT])
1243 return ENODATA;
1244
1245 if ((res = parseOCIroot(jsonfile, tb[OCI_ROOT])))
1246 return res;
1247
1248 if (!tb[OCI_MOUNTS])
1249 return ENODATA;
1250
1251 blobmsg_for_each_attr(cur, tb[OCI_MOUNTS], rem)
1252 if ((res = parseOCImount(cur)))
1253 return res;
1254
1255 if (tb[OCI_LINUX] && (res = parseOCIlinux(tb[OCI_LINUX])))
1256 return res;
1257
1258 return 0;
1259 }
1260
1261 int main(int argc, char **argv)
1262 {
1263 sigset_t sigmask;
1264 uid_t uid = getuid();
1265 const char log[] = "/dev/log";
1266 const char ubus[] = "/var/run/ubus.sock";
1267 char *jsonfile = NULL;
1268 int ch, i;
1269 int pipes[4];
1270 char sig_buf[1];
1271 int netns_fd;
1272
1273 if (uid) {
1274 ERROR("not root, aborting: %m\n");
1275 return EXIT_FAILURE;
1276 }
1277
1278 umask(022);
1279 mount_list_init();
1280 init_library_search();
1281
1282 while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
1283 switch (ch) {
1284 case 'd':
1285 debug = atoi(optarg);
1286 break;
1287 case 'p':
1288 opts.namespace |= CLONE_NEWNS;
1289 opts.procfs = 1;
1290 break;
1291 case 'o':
1292 opts.namespace |= CLONE_NEWNS;
1293 opts.ronly = 1;
1294 break;
1295 case 'f':
1296 opts.namespace |= CLONE_NEWUSER;
1297 break;
1298 case 'F':
1299 opts.namespace |= CLONE_NEWCGROUP;
1300 break;
1301 case 'R':
1302 opts.extroot = optarg;
1303 break;
1304 case 's':
1305 opts.namespace |= CLONE_NEWNS;
1306 opts.sysfs = 1;
1307 break;
1308 case 'S':
1309 opts.seccomp = optarg;
1310 add_mount(optarg, 1, -1);
1311 break;
1312 case 'C':
1313 opts.capabilities = optarg;
1314 break;
1315 case 'c':
1316 opts.no_new_privs = 1;
1317 break;
1318 case 'n':
1319 opts.name = optarg;
1320 break;
1321 case 'N':
1322 opts.namespace |= CLONE_NEWNET;
1323 break;
1324 case 'h':
1325 opts.namespace |= CLONE_NEWUTS;
1326 opts.hostname = optarg;
1327 break;
1328 case 'r':
1329 opts.namespace |= CLONE_NEWNS;
1330 add_path_and_deps(optarg, 1, 0, 0);
1331 break;
1332 case 'w':
1333 opts.namespace |= CLONE_NEWNS;
1334 add_path_and_deps(optarg, 0, 0, 0);
1335 break;
1336 case 'u':
1337 opts.namespace |= CLONE_NEWNS;
1338 add_mount(ubus, 0, -1);
1339 break;
1340 case 'l':
1341 opts.namespace |= CLONE_NEWNS;
1342 add_mount(log, 0, -1);
1343 break;
1344 case 'U':
1345 opts.user = optarg;
1346 break;
1347 case 'G':
1348 opts.group = optarg;
1349 break;
1350 case 'O':
1351 opts.overlaydir = optarg;
1352 break;
1353 case 'T':
1354 opts.tmpoverlaysize = optarg;
1355 break;
1356 case 'E':
1357 opts.require_jail = 1;
1358 break;
1359 case 'y':
1360 opts.console = 1;
1361 break;
1362 case 'J':
1363 asprintf(&jsonfile, "%s/config.json", optarg);
1364 break;
1365 }
1366 }
1367
1368 if (opts.namespace)
1369 opts.namespace |= CLONE_NEWIPC | CLONE_NEWPID;
1370
1371 if (jsonfile) {
1372 int ocires;
1373 ocires = parseOCI(jsonfile);
1374 free(jsonfile);
1375 if (ocires) {
1376 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires), ocires);
1377 return ocires;
1378 }
1379 }
1380
1381 if (opts.tmpoverlaysize && strlen(opts.tmpoverlaysize) > 8) {
1382 ERROR("size parameter too long: \"%s\"\n", opts.tmpoverlaysize);
1383 return -1;
1384 }
1385
1386 /* no <binary> param found */
1387 if (!jsonfile && (argc - optind < 1)) {
1388 usage();
1389 return EXIT_FAILURE;
1390 }
1391 if (!(opts.namespace||opts.capabilities||opts.seccomp)) {
1392 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
1393 usage();
1394 return EXIT_FAILURE;
1395 }
1396 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
1397 opts.namespace,
1398 opts.capabilities != 0 || opts.capset.apply,
1399 opts.seccomp != 0 || opts.ociseccomp != 0);
1400
1401 if (!jsonfile) {
1402 opts.jail_argv = &argv[optind];
1403 if (opts.namespace & CLONE_NEWUSER)
1404 get_jail_user(&opts.pw_uid, &opts.pw_gid, &opts.gr_gid);
1405 }
1406
1407 if (!opts.extroot) {
1408 if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
1409 ERROR("failed to load dependencies\n");
1410 return -1;
1411 }
1412 }
1413
1414 if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
1415 ERROR("failed to load libpreload-seccomp.so\n");
1416 opts.seccomp = 0;
1417 if (opts.require_jail)
1418 return -1;
1419 }
1420
1421 if (opts.name)
1422 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
1423
1424 uloop_init();
1425
1426 sigfillset(&sigmask);
1427 for (i = 0; i < _NSIG; i++) {
1428 struct sigaction s = { 0 };
1429
1430 if (!sigismember(&sigmask, i))
1431 continue;
1432 if ((i == SIGCHLD) || (i == SIGPIPE) || (i == SIGSEGV))
1433 continue;
1434
1435 s.sa_handler = jail_handle_signal;
1436 sigaction(i, &s, NULL);
1437 }
1438
1439 if (opts.namespace) {
1440 if (opts.namespace & CLONE_NEWNS) {
1441 add_mount("/dev/full", 0, -1);
1442 add_mount("/dev/null", 0, -1);
1443 add_mount("/dev/random", 0, -1);
1444 add_mount("/dev/urandom", 0, -1);
1445 add_mount("/dev/zero", 0, -1);
1446 add_mount("/dev/ptmx", 0, -1);
1447 add_mount("/dev/tty", 0, -1);
1448
1449 if (!opts.extroot && (opts.user || opts.group)) {
1450 add_mount("/etc/passwd", 0, -1);
1451 add_mount("/etc/group", 0, -1);
1452 }
1453
1454 #if defined(__GLIBC__)
1455 if (!opts.extroot)
1456 add_mount("/etc/nsswitch.conf", 0, -1);
1457 #endif
1458
1459 if (!(opts.namespace & CLONE_NEWNET)) {
1460 add_mount("/etc/resolv.conf", 0, -1);
1461 }
1462 }
1463
1464 if (pipe(&pipes[0]) < 0 || pipe(&pipes[2]) < 0)
1465 return -1;
1466
1467 jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, SIGCHLD | opts.namespace, &pipes);
1468 } else {
1469 jail_process.pid = fork();
1470 }
1471
1472 if (jail_process.pid > 0) {
1473 seteuid(0);
1474 /* parent process */
1475 close(pipes[1]);
1476 close(pipes[2]);
1477 if (read(pipes[0], sig_buf, 1) < 1) {
1478 ERROR("can't read from child\n");
1479 return -1;
1480 }
1481 close(pipes[0]);
1482 if (opts.namespace & CLONE_NEWUSER) {
1483 if (write_setgroups(jail_process.pid, true)) {
1484 ERROR("can't write setgroups\n");
1485 return -1;
1486 }
1487 if (!opts.uidmap) {
1488 bool has_gr = (opts.gr_gid != -1);
1489 if (opts.pw_uid != -1) {
1490 write_single_uid_gid_map(jail_process.pid, 0, opts.pw_uid);
1491 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:opts.pw_gid);
1492 } else {
1493 write_single_uid_gid_map(jail_process.pid, 0, 65534);
1494 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:65534);
1495 }
1496 } else {
1497 write_uid_gid_map(jail_process.pid, 0, opts.uidmap);
1498 if (opts.gidmap)
1499 write_uid_gid_map(jail_process.pid, 1, opts.gidmap);
1500 }
1501 }
1502
1503 if (opts.namespace & CLONE_NEWNET) {
1504 if (!opts.name) {
1505 ERROR("netns needs a named jail\n");
1506 return -1;
1507 }
1508 netns_fd = netns_open_pid(jail_process.pid);
1509 netns_updown(jail_process.pid, true);
1510 }
1511
1512 sig_buf[0] = 'O';
1513 if (write(pipes[3], sig_buf, 1) < 0) {
1514 ERROR("can't write to child\n");
1515 return -1;
1516 }
1517 close(pipes[3]);
1518 uloop_process_add(&jail_process);
1519 uloop_run();
1520 if (jail_running) {
1521 DEBUG("uloop interrupted, killing jail process\n");
1522 kill(jail_process.pid, SIGTERM);
1523 uloop_timeout_set(&jail_process_timeout, 1000);
1524 uloop_run();
1525 }
1526 uloop_done();
1527 if (opts.namespace & CLONE_NEWNET) {
1528 setns(netns_fd, CLONE_NEWNET);
1529 netns_updown(getpid(), false);
1530 close(netns_fd);
1531 }
1532 return jail_return_code;
1533 } else if (jail_process.pid == 0) {
1534 /* fork child process */
1535 return exec_jail(NULL);
1536 } else {
1537 ERROR("failed to clone/fork: %m\n");
1538 return EXIT_FAILURE;
1539 }
1540 }