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