]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/namespace.c
core/namespace: merge if blocks
[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_const);
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 }
331
332 static void mount_list_done(MountList *ml) {
333 assert(ml);
334
335 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts)
336 mount_entry_done(m);
337
338 ml->mounts = mfree(ml->mounts);
339 ml->n_mounts = 0;
340 }
341
342 static MountEntry *mount_list_extend(MountList *ml) {
343 assert(ml);
344
345 if (!GREEDY_REALLOC0(ml->mounts, ml->n_mounts+1))
346 return NULL;
347
348 return ml->mounts + ml->n_mounts++;
349 }
350
351 static int append_access_mounts(MountList *ml, char **strv, MountMode mode, bool forcibly_require_prefix) {
352 assert(ml);
353
354 /* Adds a list of user-supplied READWRITE/READWRITE_IMPLICIT/READONLY/INACCESSIBLE entries */
355
356 STRV_FOREACH(i, strv) {
357 bool ignore = false, needs_prefix = false;
358 const char *e = *i;
359
360 /* Look for any prefixes */
361 if (startswith(e, "-")) {
362 e++;
363 ignore = true;
364 }
365 if (startswith(e, "+")) {
366 e++;
367 needs_prefix = true;
368 }
369
370 if (!path_is_absolute(e))
371 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", e);
372
373 MountEntry *me = mount_list_extend(ml);
374 if (!me)
375 return log_oom_debug();
376
377 *me = (MountEntry) {
378 .path_const = e,
379 .mode = mode,
380 .ignore = ignore,
381 .has_prefix = !needs_prefix && !forcibly_require_prefix,
382 };
383 }
384
385 return 0;
386 }
387
388 static int append_empty_dir_mounts(MountList *ml, char **strv) {
389 assert(ml);
390
391 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
392 * "/private/" boundary directories for DynamicUser=1. */
393
394 STRV_FOREACH(i, strv) {
395 MountEntry *me = mount_list_extend(ml);
396 if (!me)
397 return log_oom_debug();
398
399 *me = (MountEntry) {
400 .path_const = *i,
401 .mode = EMPTY_DIR,
402 .ignore = false,
403 .read_only = true,
404 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
405 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
406 };
407 }
408
409 return 0;
410 }
411
412 static int append_bind_mounts(MountList *ml, const BindMount *binds, size_t n) {
413 assert(ml);
414 assert(binds || n == 0);
415
416 FOREACH_ARRAY(b, binds, n) {
417 MountEntry *me = mount_list_extend(ml);
418 if (!me)
419 return log_oom_debug();
420
421 *me = (MountEntry) {
422 .path_const = b->destination,
423 .mode = b->recursive ? BIND_MOUNT_RECURSIVE : BIND_MOUNT,
424 .read_only = b->read_only,
425 .nosuid = b->nosuid,
426 .source_const = b->source,
427 .ignore = b->ignore_enoent,
428 };
429 }
430
431 return 0;
432 }
433
434 static int append_mount_images(MountList *ml, const MountImage *mount_images, size_t n) {
435 assert(ml);
436 assert(mount_images || n == 0);
437
438 FOREACH_ARRAY(m, mount_images, n) {
439 MountEntry *me = mount_list_extend(ml);
440 if (!me)
441 return log_oom_debug();
442
443 *me = (MountEntry) {
444 .path_const = m->destination,
445 .mode = MOUNT_IMAGES,
446 .source_const = m->source,
447 .image_options_const = m->mount_options,
448 .ignore = m->ignore_enoent,
449 };
450 }
451
452 return 0;
453 }
454
455 static int append_extensions(
456 MountList *ml,
457 const char *root,
458 const char *extension_dir,
459 char **hierarchies,
460 const MountImage *mount_images,
461 size_t n,
462 char **extension_directories) {
463
464 _cleanup_strv_free_ char **overlays = NULL;
465 int r;
466
467 assert(ml);
468
469 if (n == 0 && strv_isempty(extension_directories))
470 return 0;
471
472 assert(extension_dir);
473
474 /* Prepare a list of overlays, that will have as each element a string suitable for being
475 * passed as a lowerdir= parameter, so start with the hierarchy on the root.
476 * The overlays vector will have the same number of elements and will correspond to the
477 * hierarchies vector, so they can be iterated upon together. */
478 STRV_FOREACH(hierarchy, hierarchies) {
479 _cleanup_free_ char *prefixed_hierarchy = NULL;
480
481 prefixed_hierarchy = path_join(root, *hierarchy);
482 if (!prefixed_hierarchy)
483 return -ENOMEM;
484
485 r = strv_consume(&overlays, TAKE_PTR(prefixed_hierarchy));
486 if (r < 0)
487 return r;
488 }
489
490 /* First, prepare a mount for each image, but these won't be visible to the unit, instead
491 * they will be mounted in our propagate directory, and used as a source for the overlay. */
492 for (size_t i = 0; i < n; i++) {
493 _cleanup_free_ char *mount_point = NULL;
494 const MountImage *m = mount_images + i;
495
496 if (asprintf(&mount_point, "%s/%zu", extension_dir, i) < 0)
497 return -ENOMEM;
498
499 for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
500 _cleanup_free_ char *prefixed_hierarchy = NULL, *escaped = NULL, *lowerdir = NULL;
501
502 prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
503 if (!prefixed_hierarchy)
504 return -ENOMEM;
505
506 escaped = shell_escape(prefixed_hierarchy, ",:");
507 if (!escaped)
508 return -ENOMEM;
509
510 /* Note that lowerdir= parameters are in 'reverse' order, so the
511 * top-most directory in the overlay comes first in the list. */
512 lowerdir = strjoin(escaped, ":", overlays[j]);
513 if (!lowerdir)
514 return -ENOMEM;
515
516 free_and_replace(overlays[j], lowerdir);
517 }
518
519 MountEntry *me = mount_list_extend(ml);
520 if (!me)
521 return log_oom_debug();
522
523 *me = (MountEntry) {
524 .path_malloc = TAKE_PTR(mount_point),
525 .image_options_const = m->mount_options,
526 .ignore = m->ignore_enoent,
527 .source_const = m->source,
528 .mode = EXTENSION_IMAGES,
529 .has_prefix = true,
530 };
531 }
532
533 /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
534 * Bind mount them in the same location as the ExtensionImages, so that we
535 * can check that they are valid trees (extension-release.d). */
536 STRV_FOREACH(extension_directory, extension_directories) {
537 _cleanup_free_ char *mount_point = NULL, *source = NULL;
538 const char *e = *extension_directory;
539 bool ignore_enoent = false;
540
541 /* Pick up the counter where the ExtensionImages left it. */
542 if (asprintf(&mount_point, "%s/%zu", extension_dir, n++) < 0)
543 return -ENOMEM;
544
545 /* Look for any prefixes */
546 if (startswith(e, "-")) {
547 e++;
548 ignore_enoent = true;
549 }
550 /* Ignore this for now */
551 if (startswith(e, "+"))
552 e++;
553
554 source = strdup(e);
555 if (!source)
556 return -ENOMEM;
557
558 for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
559 _cleanup_free_ char *prefixed_hierarchy = NULL, *escaped = NULL, *lowerdir = NULL;
560
561 prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
562 if (!prefixed_hierarchy)
563 return -ENOMEM;
564
565 escaped = shell_escape(prefixed_hierarchy, ",:");
566 if (!escaped)
567 return -ENOMEM;
568
569 /* Note that lowerdir= parameters are in 'reverse' order, so the
570 * top-most directory in the overlay comes first in the list. */
571 lowerdir = strjoin(escaped, ":", overlays[j]);
572 if (!lowerdir)
573 return -ENOMEM;
574
575 free_and_replace(overlays[j], lowerdir);
576 }
577
578 MountEntry *me = mount_list_extend(ml);
579 if (!me)
580 return log_oom_debug();
581
582 *me = (MountEntry) {
583 .path_malloc = TAKE_PTR(mount_point),
584 .source_malloc = TAKE_PTR(source),
585 .mode = EXTENSION_DIRECTORIES,
586 .ignore = ignore_enoent,
587 .has_prefix = true,
588 .read_only = true,
589 };
590 }
591
592 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
593 * set up earlier. */
594 for (size_t i = 0; hierarchies && hierarchies[i]; ++i) {
595 _cleanup_free_ char *prefixed_hierarchy = NULL;
596
597 prefixed_hierarchy = path_join(root, hierarchies[i]);
598 if (!prefixed_hierarchy)
599 return -ENOMEM;
600
601 MountEntry *me = mount_list_extend(ml);
602 if (!me)
603 return log_oom_debug();
604
605 *me = (MountEntry) {
606 .path_malloc = TAKE_PTR(prefixed_hierarchy),
607 .options_malloc = TAKE_PTR(overlays[i]),
608 .mode = OVERLAY_MOUNT,
609 .has_prefix = true,
610 .ignore = true, /* If the source image doesn't set the ignore bit it will fail earlier. */
611 };
612 }
613
614 return 0;
615 }
616
617 static int append_tmpfs_mounts(MountList *ml, const TemporaryFileSystem *tmpfs, size_t n) {
618 assert(ml);
619 assert(tmpfs || n == 0);
620
621 FOREACH_ARRAY(t, tmpfs, n) {
622 _cleanup_free_ char *o = NULL, *str = NULL;
623 unsigned long flags;
624 bool ro = false;
625 int r;
626
627 if (!path_is_absolute(t->path))
628 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", t->path);
629
630 str = strjoin("mode=0755" NESTED_TMPFS_LIMITS ",", t->options);
631 if (!str)
632 return -ENOMEM;
633
634 r = mount_option_mangle(str, MS_NODEV|MS_STRICTATIME, &flags, &o);
635 if (r < 0)
636 return log_debug_errno(r, "Failed to parse mount option '%s': %m", str);
637
638 ro = flags & MS_RDONLY;
639 if (ro)
640 flags ^= MS_RDONLY;
641
642 MountEntry *me = mount_list_extend(ml);
643 if (!me)
644 return log_oom_debug();
645
646 *me = (MountEntry) {
647 .path_const = t->path,
648 .mode = TMPFS,
649 .read_only = ro,
650 .options_malloc = TAKE_PTR(o),
651 .flags = flags,
652 };
653 }
654
655 return 0;
656 }
657
658 static int append_static_mounts(MountList *ml, const MountEntry *mounts, size_t n, bool ignore_protect) {
659 assert(ml);
660 assert(mounts || n == 0);
661
662 /* Adds a list of static pre-defined entries */
663
664 FOREACH_ARRAY(m, mounts, n) {
665 MountEntry *me = mount_list_extend(ml);
666 if (!me)
667 return log_oom_debug();
668
669 *me = (MountEntry) {
670 .path_const = mount_entry_path(m),
671 .mode = m->mode,
672 .ignore = m->ignore || ignore_protect,
673 };
674 }
675
676 return 0;
677 }
678
679 static int append_protect_home(MountList *ml, ProtectHome protect_home, bool ignore_protect) {
680 assert(ml);
681
682 switch (protect_home) {
683
684 case PROTECT_HOME_NO:
685 return 0;
686
687 case PROTECT_HOME_READ_ONLY:
688 return append_static_mounts(ml, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
689
690 case PROTECT_HOME_TMPFS:
691 return append_static_mounts(ml, protect_home_tmpfs_table, ELEMENTSOF(protect_home_tmpfs_table), ignore_protect);
692
693 case PROTECT_HOME_YES:
694 return append_static_mounts(ml, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
695
696 default:
697 assert_not_reached();
698 }
699 }
700
701 static int append_protect_system(MountList *ml, ProtectSystem protect_system, bool ignore_protect) {
702 assert(ml);
703
704 switch (protect_system) {
705
706 case PROTECT_SYSTEM_NO:
707 return 0;
708
709 case PROTECT_SYSTEM_STRICT:
710 return append_static_mounts(ml, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
711
712 case PROTECT_SYSTEM_YES:
713 return append_static_mounts(ml, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
714
715 case PROTECT_SYSTEM_FULL:
716 return append_static_mounts(ml, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
717
718 default:
719 assert_not_reached();
720 }
721 }
722
723 static int mount_path_compare(const MountEntry *a, const MountEntry *b) {
724 int d;
725
726 /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
727 * regardless of the prefix - they are set up in the propagate directory anyway */
728 d = -CMP(a->mode == EXTENSION_IMAGES, b->mode == EXTENSION_IMAGES);
729 if (d != 0)
730 return d;
731 d = -CMP(a->mode == EXTENSION_DIRECTORIES, b->mode == EXTENSION_DIRECTORIES);
732 if (d != 0)
733 return d;
734
735 /* If the paths are not equal, then order prefixes first */
736 d = path_compare(mount_entry_path(a), mount_entry_path(b));
737 if (d != 0)
738 return d;
739
740 /* If the paths are equal, check the mode */
741 return CMP((int) a->mode, (int) b->mode);
742 }
743
744 static int prefix_where_needed(MountList *ml, const char *root_directory) {
745 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
746
747 assert(ml);
748
749 FOREACH_ARRAY(me, ml->mounts, ml->n_mounts) {
750 char *s;
751
752 if (me->has_prefix)
753 continue;
754
755 s = path_join(root_directory, mount_entry_path(me));
756 if (!s)
757 return -ENOMEM;
758
759 mount_entry_consume_prefix(me, s);
760 }
761
762 return 0;
763 }
764
765 static void drop_duplicates(MountList *ml) {
766 MountEntry *f, *t, *previous;
767
768 assert(ml);
769
770 /* Drops duplicate entries. Expects that the array is properly ordered already. */
771
772 for (f = ml->mounts, t = ml->mounts, previous = NULL; f < ml->mounts + ml->n_mounts; f++) {
773
774 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
775 * above. Note that we only drop duplicates that haven't been mounted yet. */
776 if (previous &&
777 path_equal(mount_entry_path(f), mount_entry_path(previous)) &&
778 !f->applied && !previous->applied) {
779 log_debug("%s (%s) is duplicate.", mount_entry_path(f), mount_mode_to_string(f->mode));
780 /* Propagate the flags to the remaining entry */
781 previous->read_only = previous->read_only || mount_entry_read_only(f);
782 previous->noexec = previous->noexec || mount_entry_noexec(f);
783 previous->exec = previous->exec || mount_entry_exec(f);
784 mount_entry_done(f);
785 continue;
786 }
787
788 *t = *f;
789 previous = t;
790 t++;
791 }
792
793 ml->n_mounts = t - ml->mounts;
794 }
795
796 static void drop_inaccessible(MountList *ml) {
797 MountEntry *f, *t;
798 const char *clear = NULL;
799
800 assert(ml);
801
802 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
803 * ordered already. */
804
805 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
806
807 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
808 * it, as inaccessible paths really should drop the entire subtree. */
809 if (clear && path_startswith(mount_entry_path(f), clear)) {
810 log_debug("%s is masked by %s.", mount_entry_path(f), clear);
811 mount_entry_done(f);
812 continue;
813 }
814
815 clear = f->mode == INACCESSIBLE ? mount_entry_path(f) : NULL;
816
817 *t = *f;
818 t++;
819 }
820
821 ml->n_mounts = t - ml->mounts;
822 }
823
824 static void drop_nop(MountList *ml) {
825 MountEntry *f, *t;
826
827 assert(ml);
828
829 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
830 * list is ordered by prefixes. */
831
832 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
833
834 /* Only suppress such subtrees for READONLY, READWRITE and READWRITE_IMPLICIT entries */
835 if (IN_SET(f->mode, READONLY, READWRITE, READWRITE_IMPLICIT)) {
836 MountEntry *found = NULL;
837
838 /* Now let's find the first parent of the entry we are looking at. */
839 for (MountEntry *p = PTR_SUB1(t, ml->mounts); p; p = PTR_SUB1(p, ml->mounts))
840 if (path_startswith(mount_entry_path(f), mount_entry_path(p))) {
841 found = p;
842 break;
843 }
844
845 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
846 if (found && found->mode == f->mode) {
847 log_debug("%s (%s) is made redundant by %s (%s)",
848 mount_entry_path(f), mount_mode_to_string(f->mode),
849 mount_entry_path(found), mount_mode_to_string(found->mode));
850 mount_entry_done(f);
851 continue;
852 }
853 }
854
855 *t = *f;
856 t++;
857 }
858
859 ml->n_mounts = t - ml->mounts;
860 }
861
862 static void drop_outside_root(MountList *ml, const char *root_directory) {
863 MountEntry *f, *t;
864
865 assert(ml);
866
867 /* Nothing to do */
868 if (!root_directory)
869 return;
870
871 /* Drops all mounts that are outside of the root directory. */
872
873 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
874
875 /* ExtensionImages/Directories bases are opened in /run/systemd/unit-extensions on the host */
876 if (!IN_SET(f->mode, EXTENSION_IMAGES, EXTENSION_DIRECTORIES) && !path_startswith(mount_entry_path(f), root_directory)) {
877 log_debug("%s is outside of root directory.", mount_entry_path(f));
878 mount_entry_done(f);
879 continue;
880 }
881
882 *t = *f;
883 t++;
884 }
885
886 ml->n_mounts = t - ml->mounts;
887 }
888
889 static int clone_device_node(
890 const char *d,
891 const char *temporary_mount,
892 bool *make_devnode) {
893
894 _cleanup_free_ char *sl = NULL;
895 const char *dn, *bn, *t;
896 struct stat st;
897 int r;
898
899 if (stat(d, &st) < 0) {
900 if (errno == ENOENT) {
901 log_debug_errno(errno, "Device node '%s' to clone does not exist, ignoring.", d);
902 return -ENXIO;
903 }
904
905 return log_debug_errno(errno, "Failed to stat() device node '%s' to clone, ignoring: %m", d);
906 }
907
908 if (!S_ISBLK(st.st_mode) &&
909 !S_ISCHR(st.st_mode))
910 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
911 "Device node '%s' to clone is not a device node, ignoring.",
912 d);
913
914 dn = strjoina(temporary_mount, d);
915
916 /* First, try to create device node properly */
917 if (*make_devnode) {
918 mac_selinux_create_file_prepare(d, st.st_mode);
919 r = mknod(dn, st.st_mode, st.st_rdev);
920 mac_selinux_create_file_clear();
921 if (r >= 0)
922 goto add_symlink;
923 if (errno != EPERM)
924 return log_debug_errno(errno, "mknod failed for %s: %m", d);
925
926 /* This didn't work, let's not try this again for the next iterations. */
927 *make_devnode = false;
928 }
929
930 /* We're about to fall back to bind-mounting the device node. So create a dummy bind-mount target.
931 * Do not prepare device-node SELinux label (see issue 13762) */
932 r = mknod(dn, S_IFREG, 0);
933 if (r < 0 && errno != EEXIST)
934 return log_debug_errno(errno, "mknod() fallback failed for '%s': %m", d);
935
936 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
937 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
938 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
939 r = mount_nofollow_verbose(LOG_DEBUG, d, dn, NULL, MS_BIND, NULL);
940 if (r < 0)
941 return r;
942
943 add_symlink:
944 bn = path_startswith(d, "/dev/");
945 if (!bn)
946 return 0;
947
948 /* Create symlinks like /dev/char/1:9 → ../urandom */
949 if (asprintf(&sl, "%s/dev/%s/" DEVNUM_FORMAT_STR,
950 temporary_mount,
951 S_ISCHR(st.st_mode) ? "char" : "block",
952 DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
953 return log_oom_debug();
954
955 (void) mkdir_parents(sl, 0755);
956
957 t = strjoina("../", bn);
958 if (symlink(t, sl) < 0)
959 log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, sl);
960
961 return 0;
962 }
963
964 static char *settle_runtime_dir(RuntimeScope scope) {
965 char *runtime_dir;
966
967 if (scope != RUNTIME_SCOPE_USER)
968 return strdup("/run/");
969
970 if (asprintf(&runtime_dir, "/run/user/" UID_FMT, geteuid()) < 0)
971 return NULL;
972
973 return runtime_dir;
974 }
975
976 static int mount_private_dev(MountEntry *m, RuntimeScope scope) {
977 static const char devnodes[] =
978 "/dev/null\0"
979 "/dev/zero\0"
980 "/dev/full\0"
981 "/dev/random\0"
982 "/dev/urandom\0"
983 "/dev/tty\0";
984
985 _cleanup_free_ char *runtime_dir = NULL, *temporary_mount = NULL;
986 const char *dev = NULL, *devpts = NULL, *devshm = NULL, *devhugepages = NULL, *devmqueue = NULL, *devlog = NULL, *devptmx = NULL;
987 bool can_mknod = true;
988 int r;
989
990 assert(m);
991
992 runtime_dir = settle_runtime_dir(scope);
993 if (!runtime_dir)
994 return log_oom_debug();
995
996 temporary_mount = path_join(runtime_dir, "systemd/namespace-dev-XXXXXX");
997 if (!temporary_mount)
998 return log_oom_debug();
999
1000 if (!mkdtemp(temporary_mount))
1001 return log_debug_errno(errno, "Failed to create temporary directory '%s': %m", temporary_mount);
1002
1003 dev = strjoina(temporary_mount, "/dev");
1004 (void) mkdir(dev, 0755);
1005 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=0755" TMPFS_LIMITS_PRIVATE_DEV);
1006 if (r < 0)
1007 goto fail;
1008
1009 r = label_fix_full(AT_FDCWD, dev, "/dev", 0);
1010 if (r < 0) {
1011 log_debug_errno(r, "Failed to fix label of '%s' as /dev: %m", dev);
1012 goto fail;
1013 }
1014
1015 devpts = strjoina(temporary_mount, "/dev/pts");
1016 (void) mkdir(devpts, 0755);
1017 r = mount_nofollow_verbose(LOG_DEBUG, "/dev/pts", devpts, NULL, MS_BIND, NULL);
1018 if (r < 0)
1019 goto fail;
1020
1021 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
1022 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
1023 * Thus, in that case make a clone.
1024 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
1025 r = is_symlink("/dev/ptmx");
1026 if (r < 0) {
1027 log_debug_errno(r, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
1028 goto fail;
1029 } else if (r > 0) {
1030 devptmx = strjoina(temporary_mount, "/dev/ptmx");
1031 if (symlink("pts/ptmx", devptmx) < 0) {
1032 r = log_debug_errno(errno, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx);
1033 goto fail;
1034 }
1035 } else {
1036 r = clone_device_node("/dev/ptmx", temporary_mount, &can_mknod);
1037 if (r < 0)
1038 goto fail;
1039 }
1040
1041 devshm = strjoina(temporary_mount, "/dev/shm");
1042 (void) mkdir(devshm, 0755);
1043 r = mount_nofollow_verbose(LOG_DEBUG, "/dev/shm", devshm, NULL, MS_BIND, NULL);
1044 if (r < 0)
1045 goto fail;
1046
1047 devmqueue = strjoina(temporary_mount, "/dev/mqueue");
1048 (void) mkdir(devmqueue, 0755);
1049 (void) mount_nofollow_verbose(LOG_DEBUG, "/dev/mqueue", devmqueue, NULL, MS_BIND, NULL);
1050
1051 devhugepages = strjoina(temporary_mount, "/dev/hugepages");
1052 (void) mkdir(devhugepages, 0755);
1053 (void) mount_nofollow_verbose(LOG_DEBUG, "/dev/hugepages", devhugepages, NULL, MS_BIND, NULL);
1054
1055 devlog = strjoina(temporary_mount, "/dev/log");
1056 if (symlink("/run/systemd/journal/dev-log", devlog) < 0)
1057 log_debug_errno(errno, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog);
1058
1059 NULSTR_FOREACH(d, devnodes) {
1060 r = clone_device_node(d, temporary_mount, &can_mknod);
1061 /* ENXIO means the *source* is not a device file, skip creation in that case */
1062 if (r < 0 && r != -ENXIO)
1063 goto fail;
1064 }
1065
1066 r = dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
1067 if (r < 0)
1068 log_debug_errno(r, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount);
1069
1070 /* Make the bind mount read-only. */
1071 r = mount_nofollow_verbose(LOG_DEBUG, NULL, dev, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1072 if (r < 0)
1073 return r;
1074
1075 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
1076 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
1077 (void) mkdir_p_label(mount_entry_path(m), 0755);
1078
1079 /* Unmount everything in old /dev */
1080 r = umount_recursive(mount_entry_path(m), 0);
1081 if (r < 0)
1082 log_debug_errno(r, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m));
1083
1084 r = mount_nofollow_verbose(LOG_DEBUG, dev, mount_entry_path(m), NULL, MS_MOVE, NULL);
1085 if (r < 0)
1086 goto fail;
1087
1088 (void) rmdir(dev);
1089 (void) rmdir(temporary_mount);
1090
1091 return 0;
1092
1093 fail:
1094 if (devpts)
1095 (void) umount_verbose(LOG_DEBUG, devpts, UMOUNT_NOFOLLOW);
1096
1097 if (devshm)
1098 (void) umount_verbose(LOG_DEBUG, devshm, UMOUNT_NOFOLLOW);
1099
1100 if (devhugepages)
1101 (void) umount_verbose(LOG_DEBUG, devhugepages, UMOUNT_NOFOLLOW);
1102
1103 if (devmqueue)
1104 (void) umount_verbose(LOG_DEBUG, devmqueue, UMOUNT_NOFOLLOW);
1105
1106 (void) umount_verbose(LOG_DEBUG, dev, UMOUNT_NOFOLLOW);
1107 (void) rmdir(dev);
1108 (void) rmdir(temporary_mount);
1109
1110 return r;
1111 }
1112
1113 static int mount_bind_dev(const MountEntry *m) {
1114 int r;
1115
1116 assert(m);
1117
1118 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1119 * service's /dev. This is only used when RootDirectory= is set. */
1120
1121 (void) mkdir_p_label(mount_entry_path(m), 0755);
1122
1123 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
1124 if (r < 0)
1125 return log_debug_errno(r, "Unable to determine whether /dev is already mounted: %m");
1126 if (r > 0) /* make this a NOP if /dev is already a mount point */
1127 return 0;
1128
1129 return mount_nofollow_verbose(LOG_DEBUG, "/dev", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
1130 }
1131
1132 static int mount_bind_sysfs(const MountEntry *m) {
1133 int r;
1134
1135 assert(m);
1136
1137 (void) mkdir_p_label(mount_entry_path(m), 0755);
1138
1139 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
1140 if (r < 0)
1141 return log_debug_errno(r, "Unable to determine whether /sys is already mounted: %m");
1142 if (r > 0) /* make this a NOP if /sys is already a mount point */
1143 return 0;
1144
1145 /* Bind mount the host's version so that we get all child mounts of it, too. */
1146 return mount_nofollow_verbose(LOG_DEBUG, "/sys", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
1147 }
1148
1149 static int mount_private_sysfs(const MountEntry *m) {
1150 const char *entry_path = mount_entry_path(ASSERT_PTR(m));
1151 int r, n;
1152
1153 (void) mkdir_p_label(entry_path, 0755);
1154
1155 n = umount_recursive(entry_path, 0);
1156
1157 r = mount_nofollow_verbose(LOG_DEBUG, "sysfs", entry_path, "sysfs", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
1158 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
1159 /* When we do not have enough privileges to mount sysfs, fall back to use existing /sys. */
1160
1161 if (n > 0)
1162 /* /sys or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1163 * Propagate the original error code returned by mount() in the above. */
1164 return r;
1165
1166 return mount_bind_sysfs(m);
1167
1168 } else if (r < 0)
1169 return r;
1170
1171 /* We mounted a new instance now. Let's bind mount the children over now. */
1172 (void) bind_mount_submounts("/sys", entry_path);
1173 return 0;
1174 }
1175
1176 static int mount_procfs(const MountEntry *m, const NamespaceParameters *p) {
1177 _cleanup_free_ char *opts = NULL;
1178 const char *entry_path;
1179 int r, n;
1180
1181 assert(m);
1182 assert(p);
1183
1184 if (p->protect_proc != PROTECT_PROC_DEFAULT ||
1185 p->proc_subset != PROC_SUBSET_ALL) {
1186
1187 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
1188 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
1189 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
1190 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
1191 * added in the same commit: if it's supported it is thus also per-instance. */
1192
1193 const char *hpv = p->protect_proc == PROTECT_PROC_DEFAULT ?
1194 "off" :
1195 protect_proc_to_string(p->protect_proc);
1196
1197 /* hidepid= support was added in 5.8, so we can use fsconfig()/fsopen() (which were added in
1198 * 5.2) to check if hidepid= is supported. This avoids a noisy dmesg log by the kernel when
1199 * trying to use hidepid= on systems where it isn't supported. The same applies for subset=.
1200 * fsopen()/fsconfig() was also backported on some distros which allows us to detect
1201 * hidepid=/subset= support in even more scenarios. */
1202
1203 if (mount_option_supported("proc", "hidepid", hpv) != 0) {
1204 opts = strjoin("hidepid=", hpv);
1205 if (!opts)
1206 return -ENOMEM;
1207 }
1208
1209 if (p->proc_subset == PROC_SUBSET_PID &&
1210 mount_option_supported("proc", "subset", "pid") != 0)
1211 if (!strextend_with_separator(&opts, ",", "subset=pid"))
1212 return -ENOMEM;
1213 }
1214
1215 entry_path = mount_entry_path(m);
1216 (void) mkdir_p_label(entry_path, 0755);
1217
1218 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1219 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1220 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1221 * mounted on /proc/ first. */
1222
1223 n = umount_recursive(entry_path, 0);
1224
1225 r = mount_nofollow_verbose(LOG_DEBUG, "proc", entry_path, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
1226 if (r == -EINVAL && opts)
1227 /* If this failed with EINVAL then this likely means the textual hidepid= stuff is
1228 * not supported by the kernel, and thus the per-instance hidepid= neither, which
1229 * means we really don't want to use it, since it would affect our host's /proc
1230 * mount. Hence let's gracefully fallback to a classic, unrestricted version. */
1231 r = mount_nofollow_verbose(LOG_DEBUG, "proc", entry_path, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
1232 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
1233 /* When we do not have enough privileges to mount /proc, fall back to use existing /proc. */
1234
1235 if (n > 0)
1236 /* /proc or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1237 * Propagate the original error code returned by mount() in the above. */
1238 return r;
1239
1240 r = path_is_mount_point(entry_path, NULL, 0);
1241 if (r < 0)
1242 return log_debug_errno(r, "Unable to determine whether /proc is already mounted: %m");
1243 if (r > 0)
1244 return 0;
1245
1246 /* We lack permissions to mount a new instance of /proc, and it is not already mounted. But
1247 * we can access the host's, so as a final fallback bind-mount it to the destination, as most
1248 * likely we are inside a user manager in an unprivileged user namespace. */
1249 return mount_nofollow_verbose(LOG_DEBUG, "/proc", entry_path, NULL, MS_BIND|MS_REC, NULL);
1250
1251 } else if (r < 0)
1252 return r;
1253
1254 /* We mounted a new instance now. Let's bind mount the children over now. This matters for nspawn
1255 * where a bunch of files are overmounted, in particular the boot id */
1256 (void) bind_mount_submounts("/proc", entry_path);
1257 return 0;
1258 }
1259
1260 static int mount_tmpfs(const MountEntry *m) {
1261 const char *entry_path, *inner_path;
1262 int r;
1263
1264 assert(m);
1265
1266 entry_path = mount_entry_path(m);
1267 inner_path = mount_entry_unprefixed_path(m);
1268
1269 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1270 * tmpfs */
1271
1272 (void) mkdir_p_label(entry_path, 0755);
1273 (void) umount_recursive(entry_path, 0);
1274
1275 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", entry_path, "tmpfs", m->flags, mount_entry_options(m));
1276 if (r < 0)
1277 return r;
1278
1279 r = label_fix_full(AT_FDCWD, entry_path, inner_path, 0);
1280 if (r < 0)
1281 return log_debug_errno(r, "Failed to fix label of '%s' as '%s': %m", entry_path, inner_path);
1282
1283 return 0;
1284 }
1285
1286 static int mount_run(const MountEntry *m) {
1287 int r;
1288
1289 assert(m);
1290
1291 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
1292 if (r < 0 && r != -ENOENT)
1293 return log_debug_errno(r, "Unable to determine whether /run is already mounted: %m");
1294 if (r > 0) /* make this a NOP if /run is already a mount point */
1295 return 0;
1296
1297 return mount_tmpfs(m);
1298 }
1299
1300 static int mount_mqueuefs(const MountEntry *m) {
1301 int r;
1302 const char *entry_path;
1303
1304 assert(m);
1305
1306 entry_path = mount_entry_path(m);
1307
1308 (void) mkdir_p_label(entry_path, 0755);
1309 (void) umount_recursive(entry_path, 0);
1310
1311 r = mount_nofollow_verbose(LOG_DEBUG, "mqueue", entry_path, "mqueue", m->flags, mount_entry_options(m));
1312 if (r < 0)
1313 return r;
1314
1315 return 0;
1316 }
1317
1318 static int mount_image(
1319 const MountEntry *m,
1320 const char *root_directory,
1321 const ImagePolicy *image_policy) {
1322
1323 _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_version_id = NULL,
1324 *host_os_release_sysext_level = NULL, *host_os_release_confext_level = NULL,
1325 *extension_name = NULL;
1326 int r;
1327
1328 assert(m);
1329
1330 r = path_extract_filename(mount_entry_source(m), &extension_name);
1331 if (r < 0)
1332 return log_debug_errno(r, "Failed to extract extension name from %s: %m", mount_entry_source(m));
1333
1334 if (m->mode == EXTENSION_IMAGES) {
1335 r = parse_os_release(
1336 empty_to_root(root_directory),
1337 "ID", &host_os_release_id,
1338 "VERSION_ID", &host_os_release_version_id,
1339 image_class_info[IMAGE_SYSEXT].level_env, &host_os_release_sysext_level,
1340 image_class_info[IMAGE_CONFEXT].level_env, &host_os_release_confext_level,
1341 NULL);
1342 if (r < 0)
1343 return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1344 if (isempty(host_os_release_id))
1345 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));
1346 }
1347
1348 r = verity_dissect_and_mount(
1349 /* src_fd= */ -1,
1350 mount_entry_source(m),
1351 mount_entry_path(m),
1352 m->image_options_const,
1353 image_policy,
1354 host_os_release_id,
1355 host_os_release_version_id,
1356 host_os_release_sysext_level,
1357 host_os_release_confext_level,
1358 /* required_sysext_scope= */ NULL,
1359 /* ret_image= */ NULL);
1360 if (r == -ENOENT && m->ignore)
1361 return 0;
1362 if (r == -ESTALE && host_os_release_id)
1363 return log_error_errno(r, // FIXME: this should not be logged ad LOG_ERR, as it will result in duplicate logging.
1364 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s%s%s",
1365 mount_entry_source(m),
1366 host_os_release_id,
1367 host_os_release_version_id ? " VERSION_ID=" : "",
1368 strempty(host_os_release_version_id),
1369 host_os_release_sysext_level ? image_class_info[IMAGE_SYSEXT].level_env_print : "",
1370 strempty(host_os_release_sysext_level),
1371 host_os_release_confext_level ? image_class_info[IMAGE_CONFEXT].level_env_print : "",
1372 strempty(host_os_release_confext_level));
1373 if (r < 0)
1374 return log_debug_errno(r, "Failed to mount image %s on %s: %m", mount_entry_source(m), mount_entry_path(m));
1375
1376 return 0;
1377 }
1378
1379 static int mount_overlay(const MountEntry *m) {
1380 const char *options;
1381 int r;
1382
1383 assert(m);
1384
1385 options = strjoina("lowerdir=", mount_entry_options(m));
1386
1387 (void) mkdir_p_label(mount_entry_path(m), 0755);
1388
1389 r = mount_nofollow_verbose(LOG_DEBUG, "overlay", mount_entry_path(m), "overlay", MS_RDONLY, options);
1390 if (r == -ENOENT && m->ignore)
1391 return 0;
1392
1393 return r;
1394 }
1395
1396 static int follow_symlink(
1397 const char *root_directory,
1398 MountEntry *m) {
1399
1400 _cleanup_free_ char *target = NULL;
1401 int r;
1402
1403 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1404 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1405 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1406 * end and already have a fully normalized name. */
1407
1408 r = chase(mount_entry_path(m), root_directory, CHASE_STEP|CHASE_NONEXISTENT, &target, NULL);
1409 if (r < 0)
1410 return log_debug_errno(r, "Failed to chase symlinks '%s': %m", mount_entry_path(m));
1411 if (r > 0) /* Reached the end, nothing more to resolve */
1412 return 1;
1413
1414 if (m->n_followed >= CHASE_MAX) /* put a boundary on things */
1415 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1416 "Symlink loop on '%s'.",
1417 mount_entry_path(m));
1418
1419 log_debug("Followed mount entry path symlink %s %s %s.",
1420 mount_entry_path(m), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), target);
1421
1422 mount_entry_consume_prefix(m, TAKE_PTR(target));
1423
1424 m->n_followed ++;
1425
1426 return 0;
1427 }
1428
1429 static int apply_one_mount(
1430 const char *root_directory,
1431 MountEntry *m,
1432 const NamespaceParameters *p) {
1433
1434 _cleanup_free_ char *inaccessible = NULL;
1435 bool rbind = true, make = false;
1436 const char *what;
1437 int r;
1438
1439 assert(m);
1440 assert(p);
1441
1442 log_debug("Applying namespace mount on %s", mount_entry_path(m));
1443
1444 switch (m->mode) {
1445
1446 case INACCESSIBLE: {
1447 _cleanup_free_ char *runtime_dir = NULL;
1448 struct stat target;
1449
1450 /* First, get rid of everything that is below if there
1451 * is anything... Then, overmount it with an
1452 * inaccessible path. */
1453 (void) umount_recursive(mount_entry_path(m), 0);
1454
1455 if (lstat(mount_entry_path(m), &target) < 0) {
1456 if (errno == ENOENT && m->ignore)
1457 return 0;
1458
1459 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m",
1460 mount_entry_path(m));
1461 }
1462
1463 /* We don't pass the literal runtime scope through here but one based purely on our UID. This
1464 * means that the root user's --user services will use the host's inaccessible inodes rather
1465 * then root's private ones. This is preferable since it means device nodes that are
1466 * overmounted to make them inaccessible will be overmounted with a device node, rather than
1467 * an AF_UNIX socket inode. */
1468 runtime_dir = settle_runtime_dir(geteuid() == 0 ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER);
1469 if (!runtime_dir)
1470 return log_oom_debug();
1471
1472 r = mode_to_inaccessible_node(runtime_dir, target.st_mode, &inaccessible);
1473 if (r < 0)
1474 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1475 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
1476 what = inaccessible;
1477 break;
1478 }
1479
1480 case READONLY:
1481 case READWRITE:
1482 case READWRITE_IMPLICIT:
1483 case EXEC:
1484 case NOEXEC:
1485 r = path_is_mount_point(mount_entry_path(m), root_directory, 0);
1486 if (r == -ENOENT && m->ignore)
1487 return 0;
1488 if (r < 0)
1489 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m",
1490 mount_entry_path(m));
1491 if (r > 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1492 * and MS_NOEXEC bits for the mount point if needed. */
1493 return 0;
1494 /* This isn't a mount point yet, let's make it one. */
1495 what = mount_entry_path(m);
1496 break;
1497
1498 case EXTENSION_DIRECTORIES: {
1499 _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_version_id = NULL,
1500 *host_os_release_level = NULL, *extension_name = NULL;
1501 _cleanup_strv_free_ char **extension_release = NULL;
1502 ImageClass class = IMAGE_SYSEXT;
1503
1504 r = path_extract_filename(mount_entry_source(m), &extension_name);
1505 if (r < 0)
1506 return log_debug_errno(r, "Failed to extract extension name from %s: %m", mount_entry_source(m));
1507
1508 r = load_extension_release_pairs(mount_entry_source(m), IMAGE_SYSEXT, extension_name, /* relax_extension_release_check= */ false, &extension_release);
1509 if (r == -ENOENT) {
1510 r = load_extension_release_pairs(mount_entry_source(m), IMAGE_CONFEXT, extension_name, /* relax_extension_release_check= */ false, &extension_release);
1511 if (r >= 0)
1512 class = IMAGE_CONFEXT;
1513 }
1514 if (r < 0)
1515 return log_debug_errno(r, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m));
1516
1517 r = parse_os_release(
1518 empty_to_root(root_directory),
1519 "ID", &host_os_release_id,
1520 "VERSION_ID", &host_os_release_version_id,
1521 image_class_info[class].level_env, &host_os_release_level,
1522 NULL);
1523 if (r < 0)
1524 return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1525 if (isempty(host_os_release_id))
1526 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));
1527
1528 r = load_extension_release_pairs(mount_entry_source(m), class, extension_name, /* relax_extension_release_check= */ false, &extension_release);
1529 if (r == -ENOENT && m->ignore)
1530 return 0;
1531 if (r < 0)
1532 return log_debug_errno(r, "Failed to parse directory %s extension-release metadata: %m", extension_name);
1533
1534 r = extension_release_validate(
1535 extension_name,
1536 host_os_release_id,
1537 host_os_release_version_id,
1538 host_os_release_level,
1539 /* host_extension_scope */ NULL, /* Leave empty, we need to accept both system and portable */
1540 extension_release,
1541 class);
1542 if (r == 0)
1543 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Directory %s extension-release metadata does not match the root's", extension_name);
1544 if (r < 0)
1545 return log_debug_errno(r, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name);
1546
1547 _fallthrough_;
1548 }
1549
1550 case BIND_MOUNT:
1551 rbind = false;
1552
1553 _fallthrough_;
1554 case BIND_MOUNT_RECURSIVE: {
1555 _cleanup_free_ char *chased = NULL;
1556
1557 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1558 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1559 * root directory to chase() here. */
1560
1561 r = chase(mount_entry_source(m), NULL, CHASE_TRAIL_SLASH, &chased, NULL);
1562 if (r == -ENOENT && m->ignore) {
1563 log_debug_errno(r, "Path %s does not exist, ignoring.", mount_entry_source(m));
1564 return 0;
1565 }
1566 if (r < 0)
1567 return log_debug_errno(r, "Failed to follow symlinks on %s: %m", mount_entry_source(m));
1568
1569 log_debug("Followed source symlinks %s %s %s.",
1570 mount_entry_source(m), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), chased);
1571
1572 free_and_replace(m->source_malloc, chased);
1573
1574 what = mount_entry_source(m);
1575 make = true;
1576 break;
1577 }
1578
1579 case EMPTY_DIR:
1580 case TMPFS:
1581 return mount_tmpfs(m);
1582
1583 case PRIVATE_TMP:
1584 case PRIVATE_TMP_READONLY:
1585 what = mount_entry_source(m);
1586 make = true;
1587 break;
1588
1589 case PRIVATE_DEV:
1590 return mount_private_dev(m, p->runtime_scope);
1591
1592 case BIND_DEV:
1593 return mount_bind_dev(m);
1594
1595 case PRIVATE_SYSFS:
1596 return mount_private_sysfs(m);
1597
1598 case BIND_SYSFS:
1599 return mount_bind_sysfs(m);
1600
1601 case PROCFS:
1602 return mount_procfs(m, p);
1603
1604 case RUN:
1605 return mount_run(m);
1606
1607 case MQUEUEFS:
1608 return mount_mqueuefs(m);
1609
1610 case MOUNT_IMAGES:
1611 return mount_image(m, NULL, p->mount_image_policy);
1612
1613 case EXTENSION_IMAGES:
1614 return mount_image(m, root_directory, p->extension_image_policy);
1615
1616 case OVERLAY_MOUNT:
1617 return mount_overlay(m);
1618
1619 default:
1620 assert_not_reached();
1621 }
1622
1623 assert(what);
1624
1625 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
1626 if (r < 0) {
1627 bool try_again = false;
1628
1629 if (r == -ENOENT && make) {
1630 int q;
1631
1632 /* Hmm, either the source or the destination are missing. Let's see if we can create
1633 the destination, then try again. */
1634
1635 (void) mkdir_parents(mount_entry_path(m), 0755);
1636
1637 q = make_mount_point_inode_from_path(what, mount_entry_path(m), 0755);
1638 if (q < 0) {
1639 if (q != -EEXIST) // FIXME: this shouldn't be logged at LOG_WARNING, but be bubbled up, and logged there to avoid duplicate logging
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)); // FIXME: this should not be logged here, but be bubbled up, to avoid duplicate logging
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_debug();
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 supported for
2528 * non-shared mounts. This needs to happen after remounting / or it will fail. */
2529 if (setup_propagate && mount(NULL, p->incoming_dir, NULL, MS_SLAVE, NULL) < 0)
2530 return log_debug_errno(errno, "Failed to remount %s with MS_SLAVE: %m", p->incoming_dir);
2531
2532 return 0;
2533 }
2534
2535 void bind_mount_free_many(BindMount *b, size_t n) {
2536 assert(b || n == 0);
2537
2538 for (size_t i = 0; i < n; i++) {
2539 free(b[i].source);
2540 free(b[i].destination);
2541 }
2542
2543 free(b);
2544 }
2545
2546 int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
2547 _cleanup_free_ char *s = NULL, *d = NULL;
2548 BindMount *c;
2549
2550 assert(b);
2551 assert(n);
2552 assert(item);
2553
2554 s = strdup(item->source);
2555 if (!s)
2556 return -ENOMEM;
2557
2558 d = strdup(item->destination);
2559 if (!d)
2560 return -ENOMEM;
2561
2562 c = reallocarray(*b, *n + 1, sizeof(BindMount));
2563 if (!c)
2564 return -ENOMEM;
2565
2566 *b = c;
2567
2568 c[(*n) ++] = (BindMount) {
2569 .source = TAKE_PTR(s),
2570 .destination = TAKE_PTR(d),
2571 .read_only = item->read_only,
2572 .nosuid = item->nosuid,
2573 .recursive = item->recursive,
2574 .ignore_enoent = item->ignore_enoent,
2575 };
2576
2577 return 0;
2578 }
2579
2580 MountImage* mount_image_free_many(MountImage *m, size_t *n) {
2581 assert(n);
2582 assert(m || *n == 0);
2583
2584 for (size_t i = 0; i < *n; i++) {
2585 free(m[i].source);
2586 free(m[i].destination);
2587 mount_options_free_all(m[i].mount_options);
2588 }
2589
2590 free(m);
2591 *n = 0;
2592 return NULL;
2593 }
2594
2595 int mount_image_add(MountImage **m, size_t *n, const MountImage *item) {
2596 _cleanup_free_ char *s = NULL, *d = NULL;
2597 _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
2598 MountImage *c;
2599
2600 assert(m);
2601 assert(n);
2602 assert(item);
2603
2604 s = strdup(item->source);
2605 if (!s)
2606 return -ENOMEM;
2607
2608 if (item->destination) {
2609 d = strdup(item->destination);
2610 if (!d)
2611 return -ENOMEM;
2612 }
2613
2614 LIST_FOREACH(mount_options, i, item->mount_options) {
2615 _cleanup_(mount_options_free_allp) MountOptions *o = NULL;
2616
2617 o = new(MountOptions, 1);
2618 if (!o)
2619 return -ENOMEM;
2620
2621 *o = (MountOptions) {
2622 .partition_designator = i->partition_designator,
2623 .options = strdup(i->options),
2624 };
2625 if (!o->options)
2626 return -ENOMEM;
2627
2628 LIST_APPEND(mount_options, options, TAKE_PTR(o));
2629 }
2630
2631 c = reallocarray(*m, *n + 1, sizeof(MountImage));
2632 if (!c)
2633 return -ENOMEM;
2634
2635 *m = c;
2636
2637 c[(*n) ++] = (MountImage) {
2638 .source = TAKE_PTR(s),
2639 .destination = TAKE_PTR(d),
2640 .mount_options = TAKE_PTR(options),
2641 .ignore_enoent = item->ignore_enoent,
2642 .type = item->type,
2643 };
2644
2645 return 0;
2646 }
2647
2648 void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
2649 assert(t || n == 0);
2650
2651 for (size_t i = 0; i < n; i++) {
2652 free(t[i].path);
2653 free(t[i].options);
2654 }
2655
2656 free(t);
2657 }
2658
2659 int temporary_filesystem_add(
2660 TemporaryFileSystem **t,
2661 size_t *n,
2662 const char *path,
2663 const char *options) {
2664
2665 _cleanup_free_ char *p = NULL, *o = NULL;
2666 TemporaryFileSystem *c;
2667
2668 assert(t);
2669 assert(n);
2670 assert(path);
2671
2672 p = strdup(path);
2673 if (!p)
2674 return -ENOMEM;
2675
2676 if (!isempty(options)) {
2677 o = strdup(options);
2678 if (!o)
2679 return -ENOMEM;
2680 }
2681
2682 c = reallocarray(*t, *n + 1, sizeof(TemporaryFileSystem));
2683 if (!c)
2684 return -ENOMEM;
2685
2686 *t = c;
2687
2688 c[(*n) ++] = (TemporaryFileSystem) {
2689 .path = TAKE_PTR(p),
2690 .options = TAKE_PTR(o),
2691 };
2692
2693 return 0;
2694 }
2695
2696 static int make_tmp_prefix(const char *prefix) {
2697 _cleanup_free_ char *t = NULL;
2698 _cleanup_close_ int fd = -EBADF;
2699 int r;
2700
2701 /* Don't do anything unless we know the dir is actually missing */
2702 r = access(prefix, F_OK);
2703 if (r >= 0)
2704 return 0;
2705 if (errno != ENOENT)
2706 return -errno;
2707
2708 WITH_UMASK(000)
2709 r = mkdir_parents(prefix, 0755);
2710 if (r < 0)
2711 return r;
2712
2713 r = tempfn_random(prefix, NULL, &t);
2714 if (r < 0)
2715 return r;
2716
2717 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2718 * the suid bit, below. */
2719 fd = open_mkdir_at(AT_FDCWD, t, O_EXCL|O_CLOEXEC, 0777);
2720 if (fd < 0)
2721 return fd;
2722
2723 r = RET_NERRNO(fchmod(fd, 01777));
2724 if (r < 0) {
2725 (void) rmdir(t);
2726 return r;
2727 }
2728
2729 r = RET_NERRNO(rename(t, prefix));
2730 if (r < 0) {
2731 (void) rmdir(t);
2732 return r == -EEXIST ? 0 : r; /* it's fine if someone else created the dir by now */
2733 }
2734
2735 return 0;
2736
2737 }
2738
2739 static int setup_one_tmp_dir(const char *id, const char *prefix, char **path, char **tmp_path) {
2740 _cleanup_free_ char *x = NULL;
2741 _cleanup_free_ char *y = NULL;
2742 sd_id128_t boot_id;
2743 bool rw = true;
2744 int r;
2745
2746 assert(id);
2747 assert(prefix);
2748 assert(path);
2749
2750 /* We include the boot id in the directory so that after a
2751 * reboot we can easily identify obsolete directories. */
2752
2753 r = sd_id128_get_boot(&boot_id);
2754 if (r < 0)
2755 return r;
2756
2757 x = strjoin(prefix, "/systemd-private-", SD_ID128_TO_STRING(boot_id), "-", id, "-XXXXXX");
2758 if (!x)
2759 return -ENOMEM;
2760
2761 r = make_tmp_prefix(prefix);
2762 if (r < 0)
2763 return r;
2764
2765 WITH_UMASK(0077)
2766 if (!mkdtemp(x)) {
2767 if (errno == EROFS || ERRNO_IS_DISK_SPACE(errno))
2768 rw = false;
2769 else
2770 return -errno;
2771 }
2772
2773 if (rw) {
2774 y = strjoin(x, "/tmp");
2775 if (!y)
2776 return -ENOMEM;
2777
2778 WITH_UMASK(0000)
2779 if (mkdir(y, 0777 | S_ISVTX) < 0)
2780 return -errno;
2781
2782 r = label_fix_full(AT_FDCWD, y, prefix, 0);
2783 if (r < 0)
2784 return r;
2785
2786 if (tmp_path)
2787 *tmp_path = TAKE_PTR(y);
2788 } else {
2789 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2790 * read-only. This way the service will get the EROFS result as if it was writing to the real
2791 * file system. */
2792 WITH_UMASK(0000)
2793 r = mkdir_p(RUN_SYSTEMD_EMPTY, 0500);
2794 if (r < 0)
2795 return r;
2796
2797 r = free_and_strdup(&x, RUN_SYSTEMD_EMPTY);
2798 if (r < 0)
2799 return r;
2800 }
2801
2802 *path = TAKE_PTR(x);
2803 return 0;
2804 }
2805
2806 int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
2807 _cleanup_(namespace_cleanup_tmpdirp) char *a = NULL;
2808 _cleanup_(rmdir_and_freep) char *a_tmp = NULL;
2809 char *b;
2810 int r;
2811
2812 assert(id);
2813 assert(tmp_dir);
2814 assert(var_tmp_dir);
2815
2816 r = setup_one_tmp_dir(id, "/tmp", &a, &a_tmp);
2817 if (r < 0)
2818 return r;
2819
2820 r = setup_one_tmp_dir(id, "/var/tmp", &b, NULL);
2821 if (r < 0)
2822 return r;
2823
2824 a_tmp = mfree(a_tmp); /* avoid rmdir */
2825 *tmp_dir = TAKE_PTR(a);
2826 *var_tmp_dir = TAKE_PTR(b);
2827
2828 return 0;
2829 }
2830
2831 int setup_shareable_ns(int ns_storage_socket[static 2], unsigned long nsflag) {
2832 _cleanup_close_ int ns = -EBADF;
2833 int r;
2834 const char *ns_name, *ns_path;
2835
2836 assert(ns_storage_socket);
2837 assert(ns_storage_socket[0] >= 0);
2838 assert(ns_storage_socket[1] >= 0);
2839
2840 ns_name = namespace_single_flag_to_string(nsflag);
2841 assert(ns_name);
2842
2843 /* We use the passed socketpair as a storage buffer for our
2844 * namespace reference fd. Whatever process runs this first
2845 * shall create a new namespace, all others should just join
2846 * it. To serialize that we use a file lock on the socket
2847 * pair.
2848 *
2849 * It's a bit crazy, but hey, works great! */
2850
2851 r = posix_lock(ns_storage_socket[0], LOCK_EX);
2852 if (r < 0)
2853 return r;
2854
2855 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
2856
2857 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2858 if (ns >= 0) {
2859 /* Yay, found something, so let's join the namespace */
2860 r = RET_NERRNO(setns(ns, nsflag));
2861 if (r < 0)
2862 return r;
2863
2864 return 0;
2865 }
2866
2867 if (ns != -EAGAIN)
2868 return ns;
2869
2870 /* Nothing stored yet, so let's create a new namespace. */
2871
2872 if (unshare(nsflag) < 0)
2873 return -errno;
2874
2875 (void) loopback_setup();
2876
2877 ns_path = strjoina("/proc/self/ns/", ns_name);
2878 ns = open(ns_path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
2879 if (ns < 0)
2880 return -errno;
2881
2882 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
2883 if (r < 0)
2884 return r;
2885
2886 return 1;
2887 }
2888
2889 int open_shareable_ns_path(int ns_storage_socket[static 2], const char *path, unsigned long nsflag) {
2890 _cleanup_close_ int ns = -EBADF;
2891 int r;
2892
2893 assert(ns_storage_socket);
2894 assert(ns_storage_socket[0] >= 0);
2895 assert(ns_storage_socket[1] >= 0);
2896 assert(path);
2897
2898 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2899 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2900 * allocate a new anonymous ns if needed. */
2901
2902 r = posix_lock(ns_storage_socket[0], LOCK_EX);
2903 if (r < 0)
2904 return r;
2905
2906 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
2907
2908 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
2909 if (ns >= 0)
2910 return 0;
2911 if (ns != -EAGAIN)
2912 return ns;
2913
2914 /* Nothing stored yet. Open the file from the file system. */
2915
2916 ns = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
2917 if (ns < 0)
2918 return -errno;
2919
2920 r = fd_is_ns(ns, nsflag);
2921 if (r == 0)
2922 return -EINVAL;
2923 if (r < 0 && r != -EUCLEAN) /* EUCLEAN: we don't know */
2924 return r;
2925
2926 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
2927 if (r < 0)
2928 return r;
2929
2930 return 1;
2931 }
2932
2933 bool ns_type_supported(NamespaceType type) {
2934 const char *t, *ns_proc;
2935
2936 t = namespace_type_to_string(type);
2937 if (!t) /* Don't know how to translate this? Then it's not supported */
2938 return false;
2939
2940 ns_proc = strjoina("/proc/self/ns/", t);
2941 return access(ns_proc, F_OK) == 0;
2942 }
2943
2944 static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
2945 [PROTECT_HOME_NO] = "no",
2946 [PROTECT_HOME_YES] = "yes",
2947 [PROTECT_HOME_READ_ONLY] = "read-only",
2948 [PROTECT_HOME_TMPFS] = "tmpfs",
2949 };
2950
2951 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home, ProtectHome, PROTECT_HOME_YES);
2952
2953 static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
2954 [PROTECT_SYSTEM_NO] = "no",
2955 [PROTECT_SYSTEM_YES] = "yes",
2956 [PROTECT_SYSTEM_FULL] = "full",
2957 [PROTECT_SYSTEM_STRICT] = "strict",
2958 };
2959
2960 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system, ProtectSystem, PROTECT_SYSTEM_YES);
2961
2962 static const char* const namespace_type_table[] = {
2963 [NAMESPACE_MOUNT] = "mnt",
2964 [NAMESPACE_CGROUP] = "cgroup",
2965 [NAMESPACE_UTS] = "uts",
2966 [NAMESPACE_IPC] = "ipc",
2967 [NAMESPACE_USER] = "user",
2968 [NAMESPACE_PID] = "pid",
2969 [NAMESPACE_NET] = "net",
2970 [NAMESPACE_TIME] = "time",
2971 };
2972
2973 DEFINE_STRING_TABLE_LOOKUP(namespace_type, NamespaceType);
2974
2975 static const char* const protect_proc_table[_PROTECT_PROC_MAX] = {
2976 [PROTECT_PROC_DEFAULT] = "default",
2977 [PROTECT_PROC_NOACCESS] = "noaccess",
2978 [PROTECT_PROC_INVISIBLE] = "invisible",
2979 [PROTECT_PROC_PTRACEABLE] = "ptraceable",
2980 };
2981
2982 DEFINE_STRING_TABLE_LOOKUP(protect_proc, ProtectProc);
2983
2984 static const char* const proc_subset_table[_PROC_SUBSET_MAX] = {
2985 [PROC_SUBSET_ALL] = "all",
2986 [PROC_SUBSET_PID] = "pid",
2987 };
2988
2989 DEFINE_STRING_TABLE_LOOKUP(proc_subset, ProcSubset);