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