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