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