ujail: add <stdio.h> and <syslog.h> to seccomp.h
[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
29 #include "elf.h"
30 #include "capabilities.h"
31
32 #include <libubox/list.h>
33 #include <libubox/uloop.h>
34
35 #define STACK_SIZE      (1024 * 1024)
36 #define OPT_ARGS        "P:S:C:n:r:w:d:psulo"
37
38 static struct {
39         char *path;
40         char *name;
41         char **jail_argv;
42         char *seccomp;
43         char *capabilities;
44         int namespace;
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 | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0);
196         }
197         if (opts.sysfs) {
198                 mkdir("/sys", 0755);
199                 mount("sysfs", "/sys", "sysfs", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 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         const 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, "  -d <num>\tshow debug log (increase num to increase verbosity)\n");
237         fprintf(stderr, "  -S <file>\tseccomp filter config\n");
238         fprintf(stderr, "  -C <file>\tcapabilities drop config\n");
239         fprintf(stderr, "  -n <name>\tthe name of the jail\n");
240         fprintf(stderr, "namespace jail options:\n");
241         fprintf(stderr, "  -P <path>\tpath where the jail will be staged\n");
242         fprintf(stderr, "  -r <file>\treadonly files that should be staged\n");
243         fprintf(stderr, "  -w <file>\twriteable files that should be staged\n");
244         fprintf(stderr, "  -p\t\tjail has /proc\n");
245         fprintf(stderr, "  -s\t\tjail has /sys\n");
246         fprintf(stderr, "  -l\t\tjail has /dev/log\n");
247         fprintf(stderr, "  -u\t\tjail has a ubus socket\n");
248         fprintf(stderr, "  -o\t\tremont jail root (/) read only\n");
249         fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
250 and he has the same powers as root outside the jail,\n\
251 thus he can escape the jail and/or break stuff.\n\
252 Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
253 If you use none of the namespace jail options,\n\
254 ujail will not use namespace/build a jail,\n\
255 and will only drop capabilities/apply seccomp filter.\n\n");
256 }
257
258 static int exec_jail()
259 {
260         char **envp = build_envp(opts.seccomp);
261         if (!envp)
262                 exit(EXIT_FAILURE);
263
264         if (opts.capabilities && drop_capabilities(opts.capabilities))
265                 exit(EXIT_FAILURE);
266
267         INFO("exec-ing %s\n", *opts.jail_argv);
268         execve(*opts.jail_argv, opts.jail_argv, envp);
269         //we get there only if execve fails
270         ERROR("failed to execve %s: %s\n", *opts.jail_argv, strerror(errno));
271         exit(EXIT_FAILURE);
272 }
273
274 static int spawn_jail(void *_notused)
275 {
276         if (opts.name && sethostname(opts.name, strlen(opts.name))) {
277                 ERROR("failed to sethostname: %s\n", strerror(errno));
278         }
279
280         if (build_jail_fs()) {
281                 ERROR("failed to build jail fs");
282                 exit(EXIT_FAILURE);
283         }
284
285         return exec_jail();
286 }
287
288 static int jail_running = 1;
289 static int jail_return_code = 0;
290
291 static void jail_process_handler(struct uloop_process *c, int ret)
292 {
293         if (WIFEXITED(ret)) {
294                 jail_return_code = WEXITSTATUS(ret);
295                 INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
296         } else {
297                 jail_return_code = WTERMSIG(ret);
298                 INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
299         }
300         jail_running = 0;
301         uloop_end();
302 }
303
304 static struct uloop_process jail_process = {
305         .cb = jail_process_handler,
306 };
307
308 static void add_extra(char *name, int readonly)
309 {
310         struct extra *f;
311
312         if (*name != '/') {
313                 ERROR("%s is not an absolute path\n", name);
314                 return;
315         }
316
317         f = calloc(1, sizeof(struct extra));
318
319         f->name = basename(name);
320         f->path = dirname(strdup(name));
321         f->readonly = readonly;
322
323         list_add_tail(&f->list, &extras);
324 }
325
326 int main(int argc, char **argv)
327 {
328         uid_t uid = getuid();
329         char log[] = "/dev/log";
330         char ubus[] = "/var/run/ubus.sock";
331         int ret = EXIT_SUCCESS;
332         int ch;
333
334         if (uid) {
335                 ERROR("not root, aborting: %s\n", strerror(errno));
336                 return EXIT_FAILURE;
337         }
338
339         umask(022);
340
341         while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
342                 switch (ch) {
343                 case 'd':
344                         debug = atoi(optarg);
345                         break;
346                 case 'p':
347                         opts.namespace = 1;
348                         opts.procfs = 1;
349                         break;
350                 case 'o':
351                         opts.namespace = 1;
352                         opts.ronly = 1;
353                         break;
354                 case 's':
355                         opts.namespace = 1;
356                         opts.sysfs = 1;
357                         break;
358                 case 'S':
359                         opts.seccomp = optarg;
360                         add_extra(optarg, 1);
361                         break;
362                 case 'C':
363                         opts.capabilities = optarg;
364                         add_extra(optarg, 1);
365                         break;
366                 case 'P':
367                         opts.namespace = 1;
368                         opts.path = optarg;
369                         break;
370                 case 'n':
371                         opts.name = optarg;
372                         break;
373                 case 'r':
374                         opts.namespace = 1;
375                         add_extra(optarg, 1);
376                         break;
377                 case 'w':
378                         opts.namespace = 1;
379                         add_extra(optarg, 0);
380                         break;
381                 case 'u':
382                         opts.namespace = 1;
383                         add_extra(ubus, 0);
384                         break;
385                 case 'l':
386                         opts.namespace = 1;
387                         add_extra(log, 0);
388                         break;
389                 }
390         }
391
392         //no <binary> param found
393         if (argc - optind < 1) {
394                 usage();
395                 return EXIT_FAILURE;
396         }
397         if (!(opts.namespace||opts.capabilities||opts.seccomp)) {
398                 ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
399                 usage();
400                 return EXIT_FAILURE;
401         }
402         DEBUG("Using namespaces(%d), capabilities(%d), seccomp(%d)\n",
403                 opts.namespace,
404                 opts.capabilities != 0,
405                 opts.seccomp != 0);
406
407         opts.jail_argv = &argv[optind];
408
409         if (opts.name)
410                 prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
411
412         if (opts.namespace && !opts.path && asprintf(&opts.path, "/tmp/%s", basename(*opts.jail_argv)) == -1) {
413                 ERROR("failed to asprintf root path: %s\n", strerror(errno));
414                 return EXIT_FAILURE;
415         }
416
417         if (opts.namespace && mkdir(opts.path, 0755)) {
418                 ERROR("unable to create root path: %s (%s)\n", opts.path, strerror(errno));
419                 return EXIT_FAILURE;
420         }
421
422         uloop_init();
423         if (opts.namespace) {
424                 jail_process.pid = clone(spawn_jail,
425                         child_stack + STACK_SIZE,
426                         CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | SIGCHLD, NULL);
427         } else {
428                 jail_process.pid = fork();
429         }
430
431         if (jail_process.pid > 0) {
432                 //parent process
433                 uloop_process_add(&jail_process);
434                 uloop_run();
435                 uloop_done();
436                 if (jail_running) {
437                         DEBUG("uloop interrupted, killing jail process\n");
438                         kill(jail_process.pid, SIGTERM);
439                         waitpid(jail_process.pid, NULL, 0);
440                 }
441         } else if (jail_process.pid == 0) {
442                 //fork child process
443                 return exec_jail();
444         } else {
445                 ERROR("failed to clone/fork: %s\n", strerror(errno));
446                 ret = EXIT_FAILURE;
447         }
448
449         if (opts.namespace && rmdir(opts.path)) {
450                 ERROR("Unable to remove root path: %s (%s)\n", opts.path, strerror(errno));
451                 ret = EXIT_FAILURE;
452         }
453
454         if (ret)
455                 return ret;
456
457         return jail_return_code;
458 }