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