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