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