1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
11 #include "alloc-util.h"
12 #include "base-filesystem.h"
13 #include "chase-symlinks.h"
14 #include "dev-setup.h"
17 #include "extension-release.h"
19 #include "format-util.h"
22 #include "loop-util.h"
23 #include "loopback-setup.h"
24 #include "mkdir-label.h"
25 #include "mount-util.h"
26 #include "mountpoint-util.h"
27 #include "namespace-util.h"
28 #include "namespace.h"
30 #include "nulstr-util.h"
32 #include "path-util.h"
33 #include "selinux-util.h"
34 #include "socket-util.h"
35 #include "sort-util.h"
36 #include "stat-util.h"
37 #include "string-table.h"
38 #include "string-util.h"
40 #include "tmpfile-util.h"
41 #include "umask-util.h"
42 #include "user-util.h"
44 #define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
46 typedef enum MountMode
{
47 /* This is ordered by priority! */
66 EXTENSION_DIRECTORIES
, /* Bind-mounted outside the root directory, and used by subsequent mounts */
67 EXTENSION_IMAGES
, /* Mounted outside the root directory, and used by subsequent mounts */
69 READWRITE_IMPLICIT
, /* Should have the lowest priority. */
73 typedef struct MountEntry
{
74 const char *path_const
; /* Memory allocated on stack or static */
76 bool ignore
:1; /* Ignore if path does not exist? */
77 bool has_prefix
:1; /* Already is prefixed by the root dir? */
78 bool read_only
:1; /* Shall this mount point be read-only? */
79 bool nosuid
:1; /* Shall set MS_NOSUID on the mount itself */
80 bool noexec
:1; /* Shall set MS_NOEXEC on the mount itself */
81 bool exec
:1; /* Shall clear MS_NOEXEC on the mount itself */
82 bool applied
:1; /* Already applied */
83 char *path_malloc
; /* Use this instead of 'path_const' if we had to allocate memory */
84 const char *unprefixed_path_const
; /* If the path was amended with a prefix, these will save the original */
85 char *unprefixed_path_malloc
;
86 const char *source_const
; /* The source path, for bind mounts or images */
88 const char *options_const
;/* Mount options for tmpfs */
90 unsigned long flags
; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
92 LIST_HEAD(MountOptions
, image_options
);
95 /* If MountAPIVFS= is used, let's mount /sys, /proc, /dev and /run into the it, but only as a fallback if the user hasn't mounted
96 * something there already. These mounts are hence overridden by any other explicitly configured mounts. */
97 static const MountEntry apivfs_table
[] = {
98 { "/proc", PROCFS
, false },
99 { "/dev", BIND_DEV
, false },
100 { "/sys", SYSFS
, false },
101 { "/run", RUN
, false, .options_const
= "mode=755" TMPFS_LIMITS_RUN
, .flags
= MS_NOSUID
|MS_NODEV
|MS_STRICTATIME
},
104 /* ProtectKernelTunables= option and the related filesystem APIs */
105 static const MountEntry protect_kernel_tunables_proc_table
[] = {
106 { "/proc/acpi", READONLY
, true },
107 { "/proc/apm", READONLY
, true }, /* Obsolete API, there's no point in permitting access to this, ever */
108 { "/proc/asound", READONLY
, true },
109 { "/proc/bus", READONLY
, true },
110 { "/proc/fs", READONLY
, true },
111 { "/proc/irq", READONLY
, true },
112 { "/proc/kallsyms", INACCESSIBLE
, true },
113 { "/proc/kcore", INACCESSIBLE
, true },
114 { "/proc/latency_stats", READONLY
, true },
115 { "/proc/mtrr", READONLY
, true },
116 { "/proc/scsi", READONLY
, true },
117 { "/proc/sys", READONLY
, true },
118 { "/proc/sysrq-trigger", READONLY
, true },
119 { "/proc/timer_stats", READONLY
, true },
122 static const MountEntry protect_kernel_tunables_sys_table
[] = {
123 { "/sys", READONLY
, false },
124 { "/sys/fs/bpf", READONLY
, true },
125 { "/sys/fs/cgroup", READWRITE_IMPLICIT
, false }, /* READONLY is set by ProtectControlGroups= option */
126 { "/sys/fs/selinux", READWRITE_IMPLICIT
, true },
127 { "/sys/kernel/debug", READONLY
, true },
128 { "/sys/kernel/tracing", READONLY
, true },
131 /* ProtectKernelModules= option */
132 static const MountEntry protect_kernel_modules_table
[] = {
134 { "/lib/modules", INACCESSIBLE
, true },
136 { "/usr/lib/modules", INACCESSIBLE
, true },
139 /* ProtectKernelLogs= option */
140 static const MountEntry protect_kernel_logs_proc_table
[] = {
141 { "/proc/kmsg", INACCESSIBLE
, true },
144 static const MountEntry protect_kernel_logs_dev_table
[] = {
145 { "/dev/kmsg", INACCESSIBLE
, true },
149 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
150 * system should be protected by ProtectSystem=
152 static const MountEntry protect_home_read_only_table
[] = {
153 { "/home", READONLY
, true },
154 { "/run/user", READONLY
, true },
155 { "/root", READONLY
, true },
158 /* ProtectHome=tmpfs table */
159 static const MountEntry protect_home_tmpfs_table
[] = {
160 { "/home", TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
161 { "/run/user", TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
162 { "/root", TMPFS
, true, .read_only
= true, .options_const
= "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
165 /* ProtectHome=yes table */
166 static const MountEntry protect_home_yes_table
[] = {
167 { "/home", INACCESSIBLE
, true },
168 { "/run/user", INACCESSIBLE
, true },
169 { "/root", INACCESSIBLE
, true },
172 /* ProtectSystem=yes table */
173 static const MountEntry protect_system_yes_table
[] = {
174 { "/usr", READONLY
, false },
175 { "/boot", READONLY
, true },
176 { "/efi", READONLY
, true },
178 { "/lib", READONLY
, true },
179 { "/lib64", READONLY
, true },
180 { "/bin", READONLY
, true },
182 { "/sbin", READONLY
, true },
187 /* ProtectSystem=full includes ProtectSystem=yes */
188 static const MountEntry protect_system_full_table
[] = {
189 { "/usr", READONLY
, false },
190 { "/boot", READONLY
, true },
191 { "/efi", READONLY
, true },
192 { "/etc", READONLY
, false },
194 { "/lib", READONLY
, true },
195 { "/lib64", READONLY
, true },
196 { "/bin", READONLY
, true },
198 { "/sbin", READONLY
, true },
204 * ProtectSystem=strict table. In this strict mode, we mount everything
205 * read-only, except for /proc, /dev, /sys which are the kernel API VFS,
206 * which are left writable, but PrivateDevices= + ProtectKernelTunables=
207 * protect those, and these options should be fully orthogonal.
208 * (And of course /home and friends are also left writable, as ProtectHome=
209 * shall manage those, orthogonally).
211 static const MountEntry protect_system_strict_table
[] = {
212 { "/", READONLY
, false },
213 { "/proc", READWRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
214 { "/sys", READWRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
215 { "/dev", READWRITE_IMPLICIT
, false }, /* PrivateDevices= */
216 { "/home", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
217 { "/run/user", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
218 { "/root", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
221 static const char * const mount_mode_table
[_MOUNT_MODE_MAX
] = {
222 [INACCESSIBLE
] = "inaccessible",
223 [OVERLAY_MOUNT
] = "overlay",
224 [BIND_MOUNT
] = "bind",
225 [BIND_MOUNT_RECURSIVE
] = "rbind",
226 [PRIVATE_TMP
] = "private-tmp",
227 [PRIVATE_DEV
] = "private-dev",
228 [BIND_DEV
] = "bind-dev",
229 [EMPTY_DIR
] = "empty",
232 [READONLY
] = "read-only",
233 [READWRITE
] = "read-write",
235 [MOUNT_IMAGES
] = "mount-images",
236 [READWRITE_IMPLICIT
] = "rw-implicit",
239 [MQUEUEFS
] = "mqueuefs",
242 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode
, MountMode
);
244 static const char *mount_entry_path(const MountEntry
*p
) {
247 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
248 * otherwise the stack/static ->path field is returned. */
250 return p
->path_malloc
?: p
->path_const
;
253 static const char *mount_entry_unprefixed_path(const MountEntry
*p
) {
256 /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
258 return p
->unprefixed_path_malloc
?: p
->unprefixed_path_const
?: mount_entry_path(p
);
261 static void mount_entry_consume_prefix(MountEntry
*p
, char *new_path
) {
263 assert(p
->path_malloc
|| p
->path_const
);
266 /* Saves current path in unprefixed_ variable, and takes over new_path */
268 free_and_replace(p
->unprefixed_path_malloc
, p
->path_malloc
);
269 /* If we didn't have a path on the heap, then it's a static one */
270 if (!p
->unprefixed_path_malloc
)
271 p
->unprefixed_path_const
= p
->path_const
;
272 p
->path_malloc
= new_path
;
273 p
->has_prefix
= true;
276 static bool mount_entry_read_only(const MountEntry
*p
) {
279 return p
->read_only
|| IN_SET(p
->mode
, READONLY
, INACCESSIBLE
, PRIVATE_TMP_READONLY
);
282 static bool mount_entry_noexec(const MountEntry
*p
) {
285 return p
->noexec
|| IN_SET(p
->mode
, NOEXEC
, INACCESSIBLE
, SYSFS
, PROCFS
);
288 static bool mount_entry_exec(const MountEntry
*p
) {
291 return p
->exec
|| p
->mode
== EXEC
;
294 static const char *mount_entry_source(const MountEntry
*p
) {
297 return p
->source_malloc
?: p
->source_const
;
300 static const char *mount_entry_options(const MountEntry
*p
) {
303 return p
->options_malloc
?: p
->options_const
;
306 static void mount_entry_done(MountEntry
*p
) {
309 p
->path_malloc
= mfree(p
->path_malloc
);
310 p
->unprefixed_path_malloc
= mfree(p
->unprefixed_path_malloc
);
311 p
->source_malloc
= mfree(p
->source_malloc
);
312 p
->options_malloc
= mfree(p
->options_malloc
);
313 p
->image_options
= mount_options_free_all(p
->image_options
);
316 static int append_access_mounts(MountEntry
**p
, char **strv
, MountMode mode
, bool forcibly_require_prefix
) {
321 /* Adds a list of user-supplied READWRITE/READWRITE_IMPLICIT/READONLY/INACCESSIBLE entries */
323 STRV_FOREACH(i
, strv
) {
324 bool ignore
= false, needs_prefix
= false;
327 /* Look for any prefixes */
328 if (startswith(e
, "-")) {
332 if (startswith(e
, "+")) {
337 if (!path_is_absolute(e
))
338 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
339 "Path is not absolute: %s", e
);
341 *((*p
)++) = (MountEntry
) {
345 .has_prefix
= !needs_prefix
&& !forcibly_require_prefix
,
352 static int append_empty_dir_mounts(MountEntry
**p
, char **strv
) {
357 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
358 * "/private/" boundary directories for DynamicUser=1. */
360 STRV_FOREACH(i
, strv
) {
362 *((*p
)++) = (MountEntry
) {
367 .options_const
= "mode=755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
368 .flags
= MS_NOSUID
|MS_NOEXEC
|MS_NODEV
|MS_STRICTATIME
,
375 static int append_bind_mounts(MountEntry
**p
, const BindMount
*binds
, size_t n
) {
378 for (size_t i
= 0; i
< n
; i
++) {
379 const BindMount
*b
= binds
+ i
;
381 *((*p
)++) = (MountEntry
) {
382 .path_const
= b
->destination
,
383 .mode
= b
->recursive
? BIND_MOUNT_RECURSIVE
: BIND_MOUNT
,
384 .read_only
= b
->read_only
,
386 .source_const
= b
->source
,
387 .ignore
= b
->ignore_enoent
,
394 static int append_mount_images(MountEntry
**p
, const MountImage
*mount_images
, size_t n
) {
397 for (size_t i
= 0; i
< n
; i
++) {
398 const MountImage
*m
= mount_images
+ i
;
400 *((*p
)++) = (MountEntry
) {
401 .path_const
= m
->destination
,
402 .mode
= MOUNT_IMAGES
,
403 .source_const
= m
->source
,
404 .image_options
= m
->mount_options
,
405 .ignore
= m
->ignore_enoent
,
412 static int append_extensions(
415 const char *extension_dir
,
417 const MountImage
*mount_images
,
419 char **extension_directories
) {
421 _cleanup_strv_free_
char **overlays
= NULL
;
422 char **hierarchy
, **extension_directory
;
425 if (n
== 0 && strv_isempty(extension_directories
))
429 assert(extension_dir
);
431 /* Prepare a list of overlays, that will have as each element a string suitable for being
432 * passed as a lowerdir= parameter, so start with the hierarchy on the root.
433 * The overlays vector will have the same number of elements and will correspond to the
434 * hierarchies vector, so they can be iterated upon together. */
435 STRV_FOREACH(hierarchy
, hierarchies
) {
436 _cleanup_free_
char *prefixed_hierarchy
= NULL
;
438 prefixed_hierarchy
= path_join(root
, *hierarchy
);
439 if (!prefixed_hierarchy
)
442 r
= strv_consume(&overlays
, TAKE_PTR(prefixed_hierarchy
));
447 /* First, prepare a mount for each image, but these won't be visible to the unit, instead
448 * they will be mounted in our propagate directory, and used as a source for the overlay. */
449 for (size_t i
= 0; i
< n
; i
++) {
450 _cleanup_free_
char *mount_point
= NULL
;
451 const MountImage
*m
= mount_images
+ i
;
453 r
= asprintf(&mount_point
, "%s/%zu", extension_dir
, i
);
457 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
458 _cleanup_free_
char *prefixed_hierarchy
= NULL
, *escaped
= NULL
, *lowerdir
= NULL
;
460 prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
461 if (!prefixed_hierarchy
)
464 escaped
= shell_escape(prefixed_hierarchy
, ",:");
468 /* Note that lowerdir= parameters are in 'reverse' order, so the
469 * top-most directory in the overlay comes first in the list. */
470 lowerdir
= strjoin(escaped
, ":", overlays
[j
]);
474 free_and_replace(overlays
[j
], lowerdir
);
477 *((*p
)++) = (MountEntry
) {
478 .path_malloc
= TAKE_PTR(mount_point
),
479 .image_options
= m
->mount_options
,
480 .ignore
= m
->ignore_enoent
,
481 .source_const
= m
->source
,
482 .mode
= EXTENSION_IMAGES
,
487 /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
488 * Bind mount them in the same location as the ExtensionImages, so that we
489 * can check that they are valid trees (extension-release.d). */
490 STRV_FOREACH(extension_directory
, extension_directories
) {
491 _cleanup_free_
char *mount_point
= NULL
, *source
= NULL
;
492 const char *e
= *extension_directory
;
493 bool ignore_enoent
= false;
495 /* Pick up the counter where the ExtensionImages left it. */
496 r
= asprintf(&mount_point
, "%s/%zu", extension_dir
, n
++);
500 /* Look for any prefixes */
501 if (startswith(e
, "-")) {
503 ignore_enoent
= true;
505 /* Ignore this for now */
506 if (startswith(e
, "+"))
513 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
514 _cleanup_free_
char *prefixed_hierarchy
= NULL
, *escaped
= NULL
, *lowerdir
= NULL
;
516 prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
517 if (!prefixed_hierarchy
)
520 escaped
= shell_escape(prefixed_hierarchy
, ",:");
524 /* Note that lowerdir= parameters are in 'reverse' order, so the
525 * top-most directory in the overlay comes first in the list. */
526 lowerdir
= strjoin(escaped
, ":", overlays
[j
]);
530 free_and_replace(overlays
[j
], lowerdir
);
533 *((*p
)++) = (MountEntry
) {
534 .path_malloc
= TAKE_PTR(mount_point
),
535 .source_const
= TAKE_PTR(source
),
536 .mode
= EXTENSION_DIRECTORIES
,
537 .ignore
= ignore_enoent
,
543 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
545 for (size_t i
= 0; hierarchies
&& hierarchies
[i
]; ++i
) {
546 _cleanup_free_
char *prefixed_hierarchy
= NULL
;
548 prefixed_hierarchy
= path_join(root
, hierarchies
[i
]);
549 if (!prefixed_hierarchy
)
552 *((*p
)++) = (MountEntry
) {
553 .path_malloc
= TAKE_PTR(prefixed_hierarchy
),
554 .options_malloc
= TAKE_PTR(overlays
[i
]),
555 .mode
= OVERLAY_MOUNT
,
557 .ignore
= true, /* If the source image doesn't set the ignore bit it will fail earlier. */
564 static int append_tmpfs_mounts(MountEntry
**p
, const TemporaryFileSystem
*tmpfs
, size_t n
) {
567 for (size_t i
= 0; i
< n
; i
++) {
568 const TemporaryFileSystem
*t
= tmpfs
+ i
;
569 _cleanup_free_
char *o
= NULL
, *str
= NULL
;
574 if (!path_is_absolute(t
->path
))
575 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
576 "Path is not absolute: %s",
579 str
= strjoin("mode=0755" NESTED_TMPFS_LIMITS
",", t
->options
);
583 r
= mount_option_mangle(str
, MS_NODEV
|MS_STRICTATIME
, &flags
, &o
);
585 return log_debug_errno(r
, "Failed to parse mount option '%s': %m", str
);
587 ro
= flags
& MS_RDONLY
;
591 *((*p
)++) = (MountEntry
) {
592 .path_const
= t
->path
,
595 .options_malloc
= TAKE_PTR(o
),
603 static int append_static_mounts(MountEntry
**p
, const MountEntry
*mounts
, size_t n
, bool ignore_protect
) {
607 /* Adds a list of static pre-defined entries */
609 for (size_t i
= 0; i
< n
; i
++)
610 *((*p
)++) = (MountEntry
) {
611 .path_const
= mount_entry_path(mounts
+i
),
612 .mode
= mounts
[i
].mode
,
613 .ignore
= mounts
[i
].ignore
|| ignore_protect
,
619 static int append_protect_home(MountEntry
**p
, ProtectHome protect_home
, bool ignore_protect
) {
622 switch (protect_home
) {
624 case PROTECT_HOME_NO
:
627 case PROTECT_HOME_READ_ONLY
:
628 return append_static_mounts(p
, protect_home_read_only_table
, ELEMENTSOF(protect_home_read_only_table
), ignore_protect
);
630 case PROTECT_HOME_TMPFS
:
631 return append_static_mounts(p
, protect_home_tmpfs_table
, ELEMENTSOF(protect_home_tmpfs_table
), ignore_protect
);
633 case PROTECT_HOME_YES
:
634 return append_static_mounts(p
, protect_home_yes_table
, ELEMENTSOF(protect_home_yes_table
), ignore_protect
);
637 assert_not_reached();
641 static int append_protect_system(MountEntry
**p
, ProtectSystem protect_system
, bool ignore_protect
) {
644 switch (protect_system
) {
646 case PROTECT_SYSTEM_NO
:
649 case PROTECT_SYSTEM_STRICT
:
650 return append_static_mounts(p
, protect_system_strict_table
, ELEMENTSOF(protect_system_strict_table
), ignore_protect
);
652 case PROTECT_SYSTEM_YES
:
653 return append_static_mounts(p
, protect_system_yes_table
, ELEMENTSOF(protect_system_yes_table
), ignore_protect
);
655 case PROTECT_SYSTEM_FULL
:
656 return append_static_mounts(p
, protect_system_full_table
, ELEMENTSOF(protect_system_full_table
), ignore_protect
);
659 assert_not_reached();
663 static int mount_path_compare(const MountEntry
*a
, const MountEntry
*b
) {
666 /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
667 * regardless of the prefix - they are set up in the propagate directory anyway */
668 d
= -CMP(a
->mode
== EXTENSION_IMAGES
, b
->mode
== EXTENSION_IMAGES
);
671 d
= -CMP(a
->mode
== EXTENSION_DIRECTORIES
, b
->mode
== EXTENSION_DIRECTORIES
);
675 /* If the paths are not equal, then order prefixes first */
676 d
= path_compare(mount_entry_path(a
), mount_entry_path(b
));
680 /* If the paths are equal, check the mode */
681 return CMP((int) a
->mode
, (int) b
->mode
);
684 static int prefix_where_needed(MountEntry
*m
, size_t n
, const char *root_directory
) {
685 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
689 for (size_t i
= 0; i
< n
; i
++) {
695 s
= path_join(root_directory
, mount_entry_path(m
+i
));
699 mount_entry_consume_prefix(&m
[i
], s
);
705 static void drop_duplicates(MountEntry
*m
, size_t *n
) {
706 MountEntry
*f
, *t
, *previous
;
711 /* Drops duplicate entries. Expects that the array is properly ordered already. */
713 for (f
= m
, t
= m
, previous
= NULL
; f
< m
+ *n
; f
++) {
715 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
716 * above. Note that we only drop duplicates that haven't been mounted yet. */
718 path_equal(mount_entry_path(f
), mount_entry_path(previous
)) &&
719 !f
->applied
&& !previous
->applied
) {
720 log_debug("%s (%s) is duplicate.", mount_entry_path(f
), mount_mode_to_string(f
->mode
));
721 /* Propagate the flags to the remaining entry */
722 previous
->read_only
= previous
->read_only
|| mount_entry_read_only(f
);
723 previous
->noexec
= previous
->noexec
|| mount_entry_noexec(f
);
724 previous
->exec
= previous
->exec
|| mount_entry_exec(f
);
737 static void drop_inaccessible(MountEntry
*m
, size_t *n
) {
739 const char *clear
= NULL
;
744 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
745 * ordered already. */
747 for (f
= m
, t
= m
; f
< m
+ *n
; f
++) {
749 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
750 * it, as inaccessible paths really should drop the entire subtree. */
751 if (clear
&& path_startswith(mount_entry_path(f
), clear
)) {
752 log_debug("%s is masked by %s.", mount_entry_path(f
), clear
);
757 clear
= f
->mode
== INACCESSIBLE
? mount_entry_path(f
) : NULL
;
766 static void drop_nop(MountEntry
*m
, size_t *n
) {
772 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
773 * list is ordered by prefixes. */
775 for (f
= m
, t
= m
; f
< m
+ *n
; f
++) {
777 /* Only suppress such subtrees for READONLY, READWRITE and READWRITE_IMPLICIT entries */
778 if (IN_SET(f
->mode
, READONLY
, READWRITE
, READWRITE_IMPLICIT
)) {
782 /* Now let's find the first parent of the entry we are looking at. */
783 for (p
= t
-1; p
>= m
; p
--) {
784 if (path_startswith(mount_entry_path(f
), mount_entry_path(p
))) {
790 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
791 if (found
&& p
->mode
== f
->mode
) {
792 log_debug("%s (%s) is made redundant by %s (%s)",
793 mount_entry_path(f
), mount_mode_to_string(f
->mode
),
794 mount_entry_path(p
), mount_mode_to_string(p
->mode
));
807 static void drop_outside_root(const char *root_directory
, MountEntry
*m
, size_t *n
) {
817 /* Drops all mounts that are outside of the root directory. */
819 for (f
= m
, t
= m
; f
< m
+ *n
; f
++) {
821 /* ExtensionImages/Directories bases are opened in /run/systemd/unit-extensions on the host */
822 if (!IN_SET(f
->mode
, EXTENSION_IMAGES
, EXTENSION_DIRECTORIES
) && !path_startswith(mount_entry_path(f
), root_directory
)) {
823 log_debug("%s is outside of root directory.", mount_entry_path(f
));
835 static int clone_device_node(
837 const char *temporary_mount
,
838 bool *make_devnode
) {
840 _cleanup_free_
char *sl
= NULL
;
841 const char *dn
, *bn
, *t
;
845 if (stat(d
, &st
) < 0) {
846 if (errno
== ENOENT
) {
847 log_debug_errno(errno
, "Device node '%s' to clone does not exist, ignoring.", d
);
851 return log_debug_errno(errno
, "Failed to stat() device node '%s' to clone, ignoring: %m", d
);
854 if (!S_ISBLK(st
.st_mode
) &&
855 !S_ISCHR(st
.st_mode
))
856 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
857 "Device node '%s' to clone is not a device node, ignoring.",
860 dn
= strjoina(temporary_mount
, d
);
862 /* First, try to create device node properly */
864 mac_selinux_create_file_prepare(d
, st
.st_mode
);
865 r
= mknod(dn
, st
.st_mode
, st
.st_rdev
);
866 mac_selinux_create_file_clear();
870 return log_debug_errno(errno
, "mknod failed for %s: %m", d
);
872 /* This didn't work, let's not try this again for the next iterations. */
873 *make_devnode
= false;
876 /* We're about to fall back to bind-mounting the device node. So create a dummy bind-mount target.
877 * Do not prepare device-node SELinux label (see issue 13762) */
878 r
= mknod(dn
, S_IFREG
, 0);
879 if (r
< 0 && errno
!= EEXIST
)
880 return log_debug_errno(errno
, "mknod() fallback failed for '%s': %m", d
);
882 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
883 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
884 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
885 r
= mount_nofollow_verbose(LOG_DEBUG
, d
, dn
, NULL
, MS_BIND
, NULL
);
890 bn
= path_startswith(d
, "/dev/");
894 /* Create symlinks like /dev/char/1:9 → ../urandom */
895 if (asprintf(&sl
, "%s/dev/%s/%u:%u",
897 S_ISCHR(st
.st_mode
) ? "char" : "block",
898 major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
901 (void) mkdir_parents(sl
, 0755);
903 t
= strjoina("../", bn
);
904 if (symlink(t
, sl
) < 0)
905 log_debug_errno(errno
, "Failed to symlink '%s' to '%s', ignoring: %m", t
, sl
);
910 static int mount_private_dev(MountEntry
*m
) {
911 static const char devnodes
[] =
919 char temporary_mount
[] = "/tmp/namespace-dev-XXXXXX";
920 const char *d
, *dev
= NULL
, *devpts
= NULL
, *devshm
= NULL
, *devhugepages
= NULL
, *devmqueue
= NULL
, *devlog
= NULL
, *devptmx
= NULL
;
921 bool can_mknod
= true;
926 if (!mkdtemp(temporary_mount
))
927 return log_debug_errno(errno
, "Failed to create temporary directory '%s': %m", temporary_mount
);
929 dev
= strjoina(temporary_mount
, "/dev");
930 (void) mkdir(dev
, 0755);
931 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", dev
, "tmpfs", DEV_MOUNT_OPTIONS
, "mode=755" TMPFS_LIMITS_DEV
);
935 r
= label_fix_container(dev
, "/dev", 0);
937 log_debug_errno(errno
, "Failed to fix label of '%s' as /dev: %m", dev
);
941 devpts
= strjoina(temporary_mount
, "/dev/pts");
942 (void) mkdir(devpts
, 0755);
943 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/pts", devpts
, NULL
, MS_BIND
, NULL
);
947 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
948 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
949 * Thus, in that case make a clone.
950 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
951 r
= is_symlink("/dev/ptmx");
953 log_debug_errno(r
, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
956 devptmx
= strjoina(temporary_mount
, "/dev/ptmx");
957 if (symlink("pts/ptmx", devptmx
) < 0) {
958 r
= log_debug_errno(errno
, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx
);
962 r
= clone_device_node("/dev/ptmx", temporary_mount
, &can_mknod
);
967 devshm
= strjoina(temporary_mount
, "/dev/shm");
968 (void) mkdir(devshm
, 0755);
969 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/shm", devshm
, NULL
, MS_BIND
, NULL
);
973 devmqueue
= strjoina(temporary_mount
, "/dev/mqueue");
974 (void) mkdir(devmqueue
, 0755);
975 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/mqueue", devmqueue
, NULL
, MS_BIND
, NULL
);
977 devhugepages
= strjoina(temporary_mount
, "/dev/hugepages");
978 (void) mkdir(devhugepages
, 0755);
979 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/hugepages", devhugepages
, NULL
, MS_BIND
, NULL
);
981 devlog
= strjoina(temporary_mount
, "/dev/log");
982 if (symlink("/run/systemd/journal/dev-log", devlog
) < 0)
983 log_debug_errno(errno
, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog
);
985 NULSTR_FOREACH(d
, devnodes
) {
986 r
= clone_device_node(d
, temporary_mount
, &can_mknod
);
987 /* ENXIO means the *source* is not a device file, skip creation in that case */
988 if (r
< 0 && r
!= -ENXIO
)
992 r
= dev_setup(temporary_mount
, UID_INVALID
, GID_INVALID
);
994 log_debug_errno(r
, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount
);
996 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
997 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
998 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1000 /* Unmount everything in old /dev */
1001 r
= umount_recursive(mount_entry_path(m
), 0);
1003 log_debug_errno(r
, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m
));
1005 r
= mount_nofollow_verbose(LOG_DEBUG
, dev
, mount_entry_path(m
), NULL
, MS_MOVE
, NULL
);
1010 (void) rmdir(temporary_mount
);
1016 (void) umount_verbose(LOG_DEBUG
, devpts
, UMOUNT_NOFOLLOW
);
1019 (void) umount_verbose(LOG_DEBUG
, devshm
, UMOUNT_NOFOLLOW
);
1022 (void) umount_verbose(LOG_DEBUG
, devhugepages
, UMOUNT_NOFOLLOW
);
1025 (void) umount_verbose(LOG_DEBUG
, devmqueue
, UMOUNT_NOFOLLOW
);
1027 (void) umount_verbose(LOG_DEBUG
, dev
, UMOUNT_NOFOLLOW
);
1029 (void) rmdir(temporary_mount
);
1034 static int mount_bind_dev(const MountEntry
*m
) {
1039 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1040 * service's /dev. This is only used when RootDirectory= is set. */
1042 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1044 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1046 return log_debug_errno(r
, "Unable to determine whether /dev is already mounted: %m");
1047 if (r
> 0) /* make this a NOP if /dev is already a mount point */
1050 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1057 static int mount_sysfs(const MountEntry
*m
) {
1062 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1064 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1066 return log_debug_errno(r
, "Unable to determine whether /sys is already mounted: %m");
1067 if (r
> 0) /* make this a NOP if /sys is already a mount point */
1070 /* Bind mount the host's version so that we get all child mounts of it, too. */
1071 r
= mount_nofollow_verbose(LOG_DEBUG
, "/sys", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1078 static int mount_procfs(const MountEntry
*m
, const NamespaceInfo
*ns_info
) {
1079 _cleanup_free_
char *opts
= NULL
;
1080 const char *entry_path
;
1086 if (ns_info
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1087 ns_info
->proc_subset
!= PROC_SUBSET_ALL
) {
1089 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
1090 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
1091 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
1092 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
1093 * added in the same commit: if it's supported it is thus also per-instance. */
1095 opts
= strjoin("hidepid=",
1096 ns_info
->protect_proc
== PROTECT_PROC_DEFAULT
? "off" :
1097 protect_proc_to_string(ns_info
->protect_proc
),
1098 ns_info
->proc_subset
== PROC_SUBSET_PID
? ",subset=pid" : "");
1103 entry_path
= mount_entry_path(m
);
1104 (void) mkdir_p_label(entry_path
, 0755);
1106 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1107 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1108 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1109 * mounted on /proc/ first. */
1111 n
= umount_recursive(entry_path
, 0);
1113 r
= mount_nofollow_verbose(LOG_DEBUG
, "proc", entry_path
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, opts
);
1114 if (r
== -EINVAL
&& opts
)
1115 /* If this failed with EINVAL then this likely means the textual hidepid= stuff is
1116 * not supported by the kernel, and thus the per-instance hidepid= neither, which
1117 * means we really don't want to use it, since it would affect our host's /proc
1118 * mount. Hence let's gracefully fallback to a classic, unrestricted version. */
1119 r
= mount_nofollow_verbose(LOG_DEBUG
, "proc", entry_path
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, NULL
);
1121 /* When we do not have enough privileges to mount /proc, fallback to use existing /proc. */
1124 /* /proc or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1125 * Propagate the original error code returned by mount() in the above. */
1128 r
= path_is_mount_point(entry_path
, NULL
, 0);
1130 return log_debug_errno(r
, "Unable to determine whether /proc is already mounted: %m");
1132 /* We lack permissions to mount a new instance of /proc, and it is not already
1133 * mounted. But we can access the host's, so as a final fallback bind-mount it to
1134 * the destination, as most likely we are inside a user manager in an unprivileged
1135 * user namespace. */
1136 r
= mount_nofollow_verbose(LOG_DEBUG
, "/proc", entry_path
, NULL
, MS_BIND
|MS_REC
, NULL
);
1146 static int mount_tmpfs(const MountEntry
*m
) {
1147 const char *entry_path
, *inner_path
;
1152 entry_path
= mount_entry_path(m
);
1153 inner_path
= mount_entry_unprefixed_path(m
);
1155 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1158 (void) mkdir_p_label(entry_path
, 0755);
1159 (void) umount_recursive(entry_path
, 0);
1161 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", entry_path
, "tmpfs", m
->flags
, mount_entry_options(m
));
1165 r
= label_fix_container(entry_path
, inner_path
, 0);
1167 return log_debug_errno(r
, "Failed to fix label of '%s' as '%s': %m", entry_path
, inner_path
);
1172 static int mount_run(const MountEntry
*m
) {
1177 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1178 if (r
< 0 && r
!= -ENOENT
)
1179 return log_debug_errno(r
, "Unable to determine whether /run is already mounted: %m");
1180 if (r
> 0) /* make this a NOP if /run is already a mount point */
1183 return mount_tmpfs(m
);
1186 static int mount_mqueuefs(const MountEntry
*m
) {
1188 const char *entry_path
;
1192 entry_path
= mount_entry_path(m
);
1194 (void) mkdir_p_label(entry_path
, 0755);
1195 (void) umount_recursive(entry_path
, 0);
1197 r
= mount_nofollow_verbose(LOG_DEBUG
, "mqueue", entry_path
, "mqueue", m
->flags
, mount_entry_options(m
));
1204 static int mount_image(const MountEntry
*m
, const char *root_directory
) {
1206 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1207 *host_os_release_sysext_level
= NULL
;
1212 if (m
->mode
== EXTENSION_IMAGES
) {
1213 r
= parse_os_release(
1214 empty_to_root(root_directory
),
1215 "ID", &host_os_release_id
,
1216 "VERSION_ID", &host_os_release_version_id
,
1217 "SYSEXT_LEVEL", &host_os_release_sysext_level
,
1220 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1221 if (isempty(host_os_release_id
))
1222 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'ID' field not found or empty in 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1225 r
= verity_dissect_and_mount(
1226 mount_entry_source(m
), mount_entry_path(m
), m
->image_options
,
1227 host_os_release_id
, host_os_release_version_id
, host_os_release_sysext_level
, NULL
);
1228 if (r
== -ENOENT
&& m
->ignore
)
1230 if (r
== -ESTALE
&& host_os_release_id
)
1231 return log_error_errno(r
,
1232 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s",
1233 mount_entry_source(m
),
1235 host_os_release_version_id
? " VERSION_ID=" : "",
1236 strempty(host_os_release_version_id
),
1237 host_os_release_sysext_level
? " SYSEXT_LEVEL=" : "",
1238 strempty(host_os_release_sysext_level
));
1240 return log_debug_errno(r
, "Failed to mount image %s on %s: %m", mount_entry_source(m
), mount_entry_path(m
));
1245 static int mount_overlay(const MountEntry
*m
) {
1246 const char *options
;
1251 options
= strjoina("lowerdir=", mount_entry_options(m
));
1253 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1255 r
= mount_nofollow_verbose(LOG_DEBUG
, "overlay", mount_entry_path(m
), "overlay", MS_RDONLY
, options
);
1256 if (r
== -ENOENT
&& m
->ignore
)
1264 static int follow_symlink(
1265 const char *root_directory
,
1268 _cleanup_free_
char *target
= NULL
;
1271 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1272 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1273 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1274 * end and already have a fully normalized name. */
1276 r
= chase_symlinks(mount_entry_path(m
), root_directory
, CHASE_STEP
|CHASE_NONEXISTENT
, &target
, NULL
);
1278 return log_debug_errno(r
, "Failed to chase symlinks '%s': %m", mount_entry_path(m
));
1279 if (r
> 0) /* Reached the end, nothing more to resolve */
1282 if (m
->n_followed
>= CHASE_SYMLINKS_MAX
) /* put a boundary on things */
1283 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1284 "Symlink loop on '%s'.",
1285 mount_entry_path(m
));
1287 log_debug("Followed mount entry path symlink %s → %s.", mount_entry_path(m
), target
);
1289 mount_entry_consume_prefix(m
, TAKE_PTR(target
));
1296 static int apply_one_mount(
1297 const char *root_directory
,
1299 const NamespaceInfo
*ns_info
) {
1301 _cleanup_free_
char *inaccessible
= NULL
;
1302 bool rbind
= true, make
= false;
1309 log_debug("Applying namespace mount on %s", mount_entry_path(m
));
1313 case INACCESSIBLE
: {
1314 _cleanup_free_
char *tmp
= NULL
;
1315 const char *runtime_dir
;
1318 /* First, get rid of everything that is below if there
1319 * is anything... Then, overmount it with an
1320 * inaccessible path. */
1321 (void) umount_recursive(mount_entry_path(m
), 0);
1323 if (lstat(mount_entry_path(m
), &target
) < 0) {
1324 if (errno
== ENOENT
&& m
->ignore
)
1327 return log_debug_errno(errno
, "Failed to lstat() %s to determine what to mount over it: %m",
1328 mount_entry_path(m
));
1332 runtime_dir
= "/run";
1334 if (asprintf(&tmp
, "/run/user/" UID_FMT
, geteuid()) < 0)
1340 r
= mode_to_inaccessible_node(runtime_dir
, target
.st_mode
, &inaccessible
);
1342 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1343 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
1344 what
= inaccessible
;
1350 case READWRITE_IMPLICIT
:
1353 r
= path_is_mount_point(mount_entry_path(m
), root_directory
, 0);
1354 if (r
== -ENOENT
&& m
->ignore
)
1357 return log_debug_errno(r
, "Failed to determine whether %s is already a mount point: %m",
1358 mount_entry_path(m
));
1359 if (r
> 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1360 * and MS_NOEXEC bits for the mount point if needed. */
1362 /* This isn't a mount point yet, let's make it one. */
1363 what
= mount_entry_path(m
);
1366 case EXTENSION_DIRECTORIES
: {
1367 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1368 *host_os_release_sysext_level
= NULL
, *extension_name
= NULL
;
1369 _cleanup_strv_free_
char **extension_release
= NULL
;
1371 r
= path_extract_filename(mount_entry_source(m
), &extension_name
);
1373 return log_debug_errno(r
, "Failed to extract extension name from %s: %m", mount_entry_source(m
));
1375 r
= parse_os_release(
1376 empty_to_root(root_directory
),
1377 "ID", &host_os_release_id
,
1378 "VERSION_ID", &host_os_release_version_id
,
1379 "SYSEXT_LEVEL", &host_os_release_sysext_level
,
1382 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1383 if (isempty(host_os_release_id
))
1384 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'ID' field not found or empty in 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1386 r
= load_extension_release_pairs(mount_entry_source(m
), extension_name
, &extension_release
);
1387 if (r
== -ENOENT
&& m
->ignore
)
1390 return log_debug_errno(r
, "Failed to parse directory %s extension-release metadata: %m", extension_name
);
1392 r
= extension_release_validate(
1395 host_os_release_version_id
,
1396 host_os_release_sysext_level
,
1397 /* host_sysext_scope */ NULL
, /* Leave empty, we need to accept both system and portable */
1400 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Directory %s extension-release metadata does not match the root's", extension_name
);
1402 return log_debug_errno(r
, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name
);
1411 case BIND_MOUNT_RECURSIVE
: {
1412 _cleanup_free_
char *chased
= NULL
;
1414 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1415 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1416 * root directory to chase_symlinks() here. */
1418 r
= chase_symlinks(mount_entry_source(m
), NULL
, CHASE_TRAIL_SLASH
, &chased
, NULL
);
1419 if (r
== -ENOENT
&& m
->ignore
) {
1420 log_debug_errno(r
, "Path %s does not exist, ignoring.", mount_entry_source(m
));
1424 return log_debug_errno(r
, "Failed to follow symlinks on %s: %m", mount_entry_source(m
));
1426 log_debug("Followed source symlinks %s → %s.", mount_entry_source(m
), chased
);
1428 free_and_replace(m
->source_malloc
, chased
);
1430 what
= mount_entry_source(m
);
1437 return mount_tmpfs(m
);
1440 case PRIVATE_TMP_READONLY
:
1441 what
= mount_entry_source(m
);
1446 return mount_private_dev(m
);
1449 return mount_bind_dev(m
);
1452 return mount_sysfs(m
);
1455 return mount_procfs(m
, ns_info
);
1458 return mount_run(m
);
1461 return mount_mqueuefs(m
);
1464 return mount_image(m
, NULL
);
1466 case EXTENSION_IMAGES
:
1467 return mount_image(m
, root_directory
);
1470 return mount_overlay(m
);
1473 assert_not_reached();
1478 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1480 bool try_again
= false;
1482 if (r
== -ENOENT
&& make
) {
1485 /* Hmm, either the source or the destination are missing. Let's see if we can create
1486 the destination, then try again. */
1488 (void) mkdir_parents(mount_entry_path(m
), 0755);
1490 q
= make_mount_point_inode_from_path(what
, mount_entry_path(m
), 0755);
1491 if (q
< 0 && q
!= -EEXIST
)
1492 log_error_errno(q
, "Failed to create destination mount point node '%s': %m",
1493 mount_entry_path(m
));
1499 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1501 return log_error_errno(r
, "Failed to mount %s to %s: %m", what
, mount_entry_path(m
));
1504 log_debug("Successfully mounted %s to %s", what
, mount_entry_path(m
));
1508 static int make_read_only(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1509 unsigned long new_flags
= 0, flags_mask
= 0;
1514 assert(proc_self_mountinfo
);
1516 if (mount_entry_read_only(m
) || m
->mode
== PRIVATE_DEV
) {
1517 new_flags
|= MS_RDONLY
;
1518 flags_mask
|= MS_RDONLY
;
1522 new_flags
|= MS_NOSUID
;
1523 flags_mask
|= MS_NOSUID
;
1526 if (flags_mask
== 0) /* No Change? */
1529 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1530 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1531 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1532 * and running Linux <= 4.17. */
1534 mount_entry_read_only(m
) &&
1535 !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1537 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1539 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1541 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
1542 * read-only already stays this way. This improves compatibility with container managers, where we
1543 * won't attempt to undo read-only mounts already applied. */
1545 if (r
== -ENOENT
&& m
->ignore
)
1548 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1549 submounts
? " and its submounts" : "");
1553 static int make_noexec(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1554 unsigned long new_flags
= 0, flags_mask
= 0;
1559 assert(proc_self_mountinfo
);
1561 if (mount_entry_noexec(m
)) {
1562 new_flags
|= MS_NOEXEC
;
1563 flags_mask
|= MS_NOEXEC
;
1564 } else if (mount_entry_exec(m
)) {
1565 new_flags
&= ~MS_NOEXEC
;
1566 flags_mask
|= MS_NOEXEC
;
1569 if (flags_mask
== 0) /* No Change? */
1572 submounts
= !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1575 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1577 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1579 if (r
== -ENOENT
&& m
->ignore
)
1582 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1583 submounts
? " and its submounts" : "");
1587 static int make_nosuid(const MountEntry
*m
, FILE *proc_self_mountinfo
) {
1592 assert(proc_self_mountinfo
);
1594 submounts
= !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1597 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, NULL
, proc_self_mountinfo
);
1599 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, proc_self_mountinfo
);
1600 if (r
== -ENOENT
&& m
->ignore
)
1603 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1604 submounts
? " and its submounts" : "");
1608 static bool namespace_info_mount_apivfs(const NamespaceInfo
*ns_info
) {
1612 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1613 * since to protect the API VFS mounts, they need to be around in the
1617 return ns_info
->mount_apivfs
||
1618 ns_info
->protect_control_groups
||
1619 ns_info
->protect_kernel_tunables
||
1620 ns_info
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1621 ns_info
->proc_subset
!= PROC_SUBSET_ALL
;
1624 static size_t namespace_calculate_mounts(
1625 const NamespaceInfo
*ns_info
,
1626 char** read_write_paths
,
1627 char** read_only_paths
,
1628 char** inaccessible_paths
,
1630 char** no_exec_paths
,
1631 char** empty_directories
,
1632 size_t n_bind_mounts
,
1633 size_t n_temporary_filesystems
,
1634 size_t n_mount_images
,
1635 size_t n_extension_images
,
1636 size_t n_extension_directories
,
1637 size_t n_hierarchies
,
1638 const char* tmp_dir
,
1639 const char* var_tmp_dir
,
1640 const char *creds_path
,
1641 const char* log_namespace
,
1642 bool setup_propagate
,
1643 const char* notify_socket
) {
1645 size_t protect_home_cnt
;
1646 size_t protect_system_cnt
=
1647 (ns_info
->protect_system
== PROTECT_SYSTEM_STRICT
?
1648 ELEMENTSOF(protect_system_strict_table
) :
1649 ((ns_info
->protect_system
== PROTECT_SYSTEM_FULL
) ?
1650 ELEMENTSOF(protect_system_full_table
) :
1651 ((ns_info
->protect_system
== PROTECT_SYSTEM_YES
) ?
1652 ELEMENTSOF(protect_system_yes_table
) : 0)));
1655 (ns_info
->protect_home
== PROTECT_HOME_YES
?
1656 ELEMENTSOF(protect_home_yes_table
) :
1657 ((ns_info
->protect_home
== PROTECT_HOME_READ_ONLY
) ?
1658 ELEMENTSOF(protect_home_read_only_table
) :
1659 ((ns_info
->protect_home
== PROTECT_HOME_TMPFS
) ?
1660 ELEMENTSOF(protect_home_tmpfs_table
) : 0)));
1662 return !!tmp_dir
+ !!var_tmp_dir
+
1663 strv_length(read_write_paths
) +
1664 strv_length(read_only_paths
) +
1665 strv_length(inaccessible_paths
) +
1666 strv_length(exec_paths
) +
1667 strv_length(no_exec_paths
) +
1668 strv_length(empty_directories
) +
1671 (n_extension_images
> 0 || n_extension_directories
> 0 ? /* Mount each image and directory plus an overlay per hierarchy */
1672 n_hierarchies
+ n_extension_images
+ n_extension_directories
: 0) +
1673 n_temporary_filesystems
+
1674 ns_info
->private_dev
+
1675 (ns_info
->protect_kernel_tunables
?
1676 ELEMENTSOF(protect_kernel_tunables_proc_table
) + ELEMENTSOF(protect_kernel_tunables_sys_table
) : 0) +
1677 (ns_info
->protect_kernel_modules
? ELEMENTSOF(protect_kernel_modules_table
) : 0) +
1678 (ns_info
->protect_kernel_logs
?
1679 ELEMENTSOF(protect_kernel_logs_proc_table
) + ELEMENTSOF(protect_kernel_logs_dev_table
) : 0) +
1680 (ns_info
->protect_control_groups
? 1 : 0) +
1681 protect_home_cnt
+ protect_system_cnt
+
1682 (ns_info
->protect_hostname
? 2 : 0) +
1683 (namespace_info_mount_apivfs(ns_info
) ? ELEMENTSOF(apivfs_table
) : 0) +
1684 (creds_path
? 2 : 1) +
1686 setup_propagate
+ /* /run/systemd/incoming */
1688 ns_info
->private_ipc
; /* /dev/mqueue */
1691 /* Walk all mount entries and dropping any unused mounts. This affects all
1693 * - that are implicitly protected by a path that has been rendered inaccessible
1694 * - whose immediate parent requests the same protection mode as the mount itself
1695 * - that are outside of the relevant root directory
1696 * - which are duplicates
1698 static void drop_unused_mounts(const char *root_directory
, MountEntry
*mounts
, size_t *n_mounts
) {
1699 assert(root_directory
);
1701 assert(mounts
|| *n_mounts
== 0);
1703 typesafe_qsort(mounts
, *n_mounts
, mount_path_compare
);
1705 drop_duplicates(mounts
, n_mounts
);
1706 drop_outside_root(root_directory
, mounts
, n_mounts
);
1707 drop_inaccessible(mounts
, n_mounts
);
1708 drop_nop(mounts
, n_mounts
);
1711 static int create_symlinks_from_tuples(const char *root
, char **strv_symlinks
) {
1715 STRV_FOREACH_PAIR(src
, dst
, strv_symlinks
) {
1716 _cleanup_free_
char *src_abs
= NULL
, *dst_abs
= NULL
;
1718 src_abs
= path_join(root
, *src
);
1719 dst_abs
= path_join(root
, *dst
);
1720 if (!src_abs
|| !dst_abs
)
1723 r
= mkdir_parents_label(dst_abs
, 0755);
1727 r
= symlink_idempotent(src_abs
, dst_abs
, true);
1735 static int apply_mounts(
1737 const NamespaceInfo
*ns_info
,
1740 char **exec_dir_symlinks
,
1741 char **error_path
) {
1743 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
1744 _cleanup_free_
char **deny_list
= NULL
;
1747 if (n_mounts
== 0) /* Shortcut: nothing to do */
1754 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1755 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
1756 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
1757 if (!proc_self_mountinfo
) {
1761 *error_path
= strdup("/proc/self/mountinfo");
1763 return log_debug_errno(r
, "Failed to open /proc/self/mountinfo: %m");
1766 /* First round, establish all mounts we need */
1770 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1775 /* ExtensionImages/Directories are first opened in the propagate directory, not in the root_directory */
1776 r
= follow_symlink(!IN_SET(m
->mode
, EXTENSION_IMAGES
, EXTENSION_DIRECTORIES
) ? root
: NULL
, m
);
1778 if (error_path
&& mount_entry_path(m
))
1779 *error_path
= strdup(mount_entry_path(m
));
1783 /* We hit a symlinked mount point. The entry got rewritten and might
1784 * point to a very different place now. Let's normalize the changed
1785 * list, and start from the beginning. After all to mount the entry
1786 * at the new location we might need some other mounts first */
1791 r
= apply_one_mount(root
, m
, ns_info
);
1793 if (error_path
&& mount_entry_path(m
))
1794 *error_path
= strdup(mount_entry_path(m
));
1804 drop_unused_mounts(root
, mounts
, n_mounts
);
1807 /* Now that all filesystems have been set up, but before the
1808 * read-only switches are flipped, create the exec dirs symlinks.
1809 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
1810 * exist, which means this will be a no-op. */
1811 r
= create_symlinks_from_tuples(root
, exec_dir_symlinks
);
1813 return log_debug_errno(r
, "Failed to set up ExecDirectories symlinks inside mount namespace: %m");
1815 /* Create a deny list we can pass to bind_mount_recursive() */
1816 deny_list
= new(char*, (*n_mounts
)+1);
1819 for (size_t j
= 0; j
< *n_mounts
; j
++)
1820 deny_list
[j
] = (char*) mount_entry_path(mounts
+j
);
1821 deny_list
[*n_mounts
] = NULL
;
1823 /* Second round, flip the ro bits if necessary. */
1824 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1825 r
= make_read_only(m
, deny_list
, proc_self_mountinfo
);
1827 if (error_path
&& mount_entry_path(m
))
1828 *error_path
= strdup(mount_entry_path(m
));
1833 /* Third round, flip the noexec bits with a simplified deny list. */
1834 for (size_t j
= 0; j
< *n_mounts
; j
++)
1835 if (IN_SET((mounts
+j
)->mode
, EXEC
, NOEXEC
))
1836 deny_list
[j
] = (char*) mount_entry_path(mounts
+j
);
1837 deny_list
[*n_mounts
] = NULL
;
1839 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1840 r
= make_noexec(m
, deny_list
, proc_self_mountinfo
);
1842 if (error_path
&& mount_entry_path(m
))
1843 *error_path
= strdup(mount_entry_path(m
));
1848 /* Fourth round, flip the nosuid bits without a deny list. */
1849 if (ns_info
->mount_nosuid
)
1850 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1851 r
= make_nosuid(m
, proc_self_mountinfo
);
1853 if (error_path
&& mount_entry_path(m
))
1854 *error_path
= strdup(mount_entry_path(m
));
1862 static bool root_read_only(
1863 char **read_only_paths
,
1864 ProtectSystem protect_system
) {
1866 /* Determine whether the root directory is going to be read-only given the configured settings. */
1868 if (protect_system
== PROTECT_SYSTEM_STRICT
)
1871 if (prefixed_path_strv_contains(read_only_paths
, "/"))
1877 static bool home_read_only(
1878 char** read_only_paths
,
1879 char** inaccessible_paths
,
1880 char** empty_directories
,
1881 const BindMount
*bind_mounts
,
1882 size_t n_bind_mounts
,
1883 const TemporaryFileSystem
*temporary_filesystems
,
1884 size_t n_temporary_filesystems
,
1885 ProtectHome protect_home
) {
1887 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
1888 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
1891 if (protect_home
!= PROTECT_HOME_NO
)
1894 if (prefixed_path_strv_contains(read_only_paths
, "/home") ||
1895 prefixed_path_strv_contains(inaccessible_paths
, "/home") ||
1896 prefixed_path_strv_contains(empty_directories
, "/home"))
1899 for (size_t i
= 0; i
< n_temporary_filesystems
; i
++)
1900 if (path_equal(temporary_filesystems
[i
].path
, "/home"))
1903 /* If /home is overmounted with some dir from the host it's not writable. */
1904 for (size_t i
= 0; i
< n_bind_mounts
; i
++)
1905 if (path_equal(bind_mounts
[i
].destination
, "/home"))
1911 static int verity_settings_prepare(
1912 VeritySettings
*verity
,
1913 const char *root_image
,
1914 const void *root_hash
,
1915 size_t root_hash_size
,
1916 const char *root_hash_path
,
1917 const void *root_hash_sig
,
1918 size_t root_hash_sig_size
,
1919 const char *root_hash_sig_path
,
1920 const char *verity_data_path
) {
1929 d
= memdup(root_hash
, root_hash_size
);
1933 free_and_replace(verity
->root_hash
, d
);
1934 verity
->root_hash_size
= root_hash_size
;
1935 verity
->designator
= PARTITION_ROOT
;
1938 if (root_hash_sig
) {
1941 d
= memdup(root_hash_sig
, root_hash_sig_size
);
1945 free_and_replace(verity
->root_hash_sig
, d
);
1946 verity
->root_hash_sig_size
= root_hash_sig_size
;
1947 verity
->designator
= PARTITION_ROOT
;
1950 if (verity_data_path
) {
1951 r
= free_and_strdup(&verity
->data_path
, verity_data_path
);
1956 r
= verity_settings_load(
1960 root_hash_sig_path
);
1962 return log_debug_errno(r
, "Failed to load root hash: %m");
1967 int setup_namespace(
1968 const char* root_directory
,
1969 const char* root_image
,
1970 const MountOptions
*root_image_options
,
1971 const NamespaceInfo
*ns_info
,
1972 char** read_write_paths
,
1973 char** read_only_paths
,
1974 char** inaccessible_paths
,
1976 char** no_exec_paths
,
1977 char** empty_directories
,
1978 char** exec_dir_symlinks
,
1979 const BindMount
*bind_mounts
,
1980 size_t n_bind_mounts
,
1981 const TemporaryFileSystem
*temporary_filesystems
,
1982 size_t n_temporary_filesystems
,
1983 const MountImage
*mount_images
,
1984 size_t n_mount_images
,
1985 const char* tmp_dir
,
1986 const char* var_tmp_dir
,
1987 const char *creds_path
,
1988 const char *log_namespace
,
1989 unsigned long mount_flags
,
1990 const void *root_hash
,
1991 size_t root_hash_size
,
1992 const char *root_hash_path
,
1993 const void *root_hash_sig
,
1994 size_t root_hash_sig_size
,
1995 const char *root_hash_sig_path
,
1996 const char *verity_data_path
,
1997 const MountImage
*extension_images
,
1998 size_t n_extension_images
,
1999 char **extension_directories
,
2000 const char *propagate_dir
,
2001 const char *incoming_dir
,
2002 const char *extension_dir
,
2003 const char *notify_socket
,
2004 char **error_path
) {
2006 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2007 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
2008 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2009 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
2010 _cleanup_strv_free_
char **hierarchies
= NULL
;
2011 MountEntry
*m
= NULL
, *mounts
= NULL
;
2012 bool require_prefix
= false, setup_propagate
= false;
2014 DissectImageFlags dissect_image_flags
=
2015 DISSECT_IMAGE_GENERIC_ROOT
|
2016 DISSECT_IMAGE_REQUIRE_ROOT
|
2017 DISSECT_IMAGE_DISCARD_ON_LOOP
|
2018 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2019 DISSECT_IMAGE_FSCK
|
2020 DISSECT_IMAGE_USR_NO_ROOT
|
2021 DISSECT_IMAGE_GROWFS
;
2027 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2028 * we configure take effect */
2029 BLOCK_WITH_UMASK(0000);
2031 if (!isempty(propagate_dir
) && !isempty(incoming_dir
))
2032 setup_propagate
= true;
2034 if (mount_flags
== 0)
2035 mount_flags
= MS_SHARED
;
2038 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2039 if (root_read_only(read_only_paths
,
2040 ns_info
->protect_system
) &&
2041 home_read_only(read_only_paths
, inaccessible_paths
, empty_directories
,
2042 bind_mounts
, n_bind_mounts
, temporary_filesystems
, n_temporary_filesystems
,
2043 ns_info
->protect_home
) &&
2044 strv_isempty(read_write_paths
))
2045 dissect_image_flags
|= DISSECT_IMAGE_READ_ONLY
;
2047 r
= verity_settings_prepare(
2050 root_hash
, root_hash_size
, root_hash_path
,
2051 root_hash_sig
, root_hash_sig_size
, root_hash_sig_path
,
2056 SET_FLAG(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
, verity
.data_path
);
2058 r
= loop_device_make_by_path(
2060 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: -1 /* < 0 means writable if possible, read-only as fallback */,
2061 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
2064 return log_debug_errno(r
, "Failed to create loop device for root image: %m");
2070 loop_device
->diskseq
,
2071 loop_device
->uevent_seqnum_not_before
,
2072 loop_device
->timestamp_not_before
,
2073 dissect_image_flags
,
2076 return log_debug_errno(r
, "Failed to dissect image: %m");
2078 r
= dissected_image_load_verity_sig_partition(
2085 r
= dissected_image_decrypt(
2089 dissect_image_flags
,
2092 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
2096 root
= root_directory
;
2098 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2099 * when running tests (test-execute), it might not have been created yet so let's make sure
2100 * we create it if it doesn't already exist. */
2101 (void) mkdir_p_label("/run/systemd", 0755);
2103 /* Always create the mount namespace in a temporary directory, instead of operating directly
2104 * in the root. The temporary directory prevents any mounts from being potentially obscured
2105 * my other mounts we already applied. We use the same mount point for all images, which is
2106 * safe, since they all live in their own namespaces after all, and hence won't see each
2109 root
= "/run/systemd/unit-root";
2110 (void) mkdir_label(root
, 0700);
2111 require_prefix
= true;
2114 if (n_extension_images
> 0 || !strv_isempty(extension_directories
)) {
2115 r
= parse_env_extension_hierarchies(&hierarchies
);
2120 n_mounts
= namespace_calculate_mounts(
2129 n_temporary_filesystems
,
2132 strv_length(extension_directories
),
2133 strv_length(hierarchies
),
2134 tmp_dir
, var_tmp_dir
,
2141 m
= mounts
= new0(MountEntry
, n_mounts
);
2145 r
= append_access_mounts(&m
, read_write_paths
, READWRITE
, require_prefix
);
2149 r
= append_access_mounts(&m
, read_only_paths
, READONLY
, require_prefix
);
2153 r
= append_access_mounts(&m
, inaccessible_paths
, INACCESSIBLE
, require_prefix
);
2157 r
= append_access_mounts(&m
, exec_paths
, EXEC
, require_prefix
);
2161 r
= append_access_mounts(&m
, no_exec_paths
, NOEXEC
, require_prefix
);
2165 r
= append_empty_dir_mounts(&m
, empty_directories
);
2169 r
= append_bind_mounts(&m
, bind_mounts
, n_bind_mounts
);
2173 r
= append_tmpfs_mounts(&m
, temporary_filesystems
, n_temporary_filesystems
);
2178 bool ro
= streq(tmp_dir
, RUN_SYSTEMD_EMPTY
);
2180 *(m
++) = (MountEntry
) {
2181 .path_const
= "/tmp",
2182 .mode
= ro
? PRIVATE_TMP_READONLY
: PRIVATE_TMP
,
2183 .source_const
= tmp_dir
,
2188 bool ro
= streq(var_tmp_dir
, RUN_SYSTEMD_EMPTY
);
2190 *(m
++) = (MountEntry
) {
2191 .path_const
= "/var/tmp",
2192 .mode
= ro
? PRIVATE_TMP_READONLY
: PRIVATE_TMP
,
2193 .source_const
= var_tmp_dir
,
2197 r
= append_mount_images(&m
, mount_images
, n_mount_images
);
2201 r
= append_extensions(&m
, root
, extension_dir
, hierarchies
, extension_images
, n_extension_images
, extension_directories
);
2205 if (ns_info
->private_dev
)
2206 *(m
++) = (MountEntry
) {
2207 .path_const
= "/dev",
2208 .mode
= PRIVATE_DEV
,
2209 .flags
= DEV_MOUNT_OPTIONS
,
2212 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the
2213 protective mounts to non-pid /proc paths would fail. But the pid only option may have
2214 failed gracefully, so let's try the mounts but it's not fatal if they don't succeed. */
2215 bool ignore_protect_proc
= ns_info
->ignore_protect_paths
|| ns_info
->proc_subset
== PROC_SUBSET_PID
;
2216 if (ns_info
->protect_kernel_tunables
) {
2217 r
= append_static_mounts(&m
,
2218 protect_kernel_tunables_proc_table
,
2219 ELEMENTSOF(protect_kernel_tunables_proc_table
),
2220 ignore_protect_proc
);
2224 r
= append_static_mounts(&m
,
2225 protect_kernel_tunables_sys_table
,
2226 ELEMENTSOF(protect_kernel_tunables_sys_table
),
2227 ns_info
->ignore_protect_paths
);
2232 if (ns_info
->protect_kernel_modules
) {
2233 r
= append_static_mounts(&m
,
2234 protect_kernel_modules_table
,
2235 ELEMENTSOF(protect_kernel_modules_table
),
2236 ns_info
->ignore_protect_paths
);
2241 if (ns_info
->protect_kernel_logs
) {
2242 r
= append_static_mounts(&m
,
2243 protect_kernel_logs_proc_table
,
2244 ELEMENTSOF(protect_kernel_logs_proc_table
),
2245 ignore_protect_proc
);
2249 r
= append_static_mounts(&m
,
2250 protect_kernel_logs_dev_table
,
2251 ELEMENTSOF(protect_kernel_logs_dev_table
),
2252 ns_info
->ignore_protect_paths
);
2257 if (ns_info
->protect_control_groups
)
2258 *(m
++) = (MountEntry
) {
2259 .path_const
= "/sys/fs/cgroup",
2263 r
= append_protect_home(&m
, ns_info
->protect_home
, ns_info
->ignore_protect_paths
);
2267 r
= append_protect_system(&m
, ns_info
->protect_system
, false);
2271 if (namespace_info_mount_apivfs(ns_info
)) {
2272 r
= append_static_mounts(&m
,
2274 ELEMENTSOF(apivfs_table
),
2275 ns_info
->ignore_protect_paths
);
2280 /* Note, if proc is mounted with subset=pid then neither of the
2281 * two paths will exist, i.e. they are implicitly protected by
2282 * the mount option. */
2283 if (ns_info
->protect_hostname
) {
2284 *(m
++) = (MountEntry
) {
2285 .path_const
= "/proc/sys/kernel/hostname",
2287 .ignore
= ignore_protect_proc
,
2289 *(m
++) = (MountEntry
) {
2290 .path_const
= "/proc/sys/kernel/domainname",
2292 .ignore
= ignore_protect_proc
,
2296 if (ns_info
->private_ipc
)
2297 *(m
++) = (MountEntry
) {
2298 .path_const
= "/dev/mqueue",
2300 .flags
= MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
2304 /* If our service has a credentials store configured, then bind that one in, but hide
2305 * everything else. */
2307 *(m
++) = (MountEntry
) {
2308 .path_const
= "/run/credentials",
2311 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
2312 .flags
= MS_NODEV
|MS_STRICTATIME
|MS_NOSUID
|MS_NOEXEC
,
2315 *(m
++) = (MountEntry
) {
2316 .path_const
= creds_path
,
2319 .source_const
= creds_path
,
2322 /* If our service has no credentials store configured, then make the whole
2323 * credentials tree inaccessible wholesale. */
2325 *(m
++) = (MountEntry
) {
2326 .path_const
= "/run/credentials",
2327 .mode
= INACCESSIBLE
,
2332 if (log_namespace
) {
2333 _cleanup_free_
char *q
= NULL
;
2335 q
= strjoin("/run/systemd/journal.", log_namespace
);
2341 *(m
++) = (MountEntry
) {
2342 .path_const
= "/run/systemd/journal",
2343 .mode
= BIND_MOUNT_RECURSIVE
,
2345 .source_malloc
= TAKE_PTR(q
),
2349 /* Will be used to add bind mounts at runtime */
2350 if (setup_propagate
)
2351 *(m
++) = (MountEntry
) {
2352 .source_const
= propagate_dir
,
2353 .path_const
= incoming_dir
,
2359 *(m
++) = (MountEntry
) {
2360 .path_const
= notify_socket
,
2361 .source_const
= notify_socket
,
2366 assert(mounts
+ n_mounts
== m
);
2368 /* Prepend the root directory where that's necessary */
2369 r
= prefix_where_needed(mounts
, n_mounts
, root
);
2373 drop_unused_mounts(root
, mounts
, &n_mounts
);
2376 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
2378 if (unshare(CLONE_NEWNS
) < 0) {
2379 r
= log_debug_errno(errno
, "Failed to unshare the mount namespace: %m");
2380 if (IN_SET(r
, -EACCES
, -EPERM
, -EOPNOTSUPP
, -ENOSYS
))
2381 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
2382 * in place that doesn't allow us to create namespaces (or a missing cap), then
2383 * propagate a recognizable error back, which the caller can use to detect this case
2384 * (and only this) and optionally continue without namespacing applied. */
2390 /* Create the source directory to allow runtime propagation of mounts */
2391 if (setup_propagate
)
2392 (void) mkdir_p(propagate_dir
, 0600);
2394 if (n_extension_images
> 0 || !strv_isempty(extension_directories
))
2395 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
2396 * mounts to create, so have the parent ready */
2397 (void) mkdir_p(extension_dir
, 0600);
2399 /* Remount / as SLAVE so that nothing now mounted in the namespace
2400 * shows up in the parent */
2401 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
) < 0) {
2402 r
= log_debug_errno(errno
, "Failed to remount '/' as SLAVE: %m");
2407 /* A root image is specified, mount it to the right place */
2408 r
= dissected_image_mount(dissected_image
, root
, UID_INVALID
, UID_INVALID
, dissect_image_flags
);
2410 log_debug_errno(r
, "Failed to mount root image: %m");
2414 if (decrypted_image
) {
2415 r
= decrypted_image_relinquish(decrypted_image
);
2417 log_debug_errno(r
, "Failed to relinquish decrypted image: %m");
2422 loop_device_relinquish(loop_device
);
2424 } else if (root_directory
) {
2426 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
2427 r
= path_is_mount_point(root
, NULL
, AT_SYMLINK_FOLLOW
);
2429 log_debug_errno(r
, "Failed to detect that %s is a mount point or not: %m", root
);
2433 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2439 /* Let's mount the main root directory to the root directory to use */
2440 r
= mount_nofollow_verbose(LOG_DEBUG
, "/", root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2445 /* Try to set up the new root directory before mounting anything else there. */
2446 if (root_image
|| root_directory
)
2447 (void) base_filesystem_create(root
, UID_INVALID
, GID_INVALID
);
2449 /* Now make the magic happen */
2450 r
= apply_mounts(root
, ns_info
, mounts
, &n_mounts
, exec_dir_symlinks
, error_path
);
2454 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
2455 r
= mount_move_root(root
);
2456 if (r
== -EINVAL
&& root_directory
) {
2457 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
2458 * namespace) and the root_directory is already a mount point in the parent namespace,
2459 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
2460 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
2461 * mount point) and try again. */
2462 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2465 r
= mount_move_root(root
);
2468 log_debug_errno(r
, "Failed to mount root with MS_MOVE: %m");
2472 /* Remount / as the desired mode. Note that this will not
2473 * reestablish propagation from our side to the host, since
2474 * what's disconnected is disconnected. */
2475 if (mount(NULL
, "/", NULL
, mount_flags
| MS_REC
, NULL
) < 0) {
2476 r
= log_debug_errno(errno
, "Failed to remount '/' with desired mount flags: %m");
2480 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only
2481 * supported for non-shared mounts. This needs to happen after remounting / or it will fail. */
2482 if (setup_propagate
) {
2483 r
= mount(NULL
, incoming_dir
, NULL
, MS_SLAVE
, NULL
);
2485 log_error_errno(r
, "Failed to remount %s with MS_SLAVE: %m", incoming_dir
);
2494 for (m
= mounts
; m
< mounts
+ n_mounts
; m
++)
2495 mount_entry_done(m
);
2502 void bind_mount_free_many(BindMount
*b
, size_t n
) {
2503 assert(b
|| n
== 0);
2505 for (size_t i
= 0; i
< n
; i
++) {
2507 free(b
[i
].destination
);
2513 int bind_mount_add(BindMount
**b
, size_t *n
, const BindMount
*item
) {
2514 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2521 s
= strdup(item
->source
);
2525 d
= strdup(item
->destination
);
2529 c
= reallocarray(*b
, *n
+ 1, sizeof(BindMount
));
2535 c
[(*n
) ++] = (BindMount
) {
2536 .source
= TAKE_PTR(s
),
2537 .destination
= TAKE_PTR(d
),
2538 .read_only
= item
->read_only
,
2539 .nosuid
= item
->nosuid
,
2540 .recursive
= item
->recursive
,
2541 .ignore_enoent
= item
->ignore_enoent
,
2547 MountImage
* mount_image_free_many(MountImage
*m
, size_t *n
) {
2549 assert(m
|| *n
== 0);
2551 for (size_t i
= 0; i
< *n
; i
++) {
2553 free(m
[i
].destination
);
2554 mount_options_free_all(m
[i
].mount_options
);
2562 int mount_image_add(MountImage
**m
, size_t *n
, const MountImage
*item
) {
2563 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2564 _cleanup_(mount_options_free_allp
) MountOptions
*options
= NULL
;
2572 s
= strdup(item
->source
);
2576 if (item
->destination
) {
2577 d
= strdup(item
->destination
);
2582 LIST_FOREACH(mount_options
, i
, item
->mount_options
) {
2583 _cleanup_(mount_options_free_allp
) MountOptions
*o
= NULL
;
2585 o
= new(MountOptions
, 1);
2589 *o
= (MountOptions
) {
2590 .partition_designator
= i
->partition_designator
,
2591 .options
= strdup(i
->options
),
2596 LIST_APPEND(mount_options
, options
, TAKE_PTR(o
));
2599 c
= reallocarray(*m
, *n
+ 1, sizeof(MountImage
));
2605 c
[(*n
) ++] = (MountImage
) {
2606 .source
= TAKE_PTR(s
),
2607 .destination
= TAKE_PTR(d
),
2608 .mount_options
= TAKE_PTR(options
),
2609 .ignore_enoent
= item
->ignore_enoent
,
2616 void temporary_filesystem_free_many(TemporaryFileSystem
*t
, size_t n
) {
2617 assert(t
|| n
== 0);
2619 for (size_t i
= 0; i
< n
; i
++) {
2627 int temporary_filesystem_add(
2628 TemporaryFileSystem
**t
,
2631 const char *options
) {
2633 _cleanup_free_
char *p
= NULL
, *o
= NULL
;
2634 TemporaryFileSystem
*c
;
2644 if (!isempty(options
)) {
2645 o
= strdup(options
);
2650 c
= reallocarray(*t
, *n
+ 1, sizeof(TemporaryFileSystem
));
2656 c
[(*n
) ++] = (TemporaryFileSystem
) {
2657 .path
= TAKE_PTR(p
),
2658 .options
= TAKE_PTR(o
),
2664 static int make_tmp_prefix(const char *prefix
) {
2665 _cleanup_free_
char *t
= NULL
;
2666 _cleanup_close_
int fd
= -1;
2669 /* Don't do anything unless we know the dir is actually missing */
2670 r
= access(prefix
, F_OK
);
2673 if (errno
!= ENOENT
)
2677 r
= mkdir_parents(prefix
, 0755);
2681 r
= tempfn_random(prefix
, NULL
, &t
);
2685 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2686 * the suid bit, below. */
2687 fd
= open_mkdir_at(AT_FDCWD
, t
, O_EXCL
|O_CLOEXEC
, 0777);
2691 r
= RET_NERRNO(fchmod(fd
, 01777));
2697 r
= RET_NERRNO(rename(t
, prefix
));
2700 return r
== -EEXIST
? 0 : r
; /* it's fine if someone else created the dir by now */
2707 static int setup_one_tmp_dir(const char *id
, const char *prefix
, char **path
, char **tmp_path
) {
2708 _cleanup_free_
char *x
= NULL
;
2709 _cleanup_free_
char *y
= NULL
;
2718 /* We include the boot id in the directory so that after a
2719 * reboot we can easily identify obsolete directories. */
2721 r
= sd_id128_get_boot(&boot_id
);
2725 x
= strjoin(prefix
, "/systemd-private-", SD_ID128_TO_STRING(boot_id
), "-", id
, "-XXXXXX");
2729 r
= make_tmp_prefix(prefix
);
2733 RUN_WITH_UMASK(0077)
2735 if (errno
== EROFS
|| ERRNO_IS_DISK_SPACE(errno
))
2742 y
= strjoin(x
, "/tmp");
2746 RUN_WITH_UMASK(0000)
2747 if (mkdir(y
, 0777 | S_ISVTX
) < 0)
2750 r
= label_fix_container(y
, prefix
, 0);
2755 *tmp_path
= TAKE_PTR(y
);
2757 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2758 * read-only. This way the service will get the EROFS result as if it was writing to the real
2760 RUN_WITH_UMASK(0000)
2761 r
= mkdir_p(RUN_SYSTEMD_EMPTY
, 0500);
2765 r
= free_and_strdup(&x
, RUN_SYSTEMD_EMPTY
);
2770 *path
= TAKE_PTR(x
);
2774 int setup_tmp_dirs(const char *id
, char **tmp_dir
, char **var_tmp_dir
) {
2775 _cleanup_(namespace_cleanup_tmpdirp
) char *a
= NULL
;
2776 _cleanup_(rmdir_and_freep
) char *a_tmp
= NULL
;
2782 assert(var_tmp_dir
);
2784 r
= setup_one_tmp_dir(id
, "/tmp", &a
, &a_tmp
);
2788 r
= setup_one_tmp_dir(id
, "/var/tmp", &b
, NULL
);
2792 a_tmp
= mfree(a_tmp
); /* avoid rmdir */
2793 *tmp_dir
= TAKE_PTR(a
);
2794 *var_tmp_dir
= TAKE_PTR(b
);
2799 int setup_shareable_ns(const int ns_storage_socket
[static 2], unsigned long nsflag
) {
2800 _cleanup_close_
int ns
= -1;
2802 const char *ns_name
, *ns_path
;
2804 assert(ns_storage_socket
);
2805 assert(ns_storage_socket
[0] >= 0);
2806 assert(ns_storage_socket
[1] >= 0);
2808 ns_name
= namespace_single_flag_to_string(nsflag
);
2811 /* We use the passed socketpair as a storage buffer for our
2812 * namespace reference fd. Whatever process runs this first
2813 * shall create a new namespace, all others should just join
2814 * it. To serialize that we use a file lock on the socket
2817 * It's a bit crazy, but hey, works great! */
2819 if (lockf(ns_storage_socket
[0], F_LOCK
, 0) < 0)
2822 ns
= receive_one_fd(ns_storage_socket
[0], MSG_DONTWAIT
);
2823 if (ns
== -EAGAIN
) {
2824 /* Nothing stored yet, so let's create a new namespace. */
2826 if (unshare(nsflag
) < 0) {
2831 (void) loopback_setup();
2833 ns_path
= strjoina("/proc/self/ns/", ns_name
);
2834 ns
= open(ns_path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2842 } else if (ns
< 0) {
2847 /* Yay, found something, so let's join the namespace */
2848 if (setns(ns
, nsflag
) < 0) {
2856 q
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2863 (void) lockf(ns_storage_socket
[0], F_ULOCK
, 0);
2867 int open_shareable_ns_path(const int ns_storage_socket
[static 2], const char *path
, unsigned long nsflag
) {
2868 _cleanup_close_
int ns
= -1;
2871 assert(ns_storage_socket
);
2872 assert(ns_storage_socket
[0] >= 0);
2873 assert(ns_storage_socket
[1] >= 0);
2876 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2877 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2878 * allocate a new anonymous ns if needed. */
2880 if (lockf(ns_storage_socket
[0], F_LOCK
, 0) < 0)
2883 ns
= receive_one_fd(ns_storage_socket
[0], MSG_DONTWAIT
);
2884 if (ns
== -EAGAIN
) {
2885 /* Nothing stored yet. Open the file from the file system. */
2887 ns
= open(path
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
2893 r
= fd_is_ns(ns
, nsflag
);
2894 if (r
== 0) { /* Not a ns of our type? Refuse early. */
2898 if (r
< 0 && r
!= -EUCLEAN
) /* EUCLEAN: we don't know */
2903 } else if (ns
< 0) {
2907 r
= 0; /* Already allocated */
2909 q
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2916 (void) lockf(ns_storage_socket
[0], F_ULOCK
, 0);
2920 bool ns_type_supported(NamespaceType type
) {
2921 const char *t
, *ns_proc
;
2923 t
= namespace_type_to_string(type
);
2924 if (!t
) /* Don't know how to translate this? Then it's not supported */
2927 ns_proc
= strjoina("/proc/self/ns/", t
);
2928 return access(ns_proc
, F_OK
) == 0;
2931 static const char *const protect_home_table
[_PROTECT_HOME_MAX
] = {
2932 [PROTECT_HOME_NO
] = "no",
2933 [PROTECT_HOME_YES
] = "yes",
2934 [PROTECT_HOME_READ_ONLY
] = "read-only",
2935 [PROTECT_HOME_TMPFS
] = "tmpfs",
2938 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home
, ProtectHome
, PROTECT_HOME_YES
);
2940 static const char *const protect_system_table
[_PROTECT_SYSTEM_MAX
] = {
2941 [PROTECT_SYSTEM_NO
] = "no",
2942 [PROTECT_SYSTEM_YES
] = "yes",
2943 [PROTECT_SYSTEM_FULL
] = "full",
2944 [PROTECT_SYSTEM_STRICT
] = "strict",
2947 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system
, ProtectSystem
, PROTECT_SYSTEM_YES
);
2949 static const char* const namespace_type_table
[] = {
2950 [NAMESPACE_MOUNT
] = "mnt",
2951 [NAMESPACE_CGROUP
] = "cgroup",
2952 [NAMESPACE_UTS
] = "uts",
2953 [NAMESPACE_IPC
] = "ipc",
2954 [NAMESPACE_USER
] = "user",
2955 [NAMESPACE_PID
] = "pid",
2956 [NAMESPACE_NET
] = "net",
2959 DEFINE_STRING_TABLE_LOOKUP(namespace_type
, NamespaceType
);
2961 static const char* const protect_proc_table
[_PROTECT_PROC_MAX
] = {
2962 [PROTECT_PROC_DEFAULT
] = "default",
2963 [PROTECT_PROC_NOACCESS
] = "noaccess",
2964 [PROTECT_PROC_INVISIBLE
] = "invisible",
2965 [PROTECT_PROC_PTRACEABLE
] = "ptraceable",
2968 DEFINE_STRING_TABLE_LOOKUP(protect_proc
, ProtectProc
);
2970 static const char* const proc_subset_table
[_PROC_SUBSET_MAX
] = {
2971 [PROC_SUBSET_ALL
] = "all",
2972 [PROC_SUBSET_PID
] = "pid",
2975 DEFINE_STRING_TABLE_LOOKUP(proc_subset
, ProcSubset
);