]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/namespace.c
namespace: downgrade log message of error we ignore to LOG_WARNING
[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 && q != -EEXIST)
1640 log_warning_errno(q, "Failed to create destination mount point node '%s', ignoring: %m",
1641 mount_entry_path(m));
1642 else
1643 try_again = true;
1644 }
1645
1646 if (try_again)
1647 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
1648 if (r < 0)
1649 return log_error_errno(r, "Failed to mount %s to %s: %m", what, mount_entry_path(m));
1650 }
1651
1652 log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
1653 return 0;
1654 }
1655
1656 static int make_read_only(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
1657 unsigned long new_flags = 0, flags_mask = 0;
1658 bool submounts;
1659 int r;
1660
1661 assert(m);
1662 assert(proc_self_mountinfo);
1663
1664 if (mount_entry_read_only(m) || m->mode == PRIVATE_DEV) {
1665 new_flags |= MS_RDONLY;
1666 flags_mask |= MS_RDONLY;
1667 }
1668
1669 if (m->nosuid) {
1670 new_flags |= MS_NOSUID;
1671 flags_mask |= MS_NOSUID;
1672 }
1673
1674 if (flags_mask == 0) /* No Change? */
1675 return 0;
1676
1677 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1678 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1679 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1680 * and running Linux <= 4.17. */
1681 submounts =
1682 mount_entry_read_only(m) &&
1683 !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1684 if (submounts)
1685 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
1686 else
1687 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
1688
1689 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
1690 * read-only already stays this way. This improves compatibility with container managers, where we
1691 * won't attempt to undo read-only mounts already applied. */
1692
1693 if (r == -ENOENT && m->ignore)
1694 return 0;
1695 if (r < 0)
1696 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1697 submounts ? " and its submounts" : "");
1698 return 0;
1699 }
1700
1701 static int make_noexec(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
1702 unsigned long new_flags = 0, flags_mask = 0;
1703 bool submounts;
1704 int r;
1705
1706 assert(m);
1707 assert(proc_self_mountinfo);
1708
1709 if (mount_entry_noexec(m)) {
1710 new_flags |= MS_NOEXEC;
1711 flags_mask |= MS_NOEXEC;
1712 } else if (mount_entry_exec(m)) {
1713 new_flags &= ~MS_NOEXEC;
1714 flags_mask |= MS_NOEXEC;
1715 }
1716
1717 if (flags_mask == 0) /* No Change? */
1718 return 0;
1719
1720 submounts = !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1721
1722 if (submounts)
1723 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
1724 else
1725 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
1726
1727 if (r == -ENOENT && m->ignore)
1728 return 0;
1729 if (r < 0)
1730 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1731 submounts ? " and its submounts" : "");
1732 return 0;
1733 }
1734
1735 static int make_nosuid(const MountEntry *m, FILE *proc_self_mountinfo) {
1736 bool submounts;
1737 int r;
1738
1739 assert(m);
1740 assert(proc_self_mountinfo);
1741
1742 submounts = !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1743
1744 if (submounts)
1745 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, NULL, proc_self_mountinfo);
1746 else
1747 r = bind_remount_one_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, proc_self_mountinfo);
1748 if (r == -ENOENT && m->ignore)
1749 return 0;
1750 if (r < 0)
1751 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1752 submounts ? " and its submounts" : "");
1753 return 0;
1754 }
1755
1756 static bool namespace_parameters_mount_apivfs(const NamespaceParameters *p) {
1757 assert(p);
1758
1759 /*
1760 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1761 * since to protect the API VFS mounts, they need to be around in the
1762 * first place...
1763 */
1764
1765 return p->mount_apivfs ||
1766 p->protect_control_groups ||
1767 p->protect_kernel_tunables ||
1768 p->protect_proc != PROTECT_PROC_DEFAULT ||
1769 p->proc_subset != PROC_SUBSET_ALL;
1770 }
1771
1772 /* Walk all mount entries and dropping any unused mounts. This affects all
1773 * mounts:
1774 * - that are implicitly protected by a path that has been rendered inaccessible
1775 * - whose immediate parent requests the same protection mode as the mount itself
1776 * - that are outside of the relevant root directory
1777 * - which are duplicates
1778 */
1779 static void drop_unused_mounts(MountList *ml, const char *root_directory) {
1780 assert(ml);
1781 assert(root_directory);
1782
1783 assert(ml->mounts || ml->n_mounts == 0);
1784
1785 typesafe_qsort(ml->mounts, ml->n_mounts, mount_path_compare);
1786
1787 drop_duplicates(ml);
1788 drop_outside_root(ml, root_directory);
1789 drop_inaccessible(ml);
1790 drop_nop(ml);
1791 }
1792
1793 static int create_symlinks_from_tuples(const char *root, char **strv_symlinks) {
1794 int r;
1795
1796 STRV_FOREACH_PAIR(src, dst, strv_symlinks) {
1797 _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
1798
1799 src_abs = path_join(root, *src);
1800 dst_abs = path_join(root, *dst);
1801 if (!src_abs || !dst_abs)
1802 return -ENOMEM;
1803
1804 r = mkdir_parents_label(dst_abs, 0755);
1805 if (r < 0)
1806 return log_debug_errno(
1807 r,
1808 "Failed to create parent directory for symlink '%s': %m",
1809 dst_abs);
1810
1811 r = symlink_idempotent(src_abs, dst_abs, true);
1812 if (r < 0)
1813 return log_debug_errno(
1814 r,
1815 "Failed to create symlink from '%s' to '%s': %m",
1816 src_abs,
1817 dst_abs);
1818 }
1819
1820 return 0;
1821 }
1822
1823 static void mount_entry_path_debug_string(const char *root, MountEntry *m, char **error_path) {
1824 assert(m);
1825
1826 /* Create a string suitable for debugging logs, stripping for example the local working directory.
1827 * For example, with a BindPaths=/var/bar that does not exist on the host:
1828 *
1829 * Before:
1830 * foo.service: Failed to set up mount namespacing: /run/systemd/unit-root/var/bar: No such file or directory
1831 * After:
1832 * foo.service: Failed to set up mount namespacing: /var/bar: No such file or directory
1833 *
1834 * Note that this is an error path, so no OOM check is done on purpose. */
1835
1836 if (!error_path)
1837 return;
1838
1839 if (!mount_entry_path(m)) {
1840 *error_path = NULL;
1841 return;
1842 }
1843
1844 if (root) {
1845 const char *e = startswith(mount_entry_path(m), root);
1846 if (e) {
1847 *error_path = strdup(e);
1848 return;
1849 }
1850 }
1851
1852 *error_path = strdup(mount_entry_path(m));
1853 return;
1854 }
1855
1856 static int apply_mounts(
1857 MountList *ml,
1858 const char *root,
1859 const NamespaceParameters *p,
1860 char **error_path) {
1861
1862 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
1863 _cleanup_free_ char **deny_list = NULL;
1864 int r;
1865
1866 assert(ml);
1867 assert(root);
1868 assert(p);
1869
1870 if (ml->n_mounts == 0) /* Shortcut: nothing to do */
1871 return 0;
1872
1873 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1874 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
1875 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
1876 if (!proc_self_mountinfo) {
1877 r = -errno;
1878
1879 if (error_path)
1880 *error_path = strdup("/proc/self/mountinfo");
1881
1882 return log_debug_errno(r, "Failed to open /proc/self/mountinfo: %m");
1883 }
1884
1885 /* First round, establish all mounts we need */
1886 for (;;) {
1887 bool again = false;
1888
1889 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1890
1891 if (m->applied)
1892 continue;
1893
1894 /* ExtensionImages/Directories are first opened in the propagate directory, not in the root_directory */
1895 r = follow_symlink(!IN_SET(m->mode, EXTENSION_IMAGES, EXTENSION_DIRECTORIES) ? root : NULL, m);
1896 if (r < 0) {
1897 mount_entry_path_debug_string(root, m, error_path);
1898 return r;
1899 }
1900 if (r == 0) {
1901 /* We hit a symlinked mount point. The entry got rewritten and might
1902 * point to a very different place now. Let's normalize the changed
1903 * list, and start from the beginning. After all to mount the entry
1904 * at the new location we might need some other mounts first */
1905 again = true;
1906 break;
1907 }
1908
1909 r = apply_one_mount(root, m, p);
1910 if (r < 0) {
1911 mount_entry_path_debug_string(root, m, error_path);
1912 return r;
1913 }
1914
1915 m->applied = true;
1916 }
1917
1918 if (!again)
1919 break;
1920
1921 drop_unused_mounts(ml, root);
1922 }
1923
1924 /* Now that all filesystems have been set up, but before the
1925 * read-only switches are flipped, create the exec dirs and other symlinks.
1926 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
1927 * exist, which means this will be a no-op. */
1928 r = create_symlinks_from_tuples(root, p->symlinks);
1929 if (r < 0)
1930 return log_debug_errno(r, "Failed to set up symlinks inside mount namespace: %m");
1931
1932 /* Create a deny list we can pass to bind_mount_recursive() */
1933 deny_list = new(char*, ml->n_mounts+1);
1934 if (!deny_list)
1935 return -ENOMEM;
1936 for (size_t j = 0; j < ml->n_mounts; j++)
1937 deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
1938 deny_list[ml->n_mounts] = NULL;
1939
1940 /* Second round, flip the ro bits if necessary. */
1941 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1942 r = make_read_only(m, deny_list, proc_self_mountinfo);
1943 if (r < 0) {
1944 mount_entry_path_debug_string(root, m, error_path);
1945 return r;
1946 }
1947 }
1948
1949 /* Third round, flip the noexec bits with a simplified deny list. */
1950 for (size_t j = 0; j < ml->n_mounts; j++)
1951 if (IN_SET((ml->mounts+j)->mode, EXEC, NOEXEC))
1952 deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
1953 deny_list[ml->n_mounts] = NULL;
1954
1955 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1956 r = make_noexec(m, deny_list, proc_self_mountinfo);
1957 if (r < 0) {
1958 mount_entry_path_debug_string(root, m, error_path);
1959 return r;
1960 }
1961 }
1962
1963 /* Fourth round, flip the nosuid bits without a deny list. */
1964 if (p->mount_nosuid)
1965 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
1966 r = make_nosuid(m, proc_self_mountinfo);
1967 if (r < 0) {
1968 mount_entry_path_debug_string(root, m, error_path);
1969 return r;
1970 }
1971 }
1972
1973 return 1;
1974 }
1975
1976 static bool root_read_only(
1977 char **read_only_paths,
1978 ProtectSystem protect_system) {
1979
1980 /* Determine whether the root directory is going to be read-only given the configured settings. */
1981
1982 if (protect_system == PROTECT_SYSTEM_STRICT)
1983 return true;
1984
1985 if (prefixed_path_strv_contains(read_only_paths, "/"))
1986 return true;
1987
1988 return false;
1989 }
1990
1991 static bool home_read_only(
1992 char** read_only_paths,
1993 char** inaccessible_paths,
1994 char** empty_directories,
1995 const BindMount *bind_mounts,
1996 size_t n_bind_mounts,
1997 const TemporaryFileSystem *temporary_filesystems,
1998 size_t n_temporary_filesystems,
1999 ProtectHome protect_home) {
2000
2001 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
2002 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
2003 * settings. */
2004
2005 if (protect_home != PROTECT_HOME_NO)
2006 return true;
2007
2008 if (prefixed_path_strv_contains(read_only_paths, "/home") ||
2009 prefixed_path_strv_contains(inaccessible_paths, "/home") ||
2010 prefixed_path_strv_contains(empty_directories, "/home"))
2011 return true;
2012
2013 for (size_t i = 0; i < n_temporary_filesystems; i++)
2014 if (path_equal(temporary_filesystems[i].path, "/home"))
2015 return true;
2016
2017 /* If /home is overmounted with some dir from the host it's not writable. */
2018 for (size_t i = 0; i < n_bind_mounts; i++)
2019 if (path_equal(bind_mounts[i].destination, "/home"))
2020 return true;
2021
2022 return false;
2023 }
2024
2025 int setup_namespace(const NamespaceParameters *p, char **error_path) {
2026
2027 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2028 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2029 _cleanup_strv_free_ char **hierarchies = NULL;
2030 _cleanup_(mount_list_done) MountList ml = {};
2031 bool require_prefix = false;
2032 const char *root;
2033 DissectImageFlags dissect_image_flags =
2034 DISSECT_IMAGE_GENERIC_ROOT |
2035 DISSECT_IMAGE_REQUIRE_ROOT |
2036 DISSECT_IMAGE_DISCARD_ON_LOOP |
2037 DISSECT_IMAGE_RELAX_VAR_CHECK |
2038 DISSECT_IMAGE_FSCK |
2039 DISSECT_IMAGE_USR_NO_ROOT |
2040 DISSECT_IMAGE_GROWFS |
2041 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
2042 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
2043 int r;
2044
2045 assert(p);
2046
2047 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2048 * we configure take effect */
2049 BLOCK_WITH_UMASK(0000);
2050
2051 bool setup_propagate = !isempty(p->propagate_dir) && !isempty(p->incoming_dir);
2052 unsigned long mount_propagation_flag = p->mount_propagation_flag != 0 ? p->mount_propagation_flag : MS_SHARED;
2053
2054 if (p->root_image) {
2055 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2056 if (root_read_only(p->read_only_paths,
2057 p->protect_system) &&
2058 home_read_only(p->read_only_paths, p->inaccessible_paths, p->empty_directories,
2059 p->bind_mounts, p->n_bind_mounts, p->temporary_filesystems, p->n_temporary_filesystems,
2060 p->protect_home) &&
2061 strv_isempty(p->read_write_paths))
2062 dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
2063
2064 SET_FLAG(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE, p->verity && p->verity->data_path);
2065
2066 r = loop_device_make_by_path(
2067 p->root_image,
2068 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : -1 /* < 0 means writable if possible, read-only as fallback */,
2069 /* sector_size= */ UINT32_MAX,
2070 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2071 LOCK_SH,
2072 &loop_device);
2073 if (r < 0)
2074 return log_debug_errno(r, "Failed to create loop device for root image: %m");
2075
2076 r = dissect_loop_device(
2077 loop_device,
2078 p->verity,
2079 p->root_image_options,
2080 p->root_image_policy,
2081 dissect_image_flags,
2082 &dissected_image);
2083 if (r < 0)
2084 return log_debug_errno(r, "Failed to dissect image: %m");
2085
2086 r = dissected_image_load_verity_sig_partition(
2087 dissected_image,
2088 loop_device->fd,
2089 p->verity);
2090 if (r < 0)
2091 return r;
2092
2093 r = dissected_image_decrypt(
2094 dissected_image,
2095 NULL,
2096 p->verity,
2097 dissect_image_flags);
2098 if (r < 0)
2099 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
2100 }
2101
2102 if (p->root_directory)
2103 root = p->root_directory;
2104 else {
2105 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2106 * when running tests (test-execute), it might not have been created yet so let's make sure
2107 * we create it if it doesn't already exist. */
2108 (void) mkdir_p_label("/run/systemd", 0755);
2109
2110 /* Always create the mount namespace in a temporary directory, instead of operating directly
2111 * in the root. The temporary directory prevents any mounts from being potentially obscured
2112 * my other mounts we already applied. We use the same mount point for all images, which is
2113 * safe, since they all live in their own namespaces after all, and hence won't see each
2114 * other. (Note: this directory is also created by PID 1 early on, we create it here for
2115 * similar reasons as /run/systemd/ first.) */
2116 root = "/run/systemd/mount-rootfs";
2117 (void) mkdir_label(root, 0555);
2118
2119 require_prefix = true;
2120 }
2121
2122 if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories)) {
2123 /* Hierarchy population needs to be done for sysext and confext extension images */
2124 r = parse_env_extension_hierarchies(&hierarchies, "SYSTEMD_SYSEXT_AND_CONFEXT_HIERARCHIES");
2125 if (r < 0)
2126 return r;
2127 }
2128
2129 r = append_access_mounts(&ml, p->read_write_paths, READWRITE, require_prefix);
2130 if (r < 0)
2131 return r;
2132
2133 r = append_access_mounts(&ml, p->read_only_paths, READONLY, require_prefix);
2134 if (r < 0)
2135 return r;
2136
2137 r = append_access_mounts(&ml, p->inaccessible_paths, INACCESSIBLE, require_prefix);
2138 if (r < 0)
2139 return r;
2140
2141 r = append_access_mounts(&ml, p->exec_paths, EXEC, require_prefix);
2142 if (r < 0)
2143 return r;
2144
2145 r = append_access_mounts(&ml, p->no_exec_paths, NOEXEC, require_prefix);
2146 if (r < 0)
2147 return r;
2148
2149 r = append_empty_dir_mounts(&ml, p->empty_directories);
2150 if (r < 0)
2151 return r;
2152
2153 r = append_bind_mounts(&ml, p->bind_mounts, p->n_bind_mounts);
2154 if (r < 0)
2155 return r;
2156
2157 r = append_tmpfs_mounts(&ml, p->temporary_filesystems, p->n_temporary_filesystems);
2158 if (r < 0)
2159 return r;
2160
2161 if (p->tmp_dir) {
2162 bool ro = streq(p->tmp_dir, RUN_SYSTEMD_EMPTY);
2163
2164 MountEntry *me = mount_list_extend(&ml);
2165 if (!me)
2166 return log_oom_debug();
2167
2168 *me = (MountEntry) {
2169 .path_const = "/tmp",
2170 .mode = ro ? PRIVATE_TMP_READONLY : PRIVATE_TMP,
2171 .source_const = p->tmp_dir,
2172 };
2173 }
2174
2175 if (p->var_tmp_dir) {
2176 bool ro = streq(p->var_tmp_dir, RUN_SYSTEMD_EMPTY);
2177
2178 MountEntry *me = mount_list_extend(&ml);
2179 if (!me)
2180 return log_oom_debug();
2181
2182 *me = (MountEntry) {
2183 .path_const = "/var/tmp",
2184 .mode = ro ? PRIVATE_TMP_READONLY : PRIVATE_TMP,
2185 .source_const = p->var_tmp_dir,
2186 };
2187 }
2188
2189 r = append_mount_images(&ml, p->mount_images, p->n_mount_images);
2190 if (r < 0)
2191 return r;
2192
2193 r = append_extensions(&ml, root, p->extension_dir, hierarchies, p->extension_images, p->n_extension_images, p->extension_directories);
2194 if (r < 0)
2195 return r;
2196
2197 if (p->private_dev) {
2198 MountEntry *me = mount_list_extend(&ml);
2199 if (!me)
2200 return log_oom_debug();
2201
2202 *me = (MountEntry) {
2203 .path_const = "/dev",
2204 .mode = PRIVATE_DEV,
2205 .flags = DEV_MOUNT_OPTIONS,
2206 };
2207 }
2208
2209 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the protective
2210 mounts to non-pid /proc paths would fail. But the pid only option may have failed gracefully, so
2211 let's try the mounts but it's not fatal if they don't succeed. */
2212 bool ignore_protect_proc = p->ignore_protect_paths || p->proc_subset == PROC_SUBSET_PID;
2213 if (p->protect_kernel_tunables) {
2214 r = append_static_mounts(&ml,
2215 protect_kernel_tunables_proc_table,
2216 ELEMENTSOF(protect_kernel_tunables_proc_table),
2217 ignore_protect_proc);
2218 if (r < 0)
2219 return r;
2220
2221 r = append_static_mounts(&ml,
2222 protect_kernel_tunables_sys_table,
2223 ELEMENTSOF(protect_kernel_tunables_sys_table),
2224 p->ignore_protect_paths);
2225 if (r < 0)
2226 return r;
2227 }
2228
2229 if (p->protect_kernel_modules) {
2230 r = append_static_mounts(&ml,
2231 protect_kernel_modules_table,
2232 ELEMENTSOF(protect_kernel_modules_table),
2233 p->ignore_protect_paths);
2234 if (r < 0)
2235 return r;
2236 }
2237
2238 if (p->protect_kernel_logs) {
2239 r = append_static_mounts(&ml,
2240 protect_kernel_logs_proc_table,
2241 ELEMENTSOF(protect_kernel_logs_proc_table),
2242 ignore_protect_proc);
2243 if (r < 0)
2244 return r;
2245
2246 r = append_static_mounts(&ml,
2247 protect_kernel_logs_dev_table,
2248 ELEMENTSOF(protect_kernel_logs_dev_table),
2249 p->ignore_protect_paths);
2250 if (r < 0)
2251 return r;
2252 }
2253
2254 if (p->protect_control_groups) {
2255 MountEntry *me = mount_list_extend(&ml);
2256 if (!me)
2257 return log_oom_debug();
2258
2259 *me = (MountEntry) {
2260 .path_const = "/sys/fs/cgroup",
2261 .mode = READONLY,
2262 };
2263 }
2264
2265 r = append_protect_home(&ml, p->protect_home, p->ignore_protect_paths);
2266 if (r < 0)
2267 return r;
2268
2269 r = append_protect_system(&ml, p->protect_system, false);
2270 if (r < 0)
2271 return r;
2272
2273 if (namespace_parameters_mount_apivfs(p)) {
2274 r = append_static_mounts(&ml,
2275 apivfs_table,
2276 ELEMENTSOF(apivfs_table),
2277 p->ignore_protect_paths);
2278 if (r < 0)
2279 return r;
2280 }
2281
2282 /* Note, if proc is mounted with subset=pid then neither of the two paths will exist, i.e. they are
2283 * implicitly protected by the mount option. */
2284 if (p->protect_hostname) {
2285 r = append_static_mounts(
2286 &ml,
2287 protect_hostname_table,
2288 ELEMENTSOF(protect_hostname_table),
2289 ignore_protect_proc);
2290 if (r < 0)
2291 return r;
2292 }
2293
2294 if (p->private_network) {
2295 MountEntry *me = mount_list_extend(&ml);
2296 if (!me)
2297 return log_oom_debug();
2298
2299 *me = (MountEntry) {
2300 .path_const = "/sys",
2301 .mode = PRIVATE_SYSFS,
2302 };
2303 }
2304
2305 if (p->private_ipc) {
2306 MountEntry *me = mount_list_extend(&ml);
2307 if (!me)
2308 return log_oom_debug();
2309
2310 *me = (MountEntry) {
2311 .path_const = "/dev/mqueue",
2312 .mode = MQUEUEFS,
2313 .flags = MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
2314 };
2315 }
2316
2317 if (p->creds_path) {
2318 /* If our service has a credentials store configured, then bind that one in, but hide
2319 * everything else. */
2320
2321 MountEntry *me = mount_list_extend(&ml);
2322 if (!me)
2323 return log_oom_debug();
2324
2325 *me = (MountEntry) {
2326 .path_const = "/run/credentials",
2327 .mode = TMPFS,
2328 .read_only = true,
2329 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
2330 .flags = MS_NODEV|MS_STRICTATIME|MS_NOSUID|MS_NOEXEC,
2331 };
2332
2333 me = mount_list_extend(&ml);
2334 if (!me)
2335 return log_oom_debug();
2336
2337 *me = (MountEntry) {
2338 .path_const = p->creds_path,
2339 .mode = BIND_MOUNT,
2340 .read_only = true,
2341 .source_const = p->creds_path,
2342 .ignore = true,
2343 };
2344 } else {
2345 /* If our service has no credentials store configured, then make the whole credentials tree
2346 * inaccessible wholesale. */
2347
2348 MountEntry *me = mount_list_extend(&ml);
2349 if (!me)
2350 return log_oom_debug();
2351
2352 *me = (MountEntry) {
2353 .path_const = "/run/credentials",
2354 .mode = INACCESSIBLE,
2355 .ignore = true,
2356 };
2357 }
2358
2359 if (p->log_namespace) {
2360 _cleanup_free_ char *q = NULL;
2361
2362 q = strjoin("/run/systemd/journal.", p->log_namespace);
2363 if (!q)
2364 return log_oom();
2365
2366 MountEntry *me = mount_list_extend(&ml);
2367 if (!me)
2368 return log_oom_debug();
2369
2370 *me = (MountEntry) {
2371 .path_const = "/run/systemd/journal",
2372 .mode = BIND_MOUNT_RECURSIVE,
2373 .read_only = true,
2374 .source_malloc = TAKE_PTR(q),
2375 };
2376 }
2377
2378 /* Will be used to add bind mounts at runtime */
2379 if (setup_propagate) {
2380 MountEntry *me = mount_list_extend(&ml);
2381 if (!me)
2382 return log_oom_debug();
2383
2384 *me = (MountEntry) {
2385 .source_const = p->propagate_dir,
2386 .path_const = p->incoming_dir,
2387 .mode = BIND_MOUNT,
2388 .read_only = true,
2389 };
2390 }
2391
2392 if (p->notify_socket) {
2393 MountEntry *me = mount_list_extend(&ml);
2394 if (!me)
2395 return log_oom_debug();
2396
2397 *me = (MountEntry) {
2398 .path_const = p->notify_socket,
2399 .source_const = p->notify_socket,
2400 .mode = BIND_MOUNT,
2401 .read_only = true,
2402 };
2403 }
2404
2405 if (p->host_os_release_stage) {
2406 MountEntry *me = mount_list_extend(&ml);
2407 if (!me)
2408 return log_oom_debug();
2409
2410 *me = (MountEntry) {
2411 .path_const = "/run/host/.os-release-stage/",
2412 .source_const = p->host_os_release_stage,
2413 .mode = BIND_MOUNT,
2414 .read_only = true,
2415 .ignore = true, /* Live copy, don't hard-fail if it goes missing */
2416 };
2417 }
2418
2419 /* Prepend the root directory where that's necessary */
2420 r = prefix_where_needed(&ml, root);
2421 if (r < 0)
2422 return r;
2423
2424 drop_unused_mounts(&ml, root);
2425
2426 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
2427
2428 if (unshare(CLONE_NEWNS) < 0) {
2429 r = log_debug_errno(errno, "Failed to unshare the mount namespace: %m");
2430
2431 if (ERRNO_IS_PRIVILEGE(r) ||
2432 ERRNO_IS_NOT_SUPPORTED(r))
2433 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
2434 * in place that doesn't allow us to create namespaces (or a missing cap), then
2435 * propagate a recognizable error back, which the caller can use to detect this case
2436 * (and only this) and optionally continue without namespacing applied. */
2437 return -ENOANO;
2438
2439 return r;
2440 }
2441
2442 /* Create the source directory to allow runtime propagation of mounts */
2443 if (setup_propagate)
2444 (void) mkdir_p(p->propagate_dir, 0600);
2445
2446 if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories))
2447 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
2448 * mounts to create, so have the parent ready */
2449 (void) mkdir_p(p->extension_dir, 0600);
2450
2451 /* Remount / as SLAVE so that nothing now mounted in the namespace
2452 * shows up in the parent */
2453 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0)
2454 return log_debug_errno(errno, "Failed to remount '/' as SLAVE: %m");
2455
2456 if (p->root_image) {
2457 /* A root image is specified, mount it to the right place */
2458 r = dissected_image_mount(
2459 dissected_image,
2460 root,
2461 /* uid_shift= */ UID_INVALID,
2462 /* uid_range= */ UID_INVALID,
2463 /* userns_fd= */ -EBADF,
2464 dissect_image_flags);
2465 if (r < 0)
2466 return log_debug_errno(r, "Failed to mount root image: %m");
2467
2468 /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
2469 * if it likes. */
2470 r = loop_device_flock(loop_device, LOCK_UN);
2471 if (r < 0)
2472 return log_debug_errno(r, "Failed to release lock on loopback block device: %m");
2473
2474 r = dissected_image_relinquish(dissected_image);
2475 if (r < 0)
2476 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
2477
2478 } else if (p->root_directory) {
2479
2480 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
2481 r = path_is_mount_point(root, NULL, AT_SYMLINK_FOLLOW);
2482 if (r < 0)
2483 return log_debug_errno(r, "Failed to detect that %s is a mount point or not: %m", root);
2484 if (r == 0) {
2485 r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
2486 if (r < 0)
2487 return r;
2488 }
2489
2490 } else {
2491 /* Let's mount the main root directory to the root directory to use */
2492 r = mount_nofollow_verbose(LOG_DEBUG, "/", root, NULL, MS_BIND|MS_REC, NULL);
2493 if (r < 0)
2494 return r;
2495 }
2496
2497 /* Try to set up the new root directory before mounting anything else there. */
2498 if (p->root_image || p->root_directory)
2499 (void) base_filesystem_create(root, UID_INVALID, GID_INVALID);
2500
2501 /* Now make the magic happen */
2502 r = apply_mounts(&ml, root, p, error_path);
2503 if (r < 0)
2504 return r;
2505
2506 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
2507 r = mount_switch_root(root, /* mount_propagation_flag = */ 0);
2508 if (r == -EINVAL && p->root_directory) {
2509 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
2510 * namespace) and the root_directory is already a mount point in the parent namespace,
2511 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
2512 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
2513 * mount point) and try again. */
2514 r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
2515 if (r < 0)
2516 return r;
2517 r = mount_switch_root(root, /* mount_propagation_flag = */ 0);
2518 }
2519 if (r < 0)
2520 return log_debug_errno(r, "Failed to mount root with MS_MOVE: %m");
2521
2522 /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
2523 * the host, since what's disconnected is disconnected. */
2524 if (mount(NULL, "/", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
2525 return log_debug_errno(errno, "Failed to remount '/' with desired mount flags: %m");
2526
2527 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only
2528 * supported for non-shared mounts. This needs to happen after remounting / or it will fail. */
2529 if (setup_propagate) {
2530 if (mount(NULL, p->incoming_dir, NULL, MS_SLAVE, NULL) < 0)
2531 return log_debug_errno(errno, "Failed to remount %s with MS_SLAVE: %m", p->incoming_dir);
2532 }
2533
2534 return 0;
2535 }
2536
2537 void bind_mount_free_many(BindMount *b, size_t n) {
2538 assert(b || n == 0);
2539
2540 for (size_t i = 0; i < n; i++) {
2541 free(b[i].source);
2542 free(b[i].destination);
2543 }
2544
2545 free(b);
2546 }
2547
2548 int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
2549 _cleanup_free_ char *s = NULL, *d = NULL;
2550 BindMount *c;
2551
2552 assert(b);
2553 assert(n);
2554 assert(item);
2555
2556 s = strdup(item->source);
2557 if (!s)
2558 return -ENOMEM;
2559
2560 d = strdup(item->destination);
2561 if (!d)
2562 return -ENOMEM;
2563
2564 c = reallocarray(*b, *n + 1, sizeof(BindMount));
2565 if (!c)
2566 return -ENOMEM;
2567
2568 *b = c;
2569
2570 c[(*n) ++] = (BindMount) {
2571 .source = TAKE_PTR(s),
2572 .destination = TAKE_PTR(d),
2573 .read_only = item->read_only,
2574 .nosuid = item->nosuid,
2575 .recursive = item->recursive,
2576 .ignore_enoent = item->ignore_enoent,
2577 };
2578
2579 return 0;
2580 }
2581
2582 MountImage* mount_image_free_many(MountImage *m, size_t *n) {
2583 assert(n);
2584 assert(m || *n == 0);
2585
2586 for (size_t i = 0; i < *n; i++) {
2587 free(m[i].source);
2588 free(m[i].destination);
2589 mount_options_free_all(m[i].mount_options);
2590 }
2591
2592 free(m);
2593 *n = 0;
2594 return NULL;
2595 }
2596
2597 int mount_image_add(MountImage **m, size_t *n, const MountImage *item) {
2598 _cleanup_free_ char *s = NULL, *d = NULL;
2599 _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
2600 MountImage *c;
2601
2602 assert(m);
2603 assert(n);
2604 assert(item);
2605
2606 s = strdup(item->source);
2607 if (!s)
2608 return -ENOMEM;
2609
2610 if (item->destination) {
2611 d = strdup(item->destination);
2612 if (!d)
2613 return -ENOMEM;
2614 }
2615
2616 LIST_FOREACH(mount_options, i, item->mount_options) {
2617 _cleanup_(mount_options_free_allp) MountOptions *o = NULL;
2618
2619 o = new(MountOptions, 1);
2620 if (!o)
2621 return -ENOMEM;
2622
2623 *o = (MountOptions) {
2624 .partition_designator = i->partition_designator,
2625 .options = strdup(i->options),
2626 };
2627 if (!o->options)
2628 return -ENOMEM;
2629
2630 LIST_APPEND(mount_options, options, TAKE_PTR(o));
2631 }
2632
2633 c = reallocarray(*m, *n + 1, sizeof(MountImage));
2634 if (!c)
2635 return -ENOMEM;
2636
2637 *m = c;
2638
2639 c[(*n) ++] = (MountImage) {
2640 .source = TAKE_PTR(s),
2641 .destination = TAKE_PTR(d),
2642 .mount_options = TAKE_PTR(options),
2643 .ignore_enoent = item->ignore_enoent,
2644 .type = item->type,
2645 };
2646
2647 return 0;
2648 }
2649
2650 void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
2651 assert(t || n == 0);
2652
2653 for (size_t i = 0; i < n; i++) {
2654 free(t[i].path);
2655 free(t[i].options);
2656 }
2657
2658 free(t);
2659 }
2660
2661 int temporary_filesystem_add(
2662 TemporaryFileSystem **t,
2663 size_t *n,
2664 const char *path,
2665 const char *options) {
2666
2667 _cleanup_free_ char *p = NULL, *o = NULL;
2668 TemporaryFileSystem *c;
2669
2670 assert(t);
2671 assert(n);
2672 assert(path);
2673
2674 p = strdup(path);
2675 if (!p)
2676 return -ENOMEM;
2677
2678 if (!isempty(options)) {
2679 o = strdup(options);
2680 if (!o)
2681 return -ENOMEM;
2682 }
2683
2684 c = reallocarray(*t, *n + 1, sizeof(TemporaryFileSystem));
2685 if (!c)
2686 return -ENOMEM;
2687
2688 *t = c;
2689
2690 c[(*n) ++] = (TemporaryFileSystem) {
2691 .path = TAKE_PTR(p),
2692 .options = TAKE_PTR(o),
2693 };
2694
2695 return 0;
2696 }
2697
2698 static int make_tmp_prefix(const char *prefix) {
2699 _cleanup_free_ char *t = NULL;
2700 _cleanup_close_ int fd = -EBADF;
2701 int r;
2702
2703 /* Don't do anything unless we know the dir is actually missing */
2704 r = access(prefix, F_OK);
2705 if (r >= 0)
2706 return 0;
2707 if (errno != ENOENT)
2708 return -errno;
2709
2710 WITH_UMASK(000)
2711 r = mkdir_parents(prefix, 0755);
2712 if (r < 0)
2713 return r;
2714
2715 r = tempfn_random(prefix, NULL, &t);
2716 if (r < 0)
2717 return r;
2718
2719 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2720 * the suid bit, below. */
2721 fd = open_mkdir_at(AT_FDCWD, t, O_EXCL|O_CLOEXEC, 0777);
2722 if (fd < 0)
2723 return fd;
2724
2725 r = RET_NERRNO(fchmod(fd, 01777));
2726 if (r < 0) {
2727 (void) rmdir(t);
2728 return r;
2729 }
2730
2731 r = RET_NERRNO(rename(t, prefix));
2732 if (r < 0) {
2733 (void) rmdir(t);
2734 return r == -EEXIST ? 0 : r; /* it's fine if someone else created the dir by now */
2735 }
2736
2737 return 0;
2738
2739 }
2740
2741 static int setup_one_tmp_dir(const char *id, const char *prefix, char **path, char **tmp_path) {
2742 _cleanup_free_ char *x = NULL;
2743 _cleanup_free_ char *y = NULL;
2744 sd_id128_t boot_id;
2745 bool rw = true;
2746 int r;
2747
2748 assert(id);
2749 assert(prefix);
2750 assert(path);
2751
2752 /* We include the boot id in the directory so that after a
2753 * reboot we can easily identify obsolete directories. */
2754
2755 r = sd_id128_get_boot(&boot_id);
2756 if (r < 0)
2757 return r;
2758
2759 x = strjoin(prefix, "/systemd-private-", SD_ID128_TO_STRING(boot_id), "-", id, "-XXXXXX");
2760 if (!x)
2761 return -ENOMEM;
2762
2763 r = make_tmp_prefix(prefix);
2764 if (r < 0)
2765 return r;
2766
2767 WITH_UMASK(0077)
2768 if (!mkdtemp(x)) {
2769 if (errno == EROFS || ERRNO_IS_DISK_SPACE(errno))
2770 rw = false;
2771 else
2772 return -errno;
2773 }
2774
2775 if (rw) {
2776 y = strjoin(x, "/tmp");
2777 if (!y)
2778 return -ENOMEM;
2779
2780 WITH_UMASK(0000)
2781 if (mkdir(y, 0777 | S_ISVTX) < 0)
2782 return -errno;
2783
2784 r = label_fix_full(AT_FDCWD, y, prefix, 0);
2785 if (r < 0)
2786 return r;
2787
2788 if (tmp_path)
2789 *tmp_path = TAKE_PTR(y);
2790 } else {
2791 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2792 * read-only. This way the service will get the EROFS result as if it was writing to the real
2793 * file system. */
2794 WITH_UMASK(0000)
2795 r = mkdir_p(RUN_SYSTEMD_EMPTY, 0500);
2796 if (r < 0)
2797 return r;
2798
2799 r = free_and_strdup(&x, RUN_SYSTEMD_EMPTY);
2800 if (r < 0)
2801 return r;
2802 }
2803
2804 *path = TAKE_PTR(x);
2805 return 0;
2806 }
2807
2808 int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
2809 _cleanup_(namespace_cleanup_tmpdirp) char *a = NULL;
2810 _cleanup_(rmdir_and_freep) char *a_tmp = NULL;
2811 char *b;
2812 int r;
2813
2814 assert(id);
2815 assert(tmp_dir);
2816 assert(var_tmp_dir);
2817
2818 r = setup_one_tmp_dir(id, "/tmp", &a, &a_tmp);
2819 if (r < 0)
2820 return r;
2821
2822 r = setup_one_tmp_dir(id, "/var/tmp", &b, NULL);
2823 if (r < 0)
2824 return r;
2825
2826 a_tmp = mfree(a_tmp); /* avoid rmdir */
2827 *tmp_dir = TAKE_PTR(a);
2828 *var_tmp_dir = TAKE_PTR(b);
2829
2830 return 0;
2831 }
2832
2833 int setup_shareable_ns(int ns_storage_socket[static 2], unsigned long nsflag) {
2834 _cleanup_close_ int ns = -EBADF;
2835 int r;
2836 const char *ns_name, *ns_path;
2837
2838 assert(ns_storage_socket);
2839 assert(ns_storage_socket[0] >= 0);
2840 assert(ns_storage_socket[1] >= 0);
2841
2842 ns_name = namespace_single_flag_to_string(nsflag);
2843 assert(ns_name);
2844
2845 /* We use the passed socketpair as a storage buffer for our
2846 * namespace reference fd. Whatever process runs this first
2847 * shall create a new namespace, all others should just join
2848 * it. To serialize that we use a file lock on the socket
2849 * pair.
2850 *
2851 * It's a bit crazy, but hey, works great! */
2852
2853 r = posix_lock(ns_storage_socket[0], LOCK_EX);
2854 if (r < 0)
2855 return r;
2856
2857 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
2858
2859 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2860 if (ns >= 0) {
2861 /* Yay, found something, so let's join the namespace */
2862 r = RET_NERRNO(setns(ns, nsflag));
2863 if (r < 0)
2864 return r;
2865
2866 return 0;
2867 }
2868
2869 if (ns != -EAGAIN)
2870 return ns;
2871
2872 /* Nothing stored yet, so let's create a new namespace. */
2873
2874 if (unshare(nsflag) < 0)
2875 return -errno;
2876
2877 (void) loopback_setup();
2878
2879 ns_path = strjoina("/proc/self/ns/", ns_name);
2880 ns = open(ns_path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2881 if (ns < 0)
2882 return -errno;
2883
2884 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
2885 if (r < 0)
2886 return r;
2887
2888 return 1;
2889 }
2890
2891 int open_shareable_ns_path(int ns_storage_socket[static 2], const char *path, unsigned long nsflag) {
2892 _cleanup_close_ int ns = -EBADF;
2893 int r;
2894
2895 assert(ns_storage_socket);
2896 assert(ns_storage_socket[0] >= 0);
2897 assert(ns_storage_socket[1] >= 0);
2898 assert(path);
2899
2900 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2901 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2902 * allocate a new anonymous ns if needed. */
2903
2904 r = posix_lock(ns_storage_socket[0], LOCK_EX);
2905 if (r < 0)
2906 return r;
2907
2908 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
2909
2910 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2911 if (ns >= 0)
2912 return 0;
2913 if (ns != -EAGAIN)
2914 return ns;
2915
2916 /* Nothing stored yet. Open the file from the file system. */
2917
2918 ns = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
2919 if (ns < 0)
2920 return -errno;
2921
2922 r = fd_is_ns(ns, nsflag);
2923 if (r == 0)
2924 return -EINVAL;
2925 if (r < 0 && r != -EUCLEAN) /* EUCLEAN: we don't know */
2926 return r;
2927
2928 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
2929 if (r < 0)
2930 return r;
2931
2932 return 1;
2933 }
2934
2935 bool ns_type_supported(NamespaceType type) {
2936 const char *t, *ns_proc;
2937
2938 t = namespace_type_to_string(type);
2939 if (!t) /* Don't know how to translate this? Then it's not supported */
2940 return false;
2941
2942 ns_proc = strjoina("/proc/self/ns/", t);
2943 return access(ns_proc, F_OK) == 0;
2944 }
2945
2946 static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
2947 [PROTECT_HOME_NO] = "no",
2948 [PROTECT_HOME_YES] = "yes",
2949 [PROTECT_HOME_READ_ONLY] = "read-only",
2950 [PROTECT_HOME_TMPFS] = "tmpfs",
2951 };
2952
2953 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home, ProtectHome, PROTECT_HOME_YES);
2954
2955 static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
2956 [PROTECT_SYSTEM_NO] = "no",
2957 [PROTECT_SYSTEM_YES] = "yes",
2958 [PROTECT_SYSTEM_FULL] = "full",
2959 [PROTECT_SYSTEM_STRICT] = "strict",
2960 };
2961
2962 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system, ProtectSystem, PROTECT_SYSTEM_YES);
2963
2964 static const char* const namespace_type_table[] = {
2965 [NAMESPACE_MOUNT] = "mnt",
2966 [NAMESPACE_CGROUP] = "cgroup",
2967 [NAMESPACE_UTS] = "uts",
2968 [NAMESPACE_IPC] = "ipc",
2969 [NAMESPACE_USER] = "user",
2970 [NAMESPACE_PID] = "pid",
2971 [NAMESPACE_NET] = "net",
2972 [NAMESPACE_TIME] = "time",
2973 };
2974
2975 DEFINE_STRING_TABLE_LOOKUP(namespace_type, NamespaceType);
2976
2977 static const char* const protect_proc_table[_PROTECT_PROC_MAX] = {
2978 [PROTECT_PROC_DEFAULT] = "default",
2979 [PROTECT_PROC_NOACCESS] = "noaccess",
2980 [PROTECT_PROC_INVISIBLE] = "invisible",
2981 [PROTECT_PROC_PTRACEABLE] = "ptraceable",
2982 };
2983
2984 DEFINE_STRING_TABLE_LOOKUP(protect_proc, ProtectProc);
2985
2986 static const char* const proc_subset_table[_PROC_SUBSET_MAX] = {
2987 [PROC_SUBSET_ALL] = "all",
2988 [PROC_SUBSET_PID] = "pid",
2989 };
2990
2991 DEFINE_STRING_TABLE_LOOKUP(proc_subset, ProcSubset);