]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/namespace.c
namespace: don't retry to a mount if we didn't actually manage to create an inode
[thirdparty/systemd.git] / src / core / namespace.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <linux/loop.h>
5 #include <sched.h>
6 #include <stdio.h>
7 #include <sys/file.h>
8 #include <sys/mount.h>
9 #include <unistd.h>
10 #if WANT_LINUX_FS_H
11 #include <linux/fs.h>
12 #endif
13
14 #include "alloc-util.h"
15 #include "base-filesystem.h"
16 #include "chase.h"
17 #include "dev-setup.h"
18 #include "devnum-util.h"
19 #include "env-util.h"
20 #include "escape.h"
21 #include "extension-util.h"
22 #include "fd-util.h"
23 #include "format-util.h"
24 #include "glyph-util.h"
25 #include "label-util.h"
26 #include "list.h"
27 #include "lock-util.h"
28 #include "loop-util.h"
29 #include "loopback-setup.h"
30 #include "missing_syscall.h"
31 #include "mkdir-label.h"
32 #include "mount-util.h"
33 #include "mountpoint-util.h"
34 #include "namespace-util.h"
35 #include "namespace.h"
36 #include "nsflags.h"
37 #include "nulstr-util.h"
38 #include "os-util.h"
39 #include "path-util.h"
40 #include "selinux-util.h"
41 #include "socket-util.h"
42 #include "sort-util.h"
43 #include "stat-util.h"
44 #include "string-table.h"
45 #include "string-util.h"
46 #include "strv.h"
47 #include "tmpfile-util.h"
48 #include "umask-util.h"
49 #include "user-util.h"
50
51 #define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
52
53 typedef enum MountMode {
54 /* This is ordered by priority! */
55 INACCESSIBLE,
56 OVERLAY_MOUNT,
57 MOUNT_IMAGES,
58 BIND_MOUNT,
59 BIND_MOUNT_RECURSIVE,
60 PRIVATE_TMP,
61 PRIVATE_TMP_READONLY,
62 PRIVATE_DEV,
63 BIND_DEV,
64 EMPTY_DIR,
65 PRIVATE_SYSFS,
66 BIND_SYSFS,
67 PROCFS,
68 READONLY,
69 READWRITE,
70 NOEXEC,
71 EXEC,
72 TMPFS,
73 RUN,
74 EXTENSION_DIRECTORIES, /* Bind-mounted outside the root directory, and used by subsequent mounts */
75 EXTENSION_IMAGES, /* Mounted outside the root directory, and used by subsequent mounts */
76 MQUEUEFS,
77 READWRITE_IMPLICIT, /* Should have the lowest priority. */
78 _MOUNT_MODE_MAX,
79 } MountMode;
80
81 typedef struct MountEntry {
82 const char *path_const; /* Memory allocated on stack or static */
83 MountMode mode:5;
84 bool ignore:1; /* Ignore if path does not exist? */
85 bool has_prefix:1; /* Already is prefixed by the root dir? */
86 bool read_only:1; /* Shall this mount point be read-only? */
87 bool nosuid:1; /* Shall set MS_NOSUID on the mount itself */
88 bool noexec:1; /* Shall set MS_NOEXEC on the mount itself */
89 bool exec:1; /* Shall clear MS_NOEXEC on the mount itself */
90 bool applied:1; /* Already applied */
91 char *path_malloc; /* Use this instead of 'path_const' if we had to allocate memory */
92 const char *unprefixed_path_const; /* If the path was amended with a prefix, these will save the original */
93 char *unprefixed_path_malloc;
94 const char *source_const; /* The source path, for bind mounts or images */
95 char *source_malloc;
96 const char *options_const;/* Mount options for tmpfs */
97 char *options_malloc;
98 unsigned long flags; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
99 unsigned n_followed;
100 LIST_HEAD(MountOptions, image_options);
101 } MountEntry;
102
103 typedef struct MountList {
104 MountEntry *mounts;
105 size_t n_mounts;
106 } MountList;
107
108 /* If MountAPIVFS= is used, let's mount /sys, /proc, /dev and /run into the it, but only as a fallback if the user hasn't mounted
109 * something there already. These mounts are hence overridden by any other explicitly configured mounts. */
110 static const MountEntry apivfs_table[] = {
111 { "/proc", PROCFS, false },
112 { "/dev", BIND_DEV, false },
113 { "/sys", BIND_SYSFS, false },
114 { "/run", RUN, false, .options_const = "mode=0755" TMPFS_LIMITS_RUN, .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME },
115 };
116
117 /* ProtectKernelTunables= option and the related filesystem APIs */
118 static const MountEntry protect_kernel_tunables_proc_table[] = {
119 { "/proc/acpi", READONLY, true },
120 { "/proc/apm", READONLY, true }, /* Obsolete API, there's no point in permitting access to this, ever */
121 { "/proc/asound", READONLY, true },
122 { "/proc/bus", READONLY, true },
123 { "/proc/fs", READONLY, true },
124 { "/proc/irq", READONLY, true },
125 { "/proc/kallsyms", INACCESSIBLE, true },
126 { "/proc/kcore", INACCESSIBLE, true },
127 { "/proc/latency_stats", READONLY, true },
128 { "/proc/mtrr", READONLY, true },
129 { "/proc/scsi", READONLY, true },
130 { "/proc/sys", READONLY, true },
131 { "/proc/sysrq-trigger", READONLY, true },
132 { "/proc/timer_stats", READONLY, true },
133 };
134
135 static const MountEntry protect_kernel_tunables_sys_table[] = {
136 { "/sys", READONLY, false },
137 { "/sys/fs/bpf", READONLY, true },
138 { "/sys/fs/cgroup", READWRITE_IMPLICIT, false }, /* READONLY is set by ProtectControlGroups= option */
139 { "/sys/fs/selinux", READWRITE_IMPLICIT, true },
140 { "/sys/kernel/debug", READONLY, true },
141 { "/sys/kernel/tracing", READONLY, true },
142 };
143
144 /* ProtectKernelModules= option */
145 static const MountEntry protect_kernel_modules_table[] = {
146 { "/usr/lib/modules", INACCESSIBLE, true },
147 };
148
149 /* ProtectKernelLogs= option */
150 static const MountEntry protect_kernel_logs_proc_table[] = {
151 { "/proc/kmsg", INACCESSIBLE, true },
152 };
153
154 static const MountEntry protect_kernel_logs_dev_table[] = {
155 { "/dev/kmsg", INACCESSIBLE, true },
156 };
157
158 /*
159 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
160 * system should be protected by ProtectSystem=
161 */
162 static const MountEntry protect_home_read_only_table[] = {
163 { "/home", READONLY, true },
164 { "/run/user", READONLY, true },
165 { "/root", READONLY, true },
166 };
167
168 /* ProtectHome=tmpfs table */
169 static const MountEntry protect_home_tmpfs_table[] = {
170 { "/home", TMPFS, true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
171 { "/run/user", TMPFS, true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
172 { "/root", TMPFS, true, .read_only = true, .options_const = "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
173 };
174
175 /* ProtectHome=yes table */
176 static const MountEntry protect_home_yes_table[] = {
177 { "/home", INACCESSIBLE, true },
178 { "/run/user", INACCESSIBLE, true },
179 { "/root", INACCESSIBLE, true },
180 };
181
182 /* ProtectSystem=yes table */
183 static const MountEntry protect_system_yes_table[] = {
184 { "/usr", READONLY, false },
185 { "/boot", READONLY, true },
186 { "/efi", READONLY, true },
187 };
188
189 /* ProtectSystem=full includes ProtectSystem=yes */
190 static const MountEntry protect_system_full_table[] = {
191 { "/usr", READONLY, false },
192 { "/boot", READONLY, true },
193 { "/efi", READONLY, true },
194 { "/etc", READONLY, false },
195 };
196
197 /* ProtectSystem=strict table. In this strict mode, we mount everything read-only, except for /proc, /dev,
198 * /sys which are the kernel API VFS, which are left writable, but PrivateDevices= + ProtectKernelTunables=
199 * protect those, and these options should be fully orthogonal. (And of course /home and friends are also
200 * left writable, as ProtectHome= shall manage those, orthogonally).
201 */
202 static const MountEntry protect_system_strict_table[] = {
203 { "/", READONLY, false },
204 { "/proc", READWRITE_IMPLICIT, false }, /* ProtectKernelTunables= */
205 { "/sys", READWRITE_IMPLICIT, false }, /* ProtectKernelTunables= */
206 { "/dev", READWRITE_IMPLICIT, false }, /* PrivateDevices= */
207 { "/home", READWRITE_IMPLICIT, true }, /* ProtectHome= */
208 { "/run/user", READWRITE_IMPLICIT, true }, /* ProtectHome= */
209 { "/root", READWRITE_IMPLICIT, true }, /* ProtectHome= */
210 };
211
212 /* ProtectHostname=yes able */
213 static const MountEntry protect_hostname_table[] = {
214 { "/proc/sys/kernel/hostname", READONLY, false },
215 { "/proc/sys/kernel/domainname", READONLY, false },
216 };
217
218 static const char * const mount_mode_table[_MOUNT_MODE_MAX] = {
219 [INACCESSIBLE] = "inaccessible",
220 [OVERLAY_MOUNT] = "overlay",
221 [MOUNT_IMAGES] = "mount-images",
222 [BIND_MOUNT] = "bind",
223 [BIND_MOUNT_RECURSIVE] = "rbind",
224 [PRIVATE_TMP] = "private-tmp",
225 [PRIVATE_TMP_READONLY] = "private-tmp-read-only",
226 [PRIVATE_DEV] = "private-dev",
227 [BIND_DEV] = "bind-dev",
228 [EMPTY_DIR] = "empty",
229 [PRIVATE_SYSFS] = "private-sysfs",
230 [BIND_SYSFS] = "bind-sysfs",
231 [PROCFS] = "procfs",
232 [READONLY] = "read-only",
233 [READWRITE] = "read-write",
234 [NOEXEC] = "noexec",
235 [EXEC] = "exec",
236 [TMPFS] = "tmpfs",
237 [RUN] = "run",
238 [EXTENSION_DIRECTORIES] = "extension-directories",
239 [EXTENSION_IMAGES] = "extension-images",
240 [MQUEUEFS] = "mqueuefs",
241 [READWRITE_IMPLICIT] = "read-write-implicit",
242 };
243
244 /* Helper struct for naming simplicity and reusability */
245 static const struct {
246 const char *level_env;
247 const char *level_env_print;
248 } image_class_info[_IMAGE_CLASS_MAX] = {
249 [IMAGE_SYSEXT] = {
250 .level_env = "SYSEXT_LEVEL",
251 .level_env_print = " SYSEXT_LEVEL=",
252 },
253 [IMAGE_CONFEXT] = {
254 .level_env = "CONFEXT_LEVEL",
255 .level_env_print = " CONFEXT_LEVEL=",
256 }
257 };
258
259 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode, MountMode);
260
261 static const char *mount_entry_path(const MountEntry *p) {
262 assert(p);
263
264 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
265 * otherwise the stack/static ->path field is returned. */
266
267 return p->path_malloc ?: p->path_const;
268 }
269
270 static const char *mount_entry_unprefixed_path(const MountEntry *p) {
271 assert(p);
272
273 /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
274
275 return p->unprefixed_path_malloc ?: p->unprefixed_path_const ?: mount_entry_path(p);
276 }
277
278 static void mount_entry_consume_prefix(MountEntry *p, char *new_path) {
279 assert(p);
280 assert(p->path_malloc || p->path_const);
281 assert(new_path);
282
283 /* Saves current path in unprefixed_ variable, and takes over new_path */
284
285 free_and_replace(p->unprefixed_path_malloc, p->path_malloc);
286 /* If we didn't have a path on the heap, then it's a static one */
287 if (!p->unprefixed_path_malloc)
288 p->unprefixed_path_const = p->path_const;
289 p->path_malloc = new_path;
290 p->has_prefix = true;
291 }
292
293 static bool mount_entry_read_only(const MountEntry *p) {
294 assert(p);
295
296 return p->read_only || IN_SET(p->mode, READONLY, INACCESSIBLE, PRIVATE_TMP_READONLY);
297 }
298
299 static bool mount_entry_noexec(const MountEntry *p) {
300 assert(p);
301
302 return p->noexec || IN_SET(p->mode, NOEXEC, INACCESSIBLE, PRIVATE_SYSFS, BIND_SYSFS, PROCFS);
303 }
304
305 static bool mount_entry_exec(const MountEntry *p) {
306 assert(p);
307
308 return p->exec || p->mode == EXEC;
309 }
310
311 static const char *mount_entry_source(const MountEntry *p) {
312 assert(p);
313
314 return p->source_malloc ?: p->source_const;
315 }
316
317 static const char *mount_entry_options(const MountEntry *p) {
318 assert(p);
319
320 return p->options_malloc ?: p->options_const;
321 }
322
323 static void mount_entry_done(MountEntry *p) {
324 assert(p);
325
326 p->path_malloc = mfree(p->path_malloc);
327 p->unprefixed_path_malloc = mfree(p->unprefixed_path_malloc);
328 p->source_malloc = mfree(p->source_malloc);
329 p->options_malloc = mfree(p->options_malloc);
330 p->image_options = mount_options_free_all(p->image_options);
331 }
332
333 static void mount_list_done(MountList *ml) {
334 assert(ml);
335
336 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts)
337 mount_entry_done(m);
338
339 ml->mounts = mfree(ml->mounts);
340 ml->n_mounts = 0;
341 }
342
343 static MountEntry *mount_list_extend(MountList *ml) {
344 assert(ml);
345
346 if (!GREEDY_REALLOC0(ml->mounts, ml->n_mounts+1))
347 return NULL;
348
349 return ml->mounts + ml->n_mounts++;
350 }
351
352 static int append_access_mounts(MountList *ml, char **strv, MountMode mode, bool forcibly_require_prefix) {
353 assert(ml);
354
355 /* Adds a list of user-supplied READWRITE/READWRITE_IMPLICIT/READONLY/INACCESSIBLE entries */
356
357 STRV_FOREACH(i, strv) {
358 bool ignore = false, needs_prefix = false;
359 const char *e = *i;
360
361 /* Look for any prefixes */
362 if (startswith(e, "-")) {
363 e++;
364 ignore = true;
365 }
366 if (startswith(e, "+")) {
367 e++;
368 needs_prefix = true;
369 }
370
371 if (!path_is_absolute(e))
372 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", e);
373
374 MountEntry *me = mount_list_extend(ml);
375 if (!me)
376 return log_oom_debug();
377
378 *me = (MountEntry) {
379 .path_const = e,
380 .mode = mode,
381 .ignore = ignore,
382 .has_prefix = !needs_prefix && !forcibly_require_prefix,
383 };
384 }
385
386 return 0;
387 }
388
389 static int append_empty_dir_mounts(MountList *ml, char **strv) {
390 assert(ml);
391
392 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
393 * "/private/" boundary directories for DynamicUser=1. */
394
395 STRV_FOREACH(i, strv) {
396 MountEntry *me = mount_list_extend(ml);
397 if (!me)
398 return log_oom_debug();
399
400 *me = (MountEntry) {
401 .path_const = *i,
402 .mode = EMPTY_DIR,
403 .ignore = false,
404 .read_only = true,
405 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
406 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
407 };
408 }
409
410 return 0;
411 }
412
413 static int append_bind_mounts(MountList *ml, const BindMount *binds, size_t n) {
414 assert(ml);
415 assert(binds || n == 0);
416
417 FOREACH_ARRAY(b, binds, n) {
418 MountEntry *me = mount_list_extend(ml);
419 if (!me)
420 return log_oom_debug();
421
422 *me = (MountEntry) {
423 .path_const = b->destination,
424 .mode = b->recursive ? BIND_MOUNT_RECURSIVE : BIND_MOUNT,
425 .read_only = b->read_only,
426 .nosuid = b->nosuid,
427 .source_const = b->source,
428 .ignore = b->ignore_enoent,
429 };
430 }
431
432 return 0;
433 }
434
435 static int append_mount_images(MountList *ml, const MountImage *mount_images, size_t n) {
436 assert(ml);
437 assert(mount_images || n == 0);
438
439 FOREACH_ARRAY(m, mount_images, n) {
440 MountEntry *me = mount_list_extend(ml);
441 if (!me)
442 return log_oom_debug();
443
444 *me = (MountEntry) {
445 .path_const = m->destination,
446 .mode = MOUNT_IMAGES,
447 .source_const = m->source,
448 .image_options = m->mount_options,
449 .ignore = m->ignore_enoent,
450 };
451 }
452
453 return 0;
454 }
455
456 static int append_extensions(
457 MountList *ml,
458 const char *root,
459 const char *extension_dir,
460 char **hierarchies,
461 const MountImage *mount_images,
462 size_t n,
463 char **extension_directories) {
464
465 _cleanup_strv_free_ char **overlays = NULL;
466 int r;
467
468 assert(ml);
469
470 if (n == 0 && strv_isempty(extension_directories))
471 return 0;
472
473 assert(extension_dir);
474
475 /* Prepare a list of overlays, that will have as each element a string suitable for being
476 * passed as a lowerdir= parameter, so start with the hierarchy on the root.
477 * The overlays vector will have the same number of elements and will correspond to the
478 * hierarchies vector, so they can be iterated upon together. */
479 STRV_FOREACH(hierarchy, hierarchies) {
480 _cleanup_free_ char *prefixed_hierarchy = NULL;
481
482 prefixed_hierarchy = path_join(root, *hierarchy);
483 if (!prefixed_hierarchy)
484 return -ENOMEM;
485
486 r = strv_consume(&overlays, TAKE_PTR(prefixed_hierarchy));
487 if (r < 0)
488 return r;
489 }
490
491 /* First, prepare a mount for each image, but these won't be visible to the unit, instead
492 * they will be mounted in our propagate directory, and used as a source for the overlay. */
493 for (size_t i = 0; i < n; i++) {
494 _cleanup_free_ char *mount_point = NULL;
495 const MountImage *m = mount_images + i;
496
497 if (asprintf(&mount_point, "%s/%zu", extension_dir, i) < 0)
498 return -ENOMEM;
499
500 for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
501 _cleanup_free_ char *prefixed_hierarchy = NULL, *escaped = NULL, *lowerdir = NULL;
502
503 prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
504 if (!prefixed_hierarchy)
505 return -ENOMEM;
506
507 escaped = shell_escape(prefixed_hierarchy, ",:");
508 if (!escaped)
509 return -ENOMEM;
510
511 /* Note that lowerdir= parameters are in 'reverse' order, so the
512 * top-most directory in the overlay comes first in the list. */
513 lowerdir = strjoin(escaped, ":", overlays[j]);
514 if (!lowerdir)
515 return -ENOMEM;
516
517 free_and_replace(overlays[j], lowerdir);
518 }
519
520 MountEntry *me = mount_list_extend(ml);
521 if (!me)
522 return log_oom_debug();
523
524 *me = (MountEntry) {
525 .path_malloc = TAKE_PTR(mount_point),
526 .image_options = m->mount_options,
527 .ignore = m->ignore_enoent,
528 .source_const = m->source,
529 .mode = EXTENSION_IMAGES,
530 .has_prefix = true,
531 };
532 }
533
534 /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
535 * Bind mount them in the same location as the ExtensionImages, so that we
536 * can check that they are valid trees (extension-release.d). */
537 STRV_FOREACH(extension_directory, extension_directories) {
538 _cleanup_free_ char *mount_point = NULL, *source = NULL;
539 const char *e = *extension_directory;
540 bool ignore_enoent = false;
541
542 /* Pick up the counter where the ExtensionImages left it. */
543 if (asprintf(&mount_point, "%s/%zu", extension_dir, n++) < 0)
544 return -ENOMEM;
545
546 /* Look for any prefixes */
547 if (startswith(e, "-")) {
548 e++;
549 ignore_enoent = true;
550 }
551 /* Ignore this for now */
552 if (startswith(e, "+"))
553 e++;
554
555 source = strdup(e);
556 if (!source)
557 return -ENOMEM;
558
559 for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
560 _cleanup_free_ char *prefixed_hierarchy = NULL, *escaped = NULL, *lowerdir = NULL;
561
562 prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
563 if (!prefixed_hierarchy)
564 return -ENOMEM;
565
566 escaped = shell_escape(prefixed_hierarchy, ",:");
567 if (!escaped)
568 return -ENOMEM;
569
570 /* Note that lowerdir= parameters are in 'reverse' order, so the
571 * top-most directory in the overlay comes first in the list. */
572 lowerdir = strjoin(escaped, ":", overlays[j]);
573 if (!lowerdir)
574 return -ENOMEM;
575
576 free_and_replace(overlays[j], lowerdir);
577 }
578
579 MountEntry *me = mount_list_extend(ml);
580 if (!me)
581 return log_oom_debug();
582
583 *me = (MountEntry) {
584 .path_malloc = TAKE_PTR(mount_point),
585 .source_malloc = TAKE_PTR(source),
586 .mode = EXTENSION_DIRECTORIES,
587 .ignore = ignore_enoent,
588 .has_prefix = true,
589 .read_only = true,
590 };
591 }
592
593 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
594 * set up earlier. */
595 for (size_t i = 0; hierarchies && hierarchies[i]; ++i) {
596 _cleanup_free_ char *prefixed_hierarchy = NULL;
597
598 prefixed_hierarchy = path_join(root, hierarchies[i]);
599 if (!prefixed_hierarchy)
600 return -ENOMEM;
601
602 MountEntry *me = mount_list_extend(ml);
603 if (!me)
604 return log_oom_debug();
605
606 *me = (MountEntry) {
607 .path_malloc = TAKE_PTR(prefixed_hierarchy),
608 .options_malloc = TAKE_PTR(overlays[i]),
609 .mode = OVERLAY_MOUNT,
610 .has_prefix = true,
611 .ignore = true, /* If the source image doesn't set the ignore bit it will fail earlier. */
612 };
613 }
614
615 return 0;
616 }
617
618 static int append_tmpfs_mounts(MountList *ml, const TemporaryFileSystem *tmpfs, size_t n) {
619 assert(ml);
620 assert(tmpfs || n == 0);
621
622 FOREACH_ARRAY(t, tmpfs, n) {
623 _cleanup_free_ char *o = NULL, *str = NULL;
624 unsigned long flags;
625 bool ro = false;
626 int r;
627
628 if (!path_is_absolute(t->path))
629 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", t->path);
630
631 str = strjoin("mode=0755" NESTED_TMPFS_LIMITS ",", t->options);
632 if (!str)
633 return -ENOMEM;
634
635 r = mount_option_mangle(str, MS_NODEV|MS_STRICTATIME, &flags, &o);
636 if (r < 0)
637 return log_debug_errno(r, "Failed to parse mount option '%s': %m", str);
638
639 ro = flags & MS_RDONLY;
640 if (ro)
641 flags ^= MS_RDONLY;
642
643 MountEntry *me = mount_list_extend(ml);
644 if (!me)
645 return log_oom_debug();
646
647 *me = (MountEntry) {
648 .path_const = t->path,
649 .mode = TMPFS,
650 .read_only = ro,
651 .options_malloc = TAKE_PTR(o),
652 .flags = flags,
653 };
654 }
655
656 return 0;
657 }
658
659 static int append_static_mounts(MountList *ml, const MountEntry *mounts, size_t n, bool ignore_protect) {
660 assert(ml);
661 assert(mounts || n == 0);
662
663 /* Adds a list of static pre-defined entries */
664
665 FOREACH_ARRAY(m, mounts, n) {
666 MountEntry *me = mount_list_extend(ml);
667 if (!me)
668 return log_oom_debug();
669
670 *me = (MountEntry) {
671 .path_const = mount_entry_path(m),
672 .mode = m->mode,
673 .ignore = m->ignore || ignore_protect,
674 };
675 }
676
677 return 0;
678 }
679
680 static int append_protect_home(MountList *ml, ProtectHome protect_home, bool ignore_protect) {
681 assert(ml);
682
683 switch (protect_home) {
684
685 case PROTECT_HOME_NO:
686 return 0;
687
688 case PROTECT_HOME_READ_ONLY:
689 return append_static_mounts(ml, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
690
691 case PROTECT_HOME_TMPFS:
692 return append_static_mounts(ml, protect_home_tmpfs_table, ELEMENTSOF(protect_home_tmpfs_table), ignore_protect);
693
694 case PROTECT_HOME_YES:
695 return append_static_mounts(ml, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
696
697 default:
698 assert_not_reached();
699 }
700 }
701
702 static int append_protect_system(MountList *ml, ProtectSystem protect_system, bool ignore_protect) {
703 assert(ml);
704
705 switch (protect_system) {
706
707 case PROTECT_SYSTEM_NO:
708 return 0;
709
710 case PROTECT_SYSTEM_STRICT:
711 return append_static_mounts(ml, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
712
713 case PROTECT_SYSTEM_YES:
714 return append_static_mounts(ml, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
715
716 case PROTECT_SYSTEM_FULL:
717 return append_static_mounts(ml, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
718
719 default:
720 assert_not_reached();
721 }
722 }
723
724 static int mount_path_compare(const MountEntry *a, const MountEntry *b) {
725 int d;
726
727 /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
728 * regardless of the prefix - they are set up in the propagate directory anyway */
729 d = -CMP(a->mode == EXTENSION_IMAGES, b->mode == EXTENSION_IMAGES);
730 if (d != 0)
731 return d;
732 d = -CMP(a->mode == EXTENSION_DIRECTORIES, b->mode == EXTENSION_DIRECTORIES);
733 if (d != 0)
734 return d;
735
736 /* If the paths are not equal, then order prefixes first */
737 d = path_compare(mount_entry_path(a), mount_entry_path(b));
738 if (d != 0)
739 return d;
740
741 /* If the paths are equal, check the mode */
742 return CMP((int) a->mode, (int) b->mode);
743 }
744
745 static int prefix_where_needed(MountList *ml, const char *root_directory) {
746 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
747
748 assert(ml);
749
750 FOREACH_ARRAY(me, ml->mounts, ml->n_mounts) {
751 char *s;
752
753 if (me->has_prefix)
754 continue;
755
756 s = path_join(root_directory, mount_entry_path(me));
757 if (!s)
758 return -ENOMEM;
759
760 mount_entry_consume_prefix(me, s);
761 }
762
763 return 0;
764 }
765
766 static void drop_duplicates(MountList *ml) {
767 MountEntry *f, *t, *previous;
768
769 assert(ml);
770
771 /* Drops duplicate entries. Expects that the array is properly ordered already. */
772
773 for (f = ml->mounts, t = ml->mounts, previous = NULL; f < ml->mounts + ml->n_mounts; f++) {
774
775 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
776 * above. Note that we only drop duplicates that haven't been mounted yet. */
777 if (previous &&
778 path_equal(mount_entry_path(f), mount_entry_path(previous)) &&
779 !f->applied && !previous->applied) {
780 log_debug("%s (%s) is duplicate.", mount_entry_path(f), mount_mode_to_string(f->mode));
781 /* Propagate the flags to the remaining entry */
782 previous->read_only = previous->read_only || mount_entry_read_only(f);
783 previous->noexec = previous->noexec || mount_entry_noexec(f);
784 previous->exec = previous->exec || mount_entry_exec(f);
785 mount_entry_done(f);
786 continue;
787 }
788
789 *t = *f;
790 previous = t;
791 t++;
792 }
793
794 ml->n_mounts = t - ml->mounts;
795 }
796
797 static void drop_inaccessible(MountList *ml) {
798 MountEntry *f, *t;
799 const char *clear = NULL;
800
801 assert(ml);
802
803 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
804 * ordered already. */
805
806 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
807
808 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
809 * it, as inaccessible paths really should drop the entire subtree. */
810 if (clear && path_startswith(mount_entry_path(f), clear)) {
811 log_debug("%s is masked by %s.", mount_entry_path(f), clear);
812 mount_entry_done(f);
813 continue;
814 }
815
816 clear = f->mode == INACCESSIBLE ? mount_entry_path(f) : NULL;
817
818 *t = *f;
819 t++;
820 }
821
822 ml->n_mounts = t - ml->mounts;
823 }
824
825 static void drop_nop(MountList *ml) {
826 MountEntry *f, *t;
827
828 assert(ml);
829
830 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
831 * list is ordered by prefixes. */
832
833 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
834
835 /* Only suppress such subtrees for READONLY, READWRITE and READWRITE_IMPLICIT entries */
836 if (IN_SET(f->mode, READONLY, READWRITE, READWRITE_IMPLICIT)) {
837 MountEntry *found = NULL;
838
839 /* Now let's find the first parent of the entry we are looking at. */
840 for (MountEntry *p = PTR_SUB1(t, ml->mounts); p; p = PTR_SUB1(p, ml->mounts))
841 if (path_startswith(mount_entry_path(f), mount_entry_path(p))) {
842 found = p;
843 break;
844 }
845
846 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
847 if (found && found->mode == f->mode) {
848 log_debug("%s (%s) is made redundant by %s (%s)",
849 mount_entry_path(f), mount_mode_to_string(f->mode),
850 mount_entry_path(found), mount_mode_to_string(found->mode));
851 mount_entry_done(f);
852 continue;
853 }
854 }
855
856 *t = *f;
857 t++;
858 }
859
860 ml->n_mounts = t - ml->mounts;
861 }
862
863 static void drop_outside_root(MountList *ml, const char *root_directory) {
864 MountEntry *f, *t;
865
866 assert(ml);
867
868 /* Nothing to do */
869 if (!root_directory)
870 return;
871
872 /* Drops all mounts that are outside of the root directory. */
873
874 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
875
876 /* ExtensionImages/Directories bases are opened in /run/systemd/unit-extensions on the host */
877 if (!IN_SET(f->mode, EXTENSION_IMAGES, EXTENSION_DIRECTORIES) && !path_startswith(mount_entry_path(f), root_directory)) {
878 log_debug("%s is outside of root directory.", mount_entry_path(f));
879 mount_entry_done(f);
880 continue;
881 }
882
883 *t = *f;
884 t++;
885 }
886
887 ml->n_mounts = t - ml->mounts;
888 }
889
890 static int clone_device_node(
891 const char *d,
892 const char *temporary_mount,
893 bool *make_devnode) {
894
895 _cleanup_free_ char *sl = NULL;
896 const char *dn, *bn, *t;
897 struct stat st;
898 int r;
899
900 if (stat(d, &st) < 0) {
901 if (errno == ENOENT) {
902 log_debug_errno(errno, "Device node '%s' to clone does not exist, ignoring.", d);
903 return -ENXIO;
904 }
905
906 return log_debug_errno(errno, "Failed to stat() device node '%s' to clone, ignoring: %m", d);
907 }
908
909 if (!S_ISBLK(st.st_mode) &&
910 !S_ISCHR(st.st_mode))
911 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
912 "Device node '%s' to clone is not a device node, ignoring.",
913 d);
914
915 dn = strjoina(temporary_mount, d);
916
917 /* First, try to create device node properly */
918 if (*make_devnode) {
919 mac_selinux_create_file_prepare(d, st.st_mode);
920 r = mknod(dn, st.st_mode, st.st_rdev);
921 mac_selinux_create_file_clear();
922 if (r >= 0)
923 goto add_symlink;
924 if (errno != EPERM)
925 return log_debug_errno(errno, "mknod failed for %s: %m", d);
926
927 /* This didn't work, let's not try this again for the next iterations. */
928 *make_devnode = false;
929 }
930
931 /* We're about to fall back to bind-mounting the device node. So create a dummy bind-mount target.
932 * Do not prepare device-node SELinux label (see issue 13762) */
933 r = mknod(dn, S_IFREG, 0);
934 if (r < 0 && errno != EEXIST)
935 return log_debug_errno(errno, "mknod() fallback failed for '%s': %m", d);
936
937 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
938 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
939 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
940 r = mount_nofollow_verbose(LOG_DEBUG, d, dn, NULL, MS_BIND, NULL);
941 if (r < 0)
942 return r;
943
944 add_symlink:
945 bn = path_startswith(d, "/dev/");
946 if (!bn)
947 return 0;
948
949 /* Create symlinks like /dev/char/1:9 → ../urandom */
950 if (asprintf(&sl, "%s/dev/%s/" DEVNUM_FORMAT_STR,
951 temporary_mount,
952 S_ISCHR(st.st_mode) ? "char" : "block",
953 DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
954 return log_oom();
955
956 (void) mkdir_parents(sl, 0755);
957
958 t = strjoina("../", bn);
959 if (symlink(t, sl) < 0)
960 log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, sl);
961
962 return 0;
963 }
964
965 static char *settle_runtime_dir(RuntimeScope scope) {
966 char *runtime_dir;
967
968 if (scope != RUNTIME_SCOPE_USER)
969 return strdup("/run/");
970
971 if (asprintf(&runtime_dir, "/run/user/" UID_FMT, geteuid()) < 0)
972 return NULL;
973
974 return runtime_dir;
975 }
976
977 static int mount_private_dev(MountEntry *m, RuntimeScope scope) {
978 static const char devnodes[] =
979 "/dev/null\0"
980 "/dev/zero\0"
981 "/dev/full\0"
982 "/dev/random\0"
983 "/dev/urandom\0"
984 "/dev/tty\0";
985
986 _cleanup_free_ char *runtime_dir = NULL, *temporary_mount = NULL;
987 const char *dev = NULL, *devpts = NULL, *devshm = NULL, *devhugepages = NULL, *devmqueue = NULL, *devlog = NULL, *devptmx = NULL;
988 bool can_mknod = true;
989 int r;
990
991 assert(m);
992
993 runtime_dir = settle_runtime_dir(scope);
994 if (!runtime_dir)
995 return log_oom_debug();
996
997 temporary_mount = path_join(runtime_dir, "systemd/namespace-dev-XXXXXX");
998 if (!temporary_mount)
999 return log_oom_debug();
1000
1001 if (!mkdtemp(temporary_mount))
1002 return log_debug_errno(errno, "Failed to create temporary directory '%s': %m", temporary_mount);
1003
1004 dev = strjoina(temporary_mount, "/dev");
1005 (void) mkdir(dev, 0755);
1006 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=0755" TMPFS_LIMITS_PRIVATE_DEV);
1007 if (r < 0)
1008 goto fail;
1009
1010 r = label_fix_full(AT_FDCWD, dev, "/dev", 0);
1011 if (r < 0) {
1012 log_debug_errno(r, "Failed to fix label of '%s' as /dev: %m", dev);
1013 goto fail;
1014 }
1015
1016 devpts = strjoina(temporary_mount, "/dev/pts");
1017 (void) mkdir(devpts, 0755);
1018 r = mount_nofollow_verbose(LOG_DEBUG, "/dev/pts", devpts, NULL, MS_BIND, NULL);
1019 if (r < 0)
1020 goto fail;
1021
1022 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
1023 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
1024 * Thus, in that case make a clone.
1025 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
1026 r = is_symlink("/dev/ptmx");
1027 if (r < 0) {
1028 log_debug_errno(r, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
1029 goto fail;
1030 } else if (r > 0) {
1031 devptmx = strjoina(temporary_mount, "/dev/ptmx");
1032 if (symlink("pts/ptmx", devptmx) < 0) {
1033 r = log_debug_errno(errno, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx);
1034 goto fail;
1035 }
1036 } else {
1037 r = clone_device_node("/dev/ptmx", temporary_mount, &can_mknod);
1038 if (r < 0)
1039 goto fail;
1040 }
1041
1042 devshm = strjoina(temporary_mount, "/dev/shm");
1043 (void) mkdir(devshm, 0755);
1044 r = mount_nofollow_verbose(LOG_DEBUG, "/dev/shm", devshm, NULL, MS_BIND, NULL);
1045 if (r < 0)
1046 goto fail;
1047
1048 devmqueue = strjoina(temporary_mount, "/dev/mqueue");
1049 (void) mkdir(devmqueue, 0755);
1050 (void) mount_nofollow_verbose(LOG_DEBUG, "/dev/mqueue", devmqueue, NULL, MS_BIND, NULL);
1051
1052 devhugepages = strjoina(temporary_mount, "/dev/hugepages");
1053 (void) mkdir(devhugepages, 0755);
1054 (void) mount_nofollow_verbose(LOG_DEBUG, "/dev/hugepages", devhugepages, NULL, MS_BIND, NULL);
1055
1056 devlog = strjoina(temporary_mount, "/dev/log");
1057 if (symlink("/run/systemd/journal/dev-log", devlog) < 0)
1058 log_debug_errno(errno, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog);
1059
1060 NULSTR_FOREACH(d, devnodes) {
1061 r = clone_device_node(d, temporary_mount, &can_mknod);
1062 /* ENXIO means the *source* is not a device file, skip creation in that case */
1063 if (r < 0 && r != -ENXIO)
1064 goto fail;
1065 }
1066
1067 r = dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
1068 if (r < 0)
1069 log_debug_errno(r, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount);
1070
1071 /* Make the bind mount read-only. */
1072 r = mount_nofollow_verbose(LOG_DEBUG, NULL, dev, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1073 if (r < 0)
1074 return r;
1075
1076 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
1077 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
1078 (void) mkdir_p_label(mount_entry_path(m), 0755);
1079
1080 /* Unmount everything in old /dev */
1081 r = umount_recursive(mount_entry_path(m), 0);
1082 if (r < 0)
1083 log_debug_errno(r, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m));
1084
1085 r = mount_nofollow_verbose(LOG_DEBUG, dev, mount_entry_path(m), NULL, MS_MOVE, NULL);
1086 if (r < 0)
1087 goto fail;
1088
1089 (void) rmdir(dev);
1090 (void) rmdir(temporary_mount);
1091
1092 return 0;
1093
1094 fail:
1095 if (devpts)
1096 (void) umount_verbose(LOG_DEBUG, devpts, UMOUNT_NOFOLLOW);
1097
1098 if (devshm)
1099 (void) umount_verbose(LOG_DEBUG, devshm, UMOUNT_NOFOLLOW);
1100
1101 if (devhugepages)
1102 (void) umount_verbose(LOG_DEBUG, devhugepages, UMOUNT_NOFOLLOW);
1103
1104 if (devmqueue)
1105 (void) umount_verbose(LOG_DEBUG, devmqueue, UMOUNT_NOFOLLOW);
1106
1107 (void) umount_verbose(LOG_DEBUG, dev, UMOUNT_NOFOLLOW);
1108 (void) rmdir(dev);
1109 (void) rmdir(temporary_mount);
1110
1111 return r;
1112 }
1113
1114 static int mount_bind_dev(const MountEntry *m) {
1115 int r;
1116
1117 assert(m);
1118
1119 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1120 * service's /dev. This is only used when RootDirectory= is set. */
1121
1122 (void) mkdir_p_label(mount_entry_path(m), 0755);
1123
1124 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
1125 if (r < 0)
1126 return log_debug_errno(r, "Unable to determine whether /dev is already mounted: %m");
1127 if (r > 0) /* make this a NOP if /dev is already a mount point */
1128 return 0;
1129
1130 return mount_nofollow_verbose(LOG_DEBUG, "/dev", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
1131 }
1132
1133 static int mount_bind_sysfs(const MountEntry *m) {
1134 int r;
1135
1136 assert(m);
1137
1138 (void) mkdir_p_label(mount_entry_path(m), 0755);
1139
1140 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
1141 if (r < 0)
1142 return log_debug_errno(r, "Unable to determine whether /sys is already mounted: %m");
1143 if (r > 0) /* make this a NOP if /sys is already a mount point */
1144 return 0;
1145
1146 /* Bind mount the host's version so that we get all child mounts of it, too. */
1147 return mount_nofollow_verbose(LOG_DEBUG, "/sys", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
1148 }
1149
1150 static int mount_private_sysfs(const MountEntry *m) {
1151 const char *entry_path = mount_entry_path(ASSERT_PTR(m));
1152 int r, n;
1153
1154 (void) mkdir_p_label(entry_path, 0755);
1155
1156 n = umount_recursive(entry_path, 0);
1157
1158 r = mount_nofollow_verbose(LOG_DEBUG, "sysfs", entry_path, "sysfs", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
1159 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
1160 /* When we do not have enough privileges to mount sysfs, fall back to use existing /sys. */
1161
1162 if (n > 0)
1163 /* /sys or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1164 * Propagate the original error code returned by mount() in the above. */
1165 return r;
1166
1167 return mount_bind_sysfs(m);
1168
1169 } else if (r < 0)
1170 return r;
1171
1172 /* We mounted a new instance now. Let's bind mount the children over now. */
1173 (void) bind_mount_submounts("/sys", entry_path);
1174 return 0;
1175 }
1176
1177 static int mount_procfs(const MountEntry *m, const NamespaceParameters *p) {
1178 _cleanup_free_ char *opts = NULL;
1179 const char *entry_path;
1180 int r, n;
1181
1182 assert(m);
1183 assert(p);
1184
1185 if (p->protect_proc != PROTECT_PROC_DEFAULT ||
1186 p->proc_subset != PROC_SUBSET_ALL) {
1187
1188 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
1189 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
1190 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
1191 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
1192 * added in the same commit: if it's supported it is thus also per-instance. */
1193
1194 const char *hpv = p->protect_proc == PROTECT_PROC_DEFAULT ?
1195 "off" :
1196 protect_proc_to_string(p->protect_proc);
1197
1198 /* hidepid= support was added in 5.8, so we can use fsconfig()/fsopen() (which were added in
1199 * 5.2) to check if hidepid= is supported. This avoids a noisy dmesg log by the kernel when
1200 * trying to use hidepid= on systems where it isn't supported. The same applies for subset=.
1201 * fsopen()/fsconfig() was also backported on some distros which allows us to detect
1202 * hidepid=/subset= support in even more scenarios. */
1203
1204 if (mount_option_supported("proc", "hidepid", hpv) != 0) {
1205 opts = strjoin("hidepid=", hpv);
1206 if (!opts)
1207 return -ENOMEM;
1208 }
1209
1210 if (p->proc_subset == PROC_SUBSET_PID &&
1211 mount_option_supported("proc", "subset", "pid") != 0)
1212 if (!strextend_with_separator(&opts, ",", "subset=pid"))
1213 return -ENOMEM;
1214 }
1215
1216 entry_path = mount_entry_path(m);
1217 (void) mkdir_p_label(entry_path, 0755);
1218
1219 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1220 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1221 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1222 * mounted on /proc/ first. */
1223
1224 n = umount_recursive(entry_path, 0);
1225
1226 r = mount_nofollow_verbose(LOG_DEBUG, "proc", entry_path, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
1227 if (r == -EINVAL && opts)
1228 /* If this failed with EINVAL then this likely means the textual hidepid= stuff is
1229 * not supported by the kernel, and thus the per-instance hidepid= neither, which
1230 * means we really don't want to use it, since it would affect our host's /proc
1231 * mount. Hence let's gracefully fallback to a classic, unrestricted version. */
1232 r = mount_nofollow_verbose(LOG_DEBUG, "proc", entry_path, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
1233 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
1234 /* When we do not have enough privileges to mount /proc, fall back to use existing /proc. */
1235
1236 if (n > 0)
1237 /* /proc or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1238 * Propagate the original error code returned by mount() in the above. */
1239 return r;
1240
1241 r = path_is_mount_point(entry_path, NULL, 0);
1242 if (r < 0)
1243 return log_debug_errno(r, "Unable to determine whether /proc is already mounted: %m");
1244 if (r > 0)
1245 return 0;
1246
1247 /* We lack permissions to mount a new instance of /proc, and it is not already mounted. But
1248 * we can access the host's, so as a final fallback bind-mount it to the destination, as most
1249 * likely we are inside a user manager in an unprivileged user namespace. */
1250 return mount_nofollow_verbose(LOG_DEBUG, "/proc", entry_path, NULL, MS_BIND|MS_REC, NULL);
1251
1252 } else if (r < 0)
1253 return r;
1254
1255 /* We mounted a new instance now. Let's bind mount the children over now. This matters for nspawn
1256 * where a bunch of files are overmounted, in particular the boot id */
1257 (void) bind_mount_submounts("/proc", entry_path);
1258 return 0;
1259 }
1260
1261 static int mount_tmpfs(const MountEntry *m) {
1262 const char *entry_path, *inner_path;
1263 int r;
1264
1265 assert(m);
1266
1267 entry_path = mount_entry_path(m);
1268 inner_path = mount_entry_unprefixed_path(m);
1269
1270 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1271 * tmpfs */
1272
1273 (void) mkdir_p_label(entry_path, 0755);
1274 (void) umount_recursive(entry_path, 0);
1275
1276 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", entry_path, "tmpfs", m->flags, mount_entry_options(m));
1277 if (r < 0)
1278 return r;
1279
1280 r = label_fix_full(AT_FDCWD, entry_path, inner_path, 0);
1281 if (r < 0)
1282 return log_debug_errno(r, "Failed to fix label of '%s' as '%s': %m", entry_path, inner_path);
1283
1284 return 0;
1285 }
1286
1287 static int mount_run(const MountEntry *m) {
1288 int r;
1289
1290 assert(m);
1291
1292 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
1293 if (r < 0 && r != -ENOENT)
1294 return log_debug_errno(r, "Unable to determine whether /run is already mounted: %m");
1295 if (r > 0) /* make this a NOP if /run is already a mount point */
1296 return 0;
1297
1298 return mount_tmpfs(m);
1299 }
1300
1301 static int mount_mqueuefs(const MountEntry *m) {
1302 int r;
1303 const char *entry_path;
1304
1305 assert(m);
1306
1307 entry_path = mount_entry_path(m);
1308
1309 (void) mkdir_p_label(entry_path, 0755);
1310 (void) umount_recursive(entry_path, 0);
1311
1312 r = mount_nofollow_verbose(LOG_DEBUG, "mqueue", entry_path, "mqueue", m->flags, mount_entry_options(m));
1313 if (r < 0)
1314 return r;
1315
1316 return 0;
1317 }
1318
1319 static int mount_image(
1320 const MountEntry *m,
1321 const char *root_directory,
1322 const ImagePolicy *image_policy) {
1323
1324 _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_version_id = NULL,
1325 *host_os_release_sysext_level = NULL, *host_os_release_confext_level = NULL,
1326 *extension_name = NULL;
1327 int r;
1328
1329 assert(m);
1330
1331 r = path_extract_filename(mount_entry_source(m), &extension_name);
1332 if (r < 0)
1333 return log_debug_errno(r, "Failed to extract extension name from %s: %m", mount_entry_source(m));
1334
1335 if (m->mode == EXTENSION_IMAGES) {
1336 r = parse_os_release(
1337 empty_to_root(root_directory),
1338 "ID", &host_os_release_id,
1339 "VERSION_ID", &host_os_release_version_id,
1340 image_class_info[IMAGE_SYSEXT].level_env, &host_os_release_sysext_level,
1341 image_class_info[IMAGE_CONFEXT].level_env, &host_os_release_confext_level,
1342 NULL);
1343 if (r < 0)
1344 return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1345 if (isempty(host_os_release_id))
1346 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'ID' field not found or empty in 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1347 }
1348
1349 r = verity_dissect_and_mount(
1350 /* src_fd= */ -1,
1351 mount_entry_source(m),
1352 mount_entry_path(m),
1353 m->image_options,
1354 image_policy,
1355 host_os_release_id,
1356 host_os_release_version_id,
1357 host_os_release_sysext_level,
1358 host_os_release_confext_level,
1359 /* required_sysext_scope= */ NULL,
1360 /* ret_image= */ NULL);
1361 if (r == -ENOENT && m->ignore)
1362 return 0;
1363 if (r == -ESTALE && host_os_release_id)
1364 return log_error_errno(r,
1365 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s%s%s",
1366 mount_entry_source(m),
1367 host_os_release_id,
1368 host_os_release_version_id ? " VERSION_ID=" : "",
1369 strempty(host_os_release_version_id),
1370 host_os_release_sysext_level ? image_class_info[IMAGE_SYSEXT].level_env_print : "",
1371 strempty(host_os_release_sysext_level),
1372 host_os_release_confext_level ? image_class_info[IMAGE_CONFEXT].level_env_print : "",
1373 strempty(host_os_release_confext_level));
1374 if (r < 0)
1375 return log_debug_errno(r, "Failed to mount image %s on %s: %m", mount_entry_source(m), mount_entry_path(m));
1376
1377 return 0;
1378 }
1379
1380 static int mount_overlay(const MountEntry *m) {
1381 const char *options;
1382 int r;
1383
1384 assert(m);
1385
1386 options = strjoina("lowerdir=", mount_entry_options(m));
1387
1388 (void) mkdir_p_label(mount_entry_path(m), 0755);
1389
1390 r = mount_nofollow_verbose(LOG_DEBUG, "overlay", mount_entry_path(m), "overlay", MS_RDONLY, options);
1391 if (r == -ENOENT && m->ignore)
1392 return 0;
1393
1394 return r;
1395 }
1396
1397 static int follow_symlink(
1398 const char *root_directory,
1399 MountEntry *m) {
1400
1401 _cleanup_free_ char *target = NULL;
1402 int r;
1403
1404 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1405 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1406 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1407 * end and already have a fully normalized name. */
1408
1409 r = chase(mount_entry_path(m), root_directory, CHASE_STEP|CHASE_NONEXISTENT, &target, NULL);
1410 if (r < 0)
1411 return log_debug_errno(r, "Failed to chase symlinks '%s': %m", mount_entry_path(m));
1412 if (r > 0) /* Reached the end, nothing more to resolve */
1413 return 1;
1414
1415 if (m->n_followed >= CHASE_MAX) /* put a boundary on things */
1416 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1417 "Symlink loop on '%s'.",
1418 mount_entry_path(m));
1419
1420 log_debug("Followed mount entry path symlink %s %s %s.",
1421 mount_entry_path(m), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), target);
1422
1423 mount_entry_consume_prefix(m, TAKE_PTR(target));
1424
1425 m->n_followed ++;
1426
1427 return 0;
1428 }
1429
1430 static int apply_one_mount(
1431 const char *root_directory,
1432 MountEntry *m,
1433 const NamespaceParameters *p) {
1434
1435 _cleanup_free_ char *inaccessible = NULL;
1436 bool rbind = true, make = false;
1437 const char *what;
1438 int r;
1439
1440 assert(m);
1441 assert(p);
1442
1443 log_debug("Applying namespace mount on %s", mount_entry_path(m));
1444
1445 switch (m->mode) {
1446
1447 case INACCESSIBLE: {
1448 _cleanup_free_ char *runtime_dir = NULL;
1449 struct stat target;
1450
1451 /* First, get rid of everything that is below if there
1452 * is anything... Then, overmount it with an
1453 * inaccessible path. */
1454 (void) umount_recursive(mount_entry_path(m), 0);
1455
1456 if (lstat(mount_entry_path(m), &target) < 0) {
1457 if (errno == ENOENT && m->ignore)
1458 return 0;
1459
1460 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m",
1461 mount_entry_path(m));
1462 }
1463
1464 /* We don't pass the literal runtime scope through here but one based purely on our UID. This
1465 * means that the root user's --user services will use the host's inaccessible inodes rather
1466 * then root's private ones. This is preferable since it means device nodes that are
1467 * overmounted to make them inaccessible will be overmounted with a device node, rather than
1468 * an AF_UNIX socket inode. */
1469 runtime_dir = settle_runtime_dir(geteuid() == 0 ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER);
1470 if (!runtime_dir)
1471 return log_oom_debug();
1472
1473 r = mode_to_inaccessible_node(runtime_dir, target.st_mode, &inaccessible);
1474 if (r < 0)
1475 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1476 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
1477 what = inaccessible;
1478 break;
1479 }
1480
1481 case READONLY:
1482 case READWRITE:
1483 case READWRITE_IMPLICIT:
1484 case EXEC:
1485 case NOEXEC:
1486 r = path_is_mount_point(mount_entry_path(m), root_directory, 0);
1487 if (r == -ENOENT && m->ignore)
1488 return 0;
1489 if (r < 0)
1490 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m",
1491 mount_entry_path(m));
1492 if (r > 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1493 * and MS_NOEXEC bits for the mount point if needed. */
1494 return 0;
1495 /* This isn't a mount point yet, let's make it one. */
1496 what = mount_entry_path(m);
1497 break;
1498
1499 case EXTENSION_DIRECTORIES: {
1500 _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_version_id = NULL,
1501 *host_os_release_level = NULL, *extension_name = NULL;
1502 _cleanup_strv_free_ char **extension_release = NULL;
1503 ImageClass class = IMAGE_SYSEXT;
1504
1505 r = path_extract_filename(mount_entry_source(m), &extension_name);
1506 if (r < 0)
1507 return log_debug_errno(r, "Failed to extract extension name from %s: %m", mount_entry_source(m));
1508
1509 r = load_extension_release_pairs(mount_entry_source(m), IMAGE_SYSEXT, extension_name, /* relax_extension_release_check= */ false, &extension_release);
1510 if (r == -ENOENT) {
1511 r = load_extension_release_pairs(mount_entry_source(m), IMAGE_CONFEXT, extension_name, /* relax_extension_release_check= */ false, &extension_release);
1512 if (r >= 0)
1513 class = IMAGE_CONFEXT;
1514 }
1515 if (r < 0)
1516 return log_debug_errno(r, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m));
1517
1518 r = parse_os_release(
1519 empty_to_root(root_directory),
1520 "ID", &host_os_release_id,
1521 "VERSION_ID", &host_os_release_version_id,
1522 image_class_info[class].level_env, &host_os_release_level,
1523 NULL);
1524 if (r < 0)
1525 return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1526 if (isempty(host_os_release_id))
1527 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'ID' field not found or empty in 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1528
1529 r = load_extension_release_pairs(mount_entry_source(m), class, extension_name, /* relax_extension_release_check= */ false, &extension_release);
1530 if (r == -ENOENT && m->ignore)
1531 return 0;
1532 if (r < 0)
1533 return log_debug_errno(r, "Failed to parse directory %s extension-release metadata: %m", extension_name);
1534
1535 r = extension_release_validate(
1536 extension_name,
1537 host_os_release_id,
1538 host_os_release_version_id,
1539 host_os_release_level,
1540 /* host_extension_scope */ NULL, /* Leave empty, we need to accept both system and portable */
1541 extension_release,
1542 class);
1543 if (r == 0)
1544 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Directory %s extension-release metadata does not match the root's", extension_name);
1545 if (r < 0)
1546 return log_debug_errno(r, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name);
1547
1548 _fallthrough_;
1549 }
1550
1551 case BIND_MOUNT:
1552 rbind = false;
1553
1554 _fallthrough_;
1555 case BIND_MOUNT_RECURSIVE: {
1556 _cleanup_free_ char *chased = NULL;
1557
1558 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1559 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1560 * root directory to chase() here. */
1561
1562 r = chase(mount_entry_source(m), NULL, CHASE_TRAIL_SLASH, &chased, NULL);
1563 if (r == -ENOENT && m->ignore) {
1564 log_debug_errno(r, "Path %s does not exist, ignoring.", mount_entry_source(m));
1565 return 0;
1566 }
1567 if (r < 0)
1568 return log_debug_errno(r, "Failed to follow symlinks on %s: %m", mount_entry_source(m));
1569
1570 log_debug("Followed source symlinks %s %s %s.",
1571 mount_entry_source(m), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), chased);
1572
1573 free_and_replace(m->source_malloc, chased);
1574
1575 what = mount_entry_source(m);
1576 make = true;
1577 break;
1578 }
1579
1580 case EMPTY_DIR:
1581 case TMPFS:
1582 return mount_tmpfs(m);
1583
1584 case PRIVATE_TMP:
1585 case PRIVATE_TMP_READONLY:
1586 what = mount_entry_source(m);
1587 make = true;
1588 break;
1589
1590 case PRIVATE_DEV:
1591 return mount_private_dev(m, p->runtime_scope);
1592
1593 case BIND_DEV:
1594 return mount_bind_dev(m);
1595
1596 case PRIVATE_SYSFS:
1597 return mount_private_sysfs(m);
1598
1599 case BIND_SYSFS:
1600 return mount_bind_sysfs(m);
1601
1602 case PROCFS:
1603 return mount_procfs(m, p);
1604
1605 case RUN:
1606 return mount_run(m);
1607
1608 case MQUEUEFS:
1609 return mount_mqueuefs(m);
1610
1611 case MOUNT_IMAGES:
1612 return mount_image(m, NULL, p->mount_image_policy);
1613
1614 case EXTENSION_IMAGES:
1615 return mount_image(m, root_directory, p->extension_image_policy);
1616
1617 case OVERLAY_MOUNT:
1618 return mount_overlay(m);
1619
1620 default:
1621 assert_not_reached();
1622 }
1623
1624 assert(what);
1625
1626 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
1627 if (r < 0) {
1628 bool try_again = false;
1629
1630 if (r == -ENOENT && make) {
1631 int q;
1632
1633 /* Hmm, either the source or the destination are missing. Let's see if we can create
1634 the destination, then try again. */
1635
1636 (void) mkdir_parents(mount_entry_path(m), 0755);
1637
1638 q = make_mount_point_inode_from_path(what, mount_entry_path(m), 0755);
1639 if (q < 0) {
1640 if (q != -EEXIST)
1641 log_warning_errno(q, "Failed to create destination mount point node '%s', ignoring: %m",
1642 mount_entry_path(m));
1643 } else
1644 try_again = true;
1645 }
1646
1647 if (try_again)
1648 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
1649 if (r < 0)
1650 return log_error_errno(r, "Failed to mount %s to %s: %m", what, mount_entry_path(m));
1651 }
1652
1653 log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
1654 return 0;
1655 }
1656
1657 static int make_read_only(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
1658 unsigned long new_flags = 0, flags_mask = 0;
1659 bool submounts;
1660 int r;
1661
1662 assert(m);
1663 assert(proc_self_mountinfo);
1664
1665 if (mount_entry_read_only(m) || m->mode == PRIVATE_DEV) {
1666 new_flags |= MS_RDONLY;
1667 flags_mask |= MS_RDONLY;
1668 }
1669
1670 if (m->nosuid) {
1671 new_flags |= MS_NOSUID;
1672 flags_mask |= MS_NOSUID;
1673 }
1674
1675 if (flags_mask == 0) /* No Change? */
1676 return 0;
1677
1678 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1679 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1680 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1681 * and running Linux <= 4.17. */
1682 submounts =
1683 mount_entry_read_only(m) &&
1684 !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1685 if (submounts)
1686 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
1687 else
1688 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
1689
1690 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
1691 * read-only already stays this way. This improves compatibility with container managers, where we
1692 * won't attempt to undo read-only mounts already applied. */
1693
1694 if (r == -ENOENT && m->ignore)
1695 return 0;
1696 if (r < 0)
1697 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1698 submounts ? " and its submounts" : "");
1699 return 0;
1700 }
1701
1702 static int make_noexec(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
1703 unsigned long new_flags = 0, flags_mask = 0;
1704 bool submounts;
1705 int r;
1706
1707 assert(m);
1708 assert(proc_self_mountinfo);
1709
1710 if (mount_entry_noexec(m)) {
1711 new_flags |= MS_NOEXEC;
1712 flags_mask |= MS_NOEXEC;
1713 } else if (mount_entry_exec(m)) {
1714 new_flags &= ~MS_NOEXEC;
1715 flags_mask |= MS_NOEXEC;
1716 }
1717
1718 if (flags_mask == 0) /* No Change? */
1719 return 0;
1720
1721 submounts = !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1722
1723 if (submounts)
1724 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
1725 else
1726 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
1727
1728 if (r == -ENOENT && m->ignore)
1729 return 0;
1730 if (r < 0)
1731 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1732 submounts ? " and its submounts" : "");
1733 return 0;
1734 }
1735
1736 static int make_nosuid(const MountEntry *m, FILE *proc_self_mountinfo) {
1737 bool submounts;
1738 int r;
1739
1740 assert(m);
1741 assert(proc_self_mountinfo);
1742
1743 submounts = !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1744
1745 if (submounts)
1746 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, NULL, proc_self_mountinfo);
1747 else
1748 r = bind_remount_one_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, proc_self_mountinfo);
1749 if (r == -ENOENT && m->ignore)
1750 return 0;
1751 if (r < 0)
1752 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1753 submounts ? " and its submounts" : "");
1754 return 0;
1755 }
1756
1757 static bool namespace_parameters_mount_apivfs(const NamespaceParameters *p) {
1758 assert(p);
1759
1760 /*
1761 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1762 * since to protect the API VFS mounts, they need to be around in the
1763 * first place...
1764 */
1765
1766 return p->mount_apivfs ||
1767 p->protect_control_groups ||
1768 p->protect_kernel_tunables ||
1769 p->protect_proc != PROTECT_PROC_DEFAULT ||
1770 p->proc_subset != PROC_SUBSET_ALL;
1771 }
1772
1773 /* Walk all mount entries and dropping any unused mounts. This affects all
1774 * mounts:
1775 * - that are implicitly protected by a path that has been rendered inaccessible
1776 * - whose immediate parent requests the same protection mode as the mount itself
1777 * - that are outside of the relevant root directory
1778 * - which are duplicates
1779 */
1780 static void drop_unused_mounts(MountList *ml, const char *root_directory) {
1781 assert(ml);
1782 assert(root_directory);
1783
1784 assert(ml->mounts || ml->n_mounts == 0);
1785
1786 typesafe_qsort(ml->mounts, ml->n_mounts, mount_path_compare);
1787
1788 drop_duplicates(ml);
1789 drop_outside_root(ml, root_directory);
1790 drop_inaccessible(ml);
1791 drop_nop(ml);
1792 }
1793
1794 static int create_symlinks_from_tuples(const char *root, char **strv_symlinks) {
1795 int r;
1796
1797 STRV_FOREACH_PAIR(src, dst, strv_symlinks) {
1798 _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
1799
1800 src_abs = path_join(root, *src);
1801 dst_abs = path_join(root, *dst);
1802 if (!src_abs || !dst_abs)
1803 return -ENOMEM;
1804
1805 r = mkdir_parents_label(dst_abs, 0755);
1806 if (r < 0)
1807 return log_debug_errno(
1808 r,
1809 "Failed to create parent directory for symlink '%s': %m",
1810 dst_abs);
1811
1812 r = symlink_idempotent(src_abs, dst_abs, true);
1813 if (r < 0)
1814 return log_debug_errno(
1815 r,
1816 "Failed to create symlink from '%s' to '%s': %m",
1817 src_abs,
1818 dst_abs);
1819 }
1820
1821 return 0;
1822 }
1823
1824 static void mount_entry_path_debug_string(const char *root, MountEntry *m, char **error_path) {
1825 assert(m);
1826
1827 /* Create a string suitable for debugging logs, stripping for example the local working directory.
1828 * For example, with a BindPaths=/var/bar that does not exist on the host:
1829 *
1830 * Before:
1831 * foo.service: Failed to set up mount namespacing: /run/systemd/unit-root/var/bar: No such file or directory
1832 * After:
1833 * foo.service: Failed to set up mount namespacing: /var/bar: No such file or directory
1834 *
1835 * Note that this is an error path, so no OOM check is done on purpose. */
1836
1837 if (!error_path)
1838 return;
1839
1840 if (!mount_entry_path(m)) {
1841 *error_path = NULL;
1842 return;
1843 }
1844
1845 if (root) {
1846 const char *e = startswith(mount_entry_path(m), root);
1847 if (e) {
1848 *error_path = strdup(e);
1849 return;
1850 }
1851 }
1852
1853 *error_path = strdup(mount_entry_path(m));
1854 return;
1855 }
1856
1857 static int apply_mounts(
1858 MountList *ml,
1859 const char *root,
1860 const NamespaceParameters *p,
1861 char **error_path) {
1862
1863 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
1864 _cleanup_free_ char **deny_list = NULL;
1865 int r;
1866
1867 assert(ml);
1868 assert(root);
1869 assert(p);
1870
1871 if (ml->n_mounts == 0) /* Shortcut: nothing to do */
1872 return 0;
1873
1874 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1875 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
1876 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
1877 if (!proc_self_mountinfo) {
1878 r = -errno;
1879
1880 if (error_path)
1881 *error_path = strdup("/proc/self/mountinfo");
1882
1883 return log_debug_errno(r, "Failed to open /proc/self/mountinfo: %m");
1884 }
1885
1886 /* First round, establish all mounts we need */
1887 for (;;) {
1888 bool again = false;
1889
1890 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1891
1892 if (m->applied)
1893 continue;
1894
1895 /* ExtensionImages/Directories are first opened in the propagate directory, not in the root_directory */
1896 r = follow_symlink(!IN_SET(m->mode, EXTENSION_IMAGES, EXTENSION_DIRECTORIES) ? root : NULL, m);
1897 if (r < 0) {
1898 mount_entry_path_debug_string(root, m, error_path);
1899 return r;
1900 }
1901 if (r == 0) {
1902 /* We hit a symlinked mount point. The entry got rewritten and might
1903 * point to a very different place now. Let's normalize the changed
1904 * list, and start from the beginning. After all to mount the entry
1905 * at the new location we might need some other mounts first */
1906 again = true;
1907 break;
1908 }
1909
1910 r = apply_one_mount(root, m, p);
1911 if (r < 0) {
1912 mount_entry_path_debug_string(root, m, error_path);
1913 return r;
1914 }
1915
1916 m->applied = true;
1917 }
1918
1919 if (!again)
1920 break;
1921
1922 drop_unused_mounts(ml, root);
1923 }
1924
1925 /* Now that all filesystems have been set up, but before the
1926 * read-only switches are flipped, create the exec dirs and other symlinks.
1927 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
1928 * exist, which means this will be a no-op. */
1929 r = create_symlinks_from_tuples(root, p->symlinks);
1930 if (r < 0)
1931 return log_debug_errno(r, "Failed to set up symlinks inside mount namespace: %m");
1932
1933 /* Create a deny list we can pass to bind_mount_recursive() */
1934 deny_list = new(char*, ml->n_mounts+1);
1935 if (!deny_list)
1936 return -ENOMEM;
1937 for (size_t j = 0; j < ml->n_mounts; j++)
1938 deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
1939 deny_list[ml->n_mounts] = NULL;
1940
1941 /* Second round, flip the ro bits if necessary. */
1942 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1943 r = make_read_only(m, deny_list, proc_self_mountinfo);
1944 if (r < 0) {
1945 mount_entry_path_debug_string(root, m, error_path);
1946 return r;
1947 }
1948 }
1949
1950 /* Third round, flip the noexec bits with a simplified deny list. */
1951 for (size_t j = 0; j < ml->n_mounts; j++)
1952 if (IN_SET((ml->mounts+j)->mode, EXEC, NOEXEC))
1953 deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
1954 deny_list[ml->n_mounts] = NULL;
1955
1956 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1957 r = make_noexec(m, deny_list, proc_self_mountinfo);
1958 if (r < 0) {
1959 mount_entry_path_debug_string(root, m, error_path);
1960 return r;
1961 }
1962 }
1963
1964 /* Fourth round, flip the nosuid bits without a deny list. */
1965 if (p->mount_nosuid)
1966 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1967 r = make_nosuid(m, proc_self_mountinfo);
1968 if (r < 0) {
1969 mount_entry_path_debug_string(root, m, error_path);
1970 return r;
1971 }
1972 }
1973
1974 return 1;
1975 }
1976
1977 static bool root_read_only(
1978 char **read_only_paths,
1979 ProtectSystem protect_system) {
1980
1981 /* Determine whether the root directory is going to be read-only given the configured settings. */
1982
1983 if (protect_system == PROTECT_SYSTEM_STRICT)
1984 return true;
1985
1986 if (prefixed_path_strv_contains(read_only_paths, "/"))
1987 return true;
1988
1989 return false;
1990 }
1991
1992 static bool home_read_only(
1993 char** read_only_paths,
1994 char** inaccessible_paths,
1995 char** empty_directories,
1996 const BindMount *bind_mounts,
1997 size_t n_bind_mounts,
1998 const TemporaryFileSystem *temporary_filesystems,
1999 size_t n_temporary_filesystems,
2000 ProtectHome protect_home) {
2001
2002 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
2003 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
2004 * settings. */
2005
2006 if (protect_home != PROTECT_HOME_NO)
2007 return true;
2008
2009 if (prefixed_path_strv_contains(read_only_paths, "/home") ||
2010 prefixed_path_strv_contains(inaccessible_paths, "/home") ||
2011 prefixed_path_strv_contains(empty_directories, "/home"))
2012 return true;
2013
2014 for (size_t i = 0; i < n_temporary_filesystems; i++)
2015 if (path_equal(temporary_filesystems[i].path, "/home"))
2016 return true;
2017
2018 /* If /home is overmounted with some dir from the host it's not writable. */
2019 for (size_t i = 0; i < n_bind_mounts; i++)
2020 if (path_equal(bind_mounts[i].destination, "/home"))
2021 return true;
2022
2023 return false;
2024 }
2025
2026 int setup_namespace(const NamespaceParameters *p, char **error_path) {
2027
2028 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2029 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2030 _cleanup_strv_free_ char **hierarchies = NULL;
2031 _cleanup_(mount_list_done) MountList ml = {};
2032 bool require_prefix = false;
2033 const char *root;
2034 DissectImageFlags dissect_image_flags =
2035 DISSECT_IMAGE_GENERIC_ROOT |
2036 DISSECT_IMAGE_REQUIRE_ROOT |
2037 DISSECT_IMAGE_DISCARD_ON_LOOP |
2038 DISSECT_IMAGE_RELAX_VAR_CHECK |
2039 DISSECT_IMAGE_FSCK |
2040 DISSECT_IMAGE_USR_NO_ROOT |
2041 DISSECT_IMAGE_GROWFS |
2042 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
2043 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
2044 int r;
2045
2046 assert(p);
2047
2048 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2049 * we configure take effect */
2050 BLOCK_WITH_UMASK(0000);
2051
2052 bool setup_propagate = !isempty(p->propagate_dir) && !isempty(p->incoming_dir);
2053 unsigned long mount_propagation_flag = p->mount_propagation_flag != 0 ? p->mount_propagation_flag : MS_SHARED;
2054
2055 if (p->root_image) {
2056 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2057 if (root_read_only(p->read_only_paths,
2058 p->protect_system) &&
2059 home_read_only(p->read_only_paths, p->inaccessible_paths, p->empty_directories,
2060 p->bind_mounts, p->n_bind_mounts, p->temporary_filesystems, p->n_temporary_filesystems,
2061 p->protect_home) &&
2062 strv_isempty(p->read_write_paths))
2063 dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
2064
2065 SET_FLAG(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE, p->verity && p->verity->data_path);
2066
2067 r = loop_device_make_by_path(
2068 p->root_image,
2069 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : -1 /* < 0 means writable if possible, read-only as fallback */,
2070 /* sector_size= */ UINT32_MAX,
2071 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2072 LOCK_SH,
2073 &loop_device);
2074 if (r < 0)
2075 return log_debug_errno(r, "Failed to create loop device for root image: %m");
2076
2077 r = dissect_loop_device(
2078 loop_device,
2079 p->verity,
2080 p->root_image_options,
2081 p->root_image_policy,
2082 dissect_image_flags,
2083 &dissected_image);
2084 if (r < 0)
2085 return log_debug_errno(r, "Failed to dissect image: %m");
2086
2087 r = dissected_image_load_verity_sig_partition(
2088 dissected_image,
2089 loop_device->fd,
2090 p->verity);
2091 if (r < 0)
2092 return r;
2093
2094 r = dissected_image_decrypt(
2095 dissected_image,
2096 NULL,
2097 p->verity,
2098 dissect_image_flags);
2099 if (r < 0)
2100 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
2101 }
2102
2103 if (p->root_directory)
2104 root = p->root_directory;
2105 else {
2106 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2107 * when running tests (test-execute), it might not have been created yet so let's make sure
2108 * we create it if it doesn't already exist. */
2109 (void) mkdir_p_label("/run/systemd", 0755);
2110
2111 /* Always create the mount namespace in a temporary directory, instead of operating directly
2112 * in the root. The temporary directory prevents any mounts from being potentially obscured
2113 * my other mounts we already applied. We use the same mount point for all images, which is
2114 * safe, since they all live in their own namespaces after all, and hence won't see each
2115 * other. (Note: this directory is also created by PID 1 early on, we create it here for
2116 * similar reasons as /run/systemd/ first.) */
2117 root = "/run/systemd/mount-rootfs";
2118 (void) mkdir_label(root, 0555);
2119
2120 require_prefix = true;
2121 }
2122
2123 if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories)) {
2124 /* Hierarchy population needs to be done for sysext and confext extension images */
2125 r = parse_env_extension_hierarchies(&hierarchies, "SYSTEMD_SYSEXT_AND_CONFEXT_HIERARCHIES");
2126 if (r < 0)
2127 return r;
2128 }
2129
2130 r = append_access_mounts(&ml, p->read_write_paths, READWRITE, require_prefix);
2131 if (r < 0)
2132 return r;
2133
2134 r = append_access_mounts(&ml, p->read_only_paths, READONLY, require_prefix);
2135 if (r < 0)
2136 return r;
2137
2138 r = append_access_mounts(&ml, p->inaccessible_paths, INACCESSIBLE, require_prefix);
2139 if (r < 0)
2140 return r;
2141
2142 r = append_access_mounts(&ml, p->exec_paths, EXEC, require_prefix);
2143 if (r < 0)
2144 return r;
2145
2146 r = append_access_mounts(&ml, p->no_exec_paths, NOEXEC, require_prefix);
2147 if (r < 0)
2148 return r;
2149
2150 r = append_empty_dir_mounts(&ml, p->empty_directories);
2151 if (r < 0)
2152 return r;
2153
2154 r = append_bind_mounts(&ml, p->bind_mounts, p->n_bind_mounts);
2155 if (r < 0)
2156 return r;
2157
2158 r = append_tmpfs_mounts(&ml, p->temporary_filesystems, p->n_temporary_filesystems);
2159 if (r < 0)
2160 return r;
2161
2162 if (p->tmp_dir) {
2163 bool ro = streq(p->tmp_dir, RUN_SYSTEMD_EMPTY);
2164
2165 MountEntry *me = mount_list_extend(&ml);
2166 if (!me)
2167 return log_oom_debug();
2168
2169 *me = (MountEntry) {
2170 .path_const = "/tmp",
2171 .mode = ro ? PRIVATE_TMP_READONLY : PRIVATE_TMP,
2172 .source_const = p->tmp_dir,
2173 };
2174 }
2175
2176 if (p->var_tmp_dir) {
2177 bool ro = streq(p->var_tmp_dir, RUN_SYSTEMD_EMPTY);
2178
2179 MountEntry *me = mount_list_extend(&ml);
2180 if (!me)
2181 return log_oom_debug();
2182
2183 *me = (MountEntry) {
2184 .path_const = "/var/tmp",
2185 .mode = ro ? PRIVATE_TMP_READONLY : PRIVATE_TMP,
2186 .source_const = p->var_tmp_dir,
2187 };
2188 }
2189
2190 r = append_mount_images(&ml, p->mount_images, p->n_mount_images);
2191 if (r < 0)
2192 return r;
2193
2194 r = append_extensions(&ml, root, p->extension_dir, hierarchies, p->extension_images, p->n_extension_images, p->extension_directories);
2195 if (r < 0)
2196 return r;
2197
2198 if (p->private_dev) {
2199 MountEntry *me = mount_list_extend(&ml);
2200 if (!me)
2201 return log_oom_debug();
2202
2203 *me = (MountEntry) {
2204 .path_const = "/dev",
2205 .mode = PRIVATE_DEV,
2206 .flags = DEV_MOUNT_OPTIONS,
2207 };
2208 }
2209
2210 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the protective
2211 mounts to non-pid /proc paths would fail. But the pid only option may have failed gracefully, so
2212 let's try the mounts but it's not fatal if they don't succeed. */
2213 bool ignore_protect_proc = p->ignore_protect_paths || p->proc_subset == PROC_SUBSET_PID;
2214 if (p->protect_kernel_tunables) {
2215 r = append_static_mounts(&ml,
2216 protect_kernel_tunables_proc_table,
2217 ELEMENTSOF(protect_kernel_tunables_proc_table),
2218 ignore_protect_proc);
2219 if (r < 0)
2220 return r;
2221
2222 r = append_static_mounts(&ml,
2223 protect_kernel_tunables_sys_table,
2224 ELEMENTSOF(protect_kernel_tunables_sys_table),
2225 p->ignore_protect_paths);
2226 if (r < 0)
2227 return r;
2228 }
2229
2230 if (p->protect_kernel_modules) {
2231 r = append_static_mounts(&ml,
2232 protect_kernel_modules_table,
2233 ELEMENTSOF(protect_kernel_modules_table),
2234 p->ignore_protect_paths);
2235 if (r < 0)
2236 return r;
2237 }
2238
2239 if (p->protect_kernel_logs) {
2240 r = append_static_mounts(&ml,
2241 protect_kernel_logs_proc_table,
2242 ELEMENTSOF(protect_kernel_logs_proc_table),
2243 ignore_protect_proc);
2244 if (r < 0)
2245 return r;
2246
2247 r = append_static_mounts(&ml,
2248 protect_kernel_logs_dev_table,
2249 ELEMENTSOF(protect_kernel_logs_dev_table),
2250 p->ignore_protect_paths);
2251 if (r < 0)
2252 return r;
2253 }
2254
2255 if (p->protect_control_groups) {
2256 MountEntry *me = mount_list_extend(&ml);
2257 if (!me)
2258 return log_oom_debug();
2259
2260 *me = (MountEntry) {
2261 .path_const = "/sys/fs/cgroup",
2262 .mode = READONLY,
2263 };
2264 }
2265
2266 r = append_protect_home(&ml, p->protect_home, p->ignore_protect_paths);
2267 if (r < 0)
2268 return r;
2269
2270 r = append_protect_system(&ml, p->protect_system, false);
2271 if (r < 0)
2272 return r;
2273
2274 if (namespace_parameters_mount_apivfs(p)) {
2275 r = append_static_mounts(&ml,
2276 apivfs_table,
2277 ELEMENTSOF(apivfs_table),
2278 p->ignore_protect_paths);
2279 if (r < 0)
2280 return r;
2281 }
2282
2283 /* Note, if proc is mounted with subset=pid then neither of the two paths will exist, i.e. they are
2284 * implicitly protected by the mount option. */
2285 if (p->protect_hostname) {
2286 r = append_static_mounts(
2287 &ml,
2288 protect_hostname_table,
2289 ELEMENTSOF(protect_hostname_table),
2290 ignore_protect_proc);
2291 if (r < 0)
2292 return r;
2293 }
2294
2295 if (p->private_network) {
2296 MountEntry *me = mount_list_extend(&ml);
2297 if (!me)
2298 return log_oom_debug();
2299
2300 *me = (MountEntry) {
2301 .path_const = "/sys",
2302 .mode = PRIVATE_SYSFS,
2303 };
2304 }
2305
2306 if (p->private_ipc) {
2307 MountEntry *me = mount_list_extend(&ml);
2308 if (!me)
2309 return log_oom_debug();
2310
2311 *me = (MountEntry) {
2312 .path_const = "/dev/mqueue",
2313 .mode = MQUEUEFS,
2314 .flags = MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
2315 };
2316 }
2317
2318 if (p->creds_path) {
2319 /* If our service has a credentials store configured, then bind that one in, but hide
2320 * everything else. */
2321
2322 MountEntry *me = mount_list_extend(&ml);
2323 if (!me)
2324 return log_oom_debug();
2325
2326 *me = (MountEntry) {
2327 .path_const = "/run/credentials",
2328 .mode = TMPFS,
2329 .read_only = true,
2330 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
2331 .flags = MS_NODEV|MS_STRICTATIME|MS_NOSUID|MS_NOEXEC,
2332 };
2333
2334 me = mount_list_extend(&ml);
2335 if (!me)
2336 return log_oom_debug();
2337
2338 *me = (MountEntry) {
2339 .path_const = p->creds_path,
2340 .mode = BIND_MOUNT,
2341 .read_only = true,
2342 .source_const = p->creds_path,
2343 .ignore = true,
2344 };
2345 } else {
2346 /* If our service has no credentials store configured, then make the whole credentials tree
2347 * inaccessible wholesale. */
2348
2349 MountEntry *me = mount_list_extend(&ml);
2350 if (!me)
2351 return log_oom_debug();
2352
2353 *me = (MountEntry) {
2354 .path_const = "/run/credentials",
2355 .mode = INACCESSIBLE,
2356 .ignore = true,
2357 };
2358 }
2359
2360 if (p->log_namespace) {
2361 _cleanup_free_ char *q = NULL;
2362
2363 q = strjoin("/run/systemd/journal.", p->log_namespace);
2364 if (!q)
2365 return log_oom();
2366
2367 MountEntry *me = mount_list_extend(&ml);
2368 if (!me)
2369 return log_oom_debug();
2370
2371 *me = (MountEntry) {
2372 .path_const = "/run/systemd/journal",
2373 .mode = BIND_MOUNT_RECURSIVE,
2374 .read_only = true,
2375 .source_malloc = TAKE_PTR(q),
2376 };
2377 }
2378
2379 /* Will be used to add bind mounts at runtime */
2380 if (setup_propagate) {
2381 MountEntry *me = mount_list_extend(&ml);
2382 if (!me)
2383 return log_oom_debug();
2384
2385 *me = (MountEntry) {
2386 .source_const = p->propagate_dir,
2387 .path_const = p->incoming_dir,
2388 .mode = BIND_MOUNT,
2389 .read_only = true,
2390 };
2391 }
2392
2393 if (p->notify_socket) {
2394 MountEntry *me = mount_list_extend(&ml);
2395 if (!me)
2396 return log_oom_debug();
2397
2398 *me = (MountEntry) {
2399 .path_const = p->notify_socket,
2400 .source_const = p->notify_socket,
2401 .mode = BIND_MOUNT,
2402 .read_only = true,
2403 };
2404 }
2405
2406 if (p->host_os_release_stage) {
2407 MountEntry *me = mount_list_extend(&ml);
2408 if (!me)
2409 return log_oom_debug();
2410
2411 *me = (MountEntry) {
2412 .path_const = "/run/host/.os-release-stage/",
2413 .source_const = p->host_os_release_stage,
2414 .mode = BIND_MOUNT,
2415 .read_only = true,
2416 .ignore = true, /* Live copy, don't hard-fail if it goes missing */
2417 };
2418 }
2419
2420 /* Prepend the root directory where that's necessary */
2421 r = prefix_where_needed(&ml, root);
2422 if (r < 0)
2423 return r;
2424
2425 drop_unused_mounts(&ml, root);
2426
2427 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
2428
2429 if (unshare(CLONE_NEWNS) < 0) {
2430 r = log_debug_errno(errno, "Failed to unshare the mount namespace: %m");
2431
2432 if (ERRNO_IS_PRIVILEGE(r) ||
2433 ERRNO_IS_NOT_SUPPORTED(r))
2434 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
2435 * in place that doesn't allow us to create namespaces (or a missing cap), then
2436 * propagate a recognizable error back, which the caller can use to detect this case
2437 * (and only this) and optionally continue without namespacing applied. */
2438 return -ENOANO;
2439
2440 return r;
2441 }
2442
2443 /* Create the source directory to allow runtime propagation of mounts */
2444 if (setup_propagate)
2445 (void) mkdir_p(p->propagate_dir, 0600);
2446
2447 if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories))
2448 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
2449 * mounts to create, so have the parent ready */
2450 (void) mkdir_p(p->extension_dir, 0600);
2451
2452 /* Remount / as SLAVE so that nothing now mounted in the namespace
2453 * shows up in the parent */
2454 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0)
2455 return log_debug_errno(errno, "Failed to remount '/' as SLAVE: %m");
2456
2457 if (p->root_image) {
2458 /* A root image is specified, mount it to the right place */
2459 r = dissected_image_mount(
2460 dissected_image,
2461 root,
2462 /* uid_shift= */ UID_INVALID,
2463 /* uid_range= */ UID_INVALID,
2464 /* userns_fd= */ -EBADF,
2465 dissect_image_flags);
2466 if (r < 0)
2467 return log_debug_errno(r, "Failed to mount root image: %m");
2468
2469 /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
2470 * if it likes. */
2471 r = loop_device_flock(loop_device, LOCK_UN);
2472 if (r < 0)
2473 return log_debug_errno(r, "Failed to release lock on loopback block device: %m");
2474
2475 r = dissected_image_relinquish(dissected_image);
2476 if (r < 0)
2477 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
2478
2479 } else if (p->root_directory) {
2480
2481 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
2482 r = path_is_mount_point(root, NULL, AT_SYMLINK_FOLLOW);
2483 if (r < 0)
2484 return log_debug_errno(r, "Failed to detect that %s is a mount point or not: %m", root);
2485 if (r == 0) {
2486 r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
2487 if (r < 0)
2488 return r;
2489 }
2490
2491 } else {
2492 /* Let's mount the main root directory to the root directory to use */
2493 r = mount_nofollow_verbose(LOG_DEBUG, "/", root, NULL, MS_BIND|MS_REC, NULL);
2494 if (r < 0)
2495 return r;
2496 }
2497
2498 /* Try to set up the new root directory before mounting anything else there. */
2499 if (p->root_image || p->root_directory)
2500 (void) base_filesystem_create(root, UID_INVALID, GID_INVALID);
2501
2502 /* Now make the magic happen */
2503 r = apply_mounts(&ml, root, p, error_path);
2504 if (r < 0)
2505 return r;
2506
2507 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
2508 r = mount_switch_root(root, /* mount_propagation_flag = */ 0);
2509 if (r == -EINVAL && p->root_directory) {
2510 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
2511 * namespace) and the root_directory is already a mount point in the parent namespace,
2512 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
2513 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
2514 * mount point) and try again. */
2515 r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
2516 if (r < 0)
2517 return r;
2518 r = mount_switch_root(root, /* mount_propagation_flag = */ 0);
2519 }
2520 if (r < 0)
2521 return log_debug_errno(r, "Failed to mount root with MS_MOVE: %m");
2522
2523 /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
2524 * the host, since what's disconnected is disconnected. */
2525 if (mount(NULL, "/", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
2526 return log_debug_errno(errno, "Failed to remount '/' with desired mount flags: %m");
2527
2528 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only
2529 * supported for non-shared mounts. This needs to happen after remounting / or it will fail. */
2530 if (setup_propagate) {
2531 if (mount(NULL, p->incoming_dir, NULL, MS_SLAVE, NULL) < 0)
2532 return log_debug_errno(errno, "Failed to remount %s with MS_SLAVE: %m", p->incoming_dir);
2533 }
2534
2535 return 0;
2536 }
2537
2538 void bind_mount_free_many(BindMount *b, size_t n) {
2539 assert(b || n == 0);
2540
2541 for (size_t i = 0; i < n; i++) {
2542 free(b[i].source);
2543 free(b[i].destination);
2544 }
2545
2546 free(b);
2547 }
2548
2549 int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
2550 _cleanup_free_ char *s = NULL, *d = NULL;
2551 BindMount *c;
2552
2553 assert(b);
2554 assert(n);
2555 assert(item);
2556
2557 s = strdup(item->source);
2558 if (!s)
2559 return -ENOMEM;
2560
2561 d = strdup(item->destination);
2562 if (!d)
2563 return -ENOMEM;
2564
2565 c = reallocarray(*b, *n + 1, sizeof(BindMount));
2566 if (!c)
2567 return -ENOMEM;
2568
2569 *b = c;
2570
2571 c[(*n) ++] = (BindMount) {
2572 .source = TAKE_PTR(s),
2573 .destination = TAKE_PTR(d),
2574 .read_only = item->read_only,
2575 .nosuid = item->nosuid,
2576 .recursive = item->recursive,
2577 .ignore_enoent = item->ignore_enoent,
2578 };
2579
2580 return 0;
2581 }
2582
2583 MountImage* mount_image_free_many(MountImage *m, size_t *n) {
2584 assert(n);
2585 assert(m || *n == 0);
2586
2587 for (size_t i = 0; i < *n; i++) {
2588 free(m[i].source);
2589 free(m[i].destination);
2590 mount_options_free_all(m[i].mount_options);
2591 }
2592
2593 free(m);
2594 *n = 0;
2595 return NULL;
2596 }
2597
2598 int mount_image_add(MountImage **m, size_t *n, const MountImage *item) {
2599 _cleanup_free_ char *s = NULL, *d = NULL;
2600 _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
2601 MountImage *c;
2602
2603 assert(m);
2604 assert(n);
2605 assert(item);
2606
2607 s = strdup(item->source);
2608 if (!s)
2609 return -ENOMEM;
2610
2611 if (item->destination) {
2612 d = strdup(item->destination);
2613 if (!d)
2614 return -ENOMEM;
2615 }
2616
2617 LIST_FOREACH(mount_options, i, item->mount_options) {
2618 _cleanup_(mount_options_free_allp) MountOptions *o = NULL;
2619
2620 o = new(MountOptions, 1);
2621 if (!o)
2622 return -ENOMEM;
2623
2624 *o = (MountOptions) {
2625 .partition_designator = i->partition_designator,
2626 .options = strdup(i->options),
2627 };
2628 if (!o->options)
2629 return -ENOMEM;
2630
2631 LIST_APPEND(mount_options, options, TAKE_PTR(o));
2632 }
2633
2634 c = reallocarray(*m, *n + 1, sizeof(MountImage));
2635 if (!c)
2636 return -ENOMEM;
2637
2638 *m = c;
2639
2640 c[(*n) ++] = (MountImage) {
2641 .source = TAKE_PTR(s),
2642 .destination = TAKE_PTR(d),
2643 .mount_options = TAKE_PTR(options),
2644 .ignore_enoent = item->ignore_enoent,
2645 .type = item->type,
2646 };
2647
2648 return 0;
2649 }
2650
2651 void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
2652 assert(t || n == 0);
2653
2654 for (size_t i = 0; i < n; i++) {
2655 free(t[i].path);
2656 free(t[i].options);
2657 }
2658
2659 free(t);
2660 }
2661
2662 int temporary_filesystem_add(
2663 TemporaryFileSystem **t,
2664 size_t *n,
2665 const char *path,
2666 const char *options) {
2667
2668 _cleanup_free_ char *p = NULL, *o = NULL;
2669 TemporaryFileSystem *c;
2670
2671 assert(t);
2672 assert(n);
2673 assert(path);
2674
2675 p = strdup(path);
2676 if (!p)
2677 return -ENOMEM;
2678
2679 if (!isempty(options)) {
2680 o = strdup(options);
2681 if (!o)
2682 return -ENOMEM;
2683 }
2684
2685 c = reallocarray(*t, *n + 1, sizeof(TemporaryFileSystem));
2686 if (!c)
2687 return -ENOMEM;
2688
2689 *t = c;
2690
2691 c[(*n) ++] = (TemporaryFileSystem) {
2692 .path = TAKE_PTR(p),
2693 .options = TAKE_PTR(o),
2694 };
2695
2696 return 0;
2697 }
2698
2699 static int make_tmp_prefix(const char *prefix) {
2700 _cleanup_free_ char *t = NULL;
2701 _cleanup_close_ int fd = -EBADF;
2702 int r;
2703
2704 /* Don't do anything unless we know the dir is actually missing */
2705 r = access(prefix, F_OK);
2706 if (r >= 0)
2707 return 0;
2708 if (errno != ENOENT)
2709 return -errno;
2710
2711 WITH_UMASK(000)
2712 r = mkdir_parents(prefix, 0755);
2713 if (r < 0)
2714 return r;
2715
2716 r = tempfn_random(prefix, NULL, &t);
2717 if (r < 0)
2718 return r;
2719
2720 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2721 * the suid bit, below. */
2722 fd = open_mkdir_at(AT_FDCWD, t, O_EXCL|O_CLOEXEC, 0777);
2723 if (fd < 0)
2724 return fd;
2725
2726 r = RET_NERRNO(fchmod(fd, 01777));
2727 if (r < 0) {
2728 (void) rmdir(t);
2729 return r;
2730 }
2731
2732 r = RET_NERRNO(rename(t, prefix));
2733 if (r < 0) {
2734 (void) rmdir(t);
2735 return r == -EEXIST ? 0 : r; /* it's fine if someone else created the dir by now */
2736 }
2737
2738 return 0;
2739
2740 }
2741
2742 static int setup_one_tmp_dir(const char *id, const char *prefix, char **path, char **tmp_path) {
2743 _cleanup_free_ char *x = NULL;
2744 _cleanup_free_ char *y = NULL;
2745 sd_id128_t boot_id;
2746 bool rw = true;
2747 int r;
2748
2749 assert(id);
2750 assert(prefix);
2751 assert(path);
2752
2753 /* We include the boot id in the directory so that after a
2754 * reboot we can easily identify obsolete directories. */
2755
2756 r = sd_id128_get_boot(&boot_id);
2757 if (r < 0)
2758 return r;
2759
2760 x = strjoin(prefix, "/systemd-private-", SD_ID128_TO_STRING(boot_id), "-", id, "-XXXXXX");
2761 if (!x)
2762 return -ENOMEM;
2763
2764 r = make_tmp_prefix(prefix);
2765 if (r < 0)
2766 return r;
2767
2768 WITH_UMASK(0077)
2769 if (!mkdtemp(x)) {
2770 if (errno == EROFS || ERRNO_IS_DISK_SPACE(errno))
2771 rw = false;
2772 else
2773 return -errno;
2774 }
2775
2776 if (rw) {
2777 y = strjoin(x, "/tmp");
2778 if (!y)
2779 return -ENOMEM;
2780
2781 WITH_UMASK(0000)
2782 if (mkdir(y, 0777 | S_ISVTX) < 0)
2783 return -errno;
2784
2785 r = label_fix_full(AT_FDCWD, y, prefix, 0);
2786 if (r < 0)
2787 return r;
2788
2789 if (tmp_path)
2790 *tmp_path = TAKE_PTR(y);
2791 } else {
2792 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2793 * read-only. This way the service will get the EROFS result as if it was writing to the real
2794 * file system. */
2795 WITH_UMASK(0000)
2796 r = mkdir_p(RUN_SYSTEMD_EMPTY, 0500);
2797 if (r < 0)
2798 return r;
2799
2800 r = free_and_strdup(&x, RUN_SYSTEMD_EMPTY);
2801 if (r < 0)
2802 return r;
2803 }
2804
2805 *path = TAKE_PTR(x);
2806 return 0;
2807 }
2808
2809 int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
2810 _cleanup_(namespace_cleanup_tmpdirp) char *a = NULL;
2811 _cleanup_(rmdir_and_freep) char *a_tmp = NULL;
2812 char *b;
2813 int r;
2814
2815 assert(id);
2816 assert(tmp_dir);
2817 assert(var_tmp_dir);
2818
2819 r = setup_one_tmp_dir(id, "/tmp", &a, &a_tmp);
2820 if (r < 0)
2821 return r;
2822
2823 r = setup_one_tmp_dir(id, "/var/tmp", &b, NULL);
2824 if (r < 0)
2825 return r;
2826
2827 a_tmp = mfree(a_tmp); /* avoid rmdir */
2828 *tmp_dir = TAKE_PTR(a);
2829 *var_tmp_dir = TAKE_PTR(b);
2830
2831 return 0;
2832 }
2833
2834 int setup_shareable_ns(int ns_storage_socket[static 2], unsigned long nsflag) {
2835 _cleanup_close_ int ns = -EBADF;
2836 int r;
2837 const char *ns_name, *ns_path;
2838
2839 assert(ns_storage_socket);
2840 assert(ns_storage_socket[0] >= 0);
2841 assert(ns_storage_socket[1] >= 0);
2842
2843 ns_name = namespace_single_flag_to_string(nsflag);
2844 assert(ns_name);
2845
2846 /* We use the passed socketpair as a storage buffer for our
2847 * namespace reference fd. Whatever process runs this first
2848 * shall create a new namespace, all others should just join
2849 * it. To serialize that we use a file lock on the socket
2850 * pair.
2851 *
2852 * It's a bit crazy, but hey, works great! */
2853
2854 r = posix_lock(ns_storage_socket[0], LOCK_EX);
2855 if (r < 0)
2856 return r;
2857
2858 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
2859
2860 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2861 if (ns >= 0) {
2862 /* Yay, found something, so let's join the namespace */
2863 r = RET_NERRNO(setns(ns, nsflag));
2864 if (r < 0)
2865 return r;
2866
2867 return 0;
2868 }
2869
2870 if (ns != -EAGAIN)
2871 return ns;
2872
2873 /* Nothing stored yet, so let's create a new namespace. */
2874
2875 if (unshare(nsflag) < 0)
2876 return -errno;
2877
2878 (void) loopback_setup();
2879
2880 ns_path = strjoina("/proc/self/ns/", ns_name);
2881 ns = open(ns_path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2882 if (ns < 0)
2883 return -errno;
2884
2885 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
2886 if (r < 0)
2887 return r;
2888
2889 return 1;
2890 }
2891
2892 int open_shareable_ns_path(int ns_storage_socket[static 2], const char *path, unsigned long nsflag) {
2893 _cleanup_close_ int ns = -EBADF;
2894 int r;
2895
2896 assert(ns_storage_socket);
2897 assert(ns_storage_socket[0] >= 0);
2898 assert(ns_storage_socket[1] >= 0);
2899 assert(path);
2900
2901 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2902 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2903 * allocate a new anonymous ns if needed. */
2904
2905 r = posix_lock(ns_storage_socket[0], LOCK_EX);
2906 if (r < 0)
2907 return r;
2908
2909 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
2910
2911 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2912 if (ns >= 0)
2913 return 0;
2914 if (ns != -EAGAIN)
2915 return ns;
2916
2917 /* Nothing stored yet. Open the file from the file system. */
2918
2919 ns = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
2920 if (ns < 0)
2921 return -errno;
2922
2923 r = fd_is_ns(ns, nsflag);
2924 if (r == 0)
2925 return -EINVAL;
2926 if (r < 0 && r != -EUCLEAN) /* EUCLEAN: we don't know */
2927 return r;
2928
2929 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
2930 if (r < 0)
2931 return r;
2932
2933 return 1;
2934 }
2935
2936 bool ns_type_supported(NamespaceType type) {
2937 const char *t, *ns_proc;
2938
2939 t = namespace_type_to_string(type);
2940 if (!t) /* Don't know how to translate this? Then it's not supported */
2941 return false;
2942
2943 ns_proc = strjoina("/proc/self/ns/", t);
2944 return access(ns_proc, F_OK) == 0;
2945 }
2946
2947 static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
2948 [PROTECT_HOME_NO] = "no",
2949 [PROTECT_HOME_YES] = "yes",
2950 [PROTECT_HOME_READ_ONLY] = "read-only",
2951 [PROTECT_HOME_TMPFS] = "tmpfs",
2952 };
2953
2954 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home, ProtectHome, PROTECT_HOME_YES);
2955
2956 static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
2957 [PROTECT_SYSTEM_NO] = "no",
2958 [PROTECT_SYSTEM_YES] = "yes",
2959 [PROTECT_SYSTEM_FULL] = "full",
2960 [PROTECT_SYSTEM_STRICT] = "strict",
2961 };
2962
2963 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system, ProtectSystem, PROTECT_SYSTEM_YES);
2964
2965 static const char* const namespace_type_table[] = {
2966 [NAMESPACE_MOUNT] = "mnt",
2967 [NAMESPACE_CGROUP] = "cgroup",
2968 [NAMESPACE_UTS] = "uts",
2969 [NAMESPACE_IPC] = "ipc",
2970 [NAMESPACE_USER] = "user",
2971 [NAMESPACE_PID] = "pid",
2972 [NAMESPACE_NET] = "net",
2973 [NAMESPACE_TIME] = "time",
2974 };
2975
2976 DEFINE_STRING_TABLE_LOOKUP(namespace_type, NamespaceType);
2977
2978 static const char* const protect_proc_table[_PROTECT_PROC_MAX] = {
2979 [PROTECT_PROC_DEFAULT] = "default",
2980 [PROTECT_PROC_NOACCESS] = "noaccess",
2981 [PROTECT_PROC_INVISIBLE] = "invisible",
2982 [PROTECT_PROC_PTRACEABLE] = "ptraceable",
2983 };
2984
2985 DEFINE_STRING_TABLE_LOOKUP(protect_proc, ProtectProc);
2986
2987 static const char* const proc_subset_table[_PROC_SUBSET_MAX] = {
2988 [PROC_SUBSET_ALL] = "all",
2989 [PROC_SUBSET_PID] = "pid",
2990 };
2991
2992 DEFINE_STRING_TABLE_LOOKUP(proc_subset, ProcSubset);