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