1650534b1887ae16c85d6b0b6ce67801b50a480a
[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.cwd && chdir(opts.cwd))
714 exit(EXIT_FAILURE);
715
716 if (opts.ociseccomp && applyOCIlinuxseccomp(opts.ociseccomp))
717 exit(EXIT_FAILURE);
718
719 INFO("exec-ing %s\n", *opts.jail_argv);
720 if (opts.envp) /* respect PATH if potentially set in ENV */
721 execvpe(*opts.jail_argv, opts.jail_argv, envp);
722 else
723 execve(*opts.jail_argv, opts.jail_argv, envp);
724
725 /* we get there only if execve fails */
726 ERROR("failed to execve %s: %m\n", *opts.jail_argv);
727 exit(EXIT_FAILURE);
728 }
729
730 static int jail_running = 1;
731 static int jail_return_code = 0;
732
733 static void jail_process_timeout_cb(struct uloop_timeout *t);
734 static struct uloop_timeout jail_process_timeout = {
735 .cb = jail_process_timeout_cb,
736 };
737
738 static void jail_process_handler(struct uloop_process *c, int ret)
739 {
740 uloop_timeout_cancel(&jail_process_timeout);
741 if (WIFEXITED(ret)) {
742 jail_return_code = WEXITSTATUS(ret);
743 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
744 } else {
745 jail_return_code = WTERMSIG(ret);
746 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
747 }
748 jail_running = 0;
749 uloop_end();
750 }
751
752 static struct uloop_process jail_process = {
753 .cb = jail_process_handler,
754 };
755
756 static void jail_process_timeout_cb(struct uloop_timeout *t)
757 {
758 DEBUG("jail process failed to stop, sending SIGKILL\n");
759 kill(jail_process.pid, SIGKILL);
760 }
761
762 static void jail_handle_signal(int signo)
763 {
764 DEBUG("forwarding signal %d to the jailed process\n", signo);
765 kill(jail_process.pid, signo);
766 }
767
768 static int netns_open_pid(const pid_t target_ns)
769 {
770 char pid_net_path[PATH_MAX];
771
772 snprintf(pid_net_path, sizeof(pid_net_path), "/proc/%u/ns/net", target_ns);
773
774 return open(pid_net_path, O_RDONLY);
775 }
776
777 static void netns_updown(pid_t pid, bool start)
778 {
779 struct ubus_context *ctx = ubus_connect(NULL);
780 static struct blob_buf req;
781 uint32_t id;
782
783 if (!ctx)
784 return;
785
786 blob_buf_init(&req, 0);
787 blobmsg_add_string(&req, "jail", opts.name);
788 blobmsg_add_u32(&req, "pid", pid);
789 blobmsg_add_u8(&req, "start", start);
790
791 if (ubus_lookup_id(ctx, "network", &id) ||
792 ubus_invoke(ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
793 INFO("ubus request failed\n");
794
795 blob_buf_free(&req);
796 ubus_free(ctx);
797 }
798
799
800 enum {
801 OCI_ROOT_PATH,
802 OCI_ROOT_READONLY,
803 __OCI_ROOT_MAX,
804 };
805
806 static const struct blobmsg_policy oci_root_policy[] = {
807 [OCI_ROOT_PATH] = { "path", BLOBMSG_TYPE_STRING },
808 [OCI_ROOT_READONLY] = { "readonly", BLOBMSG_TYPE_BOOL },
809 };
810
811 static int parseOCIroot(const char *jsonfile, struct blob_attr *msg)
812 {
813 static char rootpath[PATH_MAX] = { 0 };
814 struct blob_attr *tb[__OCI_ROOT_MAX];
815 char *cur;
816
817 blobmsg_parse(oci_root_policy, __OCI_ROOT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
818
819 if (!tb[OCI_ROOT_PATH])
820 return ENODATA;
821
822 strncpy(rootpath, jsonfile, PATH_MAX);
823 cur = strrchr(rootpath, '/');
824
825 if (!cur)
826 return ENOTDIR;
827
828 *(++cur) = '\0';
829 strncat(rootpath, blobmsg_get_string(tb[OCI_ROOT_PATH]), PATH_MAX - (strlen(rootpath) + 1));
830
831 opts.extroot = rootpath;
832
833 opts.ronly = blobmsg_get_bool(tb[OCI_ROOT_READONLY]);
834
835 return 0;
836 }
837
838
839 enum {
840 OCI_MOUNT_SOURCE,
841 OCI_MOUNT_DESTINATION,
842 OCI_MOUNT_TYPE,
843 OCI_MOUNT_OPTIONS,
844 __OCI_MOUNT_MAX,
845 };
846
847 static const struct blobmsg_policy oci_mount_policy[] = {
848 [OCI_MOUNT_SOURCE] = { "source", BLOBMSG_TYPE_STRING },
849 [OCI_MOUNT_DESTINATION] = { "destination", BLOBMSG_TYPE_STRING },
850 [OCI_MOUNT_TYPE] = { "type", BLOBMSG_TYPE_STRING },
851 [OCI_MOUNT_OPTIONS] = { "options", BLOBMSG_TYPE_ARRAY },
852 };
853
854 static int parseOCImount(struct blob_attr *msg)
855 {
856 struct blob_attr *tb[__OCI_MOUNT_MAX];
857
858 blobmsg_parse(oci_mount_policy, __OCI_MOUNT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
859
860 if (!tb[OCI_MOUNT_DESTINATION])
861 return EINVAL;
862
863 if (!strcmp("proc", blobmsg_get_string(tb[OCI_MOUNT_TYPE])) &&
864 !strcmp("/proc", blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]))) {
865 opts.procfs = true;
866 return 0;
867 }
868
869 if (!strcmp("sysfs", blobmsg_get_string(tb[OCI_MOUNT_TYPE])) &&
870 !strcmp("/sys", blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]))) {
871 opts.sysfs = true;
872 return 0;
873 }
874
875 if (!strcmp("tmpfs", blobmsg_get_string(tb[OCI_MOUNT_TYPE])) &&
876 !strcmp("/dev", blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]))) {
877 /* we always mount a small tmpfs on /dev */
878 return 0;
879 }
880
881 INFO("ignoring unsupported mount %s %s -t %s -o %s\n",
882 blobmsg_get_string(tb[OCI_MOUNT_SOURCE]),
883 blobmsg_get_string(tb[OCI_MOUNT_DESTINATION]),
884 blobmsg_get_string(tb[OCI_MOUNT_TYPE]),
885 blobmsg_format_json(tb[OCI_MOUNT_OPTIONS], true));
886
887 return 0;
888 };
889
890
891 enum {
892 OCI_PROCESS_USER_UID,
893 OCI_PROCESS_USER_GID,
894 OCI_PROCESS_USER_UMASK,
895 OCI_PROCESS_USER_ADDITIONALGIDS,
896 __OCI_PROCESS_USER_MAX,
897 };
898
899 static const struct blobmsg_policy oci_process_user_policy[] = {
900 [OCI_PROCESS_USER_UID] = { "uid", BLOBMSG_TYPE_INT32 },
901 [OCI_PROCESS_USER_GID] = { "gid", BLOBMSG_TYPE_INT32 },
902 [OCI_PROCESS_USER_UMASK] = { "umask", BLOBMSG_TYPE_INT32 },
903 [OCI_PROCESS_USER_ADDITIONALGIDS] = { "additionalGids", BLOBMSG_TYPE_ARRAY },
904 };
905
906 static int parseOCIprocessuser(struct blob_attr *msg) {
907 struct blob_attr *tb[__OCI_PROCESS_USER_MAX];
908
909 blobmsg_parse(oci_process_user_policy, __OCI_PROCESS_USER_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
910
911 if (tb[OCI_PROCESS_USER_UID])
912 opts.pw_uid = blobmsg_get_u32(tb[OCI_PROCESS_USER_UID]);
913
914 if (tb[OCI_PROCESS_USER_GID]) {
915 opts.pw_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
916 opts.gr_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
917 }
918
919 /* ToDo: umask, additional GIDs */
920
921 return 0;
922 }
923
924 enum {
925 OCI_PROCESS_ARGS,
926 OCI_PROCESS_CAPABILITIES,
927 OCI_PROCESS_CWD,
928 OCI_PROCESS_ENV,
929 OCI_PROCESS_NONEWPRIVILEGES,
930 OCI_PROCESS_RLIMITS,
931 OCI_PROCESS_TERMINAL,
932 OCI_PROCESS_USER,
933 __OCI_PROCESS_MAX,
934 };
935
936 static const struct blobmsg_policy oci_process_policy[] = {
937 [OCI_PROCESS_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
938 [OCI_PROCESS_CAPABILITIES] = { "capabilities", BLOBMSG_TYPE_TABLE },
939 [OCI_PROCESS_CWD] = { "cwd", BLOBMSG_TYPE_STRING },
940 [OCI_PROCESS_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
941 [OCI_PROCESS_NONEWPRIVILEGES] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL },
942 [OCI_PROCESS_RLIMITS] = { "rlimits", BLOBMSG_TYPE_ARRAY },
943 [OCI_PROCESS_TERMINAL] = { "terminal", BLOBMSG_TYPE_BOOL },
944 [OCI_PROCESS_USER] = { "user", BLOBMSG_TYPE_TABLE },
945 };
946
947 static int parseOCIprocess(struct blob_attr *msg)
948 {
949 struct blob_attr *tb[__OCI_PROCESS_MAX];
950 struct blob_attr *cur;
951 unsigned int sz = 0;
952 int rem;
953 int res;
954
955 blobmsg_parse(oci_process_policy, __OCI_PROCESS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
956
957 if (!tb[OCI_PROCESS_ARGS])
958 return ENOENT;
959
960 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ARGS], rem)
961 ++sz;
962
963 if (!sz)
964 return ENODATA;
965
966 opts.jail_argv = calloc(1 + sz, sizeof(char*));
967 if (!opts.jail_argv)
968 return ENOMEM;
969
970 sz = 0;
971 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ARGS], rem)
972 opts.jail_argv[sz++] = blobmsg_get_string(cur);
973
974 opts.console = blobmsg_get_bool(tb[OCI_PROCESS_TERMINAL]);
975 opts.no_new_privs = blobmsg_get_bool(tb[OCI_PROCESS_NONEWPRIVILEGES]);
976
977 if (tb[OCI_PROCESS_CWD])
978 opts.cwd = blobmsg_get_string(tb[OCI_PROCESS_CWD]);
979
980 sz = 0;
981 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ENV], rem)
982 ++sz;
983
984 if (sz > 0) {
985 opts.envp = calloc(1 + sz, sizeof(char*));
986 if (!opts.envp)
987 return ENOMEM;
988 }
989
990 sz = 0;
991 blobmsg_for_each_attr(cur, tb[OCI_PROCESS_ENV], rem)
992 opts.envp[sz++] = strdup(blobmsg_get_string(cur));
993
994 if (tb[OCI_PROCESS_USER] && (res = parseOCIprocessuser(tb[OCI_PROCESS_USER])))
995 return res;
996
997 if (tb[OCI_PROCESS_CAPABILITIES] &&
998 (res = parseOCIcapabilities(&opts.capset, tb[OCI_PROCESS_CAPABILITIES])))
999 return res;
1000
1001 /* ToDo: rlimits, capabilities */
1002
1003 return 0;
1004 }
1005
1006 enum {
1007 OCI_LINUX_NAMESPACE_TYPE,
1008 OCI_LINUX_NAMESPACE_PATH,
1009 __OCI_LINUX_NAMESPACE_MAX,
1010 };
1011
1012 static const struct blobmsg_policy oci_linux_namespace_policy[] = {
1013 [OCI_LINUX_NAMESPACE_TYPE] = { "type", BLOBMSG_TYPE_STRING },
1014 [OCI_LINUX_NAMESPACE_PATH] = { "path", BLOBMSG_TYPE_STRING },
1015 };
1016
1017 static unsigned int resolve_nstype(char *type) {
1018 if (!strcmp("pid", type))
1019 return CLONE_NEWPID;
1020 else if (!strcmp("network", type))
1021 return CLONE_NEWNET;
1022 else if (!strcmp("mount", type))
1023 return CLONE_NEWNS;
1024 else if (!strcmp("ipc", type))
1025 return CLONE_NEWIPC;
1026 else if (!strcmp("uts", type))
1027 return CLONE_NEWUTS;
1028 else if (!strcmp("user", type))
1029 return CLONE_NEWUSER;
1030 else if (!strcmp("cgroup", type))
1031 return CLONE_NEWCGROUP;
1032 else
1033 return 0;
1034 }
1035
1036 static int parseOCIlinuxns(struct blob_attr *msg)
1037 {
1038 struct blob_attr *tb[__OCI_LINUX_NAMESPACE_MAX];
1039
1040
1041 blobmsg_parse(oci_linux_namespace_policy, __OCI_LINUX_NAMESPACE_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1042
1043 if (!tb[OCI_LINUX_NAMESPACE_TYPE])
1044 return EINVAL;
1045
1046 if (tb[OCI_LINUX_NAMESPACE_PATH])
1047 return ENOTSUP; /* ToDo */
1048
1049 opts.namespace |= resolve_nstype(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]));
1050
1051 return 0;
1052 };
1053
1054
1055 enum {
1056 OCI_LINUX_UIDGIDMAP_CONTAINERID,
1057 OCI_LINUX_UIDGIDMAP_HOSTID,
1058 OCI_LINUX_UIDGIDMAP_SIZE,
1059 __OCI_LINUX_UIDGIDMAP_MAX,
1060 };
1061
1062 static const struct blobmsg_policy oci_linux_uidgidmap_policy[] = {
1063 [OCI_LINUX_UIDGIDMAP_CONTAINERID] = { "containerID", BLOBMSG_TYPE_INT32 },
1064 [OCI_LINUX_UIDGIDMAP_HOSTID] = { "hostID", BLOBMSG_TYPE_INT32 },
1065 [OCI_LINUX_UIDGIDMAP_SIZE] = { "size", BLOBMSG_TYPE_INT32 },
1066 };
1067
1068 static int parseOCIuidgidmappings(struct blob_attr *msg, bool is_gidmap)
1069 {
1070 const char *map_format = "%d %d %d\n";
1071 struct blob_attr *tb[__OCI_LINUX_UIDGIDMAP_MAX];
1072 struct blob_attr *cur;
1073 int rem, len;
1074 char **mappings;
1075 char *map, *curstr;
1076 unsigned int cnt = 0;
1077 size_t totallen = 0;
1078
1079 /* count number of mappings */
1080 blobmsg_for_each_attr(cur, msg, rem)
1081 cnt++;
1082
1083 if (!cnt)
1084 return 0;
1085
1086 /* allocate array for mappings */
1087 mappings = calloc(1 + cnt, sizeof(char*));
1088 if (!mappings)
1089 return ENOMEM;
1090
1091 mappings[cnt] = NULL;
1092
1093 cnt = 0;
1094 blobmsg_for_each_attr(cur, msg, rem) {
1095 blobmsg_parse(oci_linux_uidgidmap_policy, __OCI_LINUX_UIDGIDMAP_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
1096
1097 if (!tb[OCI_LINUX_UIDGIDMAP_CONTAINERID] ||
1098 !tb[OCI_LINUX_UIDGIDMAP_HOSTID] ||
1099 !tb[OCI_LINUX_UIDGIDMAP_SIZE])
1100 return EINVAL;
1101
1102 /* write mapping line into allocated string */
1103 len = asprintf(&mappings[cnt++], map_format,
1104 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
1105 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
1106 blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
1107
1108 if (len < 0)
1109 return ENOMEM;
1110
1111 totallen += len;
1112 }
1113
1114 /* allocate combined mapping string */
1115 map = calloc(1 + totallen, sizeof(char));
1116 if (!map)
1117 return ENOMEM;
1118
1119 map[0] = '\0';
1120
1121 /* concatenate mapping strings into combined string */
1122 curstr = mappings[0];
1123 while (curstr) {
1124 strcat(map, curstr);
1125 free(curstr++);
1126 }
1127 free(mappings);
1128
1129 if (is_gidmap)
1130 opts.gidmap = map;
1131 else
1132 opts.uidmap = map;
1133
1134 return 0;
1135 }
1136
1137 enum {
1138 OCI_LINUX_RESOURCES,
1139 OCI_LINUX_SECCOMP,
1140 OCI_LINUX_SYSCTL,
1141 OCI_LINUX_NAMESPACES,
1142 OCI_LINUX_UIDMAPPINGS,
1143 OCI_LINUX_GIDMAPPINGS,
1144 OCI_LINUX_MASKEDPATHS,
1145 OCI_LINUX_READONLYPATHS,
1146 OCI_LINUX_ROOTFSPROPAGATION,
1147 __OCI_LINUX_MAX,
1148 };
1149
1150 static const struct blobmsg_policy oci_linux_policy[] = {
1151 [OCI_LINUX_RESOURCES] = { "resources", BLOBMSG_TYPE_TABLE },
1152 [OCI_LINUX_SECCOMP] = { "seccomp", BLOBMSG_TYPE_TABLE },
1153 [OCI_LINUX_SYSCTL] = { "sysctl", BLOBMSG_TYPE_TABLE },
1154 [OCI_LINUX_NAMESPACES] = { "namespaces", BLOBMSG_TYPE_ARRAY },
1155 [OCI_LINUX_UIDMAPPINGS] = { "uidMappings", BLOBMSG_TYPE_ARRAY },
1156 [OCI_LINUX_GIDMAPPINGS] = { "gidMappings", BLOBMSG_TYPE_ARRAY },
1157 [OCI_LINUX_MASKEDPATHS] = { "maskedPaths", BLOBMSG_TYPE_ARRAY },
1158 [OCI_LINUX_READONLYPATHS] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY },
1159 [OCI_LINUX_ROOTFSPROPAGATION] = { "rootfsPropagation", BLOBMSG_TYPE_STRING },
1160 };
1161
1162 static int parseOCIlinux(struct blob_attr *msg)
1163 {
1164 struct blob_attr *tb[__OCI_LINUX_MAX];
1165 struct blob_attr *cur;
1166 int rem;
1167 int res = 0;
1168
1169 blobmsg_parse(oci_linux_policy, __OCI_LINUX_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
1170
1171 if (tb[OCI_LINUX_NAMESPACES]) {
1172 blobmsg_for_each_attr(cur, tb[OCI_LINUX_NAMESPACES], rem) {
1173 res = parseOCIlinuxns(cur);
1174 if (res)
1175 return res;
1176 }
1177 }
1178
1179 if (tb[OCI_LINUX_UIDMAPPINGS]) {
1180 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 0);
1181 if (res)
1182 return res;
1183 }
1184
1185 if (tb[OCI_LINUX_GIDMAPPINGS]) {
1186 res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 1);
1187 if (res)
1188 return res;
1189 }
1190
1191 if (tb[OCI_LINUX_SECCOMP]) {
1192 opts.ociseccomp = parseOCIlinuxseccomp(tb[OCI_LINUX_SECCOMP]);
1193 if (!opts.ociseccomp)
1194 return EINVAL;
1195 }
1196
1197 return 0;
1198 }
1199
1200 enum {
1201 OCI_VERSION,
1202 OCI_HOSTNAME,
1203 OCI_PROCESS,
1204 OCI_ROOT,
1205 OCI_MOUNTS,
1206 OCI_LINUX,
1207 __OCI_MAX,
1208 };
1209
1210 static const struct blobmsg_policy oci_policy[] = {
1211 [OCI_VERSION] = { "ociVersion", BLOBMSG_TYPE_STRING },
1212 [OCI_HOSTNAME] = { "hostname", BLOBMSG_TYPE_STRING },
1213 [OCI_PROCESS] = { "process", BLOBMSG_TYPE_TABLE },
1214 [OCI_ROOT] = { "root", BLOBMSG_TYPE_TABLE },
1215 [OCI_MOUNTS] = { "mounts", BLOBMSG_TYPE_ARRAY },
1216 [OCI_LINUX] = { "linux", BLOBMSG_TYPE_TABLE },
1217 };
1218
1219 static int parseOCI(const char *jsonfile)
1220 {
1221 struct blob_attr *tb[__OCI_MAX];
1222 struct blob_attr *cur;
1223 int rem;
1224 int res;
1225
1226 blob_buf_init(&ocibuf, 0);
1227 if (!blobmsg_add_json_from_file(&ocibuf, jsonfile))
1228 return ENOENT;
1229
1230 blobmsg_parse(oci_policy, __OCI_MAX, tb, blob_data(ocibuf.head), blob_len(ocibuf.head));
1231
1232 if (!tb[OCI_VERSION])
1233 return ENOMSG;
1234
1235 if (strncmp("1.0", blobmsg_get_string(tb[OCI_VERSION]), 3)) {
1236 ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb[OCI_VERSION]));
1237 return ENOTSUP;
1238 }
1239
1240 if (tb[OCI_HOSTNAME])
1241 opts.hostname = blobmsg_get_string(tb[OCI_HOSTNAME]);
1242
1243 if (!tb[OCI_PROCESS])
1244 return ENODATA;
1245
1246 if ((res = parseOCIprocess(tb[OCI_PROCESS])))
1247 return res;
1248
1249 if (!tb[OCI_ROOT])
1250 return ENODATA;
1251
1252 if ((res = parseOCIroot(jsonfile, tb[OCI_ROOT])))
1253 return res;
1254
1255 if (!tb[OCI_MOUNTS])
1256 return ENODATA;
1257
1258 blobmsg_for_each_attr(cur, tb[OCI_MOUNTS], rem)
1259 if ((res = parseOCImount(cur)))
1260 return res;
1261
1262 if (tb[OCI_LINUX] && (res = parseOCIlinux(tb[OCI_LINUX])))
1263 return res;
1264
1265 return 0;
1266 }
1267
1268 int main(int argc, char **argv)
1269 {
1270 sigset_t sigmask;
1271 uid_t uid = getuid();
1272 const char log[] = "/dev/log";
1273 const char ubus[] = "/var/run/ubus.sock";
1274 char *jsonfile = NULL;
1275 int ch, i;
1276 int pipes[4];
1277 char sig_buf[1];
1278 int netns_fd;
1279
1280 if (uid) {
1281 ERROR("not root, aborting: %m\n");
1282 return EXIT_FAILURE;
1283 }
1284
1285 umask(022);
1286 mount_list_init();
1287 init_library_search();
1288
1289 while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
1290 switch (ch) {
1291 case 'd':
1292 debug = atoi(optarg);
1293 break;
1294 case 'p':
1295 opts.namespace |= CLONE_NEWNS;
1296 opts.procfs = 1;
1297 break;
1298 case 'o':
1299 opts.namespace |= CLONE_NEWNS;
1300 opts.ronly = 1;
1301 break;
1302 case 'f':
1303 opts.namespace |= CLONE_NEWUSER;
1304 break;
1305 case 'F':
1306 opts.namespace |= CLONE_NEWCGROUP;
1307 break;
1308 case 'R':
1309 opts.extroot = optarg;
1310 break;
1311 case 's':
1312 opts.namespace |= CLONE_NEWNS;
1313 opts.sysfs = 1;
1314 break;
1315 case 'S':
1316 opts.seccomp = optarg;
1317 add_mount(optarg, 1, -1);
1318 break;
1319 case 'C':
1320 opts.capabilities = optarg;
1321 break;
1322 case 'c':
1323 opts.no_new_privs = 1;
1324 break;
1325 case 'n':
1326 opts.name = optarg;
1327 break;
1328 case 'N':
1329 opts.namespace |= CLONE_NEWNET;
1330 break;
1331 case 'h':
1332 opts.namespace |= CLONE_NEWUTS;
1333 opts.hostname = optarg;
1334 break;
1335 case 'r':
1336 opts.namespace |= CLONE_NEWNS;
1337 add_path_and_deps(optarg, 1, 0, 0);
1338 break;
1339 case 'w':
1340 opts.namespace |= CLONE_NEWNS;
1341 add_path_and_deps(optarg, 0, 0, 0);
1342 break;
1343 case 'u':
1344 opts.namespace |= CLONE_NEWNS;
1345 add_mount(ubus, 0, -1);
1346 break;
1347 case 'l':
1348 opts.namespace |= CLONE_NEWNS;
1349 add_mount(log, 0, -1);
1350 break;
1351 case 'U':
1352 opts.user = optarg;
1353 break;
1354 case 'G':
1355 opts.group = optarg;
1356 break;
1357 case 'O':
1358 opts.overlaydir = optarg;
1359 break;
1360 case 'T':
1361 opts.tmpoverlaysize = optarg;
1362 break;
1363 case 'E':
1364 opts.require_jail = 1;
1365 break;
1366 case 'y':
1367 opts.console = 1;
1368 break;
1369 case 'J':
1370 asprintf(&jsonfile, "%s/config.json", optarg);
1371 break;
1372 }
1373 }
1374
1375 if (opts.namespace)
1376 opts.namespace |= CLONE_NEWIPC | CLONE_NEWPID;
1377
1378 if (jsonfile) {
1379 int ocires;
1380 ocires = parseOCI(jsonfile);
1381 free(jsonfile);
1382 if (ocires) {
1383 ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires), ocires);
1384 return ocires;
1385 }
1386 }
1387
1388 if (opts.tmpoverlaysize && strlen(opts.tmpoverlaysize) > 8) {
1389 ERROR("size parameter too long: \"%s\"\n", opts.tmpoverlaysize);
1390 return -1;
1391 }
1392
1393 /* no <binary> param found */
1394 if (!jsonfile && (argc - optind < 1)) {
1395 usage();
1396 return EXIT_FAILURE;
1397 }
1398 if (!(opts.namespace||opts.capabilities||opts.seccomp)) {
1399 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
1400 usage();
1401 return EXIT_FAILURE;
1402 }
1403 DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
1404 opts.namespace,
1405 opts.capabilities != 0 || opts.capset.apply,
1406 opts.seccomp != 0 || opts.ociseccomp != 0);
1407
1408 if (!jsonfile) {
1409 opts.jail_argv = &argv[optind];
1410 if (opts.namespace & CLONE_NEWUSER)
1411 get_jail_user(&opts.pw_uid, &opts.pw_gid, &opts.gr_gid);
1412 }
1413
1414 if (!opts.extroot) {
1415 if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
1416 ERROR("failed to load dependencies\n");
1417 return -1;
1418 }
1419 }
1420
1421 if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
1422 ERROR("failed to load libpreload-seccomp.so\n");
1423 opts.seccomp = 0;
1424 if (opts.require_jail)
1425 return -1;
1426 }
1427
1428 if (opts.name)
1429 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
1430
1431 uloop_init();
1432
1433 sigfillset(&sigmask);
1434 for (i = 0; i < _NSIG; i++) {
1435 struct sigaction s = { 0 };
1436
1437 if (!sigismember(&sigmask, i))
1438 continue;
1439 if ((i == SIGCHLD) || (i == SIGPIPE) || (i == SIGSEGV))
1440 continue;
1441
1442 s.sa_handler = jail_handle_signal;
1443 sigaction(i, &s, NULL);
1444 }
1445
1446 if (opts.namespace) {
1447 if (opts.namespace & CLONE_NEWNS) {
1448 add_mount("/dev/full", 0, -1);
1449 add_mount("/dev/null", 0, -1);
1450 add_mount("/dev/random", 0, -1);
1451 add_mount("/dev/urandom", 0, -1);
1452 add_mount("/dev/zero", 0, -1);
1453 add_mount("/dev/ptmx", 0, -1);
1454 add_mount("/dev/tty", 0, -1);
1455
1456 if (!opts.extroot && (opts.user || opts.group)) {
1457 add_mount("/etc/passwd", 0, -1);
1458 add_mount("/etc/group", 0, -1);
1459 }
1460
1461 #if defined(__GLIBC__)
1462 if (!opts.extroot)
1463 add_mount("/etc/nsswitch.conf", 0, -1);
1464 #endif
1465
1466 if (!(opts.namespace & CLONE_NEWNET)) {
1467 add_mount("/etc/resolv.conf", 0, -1);
1468 }
1469 }
1470
1471 if (pipe(&pipes[0]) < 0 || pipe(&pipes[2]) < 0)
1472 return -1;
1473
1474 jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, SIGCHLD | opts.namespace, &pipes);
1475 } else {
1476 jail_process.pid = fork();
1477 }
1478
1479 if (jail_process.pid > 0) {
1480 seteuid(0);
1481 /* parent process */
1482 close(pipes[1]);
1483 close(pipes[2]);
1484 if (read(pipes[0], sig_buf, 1) < 1) {
1485 ERROR("can't read from child\n");
1486 return -1;
1487 }
1488 close(pipes[0]);
1489 if (opts.namespace & CLONE_NEWUSER) {
1490 if (write_setgroups(jail_process.pid, true)) {
1491 ERROR("can't write setgroups\n");
1492 return -1;
1493 }
1494 if (!opts.uidmap) {
1495 bool has_gr = (opts.gr_gid != -1);
1496 if (opts.pw_uid != -1) {
1497 write_single_uid_gid_map(jail_process.pid, 0, opts.pw_uid);
1498 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:opts.pw_gid);
1499 } else {
1500 write_single_uid_gid_map(jail_process.pid, 0, 65534);
1501 write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:65534);
1502 }
1503 } else {
1504 write_uid_gid_map(jail_process.pid, 0, opts.uidmap);
1505 if (opts.gidmap)
1506 write_uid_gid_map(jail_process.pid, 1, opts.gidmap);
1507 }
1508 }
1509
1510 if (opts.namespace & CLONE_NEWNET) {
1511 if (!opts.name) {
1512 ERROR("netns needs a named jail\n");
1513 return -1;
1514 }
1515 netns_fd = netns_open_pid(jail_process.pid);
1516 netns_updown(jail_process.pid, true);
1517 }
1518
1519 sig_buf[0] = 'O';
1520 if (write(pipes[3], sig_buf, 1) < 0) {
1521 ERROR("can't write to child\n");
1522 return -1;
1523 }
1524 close(pipes[3]);
1525 uloop_process_add(&jail_process);
1526 uloop_run();
1527 if (jail_running) {
1528 DEBUG("uloop interrupted, killing jail process\n");
1529 kill(jail_process.pid, SIGTERM);
1530 uloop_timeout_set(&jail_process_timeout, 1000);
1531 uloop_run();
1532 }
1533 uloop_done();
1534 if (opts.namespace & CLONE_NEWNET) {
1535 setns(netns_fd, CLONE_NEWNET);
1536 netns_updown(getpid(), false);
1537 close(netns_fd);
1538 }
1539 return jail_return_code;
1540 } else if (jail_process.pid == 0) {
1541 /* fork child process */
1542 return exec_jail(NULL);
1543 } else {
1544 ERROR("failed to clone/fork: %m\n");
1545 return EXIT_FAILURE;
1546 }
1547 }