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