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