]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/namespace.c
core: add RootImage= setting for using a specific image file as root directory for...
[thirdparty/systemd.git] / src / core / namespace.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <sched.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <sys/mount.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 #include <linux/fs.h>
28
29 #include "alloc-util.h"
30 #include "dev-setup.h"
31 #include "fd-util.h"
32 #include "fs-util.h"
33 #include "loop-util.h"
34 #include "loopback-setup.h"
35 #include "missing.h"
36 #include "mkdir.h"
37 #include "mount-util.h"
38 #include "namespace.h"
39 #include "path-util.h"
40 #include "selinux-util.h"
41 #include "socket-util.h"
42 #include "string-table.h"
43 #include "string-util.h"
44 #include "strv.h"
45 #include "umask-util.h"
46 #include "user-util.h"
47 #include "util.h"
48
49 #define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
50
51 typedef enum MountMode {
52 /* This is ordered by priority! */
53 INACCESSIBLE,
54 BIND_MOUNT,
55 BIND_MOUNT_RECURSIVE,
56 PRIVATE_TMP,
57 PRIVATE_VAR_TMP,
58 PRIVATE_DEV,
59 BIND_DEV,
60 SYSFS,
61 PROCFS,
62 READONLY,
63 READWRITE,
64 } MountMode;
65
66 typedef struct MountEntry {
67 const char *path_const; /* Memory allocated on stack or static */
68 MountMode mode:5;
69 bool ignore:1; /* Ignore if path does not exist? */
70 bool has_prefix:1; /* Already is prefixed by the root dir? */
71 bool read_only:1; /* Shall this mount point be read-only? */
72 char *path_malloc; /* Use this instead of 'path' if we had to allocate memory */
73 const char *source_const; /* The source path, for bind mounts */
74 char *source_malloc;
75 } MountEntry;
76
77 /* If MountAPIVFS= is used, let's mount /sys and /proc into the it, but only as a fallback if the user hasn't mounted
78 * something there already. These mounts are hence overriden by any other explicitly configured mounts. */
79 static const MountEntry apivfs_table[] = {
80 { "/proc", PROCFS, false },
81 { "/dev", BIND_DEV, false },
82 { "/sys", SYSFS, false },
83 };
84
85 /* ProtectKernelTunables= option and the related filesystem APIs */
86 static const MountEntry protect_kernel_tunables_table[] = {
87 { "/proc/sys", READONLY, false },
88 { "/proc/sysrq-trigger", READONLY, true },
89 { "/proc/latency_stats", READONLY, true },
90 { "/proc/mtrr", READONLY, true },
91 { "/proc/apm", READONLY, true }, /* Obsolete API, there's no point in permitting access to this, ever */
92 { "/proc/acpi", READONLY, true },
93 { "/proc/timer_stats", READONLY, true },
94 { "/proc/asound", READONLY, true },
95 { "/proc/bus", READONLY, true },
96 { "/proc/fs", READONLY, true },
97 { "/proc/irq", READONLY, true },
98 { "/sys", READONLY, false },
99 { "/sys/kernel/debug", READONLY, true },
100 { "/sys/kernel/tracing", READONLY, true },
101 { "/sys/fs/cgroup", READWRITE, false }, /* READONLY is set by ProtectControlGroups= option */
102 };
103
104 /* ProtectKernelModules= option */
105 static const MountEntry protect_kernel_modules_table[] = {
106 #ifdef HAVE_SPLIT_USR
107 { "/lib/modules", INACCESSIBLE, true },
108 #endif
109 { "/usr/lib/modules", INACCESSIBLE, true },
110 };
111
112 /*
113 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
114 * system should be protected by ProtectSystem=
115 */
116 static const MountEntry protect_home_read_only_table[] = {
117 { "/home", READONLY, true },
118 { "/run/user", READONLY, true },
119 { "/root", READONLY, true },
120 };
121
122 /* ProtectHome=yes table */
123 static const MountEntry protect_home_yes_table[] = {
124 { "/home", INACCESSIBLE, true },
125 { "/run/user", INACCESSIBLE, true },
126 { "/root", INACCESSIBLE, true },
127 };
128
129 /* ProtectSystem=yes table */
130 static const MountEntry protect_system_yes_table[] = {
131 { "/usr", READONLY, false },
132 { "/boot", READONLY, true },
133 { "/efi", READONLY, true },
134 };
135
136 /* ProtectSystem=full includes ProtectSystem=yes */
137 static const MountEntry protect_system_full_table[] = {
138 { "/usr", READONLY, false },
139 { "/boot", READONLY, true },
140 { "/efi", READONLY, true },
141 { "/etc", READONLY, false },
142 };
143
144 /*
145 * ProtectSystem=strict table. In this strict mode, we mount everything
146 * read-only, except for /proc, /dev, /sys which are the kernel API VFS,
147 * which are left writable, but PrivateDevices= + ProtectKernelTunables=
148 * protect those, and these options should be fully orthogonal.
149 * (And of course /home and friends are also left writable, as ProtectHome=
150 * shall manage those, orthogonally).
151 */
152 static const MountEntry protect_system_strict_table[] = {
153 { "/", READONLY, false },
154 { "/proc", READWRITE, false }, /* ProtectKernelTunables= */
155 { "/sys", READWRITE, false }, /* ProtectKernelTunables= */
156 { "/dev", READWRITE, false }, /* PrivateDevices= */
157 { "/home", READWRITE, true }, /* ProtectHome= */
158 { "/run/user", READWRITE, true }, /* ProtectHome= */
159 { "/root", READWRITE, true }, /* ProtectHome= */
160 };
161
162 static const char *mount_entry_path(const MountEntry *p) {
163 assert(p);
164
165 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
166 * otherwise the stack/static ->path field is returned. */
167
168 return p->path_malloc ?: p->path_const;
169 }
170
171 static bool mount_entry_read_only(const MountEntry *p) {
172 assert(p);
173
174 return p->read_only || IN_SET(p->mode, READONLY, INACCESSIBLE);
175 }
176
177 static const char *mount_entry_source(const MountEntry *p) {
178 assert(p);
179
180 return p->source_malloc ?: p->source_const;
181 }
182
183 static void mount_entry_done(MountEntry *p) {
184 assert(p);
185
186 p->path_malloc = mfree(p->path_malloc);
187 p->source_malloc = mfree(p->source_malloc);
188 }
189
190 static int append_access_mounts(MountEntry **p, char **strv, MountMode mode) {
191 char **i;
192
193 assert(p);
194
195 /* Adds a list of user-supplied READWRITE/READONLY/INACCESSIBLE entries */
196
197 STRV_FOREACH(i, strv) {
198 bool ignore = false, needs_prefix = false;
199 const char *e = *i;
200
201 /* Look for any prefixes */
202 if (startswith(e, "-")) {
203 e++;
204 ignore = true;
205 }
206 if (startswith(e, "+")) {
207 e++;
208 needs_prefix = true;
209 }
210
211 if (!path_is_absolute(e))
212 return -EINVAL;
213
214 *((*p)++) = (MountEntry) {
215 .path_const = e,
216 .mode = mode,
217 .ignore = ignore,
218 .has_prefix = !needs_prefix,
219 };
220 }
221
222 return 0;
223 }
224
225 static int append_bind_mounts(MountEntry **p, const BindMount *binds, unsigned n) {
226 unsigned i;
227
228 assert(p);
229
230 for (i = 0; i < n; i++) {
231 const BindMount *b = binds + i;
232
233 *((*p)++) = (MountEntry) {
234 .path_const = b->destination,
235 .mode = b->recursive ? BIND_MOUNT_RECURSIVE : BIND_MOUNT,
236 .read_only = b->read_only,
237 .source_const = b->source,
238 };
239 }
240
241 return 0;
242 }
243
244 static int append_static_mounts(MountEntry **p, const MountEntry *mounts, unsigned n, bool ignore_protect) {
245 unsigned i;
246
247 assert(p);
248 assert(mounts);
249
250 /* Adds a list of static pre-defined entries */
251
252 for (i = 0; i < n; i++)
253 *((*p)++) = (MountEntry) {
254 .path_const = mount_entry_path(mounts+i),
255 .mode = mounts[i].mode,
256 .ignore = mounts[i].ignore || ignore_protect,
257 };
258
259 return 0;
260 }
261
262 static int append_protect_home(MountEntry **p, ProtectHome protect_home, bool ignore_protect) {
263 assert(p);
264
265 switch (protect_home) {
266
267 case PROTECT_HOME_NO:
268 return 0;
269
270 case PROTECT_HOME_READ_ONLY:
271 return append_static_mounts(p, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
272
273 case PROTECT_HOME_YES:
274 return append_static_mounts(p, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
275
276 default:
277 assert_not_reached("Unexpected ProtectHome= value");
278 }
279 }
280
281 static int append_protect_system(MountEntry **p, ProtectSystem protect_system, bool ignore_protect) {
282 assert(p);
283
284 switch (protect_system) {
285
286 case PROTECT_SYSTEM_NO:
287 return 0;
288
289 case PROTECT_SYSTEM_STRICT:
290 return append_static_mounts(p, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
291
292 case PROTECT_SYSTEM_YES:
293 return append_static_mounts(p, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
294
295 case PROTECT_SYSTEM_FULL:
296 return append_static_mounts(p, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
297
298 default:
299 assert_not_reached("Unexpected ProtectSystem= value");
300 }
301 }
302
303 static int mount_path_compare(const void *a, const void *b) {
304 const MountEntry *p = a, *q = b;
305 int d;
306
307 /* If the paths are not equal, then order prefixes first */
308 d = path_compare(mount_entry_path(p), mount_entry_path(q));
309 if (d != 0)
310 return d;
311
312 /* If the paths are equal, check the mode */
313 if (p->mode < q->mode)
314 return -1;
315
316 if (p->mode > q->mode)
317 return 1;
318
319 return 0;
320 }
321
322 static int prefix_where_needed(MountEntry *m, unsigned n, const char *root_directory) {
323 unsigned i;
324
325 /* Prefixes all paths in the bind mount table with the root directory if it is specified and the entry needs
326 * that. */
327
328 if (!root_directory)
329 return 0;
330
331 for (i = 0; i < n; i++) {
332 char *s;
333
334 if (m[i].has_prefix)
335 continue;
336
337 s = prefix_root(root_directory, mount_entry_path(m+i));
338 if (!s)
339 return -ENOMEM;
340
341 free(m[i].path_malloc);
342 m[i].path_malloc = s;
343
344 m[i].has_prefix = true;
345 }
346
347 return 0;
348 }
349
350 static void drop_duplicates(MountEntry *m, unsigned *n) {
351 MountEntry *f, *t, *previous;
352
353 assert(m);
354 assert(n);
355
356 /* Drops duplicate entries. Expects that the array is properly ordered already. */
357
358 for (f = m, t = m, previous = NULL; f < m + *n; f++) {
359
360 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
361 * above. */
362 if (previous && path_equal(mount_entry_path(f), mount_entry_path(previous))) {
363 log_debug("%s is duplicate.", mount_entry_path(f));
364 previous->read_only = previous->read_only || mount_entry_read_only(f); /* Propagate the read-only flag to the remaining entry */
365 mount_entry_done(f);
366 continue;
367 }
368
369 *t = *f;
370 previous = t;
371 t++;
372 }
373
374 *n = t - m;
375 }
376
377 static void drop_inaccessible(MountEntry *m, unsigned *n) {
378 MountEntry *f, *t;
379 const char *clear = NULL;
380
381 assert(m);
382 assert(n);
383
384 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
385 * ordered already. */
386
387 for (f = m, t = m; f < m + *n; f++) {
388
389 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
390 * it, as inaccessible paths really should drop the entire subtree. */
391 if (clear && path_startswith(mount_entry_path(f), clear)) {
392 log_debug("%s is masked by %s.", mount_entry_path(f), clear);
393 mount_entry_done(f);
394 continue;
395 }
396
397 clear = f->mode == INACCESSIBLE ? mount_entry_path(f) : NULL;
398
399 *t = *f;
400 t++;
401 }
402
403 *n = t - m;
404 }
405
406 static void drop_nop(MountEntry *m, unsigned *n) {
407 MountEntry *f, *t;
408
409 assert(m);
410 assert(n);
411
412 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
413 * list is ordered by prefixes. */
414
415 for (f = m, t = m; f < m + *n; f++) {
416
417 /* Only suppress such subtrees for READONLY and READWRITE entries */
418 if (IN_SET(f->mode, READONLY, READWRITE)) {
419 MountEntry *p;
420 bool found = false;
421
422 /* Now let's find the first parent of the entry we are looking at. */
423 for (p = t-1; p >= m; p--) {
424 if (path_startswith(mount_entry_path(f), mount_entry_path(p))) {
425 found = true;
426 break;
427 }
428 }
429
430 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
431 if (found && p->mode == f->mode) {
432 log_debug("%s is redundant by %s", mount_entry_path(f), mount_entry_path(p));
433 mount_entry_done(f);
434 continue;
435 }
436 }
437
438 *t = *f;
439 t++;
440 }
441
442 *n = t - m;
443 }
444
445 static void drop_outside_root(const char *root_directory, MountEntry *m, unsigned *n) {
446 MountEntry *f, *t;
447
448 assert(m);
449 assert(n);
450
451 /* Nothing to do */
452 if (!root_directory)
453 return;
454
455 /* Drops all mounts that are outside of the root directory. */
456
457 for (f = m, t = m; f < m + *n; f++) {
458
459 if (!path_startswith(mount_entry_path(f), root_directory)) {
460 log_debug("%s is outside of root directory.", mount_entry_path(f));
461 mount_entry_done(f);
462 continue;
463 }
464
465 *t = *f;
466 t++;
467 }
468
469 *n = t - m;
470 }
471
472 static int mount_private_dev(MountEntry *m) {
473 static const char devnodes[] =
474 "/dev/null\0"
475 "/dev/zero\0"
476 "/dev/full\0"
477 "/dev/random\0"
478 "/dev/urandom\0"
479 "/dev/tty\0";
480
481 char temporary_mount[] = "/tmp/namespace-dev-XXXXXX";
482 const char *d, *dev = NULL, *devpts = NULL, *devshm = NULL, *devhugepages = NULL, *devmqueue = NULL, *devlog = NULL, *devptmx = NULL;
483 _cleanup_umask_ mode_t u;
484 int r;
485
486 assert(m);
487
488 u = umask(0000);
489
490 if (!mkdtemp(temporary_mount))
491 return -errno;
492
493 dev = strjoina(temporary_mount, "/dev");
494 (void) mkdir(dev, 0755);
495 if (mount("tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=755") < 0) {
496 r = -errno;
497 goto fail;
498 }
499
500 devpts = strjoina(temporary_mount, "/dev/pts");
501 (void) mkdir(devpts, 0755);
502 if (mount("/dev/pts", devpts, NULL, MS_BIND, NULL) < 0) {
503 r = -errno;
504 goto fail;
505 }
506
507 devptmx = strjoina(temporary_mount, "/dev/ptmx");
508 if (symlink("pts/ptmx", devptmx) < 0) {
509 r = -errno;
510 goto fail;
511 }
512
513 devshm = strjoina(temporary_mount, "/dev/shm");
514 (void) mkdir(devshm, 01777);
515 r = mount("/dev/shm", devshm, NULL, MS_BIND, NULL);
516 if (r < 0) {
517 r = -errno;
518 goto fail;
519 }
520
521 devmqueue = strjoina(temporary_mount, "/dev/mqueue");
522 (void) mkdir(devmqueue, 0755);
523 (void) mount("/dev/mqueue", devmqueue, NULL, MS_BIND, NULL);
524
525 devhugepages = strjoina(temporary_mount, "/dev/hugepages");
526 (void) mkdir(devhugepages, 0755);
527 (void) mount("/dev/hugepages", devhugepages, NULL, MS_BIND, NULL);
528
529 devlog = strjoina(temporary_mount, "/dev/log");
530 (void) symlink("/run/systemd/journal/dev-log", devlog);
531
532 NULSTR_FOREACH(d, devnodes) {
533 _cleanup_free_ char *dn = NULL;
534 struct stat st;
535
536 r = stat(d, &st);
537 if (r < 0) {
538
539 if (errno == ENOENT)
540 continue;
541
542 r = -errno;
543 goto fail;
544 }
545
546 if (!S_ISBLK(st.st_mode) &&
547 !S_ISCHR(st.st_mode)) {
548 r = -EINVAL;
549 goto fail;
550 }
551
552 if (st.st_rdev == 0)
553 continue;
554
555 dn = strappend(temporary_mount, d);
556 if (!dn) {
557 r = -ENOMEM;
558 goto fail;
559 }
560
561 mac_selinux_create_file_prepare(d, st.st_mode);
562 r = mknod(dn, st.st_mode, st.st_rdev);
563 mac_selinux_create_file_clear();
564
565 if (r < 0) {
566 r = -errno;
567 goto fail;
568 }
569 }
570
571 dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
572
573 /* Create the /dev directory if missing. It is more likely to be
574 * missing when the service is started with RootDirectory. This is
575 * consistent with mount units creating the mount points when missing.
576 */
577 (void) mkdir_p_label(mount_entry_path(m), 0755);
578
579 /* Unmount everything in old /dev */
580 umount_recursive(mount_entry_path(m), 0);
581 if (mount(dev, mount_entry_path(m), NULL, MS_MOVE, NULL) < 0) {
582 r = -errno;
583 goto fail;
584 }
585
586 rmdir(dev);
587 rmdir(temporary_mount);
588
589 return 0;
590
591 fail:
592 if (devpts)
593 umount(devpts);
594
595 if (devshm)
596 umount(devshm);
597
598 if (devhugepages)
599 umount(devhugepages);
600
601 if (devmqueue)
602 umount(devmqueue);
603
604 umount(dev);
605 rmdir(dev);
606 rmdir(temporary_mount);
607
608 return r;
609 }
610
611 static int mount_bind_dev(MountEntry *m) {
612 int r;
613
614 assert(m);
615
616 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the service's
617 * /dev. This is only used when RootDirectory= is set. */
618
619 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
620 if (r < 0)
621 return log_debug_errno(r, "Unable to determine whether /dev is already mounted: %m");
622 if (r > 0) /* make this a NOP if /dev is already a mount point */
623 return 0;
624
625 if (mount("/dev", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL) < 0)
626 return log_debug_errno(errno, "Failed to bind mount %s: %m", mount_entry_path(m));
627
628 return 1;
629 }
630
631 static int mount_sysfs(MountEntry *m) {
632 int r;
633
634 assert(m);
635
636 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
637 if (r < 0)
638 return log_debug_errno(r, "Unable to determine whether /sys is already mounted: %m");
639 if (r > 0) /* make this a NOP if /sys is already a mount point */
640 return 0;
641
642 /* Bind mount the host's version so that we get all child mounts of it, too. */
643 if (mount("/sys", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL) < 0)
644 return log_debug_errno(errno, "Failed to mount %s: %m", mount_entry_path(m));
645
646 return 1;
647 }
648
649 static int mount_procfs(MountEntry *m) {
650 int r;
651
652 assert(m);
653
654 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
655 if (r < 0)
656 return log_debug_errno(r, "Unable to determine whether /proc is already mounted: %m");
657 if (r > 0) /* make this a NOP if /proc is already a mount point */
658 return 0;
659
660 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in one */
661 if (mount("proc", mount_entry_path(m), "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) < 0)
662 return log_debug_errno(errno, "Failed to mount %s: %m", mount_entry_path(m));
663
664 return 1;
665 }
666
667 static int mount_entry_chase(
668 const char *root_directory,
669 MountEntry *m,
670 const char *path,
671 char **location) {
672
673 char *chased;
674 int r;
675
676 assert(m);
677
678 /* Since mount() will always follow symlinks and we need to take the different root directory into account we
679 * chase the symlinks on our own first. This is called for the destination path, as well as the source path (if
680 * that applies). The result is stored in "location". */
681
682 r = chase_symlinks(path, root_directory, 0, &chased);
683 if (r == -ENOENT && m->ignore) {
684 log_debug_errno(r, "Path %s does not exist, ignoring.", path);
685 return 0;
686 }
687 if (r < 0)
688 return log_debug_errno(r, "Failed to follow symlinks on %s: %m", path);
689
690 log_debug("Followed symlinks %s → %s.", path, chased);
691
692 free(*location);
693 *location = chased;
694
695 return 1;
696 }
697
698 static int apply_mount(
699 const char *root_directory,
700 MountEntry *m,
701 const char *tmp_dir,
702 const char *var_tmp_dir) {
703
704 const char *what;
705 bool rbind = true;
706 int r;
707
708 assert(m);
709
710 r = mount_entry_chase(root_directory, m, mount_entry_path(m), &m->path_malloc);
711 if (r <= 0)
712 return r;
713
714 log_debug("Applying namespace mount on %s", mount_entry_path(m));
715
716 switch (m->mode) {
717
718 case INACCESSIBLE: {
719 struct stat target;
720
721 /* First, get rid of everything that is below if there
722 * is anything... Then, overmount it with an
723 * inaccessible path. */
724 (void) umount_recursive(mount_entry_path(m), 0);
725
726 if (lstat(mount_entry_path(m), &target) < 0)
727 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m", mount_entry_path(m));
728
729 what = mode_to_inaccessible_node(target.st_mode);
730 if (!what) {
731 log_debug("File type not supported for inaccessible mounts. Note that symlinks are not allowed");
732 return -ELOOP;
733 }
734 break;
735 }
736
737 case READONLY:
738 case READWRITE:
739 r = path_is_mount_point(mount_entry_path(m), root_directory, 0);
740 if (r < 0)
741 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m", mount_entry_path(m));
742 if (r > 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY bit for the mount point if needed. */
743 return 0;
744 /* This isn't a mount point yet, let's make it one. */
745 what = mount_entry_path(m);
746 break;
747
748 case BIND_MOUNT:
749 rbind = false;
750 /* fallthrough */
751
752 case BIND_MOUNT_RECURSIVE:
753 /* Also chase the source mount */
754
755 r = mount_entry_chase(root_directory, m, mount_entry_source(m), &m->source_malloc);
756 if (r <= 0)
757 return r;
758
759 what = mount_entry_source(m);
760 break;
761
762 case PRIVATE_TMP:
763 what = tmp_dir;
764 break;
765
766 case PRIVATE_VAR_TMP:
767 what = var_tmp_dir;
768 break;
769
770 case PRIVATE_DEV:
771 return mount_private_dev(m);
772
773 case BIND_DEV:
774 return mount_bind_dev(m);
775
776 case SYSFS:
777 return mount_sysfs(m);
778
779 case PROCFS:
780 return mount_procfs(m);
781
782 default:
783 assert_not_reached("Unknown mode");
784 }
785
786 assert(what);
787
788 if (mount(what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL) < 0)
789 return log_debug_errno(errno, "Failed to mount %s to %s: %m", what, mount_entry_path(m));
790
791 log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
792 return 0;
793 }
794
795 static int make_read_only(MountEntry *m, char **blacklist) {
796 int r = 0;
797
798 assert(m);
799
800 if (mount_entry_read_only(m))
801 r = bind_remount_recursive(mount_entry_path(m), true, blacklist);
802 else if (m->mode == PRIVATE_DEV) { /* Superblock can be readonly but the submounts can't*/
803 if (mount(NULL, mount_entry_path(m), NULL, MS_REMOUNT|DEV_MOUNT_OPTIONS|MS_RDONLY, NULL) < 0)
804 r = -errno;
805 } else
806 return 0;
807
808 /* Not that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked read-only
809 * already stays this way. This improves compatibility with container managers, where we won't attempt to undo
810 * read-only mounts already applied. */
811
812 if (r == -ENOENT && m->ignore)
813 r = 0;
814
815 return r;
816 }
817
818 static bool namespace_info_mount_apivfs(const NameSpaceInfo *ns_info) {
819 assert(ns_info);
820
821 /* ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=, since to protect the API VFS mounts,
822 * they need to be around in the first place... */
823
824 return ns_info->mount_apivfs ||
825 ns_info->protect_control_groups ||
826 ns_info->protect_kernel_tunables;
827 }
828
829 static unsigned namespace_calculate_mounts(
830 const NameSpaceInfo *ns_info,
831 char** read_write_paths,
832 char** read_only_paths,
833 char** inaccessible_paths,
834 const BindMount *bind_mounts,
835 unsigned n_bind_mounts,
836 const char* tmp_dir,
837 const char* var_tmp_dir,
838 ProtectHome protect_home,
839 ProtectSystem protect_system) {
840
841 unsigned protect_home_cnt;
842 unsigned protect_system_cnt =
843 (protect_system == PROTECT_SYSTEM_STRICT ?
844 ELEMENTSOF(protect_system_strict_table) :
845 ((protect_system == PROTECT_SYSTEM_FULL) ?
846 ELEMENTSOF(protect_system_full_table) :
847 ((protect_system == PROTECT_SYSTEM_YES) ?
848 ELEMENTSOF(protect_system_yes_table) : 0)));
849
850 protect_home_cnt =
851 (protect_home == PROTECT_HOME_YES ?
852 ELEMENTSOF(protect_home_yes_table) :
853 ((protect_home == PROTECT_HOME_READ_ONLY) ?
854 ELEMENTSOF(protect_home_read_only_table) : 0));
855
856 return !!tmp_dir + !!var_tmp_dir +
857 strv_length(read_write_paths) +
858 strv_length(read_only_paths) +
859 strv_length(inaccessible_paths) +
860 n_bind_mounts +
861 ns_info->private_dev +
862 (ns_info->protect_kernel_tunables ? ELEMENTSOF(protect_kernel_tunables_table) : 0) +
863 (ns_info->protect_control_groups ? 1 : 0) +
864 (ns_info->protect_kernel_modules ? ELEMENTSOF(protect_kernel_modules_table) : 0) +
865 protect_home_cnt + protect_system_cnt +
866 (namespace_info_mount_apivfs(ns_info) ? ELEMENTSOF(apivfs_table) : 0);
867 }
868
869 int setup_namespace(
870 const char* root_directory,
871 const char* root_image,
872 const NameSpaceInfo *ns_info,
873 char** read_write_paths,
874 char** read_only_paths,
875 char** inaccessible_paths,
876 const BindMount *bind_mounts,
877 unsigned n_bind_mounts,
878 const char* tmp_dir,
879 const char* var_tmp_dir,
880 ProtectHome protect_home,
881 ProtectSystem protect_system,
882 unsigned long mount_flags,
883 DissectImageFlags dissect_image_flags) {
884
885 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
886 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
887 MountEntry *m, *mounts = NULL;
888 bool make_slave = false;
889 unsigned n_mounts;
890 int r = 0;
891
892 assert(ns_info);
893
894 if (mount_flags == 0)
895 mount_flags = MS_SHARED;
896
897 if (root_image) {
898 dissect_image_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
899
900 if (protect_system == PROTECT_SYSTEM_STRICT && strv_isempty(read_write_paths))
901 dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
902
903 r = loop_device_make_by_path(root_image,
904 dissect_image_flags & DISSECT_IMAGE_READ_ONLY ? O_RDONLY : O_RDWR,
905 &loop_device);
906 if (r < 0)
907 return r;
908
909 r = dissect_image(loop_device->fd, NULL, 0, dissect_image_flags, &dissected_image);
910 if (r < 0)
911 return r;
912
913 if (!root_directory) {
914 /* Create a mount point for the image, if it's still missing. We use the same mount point for
915 * all images, which is safe, since they all live in their own namespaces after all, and hence
916 * won't see each other. */
917 root_directory = "/run/systemd/unit-root";
918 (void) mkdir(root_directory, 0700);
919 }
920 }
921
922 n_mounts = namespace_calculate_mounts(
923 ns_info,
924 read_write_paths,
925 read_only_paths,
926 inaccessible_paths,
927 bind_mounts, n_bind_mounts,
928 tmp_dir, var_tmp_dir,
929 protect_home, protect_system);
930
931 /* Set mount slave mode */
932 if (root_directory || n_mounts > 0)
933 make_slave = true;
934
935 if (n_mounts > 0) {
936 m = mounts = (MountEntry *) alloca0(n_mounts * sizeof(MountEntry));
937 r = append_access_mounts(&m, read_write_paths, READWRITE);
938 if (r < 0)
939 goto finish;
940
941 r = append_access_mounts(&m, read_only_paths, READONLY);
942 if (r < 0)
943 goto finish;
944
945 r = append_access_mounts(&m, inaccessible_paths, INACCESSIBLE);
946 if (r < 0)
947 goto finish;
948
949 r = append_bind_mounts(&m, bind_mounts, n_bind_mounts);
950 if (r < 0)
951 goto finish;
952
953 if (tmp_dir) {
954 *(m++) = (MountEntry) {
955 .path_const = "/tmp",
956 .mode = PRIVATE_TMP,
957 };
958 }
959
960 if (var_tmp_dir) {
961 *(m++) = (MountEntry) {
962 .path_const = "/var/tmp",
963 .mode = PRIVATE_VAR_TMP,
964 };
965 }
966
967 if (ns_info->private_dev) {
968 *(m++) = (MountEntry) {
969 .path_const = "/dev",
970 .mode = PRIVATE_DEV,
971 };
972 }
973
974 if (ns_info->protect_kernel_tunables) {
975 r = append_static_mounts(&m, protect_kernel_tunables_table, ELEMENTSOF(protect_kernel_tunables_table), ns_info->ignore_protect_paths);
976 if (r < 0)
977 goto finish;
978 }
979
980 if (ns_info->protect_kernel_modules) {
981 r = append_static_mounts(&m, protect_kernel_modules_table, ELEMENTSOF(protect_kernel_modules_table), ns_info->ignore_protect_paths);
982 if (r < 0)
983 goto finish;
984 }
985
986 if (ns_info->protect_control_groups) {
987 *(m++) = (MountEntry) {
988 .path_const = "/sys/fs/cgroup",
989 .mode = READONLY,
990 };
991 }
992
993 r = append_protect_home(&m, protect_home, ns_info->ignore_protect_paths);
994 if (r < 0)
995 goto finish;
996
997 r = append_protect_system(&m, protect_system, false);
998 if (r < 0)
999 goto finish;
1000
1001 if (namespace_info_mount_apivfs(ns_info)) {
1002 r = append_static_mounts(&m, apivfs_table, ELEMENTSOF(apivfs_table), ns_info->ignore_protect_paths);
1003 if (r < 0)
1004 goto finish;
1005 }
1006
1007 assert(mounts + n_mounts == m);
1008
1009 /* Prepend the root directory where that's necessary */
1010 r = prefix_where_needed(mounts, n_mounts, root_directory);
1011 if (r < 0)
1012 goto finish;
1013
1014 qsort(mounts, n_mounts, sizeof(MountEntry), mount_path_compare);
1015
1016 drop_duplicates(mounts, &n_mounts);
1017 drop_outside_root(root_directory, mounts, &n_mounts);
1018 drop_inaccessible(mounts, &n_mounts);
1019 drop_nop(mounts, &n_mounts);
1020 }
1021
1022 if (unshare(CLONE_NEWNS) < 0) {
1023 r = -errno;
1024 goto finish;
1025 }
1026
1027 if (make_slave) {
1028 /* Remount / as SLAVE so that nothing now mounted in the namespace
1029 shows up in the parent */
1030 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
1031 r = -errno;
1032 goto finish;
1033 }
1034 }
1035
1036 if (root_image) {
1037 r = dissected_image_mount(dissected_image, root_directory, dissect_image_flags);
1038 if (r < 0)
1039 goto finish;
1040
1041 loop_device_relinquish(loop_device);
1042
1043 } else if (root_directory) {
1044
1045 /* Turn directory into bind mount, if it isn't one yet */
1046 r = path_is_mount_point(root_directory, NULL, AT_SYMLINK_FOLLOW);
1047 if (r < 0)
1048 goto finish;
1049 if (r == 0) {
1050 if (mount(root_directory, root_directory, NULL, MS_BIND|MS_REC, NULL) < 0) {
1051 r = -errno;
1052 goto finish;
1053 }
1054 }
1055 }
1056
1057 if (n_mounts > 0) {
1058 char **blacklist;
1059 unsigned j;
1060
1061 /* First round, add in all special mounts we need */
1062 for (m = mounts; m < mounts + n_mounts; ++m) {
1063 r = apply_mount(root_directory, m, tmp_dir, var_tmp_dir);
1064 if (r < 0)
1065 goto finish;
1066 }
1067
1068 /* Create a blacklist we can pass to bind_mount_recursive() */
1069 blacklist = newa(char*, n_mounts+1);
1070 for (j = 0; j < n_mounts; j++)
1071 blacklist[j] = (char*) mount_entry_path(mounts+j);
1072 blacklist[j] = NULL;
1073
1074 /* Second round, flip the ro bits if necessary. */
1075 for (m = mounts; m < mounts + n_mounts; ++m) {
1076 r = make_read_only(m, blacklist);
1077 if (r < 0)
1078 goto finish;
1079 }
1080 }
1081
1082 if (root_directory) {
1083 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
1084 r = mount_move_root(root_directory);
1085 if (r < 0)
1086 goto finish;
1087 }
1088
1089 /* Remount / as the desired mode. Not that this will not
1090 * reestablish propagation from our side to the host, since
1091 * what's disconnected is disconnected. */
1092 if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) {
1093 r = -errno;
1094 goto finish;
1095 }
1096
1097 r = 0;
1098
1099 finish:
1100 for (m = mounts; m < mounts + n_mounts; m++)
1101 mount_entry_done(m);
1102
1103 return r;
1104 }
1105
1106 void bind_mount_free_many(BindMount *b, unsigned n) {
1107 unsigned i;
1108
1109 assert(b || n == 0);
1110
1111 for (i = 0; i < n; i++) {
1112 free(b[i].source);
1113 free(b[i].destination);
1114 }
1115
1116 free(b);
1117 }
1118
1119 int bind_mount_add(BindMount **b, unsigned *n, const BindMount *item) {
1120 _cleanup_free_ char *s = NULL, *d = NULL;
1121 BindMount *c;
1122
1123 assert(b);
1124 assert(n);
1125 assert(item);
1126
1127 s = strdup(item->source);
1128 if (!s)
1129 return -ENOMEM;
1130
1131 d = strdup(item->destination);
1132 if (!d)
1133 return -ENOMEM;
1134
1135 c = realloc_multiply(*b, sizeof(BindMount), *n + 1);
1136 if (!c)
1137 return -ENOMEM;
1138
1139 *b = c;
1140
1141 c[(*n) ++] = (BindMount) {
1142 .source = s,
1143 .destination = d,
1144 .read_only = item->read_only,
1145 .recursive = item->recursive,
1146 .ignore_enoent = item->ignore_enoent,
1147 };
1148
1149 s = d = NULL;
1150 return 0;
1151 }
1152
1153 static int setup_one_tmp_dir(const char *id, const char *prefix, char **path) {
1154 _cleanup_free_ char *x = NULL;
1155 char bid[SD_ID128_STRING_MAX];
1156 sd_id128_t boot_id;
1157 int r;
1158
1159 assert(id);
1160 assert(prefix);
1161 assert(path);
1162
1163 /* We include the boot id in the directory so that after a
1164 * reboot we can easily identify obsolete directories. */
1165
1166 r = sd_id128_get_boot(&boot_id);
1167 if (r < 0)
1168 return r;
1169
1170 x = strjoin(prefix, "/systemd-private-", sd_id128_to_string(boot_id, bid), "-", id, "-XXXXXX");
1171 if (!x)
1172 return -ENOMEM;
1173
1174 RUN_WITH_UMASK(0077)
1175 if (!mkdtemp(x))
1176 return -errno;
1177
1178 RUN_WITH_UMASK(0000) {
1179 char *y;
1180
1181 y = strjoina(x, "/tmp");
1182
1183 if (mkdir(y, 0777 | S_ISVTX) < 0)
1184 return -errno;
1185 }
1186
1187 *path = x;
1188 x = NULL;
1189
1190 return 0;
1191 }
1192
1193 int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
1194 char *a, *b;
1195 int r;
1196
1197 assert(id);
1198 assert(tmp_dir);
1199 assert(var_tmp_dir);
1200
1201 r = setup_one_tmp_dir(id, "/tmp", &a);
1202 if (r < 0)
1203 return r;
1204
1205 r = setup_one_tmp_dir(id, "/var/tmp", &b);
1206 if (r < 0) {
1207 char *t;
1208
1209 t = strjoina(a, "/tmp");
1210 rmdir(t);
1211 rmdir(a);
1212
1213 free(a);
1214 return r;
1215 }
1216
1217 *tmp_dir = a;
1218 *var_tmp_dir = b;
1219
1220 return 0;
1221 }
1222
1223 int setup_netns(int netns_storage_socket[2]) {
1224 _cleanup_close_ int netns = -1;
1225 int r, q;
1226
1227 assert(netns_storage_socket);
1228 assert(netns_storage_socket[0] >= 0);
1229 assert(netns_storage_socket[1] >= 0);
1230
1231 /* We use the passed socketpair as a storage buffer for our
1232 * namespace reference fd. Whatever process runs this first
1233 * shall create a new namespace, all others should just join
1234 * it. To serialize that we use a file lock on the socket
1235 * pair.
1236 *
1237 * It's a bit crazy, but hey, works great! */
1238
1239 if (lockf(netns_storage_socket[0], F_LOCK, 0) < 0)
1240 return -errno;
1241
1242 netns = receive_one_fd(netns_storage_socket[0], MSG_DONTWAIT);
1243 if (netns == -EAGAIN) {
1244 /* Nothing stored yet, so let's create a new namespace */
1245
1246 if (unshare(CLONE_NEWNET) < 0) {
1247 r = -errno;
1248 goto fail;
1249 }
1250
1251 loopback_setup();
1252
1253 netns = open("/proc/self/ns/net", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1254 if (netns < 0) {
1255 r = -errno;
1256 goto fail;
1257 }
1258
1259 r = 1;
1260
1261 } else if (netns < 0) {
1262 r = netns;
1263 goto fail;
1264
1265 } else {
1266 /* Yay, found something, so let's join the namespace */
1267 if (setns(netns, CLONE_NEWNET) < 0) {
1268 r = -errno;
1269 goto fail;
1270 }
1271
1272 r = 0;
1273 }
1274
1275 q = send_one_fd(netns_storage_socket[1], netns, MSG_DONTWAIT);
1276 if (q < 0) {
1277 r = q;
1278 goto fail;
1279 }
1280
1281 fail:
1282 (void) lockf(netns_storage_socket[0], F_ULOCK, 0);
1283 return r;
1284 }
1285
1286 static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
1287 [PROTECT_HOME_NO] = "no",
1288 [PROTECT_HOME_YES] = "yes",
1289 [PROTECT_HOME_READ_ONLY] = "read-only",
1290 };
1291
1292 DEFINE_STRING_TABLE_LOOKUP(protect_home, ProtectHome);
1293
1294 static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
1295 [PROTECT_SYSTEM_NO] = "no",
1296 [PROTECT_SYSTEM_YES] = "yes",
1297 [PROTECT_SYSTEM_FULL] = "full",
1298 [PROTECT_SYSTEM_STRICT] = "strict",
1299 };
1300
1301 DEFINE_STRING_TABLE_LOOKUP(protect_system, ProtectSystem);