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