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