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