chiark / gitweb /
nspawn: don't require selinux on if it is compiled in
[elogind.git] / src / nspawn.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <signal.h>
23 #include <sched.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/syscall.h>
27 #include <sys/mount.h>
28 #include <sys/wait.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdio.h>
32 #include <errno.h>
33 #include <sys/prctl.h>
34 #include <sys/capability.h>
35 #include <getopt.h>
36
37 #include "log.h"
38 #include "util.h"
39 #include "missing.h"
40
41 static char *arg_directory = NULL;
42
43 static int help(void) {
44
45         printf("%s [OPTIONS...] [PATH] [ARGUMENTS...]\n\n"
46                "Spawn a minimal namespace container for debugging, testing and building.\n\n"
47                "  -h --help            Show this help\n"
48                "  -D --directory=NAME  Root directory for the container\n",
49                program_invocation_short_name);
50
51         return 0;
52 }
53
54 static int parse_argv(int argc, char *argv[]) {
55
56         static const struct option options[] = {
57                 { "help",      no_argument,       NULL, 'h' },
58                 { "directory", required_argument, NULL, 'D' },
59                 { NULL,        0,                 NULL, 0   }
60         };
61
62         int c;
63
64         assert(argc >= 0);
65         assert(argv);
66
67         while ((c = getopt_long(argc, argv, "+hD:", options, NULL)) >= 0) {
68
69                 switch (c) {
70
71                 case 'h':
72                         help();
73                         return 0;
74
75                 case 'D':
76                         free(arg_directory);
77                         if (!(arg_directory = strdup(optarg))) {
78                                 log_error("Failed to duplicate root directory.");
79                                 return -ENOMEM;
80                         }
81
82                         break;
83
84                 case '?':
85                         return -EINVAL;
86
87                 default:
88                         log_error("Unknown option code %c", c);
89                         return -EINVAL;
90                 }
91         }
92
93         return 1;
94 }
95
96 static int mount_all(const char *dest) {
97
98         typedef struct MountPoint {
99                 const char *what;
100                 const char *where;
101                 const char *type;
102                 const char *options;
103                 unsigned long flags;
104                 bool fatal;
105         } MountPoint;
106
107         static const MountPoint mount_table[] = {
108                 { "proc",      "/proc",     "proc",      NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
109                 { "/proc/sys", "/proc/sys", "bind",      NULL,        MS_BIND, true },                      /* Bind mount first */
110                 { "/proc/sys", "/proc/sys", "bind",      NULL,        MS_BIND|MS_RDONLY|MS_REMOUNT, true }, /* Then, make it r/o */
111                 { "sysfs",     "/sys",      "sysfs",     NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, true },
112                 { "tmpfs",     "/dev",      "tmpfs",     "mode=755",  MS_NOSUID, true },
113                 { "/dev/pts",  "/dev/pts",  "bind",      NULL,        MS_BIND, true },
114                 { "tmpfs",     "/dev/.run", "tmpfs",     "mode=755",  MS_NOSUID|MS_NOEXEC|MS_NODEV, true },
115 #ifdef HAVE_SELINUX
116                 { "selinux",   "/selinux",  "selinuxfs", NULL,        MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, false },
117 #endif
118         };
119
120         unsigned k;
121         int r = 0;
122
123         for (k = 0; k < ELEMENTSOF(mount_table); k++) {
124                 char *where;
125                 int t;
126
127                 if (asprintf(&where, "%s/%s", dest, mount_table[k].where) < 0) {
128                         log_error("Out of memory");
129
130                         if (r == 0)
131                                 r = -ENOMEM;
132
133                         break;
134                 }
135
136                 if ((t = path_is_mount_point(where)) < 0) {
137                         log_error("Failed to detect whether %s is a mount point: %s", where, strerror(-t));
138                         free(where);
139
140                         if (r == 0)
141                                 r = t;
142
143                         continue;
144                 }
145
146                 mkdir_p(where, 0755);
147
148                 if (mount(mount_table[k].what,
149                           where,
150                           mount_table[k].type,
151                           mount_table[k].flags,
152                           mount_table[k].options) < 0 &&
153                     mount_table[k].fatal) {
154
155                         log_error("mount(%s) failed: %m", where);
156
157                         if (r == 0)
158                                 r = -errno;
159                 }
160
161                 free(where);
162         }
163
164         return r;
165 }
166
167 static int copy_devnodes(const char *dest) {
168
169         static const char devnodes[] =
170                 "null\0"
171                 "zero\0"
172                 "full\0"
173                 "random\0"
174                 "urandom\0"
175                 "tty\0"
176                 "ptmx\0"
177                 "kmsg\0"
178                 "rtc0\0";
179
180         const char *d;
181         int r = 0, k;
182         char *tty = NULL;
183         dev_t tty_devnum;
184         mode_t u;
185
186         u = umask(0000);
187
188         NULSTR_FOREACH(d, devnodes) {
189                 char *from = NULL, *to = NULL;
190                 struct stat st;
191
192                 asprintf(&from, "/dev/%s", d);
193                 asprintf(&to, "%s/dev/%s", dest, d);
194
195                 if (!from || !to) {
196                         log_error("Failed to allocate devnode path");
197
198                         free(from);
199                         free(to);
200
201                         if (r == 0)
202                                 r = -ENOMEM;
203
204                         break;
205                 }
206
207                 if (stat(from, &st) < 0) {
208
209                         if (errno != ENOENT) {
210                                 log_error("Failed to stat %s: %m", from);
211
212                                 if (r == 0)
213                                         r = -errno;
214                         }
215
216                 } else {
217                         if (mknod(to, st.st_mode, st.st_rdev) < 0) {
218                                 log_error("mknod(%s) failed: %m", dest);
219
220                                 if (r == 0)
221                                         r = -errno;
222                         }
223                 }
224
225                 free(from);
226                 free(to);
227         }
228
229         if ((k = get_ctty(&tty, &tty_devnum)) < 0) {
230                 log_error("Failed to determine controlling tty: %s", strerror(-k));
231
232                 if (r == 0)
233                         r = k;
234         } else {
235                 char *from = NULL, *to = NULL;
236
237                 asprintf(&from, "/dev/%s", tty);
238                 asprintf(&to, "%s/dev/console", dest);
239
240                 if (!from || !to) {
241                         log_error("Out of memory");
242
243                         if (r == 0)
244                                 r = k;
245                 } else {
246                         /* We need to bind mount our own tty on
247                          * /dev/console, since ptys cannot be used
248                          * unless on a devpts file system. But to bind
249                          * mount it we first have to create a device
250                          * node where we can bind mount it on. This is
251                          * kinda ugly since the TTY will very likely
252                          * be owned by a user/group that does not
253                          * exist in the container. */
254
255                         if (mknod(to, S_IFCHR|0600, tty_devnum) < 0) {
256                                 log_error("mknod for /dev/console failed: %m");
257
258                                 if (r == 0)
259                                         r = -errno;
260                         }
261
262                         if (mount(from, to, "bind", MS_BIND|MS_RDONLY, NULL) < 0) {
263                                 log_error("bind mount for /dev/console failed: %m");
264
265                                 if (r == 0)
266                                         r = -errno;
267                         }
268                 }
269
270                 free(from);
271                 free(to);
272         }
273
274         free(tty);
275
276         umask(u);
277
278         return r;
279 }
280
281 static int drop_capabilities(void) {
282         static const unsigned long retain[] = {
283                 CAP_CHOWN,
284                 CAP_DAC_OVERRIDE,
285                 CAP_DAC_READ_SEARCH,
286                 CAP_FOWNER,
287                 CAP_FSETID,
288                 CAP_IPC_OWNER,
289                 CAP_KILL,
290                 CAP_LEASE,
291                 CAP_LINUX_IMMUTABLE,
292                 CAP_NET_BIND_SERVICE,
293                 CAP_NET_BROADCAST,
294                 CAP_NET_RAW,
295                 CAP_SETGID,
296                 CAP_SETFCAP,
297                 CAP_SETPCAP,
298                 CAP_SETUID,
299                 CAP_SYS_ADMIN,
300                 CAP_SYS_CHROOT,
301                 CAP_SYS_NICE,
302                 CAP_SYS_PTRACE,
303                 CAP_SYS_TTY_CONFIG
304         };
305
306         unsigned long l;
307
308         for (l = 0; l <= MAX(63LU, (unsigned long) CAP_LAST_CAP); l ++) {
309                 unsigned i;
310
311                 for (i = 0; i < ELEMENTSOF(retain); i++)
312                         if (retain[i] == l)
313                                 break;
314
315                 if (i < ELEMENTSOF(retain))
316                         continue;
317
318                 if (prctl(PR_CAPBSET_DROP, l) < 0) {
319
320                         /* If this capability is not known, EINVAL
321                          * will be returned, let's ignore this. */
322                         if (errno == EINVAL)
323                                 continue;
324
325                         log_error("PR_CAPBSET_DROP failed: %m");
326                         return -errno;
327                 }
328         }
329
330         return 0;
331 }
332
333 static int is_os_tree(const char *path) {
334         int r;
335         char *p;
336         /* We use /bin/sh as flag file if something is an OS */
337
338         if (asprintf(&p, "%s/bin/sh", path) < 0)
339                 return -ENOMEM;
340
341         r = access(p, F_OK);
342         free(p);
343
344         return r < 0 ? 0 : 1;
345 }
346
347
348 int main(int argc, char *argv[]) {
349         pid_t pid = 0;
350         int r = EXIT_FAILURE;
351
352         log_parse_environment();
353         log_open();
354
355         if ((r = parse_argv(argc, argv)) <= 0)
356                 goto finish;
357
358         if (arg_directory) {
359                 char *p;
360
361                 p = path_make_absolute_cwd(arg_directory);
362                 free(arg_directory);
363                 arg_directory = p;
364         } else
365                 arg_directory = get_current_dir_name();
366
367         if (!arg_directory) {
368                 log_error("Failed to determine path");
369                 goto finish;
370         }
371
372         path_kill_slashes(arg_directory);
373
374         if (geteuid() != 0) {
375                 log_error("Need to be root.");
376                 goto finish;
377         }
378
379         if (path_equal(arg_directory, "/")) {
380                 log_error("Spawning container on root directory not supported.");
381                 goto finish;
382         }
383
384         if (is_os_tree(arg_directory) <= 0) {
385                 log_error("Directory %s doesn't look like an OS root directory. Refusing.", arg_directory);
386                 goto finish;
387         }
388
389         log_info("Spawning namespace container on %s.", arg_directory);
390
391         if ((pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS, NULL)) < 0) {
392                 log_error("clone() failed: %m");
393                 goto finish;
394         }
395
396         if (pid == 0) {
397                 const char *hn;
398                 const char *envp[] = {
399                         "HOME=/root",
400                         "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
401                         NULL
402                 };
403
404                 /* child */
405
406                 if (mount_all(arg_directory) < 0)
407                         goto child_fail;
408
409                 if (copy_devnodes(arg_directory) < 0)
410                         goto child_fail;
411
412                 if (chdir(arg_directory) < 0) {
413                         log_error("chdir(%s) failed: %m", arg_directory);
414                         goto child_fail;
415                 }
416                 if (mount(arg_directory, "/", "bind", MS_BIND|MS_MOVE, NULL) < 0) {
417                         log_error("mount(MS_MOVE) failed: %m");
418                         goto child_fail;
419                 }
420
421                 if (chroot(".") < 0) {
422                         log_error("chroot() failed: %m");
423                         goto child_fail;
424                 }
425
426                 if (chdir("/") < 0) {
427                         log_error("chdir() failed: %m");
428                         goto child_fail;
429                 }
430
431                 if (drop_capabilities() < 0)
432                         goto child_fail;
433
434                 if ((hn = file_name_from_path(arg_directory)))
435                         sethostname(hn, strlen(hn));
436
437                 if (argc > optind)
438                         execvpe(argv[optind], argv + optind, (char**) envp);
439                 else {
440                         chdir("/root");
441                         execle("/bin/bash", "-bash", NULL, (char**) envp);
442                 }
443
444                 log_error("execv() failed: %m");
445
446         child_fail:
447                 _exit(EXIT_FAILURE);
448         }
449
450         r = wait_for_terminate_and_warn(argc > optind ? argv[optind] : "bash", pid);
451
452         if (r < 0)
453                 r = EXIT_FAILURE;
454
455 finish:
456         free(arg_directory);
457
458         if (pid > 0)
459                 kill(pid, SIGTERM);
460
461         return r;
462 }