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