1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
14 #include "alloc-util.h"
15 #include "base-filesystem.h"
17 #include "dev-setup.h"
18 #include "devnum-util.h"
21 #include "extension-util.h"
23 #include "format-util.h"
24 #include "glyph-util.h"
25 #include "label-util.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"
37 #include "nulstr-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"
47 #include "tmpfile-util.h"
48 #include "umask-util.h"
49 #include "user-util.h"
51 #define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
53 typedef enum MountMode
{
54 /* This is ordered by priority! */
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 */
77 READWRITE_IMPLICIT
, /* Should have the lowest priority. */
81 typedef struct MountEntry
{
82 const char *path_const
; /* Memory allocated on stack or static */
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 */
96 const char *options_const
;/* Mount options for tmpfs */
98 unsigned long flags
; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
100 LIST_HEAD(MountOptions
, image_options
);
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
},
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 },
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 },
139 /* ProtectKernelModules= option */
140 static const MountEntry protect_kernel_modules_table
[] = {
142 { "/lib/modules", INACCESSIBLE
, true },
144 { "/usr/lib/modules", INACCESSIBLE
, true },
147 /* ProtectKernelLogs= option */
148 static const MountEntry protect_kernel_logs_proc_table
[] = {
149 { "/proc/kmsg", INACCESSIBLE
, true },
152 static const MountEntry protect_kernel_logs_dev_table
[] = {
153 { "/dev/kmsg", INACCESSIBLE
, true },
157 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
158 * system should be protected by ProtectSystem=
160 static const MountEntry protect_home_read_only_table
[] = {
161 { "/home", READONLY
, true },
162 { "/run/user", READONLY
, true },
163 { "/root", READONLY
, true },
166 /* ProtectHome=tmpfs table */
167 static const MountEntry protect_home_tmpfs_table
[] = {
168 { "/home", TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
169 { "/run/user", TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
170 { "/root", TMPFS
, true, .read_only
= true, .options_const
= "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
173 /* ProtectHome=yes table */
174 static const MountEntry protect_home_yes_table
[] = {
175 { "/home", INACCESSIBLE
, true },
176 { "/run/user", INACCESSIBLE
, true },
177 { "/root", INACCESSIBLE
, true },
180 /* ProtectSystem=yes table */
181 static const MountEntry protect_system_yes_table
[] = {
182 { "/usr", READONLY
, false },
183 { "/boot", READONLY
, true },
184 { "/efi", READONLY
, true },
186 { "/lib", READONLY
, true },
187 { "/lib64", READONLY
, true },
188 { "/bin", READONLY
, true },
190 { "/sbin", READONLY
, true },
195 /* ProtectSystem=full includes ProtectSystem=yes */
196 static const MountEntry protect_system_full_table
[] = {
197 { "/usr", READONLY
, false },
198 { "/boot", READONLY
, true },
199 { "/efi", READONLY
, true },
200 { "/etc", READONLY
, false },
202 { "/lib", READONLY
, true },
203 { "/lib64", READONLY
, true },
204 { "/bin", READONLY
, true },
206 { "/sbin", READONLY
, true },
212 * ProtectSystem=strict table. In this strict mode, we mount everything
213 * read-only, except for /proc, /dev, /sys which are the kernel API VFS,
214 * which are left writable, but PrivateDevices= + ProtectKernelTunables=
215 * protect those, and these options should be fully orthogonal.
216 * (And of course /home and friends are also left writable, as ProtectHome=
217 * shall manage those, orthogonally).
219 static const MountEntry protect_system_strict_table
[] = {
220 { "/", READONLY
, false },
221 { "/proc", READWRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
222 { "/sys", READWRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
223 { "/dev", READWRITE_IMPLICIT
, false }, /* PrivateDevices= */
224 { "/home", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
225 { "/run/user", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
226 { "/root", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
229 static const char * const mount_mode_table
[_MOUNT_MODE_MAX
] = {
230 [INACCESSIBLE
] = "inaccessible",
231 [OVERLAY_MOUNT
] = "overlay",
232 [BIND_MOUNT
] = "bind",
233 [BIND_MOUNT_RECURSIVE
] = "rbind",
234 [PRIVATE_TMP
] = "private-tmp",
235 [PRIVATE_DEV
] = "private-dev",
236 [BIND_DEV
] = "bind-dev",
237 [EMPTY_DIR
] = "empty",
238 [PRIVATE_SYSFS
] = "private-sysfs",
239 [BIND_SYSFS
] = "bind-sysfs",
241 [READONLY
] = "read-only",
242 [READWRITE
] = "read-write",
244 [MOUNT_IMAGES
] = "mount-images",
245 [READWRITE_IMPLICIT
] = "rw-implicit",
248 [MQUEUEFS
] = "mqueuefs",
251 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode
, MountMode
);
253 static const char *mount_entry_path(const MountEntry
*p
) {
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. */
259 return p
->path_malloc
?: p
->path_const
;
262 static const char *mount_entry_unprefixed_path(const MountEntry
*p
) {
265 /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
267 return p
->unprefixed_path_malloc
?: p
->unprefixed_path_const
?: mount_entry_path(p
);
270 static void mount_entry_consume_prefix(MountEntry
*p
, char *new_path
) {
272 assert(p
->path_malloc
|| p
->path_const
);
275 /* Saves current path in unprefixed_ variable, and takes over new_path */
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;
285 static bool mount_entry_read_only(const MountEntry
*p
) {
288 return p
->read_only
|| IN_SET(p
->mode
, READONLY
, INACCESSIBLE
, PRIVATE_TMP_READONLY
);
291 static bool mount_entry_noexec(const MountEntry
*p
) {
294 return p
->noexec
|| IN_SET(p
->mode
, NOEXEC
, INACCESSIBLE
, PRIVATE_SYSFS
, BIND_SYSFS
, PROCFS
);
297 static bool mount_entry_exec(const MountEntry
*p
) {
300 return p
->exec
|| p
->mode
== EXEC
;
303 static const char *mount_entry_source(const MountEntry
*p
) {
306 return p
->source_malloc
?: p
->source_const
;
309 static const char *mount_entry_options(const MountEntry
*p
) {
312 return p
->options_malloc
?: p
->options_const
;
315 static void mount_entry_done(MountEntry
*p
) {
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
);
325 static int append_access_mounts(MountEntry
**p
, char **strv
, MountMode mode
, bool forcibly_require_prefix
) {
328 /* Adds a list of user-supplied READWRITE/READWRITE_IMPLICIT/READONLY/INACCESSIBLE entries */
330 STRV_FOREACH(i
, strv
) {
331 bool ignore
= false, needs_prefix
= false;
334 /* Look for any prefixes */
335 if (startswith(e
, "-")) {
339 if (startswith(e
, "+")) {
344 if (!path_is_absolute(e
))
345 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
346 "Path is not absolute: %s", e
);
348 *((*p
)++) = (MountEntry
) {
352 .has_prefix
= !needs_prefix
&& !forcibly_require_prefix
,
359 static int append_empty_dir_mounts(MountEntry
**p
, char **strv
) {
362 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
363 * "/private/" boundary directories for DynamicUser=1. */
365 STRV_FOREACH(i
, strv
) {
367 *((*p
)++) = (MountEntry
) {
372 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
373 .flags
= MS_NOSUID
|MS_NOEXEC
|MS_NODEV
|MS_STRICTATIME
,
380 static int append_bind_mounts(MountEntry
**p
, const BindMount
*binds
, size_t n
) {
383 for (size_t i
= 0; i
< n
; i
++) {
384 const BindMount
*b
= binds
+ i
;
386 *((*p
)++) = (MountEntry
) {
387 .path_const
= b
->destination
,
388 .mode
= b
->recursive
? BIND_MOUNT_RECURSIVE
: BIND_MOUNT
,
389 .read_only
= b
->read_only
,
391 .source_const
= b
->source
,
392 .ignore
= b
->ignore_enoent
,
399 static int append_mount_images(MountEntry
**p
, const MountImage
*mount_images
, size_t n
) {
402 for (size_t i
= 0; i
< n
; i
++) {
403 const MountImage
*m
= mount_images
+ i
;
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
,
417 static int append_extensions(
420 const char *extension_dir
,
422 const MountImage
*mount_images
,
424 char **extension_directories
) {
426 _cleanup_strv_free_
char **overlays
= NULL
;
429 if (n
== 0 && strv_isempty(extension_directories
))
433 assert(extension_dir
);
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
;
442 prefixed_hierarchy
= path_join(root
, *hierarchy
);
443 if (!prefixed_hierarchy
)
446 r
= strv_consume(&overlays
, TAKE_PTR(prefixed_hierarchy
));
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
;
457 r
= asprintf(&mount_point
, "%s/%zu", extension_dir
, i
);
461 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
462 _cleanup_free_
char *prefixed_hierarchy
= NULL
, *escaped
= NULL
, *lowerdir
= NULL
;
464 prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
465 if (!prefixed_hierarchy
)
468 escaped
= shell_escape(prefixed_hierarchy
, ",:");
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
]);
478 free_and_replace(overlays
[j
], lowerdir
);
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
,
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;
499 /* Pick up the counter where the ExtensionImages left it. */
500 r
= asprintf(&mount_point
, "%s/%zu", extension_dir
, n
++);
504 /* Look for any prefixes */
505 if (startswith(e
, "-")) {
507 ignore_enoent
= true;
509 /* Ignore this for now */
510 if (startswith(e
, "+"))
517 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
518 _cleanup_free_
char *prefixed_hierarchy
= NULL
, *escaped
= NULL
, *lowerdir
= NULL
;
520 prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
521 if (!prefixed_hierarchy
)
524 escaped
= shell_escape(prefixed_hierarchy
, ",:");
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
]);
534 free_and_replace(overlays
[j
], lowerdir
);
537 *((*p
)++) = (MountEntry
) {
538 .path_malloc
= TAKE_PTR(mount_point
),
539 .source_malloc
= TAKE_PTR(source
),
540 .mode
= EXTENSION_DIRECTORIES
,
541 .ignore
= ignore_enoent
,
547 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
549 for (size_t i
= 0; hierarchies
&& hierarchies
[i
]; ++i
) {
550 _cleanup_free_
char *prefixed_hierarchy
= NULL
;
552 prefixed_hierarchy
= path_join(root
, hierarchies
[i
]);
553 if (!prefixed_hierarchy
)
556 *((*p
)++) = (MountEntry
) {
557 .path_malloc
= TAKE_PTR(prefixed_hierarchy
),
558 .options_malloc
= TAKE_PTR(overlays
[i
]),
559 .mode
= OVERLAY_MOUNT
,
561 .ignore
= true, /* If the source image doesn't set the ignore bit it will fail earlier. */
568 static int append_tmpfs_mounts(MountEntry
**p
, const TemporaryFileSystem
*tmpfs
, size_t n
) {
571 for (size_t i
= 0; i
< n
; i
++) {
572 const TemporaryFileSystem
*t
= tmpfs
+ i
;
573 _cleanup_free_
char *o
= NULL
, *str
= NULL
;
578 if (!path_is_absolute(t
->path
))
579 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
580 "Path is not absolute: %s",
583 str
= strjoin("mode=0755" NESTED_TMPFS_LIMITS
",", t
->options
);
587 r
= mount_option_mangle(str
, MS_NODEV
|MS_STRICTATIME
, &flags
, &o
);
589 return log_debug_errno(r
, "Failed to parse mount option '%s': %m", str
);
591 ro
= flags
& MS_RDONLY
;
595 *((*p
)++) = (MountEntry
) {
596 .path_const
= t
->path
,
599 .options_malloc
= TAKE_PTR(o
),
607 static int append_static_mounts(MountEntry
**p
, const MountEntry
*mounts
, size_t n
, bool ignore_protect
) {
611 /* Adds a list of static pre-defined entries */
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
,
623 static int append_protect_home(MountEntry
**p
, ProtectHome protect_home
, bool ignore_protect
) {
626 switch (protect_home
) {
628 case PROTECT_HOME_NO
:
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
);
634 case PROTECT_HOME_TMPFS
:
635 return append_static_mounts(p
, protect_home_tmpfs_table
, ELEMENTSOF(protect_home_tmpfs_table
), ignore_protect
);
637 case PROTECT_HOME_YES
:
638 return append_static_mounts(p
, protect_home_yes_table
, ELEMENTSOF(protect_home_yes_table
), ignore_protect
);
641 assert_not_reached();
645 static int append_protect_system(MountEntry
**p
, ProtectSystem protect_system
, bool ignore_protect
) {
648 switch (protect_system
) {
650 case PROTECT_SYSTEM_NO
:
653 case PROTECT_SYSTEM_STRICT
:
654 return append_static_mounts(p
, protect_system_strict_table
, ELEMENTSOF(protect_system_strict_table
), ignore_protect
);
656 case PROTECT_SYSTEM_YES
:
657 return append_static_mounts(p
, protect_system_yes_table
, ELEMENTSOF(protect_system_yes_table
), ignore_protect
);
659 case PROTECT_SYSTEM_FULL
:
660 return append_static_mounts(p
, protect_system_full_table
, ELEMENTSOF(protect_system_full_table
), ignore_protect
);
663 assert_not_reached();
667 static int mount_path_compare(const MountEntry
*a
, const MountEntry
*b
) {
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
);
675 d
= -CMP(a
->mode
== EXTENSION_DIRECTORIES
, b
->mode
== EXTENSION_DIRECTORIES
);
679 /* If the paths are not equal, then order prefixes first */
680 d
= path_compare(mount_entry_path(a
), mount_entry_path(b
));
684 /* If the paths are equal, check the mode */
685 return CMP((int) a
->mode
, (int) b
->mode
);
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. */
693 for (size_t i
= 0; i
< n
; i
++) {
699 s
= path_join(root_directory
, mount_entry_path(m
+i
));
703 mount_entry_consume_prefix(&m
[i
], s
);
709 static void drop_duplicates(MountEntry
*m
, size_t *n
) {
710 MountEntry
*f
, *t
, *previous
;
715 /* Drops duplicate entries. Expects that the array is properly ordered already. */
717 for (f
= m
, t
= m
, previous
= NULL
; f
< m
+ *n
; f
++) {
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. */
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
);
741 static void drop_inaccessible(MountEntry
*m
, size_t *n
) {
743 const char *clear
= NULL
;
748 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
749 * ordered already. */
751 for (f
= m
, t
= m
; f
< m
+ *n
; f
++) {
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
);
761 clear
= f
->mode
== INACCESSIBLE
? mount_entry_path(f
) : NULL
;
770 static void drop_nop(MountEntry
*m
, size_t *n
) {
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. */
779 for (f
= m
, t
= m
; f
< m
+ *n
; f
++) {
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
;
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
))) {
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
));
809 static void drop_outside_root(const char *root_directory
, MountEntry
*m
, size_t *n
) {
819 /* Drops all mounts that are outside of the root directory. */
821 for (f
= m
, t
= m
; f
< m
+ *n
; f
++) {
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
));
837 static int clone_device_node(
839 const char *temporary_mount
,
840 bool *make_devnode
) {
842 _cleanup_free_
char *sl
= NULL
;
843 const char *dn
, *bn
, *t
;
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
);
853 return log_debug_errno(errno
, "Failed to stat() device node '%s' to clone, ignoring: %m", d
);
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.",
862 dn
= strjoina(temporary_mount
, d
);
864 /* First, try to create device node properly */
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();
872 return log_debug_errno(errno
, "mknod failed for %s: %m", d
);
874 /* This didn't work, let's not try this again for the next iterations. */
875 *make_devnode
= false;
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
);
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
);
892 bn
= path_startswith(d
, "/dev/");
896 /* Create symlinks like /dev/char/1:9 → ../urandom */
897 if (asprintf(&sl
, "%s/dev/%s/" DEVNUM_FORMAT_STR
,
899 S_ISCHR(st
.st_mode
) ? "char" : "block",
900 DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
903 (void) mkdir_parents(sl
, 0755);
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
);
912 static int mount_private_dev(MountEntry
*m
) {
913 static const char devnodes
[] =
921 char temporary_mount
[] = "/tmp/namespace-dev-XXXXXX";
922 const char *dev
= NULL
, *devpts
= NULL
, *devshm
= NULL
, *devhugepages
= NULL
, *devmqueue
= NULL
, *devlog
= NULL
, *devptmx
= NULL
;
923 bool can_mknod
= true;
928 if (!mkdtemp(temporary_mount
))
929 return log_debug_errno(errno
, "Failed to create temporary directory '%s': %m", temporary_mount
);
931 dev
= strjoina(temporary_mount
, "/dev");
932 (void) mkdir(dev
, 0755);
933 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", dev
, "tmpfs", DEV_MOUNT_OPTIONS
, "mode=0755" TMPFS_LIMITS_PRIVATE_DEV
);
937 r
= label_fix_full(AT_FDCWD
, dev
, "/dev", 0);
939 log_debug_errno(r
, "Failed to fix label of '%s' as /dev: %m", dev
);
943 devpts
= strjoina(temporary_mount
, "/dev/pts");
944 (void) mkdir(devpts
, 0755);
945 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/pts", devpts
, NULL
, MS_BIND
, NULL
);
949 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
950 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
951 * Thus, in that case make a clone.
952 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
953 r
= is_symlink("/dev/ptmx");
955 log_debug_errno(r
, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
958 devptmx
= strjoina(temporary_mount
, "/dev/ptmx");
959 if (symlink("pts/ptmx", devptmx
) < 0) {
960 r
= log_debug_errno(errno
, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx
);
964 r
= clone_device_node("/dev/ptmx", temporary_mount
, &can_mknod
);
969 devshm
= strjoina(temporary_mount
, "/dev/shm");
970 (void) mkdir(devshm
, 0755);
971 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/shm", devshm
, NULL
, MS_BIND
, NULL
);
975 devmqueue
= strjoina(temporary_mount
, "/dev/mqueue");
976 (void) mkdir(devmqueue
, 0755);
977 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/mqueue", devmqueue
, NULL
, MS_BIND
, NULL
);
979 devhugepages
= strjoina(temporary_mount
, "/dev/hugepages");
980 (void) mkdir(devhugepages
, 0755);
981 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/hugepages", devhugepages
, NULL
, MS_BIND
, NULL
);
983 devlog
= strjoina(temporary_mount
, "/dev/log");
984 if (symlink("/run/systemd/journal/dev-log", devlog
) < 0)
985 log_debug_errno(errno
, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog
);
987 NULSTR_FOREACH(d
, devnodes
) {
988 r
= clone_device_node(d
, temporary_mount
, &can_mknod
);
989 /* ENXIO means the *source* is not a device file, skip creation in that case */
990 if (r
< 0 && r
!= -ENXIO
)
994 r
= dev_setup(temporary_mount
, UID_INVALID
, GID_INVALID
);
996 log_debug_errno(r
, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount
);
998 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
999 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
1000 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1002 /* Unmount everything in old /dev */
1003 r
= umount_recursive(mount_entry_path(m
), 0);
1005 log_debug_errno(r
, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m
));
1007 r
= mount_nofollow_verbose(LOG_DEBUG
, dev
, mount_entry_path(m
), NULL
, MS_MOVE
, NULL
);
1012 (void) rmdir(temporary_mount
);
1018 (void) umount_verbose(LOG_DEBUG
, devpts
, UMOUNT_NOFOLLOW
);
1021 (void) umount_verbose(LOG_DEBUG
, devshm
, UMOUNT_NOFOLLOW
);
1024 (void) umount_verbose(LOG_DEBUG
, devhugepages
, UMOUNT_NOFOLLOW
);
1027 (void) umount_verbose(LOG_DEBUG
, devmqueue
, UMOUNT_NOFOLLOW
);
1029 (void) umount_verbose(LOG_DEBUG
, dev
, UMOUNT_NOFOLLOW
);
1031 (void) rmdir(temporary_mount
);
1036 static int mount_bind_dev(const MountEntry
*m
) {
1041 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1042 * service's /dev. This is only used when RootDirectory= is set. */
1044 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1046 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1048 return log_debug_errno(r
, "Unable to determine whether /dev is already mounted: %m");
1049 if (r
> 0) /* make this a NOP if /dev is already a mount point */
1052 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1059 static int mount_private_sysfs(const MountEntry
*m
) {
1060 const char *p
= mount_entry_path(ASSERT_PTR(m
));
1063 (void) mkdir_p_label(p
, 0755);
1065 r
= remount_sysfs(p
);
1066 if (r
< 0 && (ERRNO_IS_PRIVILEGE(r
) || ERRNO_IS_NOT_SUPPORTED(r
))) {
1067 /* Running with an unprivileged user (PrivateUsers=yes), or the kernel seems old. Falling
1068 * back to bind mount the host's version so that we get all child mounts of it, too. */
1070 log_debug_errno(r
, "Failed to remount sysfs on %s, falling back to bind mount: %m", p
);
1072 (void) umount_recursive(p
, 0);
1074 r
= mount_nofollow_verbose(LOG_DEBUG
, "/sys", p
, NULL
, MS_BIND
|MS_REC
, NULL
);
1077 return log_debug_errno(r
, "Failed to remount sysfs on %s: %m", p
);
1082 static int mount_bind_sysfs(const MountEntry
*m
) {
1087 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1089 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1091 return log_debug_errno(r
, "Unable to determine whether /sys is already mounted: %m");
1092 if (r
> 0) /* make this a NOP if /sys is already a mount point */
1095 /* Bind mount the host's version so that we get all child mounts of it, too. */
1096 r
= mount_nofollow_verbose(LOG_DEBUG
, "/sys", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1103 static int mount_procfs(const MountEntry
*m
, const NamespaceInfo
*ns_info
) {
1104 _cleanup_free_
char *opts
= NULL
;
1105 const char *entry_path
;
1111 if (ns_info
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1112 ns_info
->proc_subset
!= PROC_SUBSET_ALL
) {
1114 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
1115 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
1116 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
1117 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
1118 * added in the same commit: if it's supported it is thus also per-instance. */
1120 const char *hpv
= ns_info
->protect_proc
== PROTECT_PROC_DEFAULT
?
1122 protect_proc_to_string(ns_info
->protect_proc
);
1124 /* hidepid= support was added in 5.8, so we can use fsconfig()/fsopen() (which were added in
1125 * 5.2) to check if hidepid= is supported. This avoids a noisy dmesg log by the kernel when
1126 * trying to use hidepid= on systems where it isn't supported. The same applies for subset=.
1127 * fsopen()/fsconfig() was also backported on some distros which allows us to detect
1128 * hidepid=/subset= support in even more scenarios. */
1130 if (mount_option_supported("proc", "hidepid", hpv
) != 0) {
1131 opts
= strjoin("hidepid=", hpv
);
1136 if (ns_info
->proc_subset
== PROC_SUBSET_PID
&&
1137 mount_option_supported("proc", "subset", "pid") != 0)
1138 if (!strextend_with_separator(&opts
, ",", "subset=pid"))
1142 entry_path
= mount_entry_path(m
);
1143 (void) mkdir_p_label(entry_path
, 0755);
1145 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1146 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1147 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1148 * mounted on /proc/ first. */
1150 n
= umount_recursive(entry_path
, 0);
1152 r
= mount_nofollow_verbose(LOG_DEBUG
, "proc", entry_path
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, opts
);
1153 if (r
== -EINVAL
&& opts
)
1154 /* If this failed with EINVAL then this likely means the textual hidepid= stuff is
1155 * not supported by the kernel, and thus the per-instance hidepid= neither, which
1156 * means we really don't want to use it, since it would affect our host's /proc
1157 * mount. Hence let's gracefully fallback to a classic, unrestricted version. */
1158 r
= mount_nofollow_verbose(LOG_DEBUG
, "proc", entry_path
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, NULL
);
1160 /* When we do not have enough privileges to mount /proc, fallback to use existing /proc. */
1163 /* /proc or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1164 * Propagate the original error code returned by mount() in the above. */
1167 r
= path_is_mount_point(entry_path
, NULL
, 0);
1169 return log_debug_errno(r
, "Unable to determine whether /proc is already mounted: %m");
1171 /* We lack permissions to mount a new instance of /proc, and it is not already
1172 * mounted. But we can access the host's, so as a final fallback bind-mount it to
1173 * the destination, as most likely we are inside a user manager in an unprivileged
1174 * user namespace. */
1175 r
= mount_nofollow_verbose(LOG_DEBUG
, "/proc", entry_path
, NULL
, MS_BIND
|MS_REC
, NULL
);
1182 /* We mounted a new instance now. Let's bind mount the children over now. This matters for
1183 * nspawn where a bunch of files are overmounted, in particular the boot id */
1184 (void) bind_mount_submounts("/proc", entry_path
);
1189 static int mount_tmpfs(const MountEntry
*m
) {
1190 const char *entry_path
, *inner_path
;
1195 entry_path
= mount_entry_path(m
);
1196 inner_path
= mount_entry_unprefixed_path(m
);
1198 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1201 (void) mkdir_p_label(entry_path
, 0755);
1202 (void) umount_recursive(entry_path
, 0);
1204 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", entry_path
, "tmpfs", m
->flags
, mount_entry_options(m
));
1208 r
= label_fix_full(AT_FDCWD
, entry_path
, inner_path
, 0);
1210 return log_debug_errno(r
, "Failed to fix label of '%s' as '%s': %m", entry_path
, inner_path
);
1215 static int mount_run(const MountEntry
*m
) {
1220 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1221 if (r
< 0 && r
!= -ENOENT
)
1222 return log_debug_errno(r
, "Unable to determine whether /run is already mounted: %m");
1223 if (r
> 0) /* make this a NOP if /run is already a mount point */
1226 return mount_tmpfs(m
);
1229 static int mount_mqueuefs(const MountEntry
*m
) {
1231 const char *entry_path
;
1235 entry_path
= mount_entry_path(m
);
1237 (void) mkdir_p_label(entry_path
, 0755);
1238 (void) umount_recursive(entry_path
, 0);
1240 r
= mount_nofollow_verbose(LOG_DEBUG
, "mqueue", entry_path
, "mqueue", m
->flags
, mount_entry_options(m
));
1247 static int mount_image(
1248 const MountEntry
*m
,
1249 const char *root_directory
,
1250 const ImagePolicy
*image_policy
) {
1252 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1253 *host_os_release_sysext_level
= NULL
;
1258 if (m
->mode
== EXTENSION_IMAGES
) {
1259 r
= parse_os_release(
1260 empty_to_root(root_directory
),
1261 "ID", &host_os_release_id
,
1262 "VERSION_ID", &host_os_release_version_id
,
1263 "SYSEXT_LEVEL", &host_os_release_sysext_level
,
1266 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1267 if (isempty(host_os_release_id
))
1268 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
));
1271 r
= verity_dissect_and_mount(
1273 mount_entry_source(m
),
1274 mount_entry_path(m
),
1278 host_os_release_version_id
,
1279 host_os_release_sysext_level
,
1281 if (r
== -ENOENT
&& m
->ignore
)
1283 if (r
== -ESTALE
&& host_os_release_id
)
1284 return log_error_errno(r
,
1285 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s",
1286 mount_entry_source(m
),
1288 host_os_release_version_id
? " VERSION_ID=" : "",
1289 strempty(host_os_release_version_id
),
1290 host_os_release_sysext_level
? " SYSEXT_LEVEL=" : "",
1291 strempty(host_os_release_sysext_level
));
1293 return log_debug_errno(r
, "Failed to mount image %s on %s: %m", mount_entry_source(m
), mount_entry_path(m
));
1298 static int mount_overlay(const MountEntry
*m
) {
1299 const char *options
;
1304 options
= strjoina("lowerdir=", mount_entry_options(m
));
1306 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1308 r
= mount_nofollow_verbose(LOG_DEBUG
, "overlay", mount_entry_path(m
), "overlay", MS_RDONLY
, options
);
1309 if (r
== -ENOENT
&& m
->ignore
)
1317 static int follow_symlink(
1318 const char *root_directory
,
1321 _cleanup_free_
char *target
= NULL
;
1324 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1325 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1326 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1327 * end and already have a fully normalized name. */
1329 r
= chase(mount_entry_path(m
), root_directory
, CHASE_STEP
|CHASE_NONEXISTENT
, &target
, NULL
);
1331 return log_debug_errno(r
, "Failed to chase symlinks '%s': %m", mount_entry_path(m
));
1332 if (r
> 0) /* Reached the end, nothing more to resolve */
1335 if (m
->n_followed
>= CHASE_MAX
) /* put a boundary on things */
1336 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1337 "Symlink loop on '%s'.",
1338 mount_entry_path(m
));
1340 log_debug("Followed mount entry path symlink %s %s %s.",
1341 mount_entry_path(m
), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), target
);
1343 mount_entry_consume_prefix(m
, TAKE_PTR(target
));
1350 static int apply_one_mount(
1351 const char *root_directory
,
1353 const ImagePolicy
*mount_image_policy
,
1354 const ImagePolicy
*extension_image_policy
,
1355 const NamespaceInfo
*ns_info
) {
1357 _cleanup_free_
char *inaccessible
= NULL
;
1358 bool rbind
= true, make
= false;
1365 log_debug("Applying namespace mount on %s", mount_entry_path(m
));
1369 case INACCESSIBLE
: {
1370 _cleanup_free_
char *tmp
= NULL
;
1371 const char *runtime_dir
;
1374 /* First, get rid of everything that is below if there
1375 * is anything... Then, overmount it with an
1376 * inaccessible path. */
1377 (void) umount_recursive(mount_entry_path(m
), 0);
1379 if (lstat(mount_entry_path(m
), &target
) < 0) {
1380 if (errno
== ENOENT
&& m
->ignore
)
1383 return log_debug_errno(errno
, "Failed to lstat() %s to determine what to mount over it: %m",
1384 mount_entry_path(m
));
1388 runtime_dir
= "/run";
1390 if (asprintf(&tmp
, "/run/user/" UID_FMT
, geteuid()) < 0)
1396 r
= mode_to_inaccessible_node(runtime_dir
, target
.st_mode
, &inaccessible
);
1398 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1399 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
1400 what
= inaccessible
;
1406 case READWRITE_IMPLICIT
:
1409 r
= path_is_mount_point(mount_entry_path(m
), root_directory
, 0);
1410 if (r
== -ENOENT
&& m
->ignore
)
1413 return log_debug_errno(r
, "Failed to determine whether %s is already a mount point: %m",
1414 mount_entry_path(m
));
1415 if (r
> 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1416 * and MS_NOEXEC bits for the mount point if needed. */
1418 /* This isn't a mount point yet, let's make it one. */
1419 what
= mount_entry_path(m
);
1422 case EXTENSION_DIRECTORIES
: {
1423 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1424 *host_os_release_sysext_level
= NULL
, *extension_name
= NULL
;
1425 _cleanup_strv_free_
char **extension_release
= NULL
;
1427 r
= path_extract_filename(mount_entry_source(m
), &extension_name
);
1429 return log_debug_errno(r
, "Failed to extract extension name from %s: %m", mount_entry_source(m
));
1431 r
= parse_os_release(
1432 empty_to_root(root_directory
),
1433 "ID", &host_os_release_id
,
1434 "VERSION_ID", &host_os_release_version_id
,
1435 "SYSEXT_LEVEL", &host_os_release_sysext_level
,
1438 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1439 if (isempty(host_os_release_id
))
1440 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
));
1442 r
= load_extension_release_pairs(mount_entry_source(m
), IMAGE_SYSEXT
, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1443 if (r
== -ENOENT
&& m
->ignore
)
1446 return log_debug_errno(r
, "Failed to parse directory %s extension-release metadata: %m", extension_name
);
1448 r
= extension_release_validate(
1451 host_os_release_version_id
,
1452 host_os_release_sysext_level
,
1453 /* host_sysext_scope */ NULL
, /* Leave empty, we need to accept both system and portable */
1457 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Directory %s extension-release metadata does not match the root's", extension_name
);
1459 return log_debug_errno(r
, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name
);
1468 case BIND_MOUNT_RECURSIVE
: {
1469 _cleanup_free_
char *chased
= NULL
;
1471 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1472 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1473 * root directory to chase() here. */
1475 r
= chase(mount_entry_source(m
), NULL
, CHASE_TRAIL_SLASH
, &chased
, NULL
);
1476 if (r
== -ENOENT
&& m
->ignore
) {
1477 log_debug_errno(r
, "Path %s does not exist, ignoring.", mount_entry_source(m
));
1481 return log_debug_errno(r
, "Failed to follow symlinks on %s: %m", mount_entry_source(m
));
1483 log_debug("Followed source symlinks %s %s %s.",
1484 mount_entry_source(m
), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), chased
);
1486 free_and_replace(m
->source_malloc
, chased
);
1488 what
= mount_entry_source(m
);
1495 return mount_tmpfs(m
);
1498 case PRIVATE_TMP_READONLY
:
1499 what
= mount_entry_source(m
);
1504 return mount_private_dev(m
);
1507 return mount_bind_dev(m
);
1510 return mount_private_sysfs(m
);
1513 return mount_bind_sysfs(m
);
1516 return mount_procfs(m
, ns_info
);
1519 return mount_run(m
);
1522 return mount_mqueuefs(m
);
1525 return mount_image(m
, NULL
, mount_image_policy
);
1527 case EXTENSION_IMAGES
:
1528 return mount_image(m
, root_directory
, extension_image_policy
);
1531 return mount_overlay(m
);
1534 assert_not_reached();
1539 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1541 bool try_again
= false;
1543 if (r
== -ENOENT
&& make
) {
1546 /* Hmm, either the source or the destination are missing. Let's see if we can create
1547 the destination, then try again. */
1549 (void) mkdir_parents(mount_entry_path(m
), 0755);
1551 q
= make_mount_point_inode_from_path(what
, mount_entry_path(m
), 0755);
1552 if (q
< 0 && q
!= -EEXIST
)
1553 log_error_errno(q
, "Failed to create destination mount point node '%s': %m",
1554 mount_entry_path(m
));
1560 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1562 return log_error_errno(r
, "Failed to mount %s to %s: %m", what
, mount_entry_path(m
));
1565 log_debug("Successfully mounted %s to %s", what
, mount_entry_path(m
));
1569 static int make_read_only(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1570 unsigned long new_flags
= 0, flags_mask
= 0;
1575 assert(proc_self_mountinfo
);
1577 if (mount_entry_read_only(m
) || m
->mode
== PRIVATE_DEV
) {
1578 new_flags
|= MS_RDONLY
;
1579 flags_mask
|= MS_RDONLY
;
1583 new_flags
|= MS_NOSUID
;
1584 flags_mask
|= MS_NOSUID
;
1587 if (flags_mask
== 0) /* No Change? */
1590 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1591 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1592 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1593 * and running Linux <= 4.17. */
1595 mount_entry_read_only(m
) &&
1596 !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1598 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1600 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1602 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
1603 * read-only already stays this way. This improves compatibility with container managers, where we
1604 * won't attempt to undo read-only mounts already applied. */
1606 if (r
== -ENOENT
&& m
->ignore
)
1609 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1610 submounts
? " and its submounts" : "");
1614 static int make_noexec(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1615 unsigned long new_flags
= 0, flags_mask
= 0;
1620 assert(proc_self_mountinfo
);
1622 if (mount_entry_noexec(m
)) {
1623 new_flags
|= MS_NOEXEC
;
1624 flags_mask
|= MS_NOEXEC
;
1625 } else if (mount_entry_exec(m
)) {
1626 new_flags
&= ~MS_NOEXEC
;
1627 flags_mask
|= MS_NOEXEC
;
1630 if (flags_mask
== 0) /* No Change? */
1633 submounts
= !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1636 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1638 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1640 if (r
== -ENOENT
&& m
->ignore
)
1643 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1644 submounts
? " and its submounts" : "");
1648 static int make_nosuid(const MountEntry
*m
, FILE *proc_self_mountinfo
) {
1653 assert(proc_self_mountinfo
);
1655 submounts
= !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1658 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, NULL
, proc_self_mountinfo
);
1660 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, proc_self_mountinfo
);
1661 if (r
== -ENOENT
&& m
->ignore
)
1664 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1665 submounts
? " and its submounts" : "");
1669 static bool namespace_info_mount_apivfs(const NamespaceInfo
*ns_info
) {
1673 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1674 * since to protect the API VFS mounts, they need to be around in the
1678 return ns_info
->mount_apivfs
||
1679 ns_info
->protect_control_groups
||
1680 ns_info
->protect_kernel_tunables
||
1681 ns_info
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1682 ns_info
->proc_subset
!= PROC_SUBSET_ALL
;
1685 static size_t namespace_calculate_mounts(
1686 const NamespaceInfo
*ns_info
,
1687 char** read_write_paths
,
1688 char** read_only_paths
,
1689 char** inaccessible_paths
,
1691 char** no_exec_paths
,
1692 char** empty_directories
,
1693 size_t n_bind_mounts
,
1694 size_t n_temporary_filesystems
,
1695 size_t n_mount_images
,
1696 size_t n_extension_images
,
1697 size_t n_extension_directories
,
1698 size_t n_hierarchies
,
1699 const char* tmp_dir
,
1700 const char* var_tmp_dir
,
1701 const char *creds_path
,
1702 const char* log_namespace
,
1703 bool setup_propagate
,
1704 const char* notify_socket
) {
1706 size_t protect_home_cnt
;
1707 size_t protect_system_cnt
=
1708 (ns_info
->protect_system
== PROTECT_SYSTEM_STRICT
?
1709 ELEMENTSOF(protect_system_strict_table
) :
1710 ((ns_info
->protect_system
== PROTECT_SYSTEM_FULL
) ?
1711 ELEMENTSOF(protect_system_full_table
) :
1712 ((ns_info
->protect_system
== PROTECT_SYSTEM_YES
) ?
1713 ELEMENTSOF(protect_system_yes_table
) : 0)));
1716 (ns_info
->protect_home
== PROTECT_HOME_YES
?
1717 ELEMENTSOF(protect_home_yes_table
) :
1718 ((ns_info
->protect_home
== PROTECT_HOME_READ_ONLY
) ?
1719 ELEMENTSOF(protect_home_read_only_table
) :
1720 ((ns_info
->protect_home
== PROTECT_HOME_TMPFS
) ?
1721 ELEMENTSOF(protect_home_tmpfs_table
) : 0)));
1723 return !!tmp_dir
+ !!var_tmp_dir
+
1724 strv_length(read_write_paths
) +
1725 strv_length(read_only_paths
) +
1726 strv_length(inaccessible_paths
) +
1727 strv_length(exec_paths
) +
1728 strv_length(no_exec_paths
) +
1729 strv_length(empty_directories
) +
1732 (n_extension_images
> 0 || n_extension_directories
> 0 ? /* Mount each image and directory plus an overlay per hierarchy */
1733 n_hierarchies
+ n_extension_images
+ n_extension_directories
: 0) +
1734 n_temporary_filesystems
+
1735 ns_info
->private_dev
+
1736 (ns_info
->protect_kernel_tunables
?
1737 ELEMENTSOF(protect_kernel_tunables_proc_table
) + ELEMENTSOF(protect_kernel_tunables_sys_table
) : 0) +
1738 (ns_info
->protect_kernel_modules
? ELEMENTSOF(protect_kernel_modules_table
) : 0) +
1739 (ns_info
->protect_kernel_logs
?
1740 ELEMENTSOF(protect_kernel_logs_proc_table
) + ELEMENTSOF(protect_kernel_logs_dev_table
) : 0) +
1741 (ns_info
->protect_control_groups
? 1 : 0) +
1742 protect_home_cnt
+ protect_system_cnt
+
1743 (ns_info
->protect_hostname
? 2 : 0) +
1744 (namespace_info_mount_apivfs(ns_info
) ? ELEMENTSOF(apivfs_table
) : 0) +
1745 (creds_path
? 2 : 1) +
1747 setup_propagate
+ /* /run/systemd/incoming */
1749 ns_info
->private_network
+ /* /sys */
1750 ns_info
->private_ipc
; /* /dev/mqueue */
1753 /* Walk all mount entries and dropping any unused mounts. This affects all
1755 * - that are implicitly protected by a path that has been rendered inaccessible
1756 * - whose immediate parent requests the same protection mode as the mount itself
1757 * - that are outside of the relevant root directory
1758 * - which are duplicates
1760 static void drop_unused_mounts(const char *root_directory
, MountEntry
*mounts
, size_t *n_mounts
) {
1761 assert(root_directory
);
1763 assert(mounts
|| *n_mounts
== 0);
1765 typesafe_qsort(mounts
, *n_mounts
, mount_path_compare
);
1767 drop_duplicates(mounts
, n_mounts
);
1768 drop_outside_root(root_directory
, mounts
, n_mounts
);
1769 drop_inaccessible(mounts
, n_mounts
);
1770 drop_nop(mounts
, n_mounts
);
1773 static int create_symlinks_from_tuples(const char *root
, char **strv_symlinks
) {
1776 STRV_FOREACH_PAIR(src
, dst
, strv_symlinks
) {
1777 _cleanup_free_
char *src_abs
= NULL
, *dst_abs
= NULL
;
1779 src_abs
= path_join(root
, *src
);
1780 dst_abs
= path_join(root
, *dst
);
1781 if (!src_abs
|| !dst_abs
)
1784 r
= mkdir_parents_label(dst_abs
, 0755);
1788 r
= symlink_idempotent(src_abs
, dst_abs
, true);
1796 static int apply_mounts(
1798 const ImagePolicy
*mount_image_policy
,
1799 const ImagePolicy
*extension_image_policy
,
1800 const NamespaceInfo
*ns_info
,
1803 char **exec_dir_symlinks
,
1804 char **error_path
) {
1806 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
1807 _cleanup_free_
char **deny_list
= NULL
;
1810 if (n_mounts
== 0) /* Shortcut: nothing to do */
1817 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1818 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
1819 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
1820 if (!proc_self_mountinfo
) {
1824 *error_path
= strdup("/proc/self/mountinfo");
1826 return log_debug_errno(r
, "Failed to open /proc/self/mountinfo: %m");
1829 /* First round, establish all mounts we need */
1833 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1838 /* ExtensionImages/Directories are first opened in the propagate directory, not in the root_directory */
1839 r
= follow_symlink(!IN_SET(m
->mode
, EXTENSION_IMAGES
, EXTENSION_DIRECTORIES
) ? root
: NULL
, m
);
1841 if (error_path
&& mount_entry_path(m
))
1842 *error_path
= strdup(mount_entry_path(m
));
1846 /* We hit a symlinked mount point. The entry got rewritten and might
1847 * point to a very different place now. Let's normalize the changed
1848 * list, and start from the beginning. After all to mount the entry
1849 * at the new location we might need some other mounts first */
1854 r
= apply_one_mount(root
, m
, mount_image_policy
, extension_image_policy
, ns_info
);
1856 if (error_path
&& mount_entry_path(m
))
1857 *error_path
= strdup(mount_entry_path(m
));
1867 drop_unused_mounts(root
, mounts
, n_mounts
);
1870 /* Now that all filesystems have been set up, but before the
1871 * read-only switches are flipped, create the exec dirs symlinks.
1872 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
1873 * exist, which means this will be a no-op. */
1874 r
= create_symlinks_from_tuples(root
, exec_dir_symlinks
);
1876 return log_debug_errno(r
, "Failed to set up ExecDirectories symlinks inside mount namespace: %m");
1878 /* Create a deny list we can pass to bind_mount_recursive() */
1879 deny_list
= new(char*, (*n_mounts
)+1);
1882 for (size_t j
= 0; j
< *n_mounts
; j
++)
1883 deny_list
[j
] = (char*) mount_entry_path(mounts
+j
);
1884 deny_list
[*n_mounts
] = NULL
;
1886 /* Second round, flip the ro bits if necessary. */
1887 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1888 r
= make_read_only(m
, deny_list
, proc_self_mountinfo
);
1890 if (error_path
&& mount_entry_path(m
))
1891 *error_path
= strdup(mount_entry_path(m
));
1896 /* Third round, flip the noexec bits with a simplified deny list. */
1897 for (size_t j
= 0; j
< *n_mounts
; j
++)
1898 if (IN_SET((mounts
+j
)->mode
, EXEC
, NOEXEC
))
1899 deny_list
[j
] = (char*) mount_entry_path(mounts
+j
);
1900 deny_list
[*n_mounts
] = NULL
;
1902 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1903 r
= make_noexec(m
, deny_list
, proc_self_mountinfo
);
1905 if (error_path
&& mount_entry_path(m
))
1906 *error_path
= strdup(mount_entry_path(m
));
1911 /* Fourth round, flip the nosuid bits without a deny list. */
1912 if (ns_info
->mount_nosuid
)
1913 for (MountEntry
*m
= mounts
; m
< mounts
+ *n_mounts
; ++m
) {
1914 r
= make_nosuid(m
, proc_self_mountinfo
);
1916 if (error_path
&& mount_entry_path(m
))
1917 *error_path
= strdup(mount_entry_path(m
));
1925 static bool root_read_only(
1926 char **read_only_paths
,
1927 ProtectSystem protect_system
) {
1929 /* Determine whether the root directory is going to be read-only given the configured settings. */
1931 if (protect_system
== PROTECT_SYSTEM_STRICT
)
1934 if (prefixed_path_strv_contains(read_only_paths
, "/"))
1940 static bool home_read_only(
1941 char** read_only_paths
,
1942 char** inaccessible_paths
,
1943 char** empty_directories
,
1944 const BindMount
*bind_mounts
,
1945 size_t n_bind_mounts
,
1946 const TemporaryFileSystem
*temporary_filesystems
,
1947 size_t n_temporary_filesystems
,
1948 ProtectHome protect_home
) {
1950 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
1951 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
1954 if (protect_home
!= PROTECT_HOME_NO
)
1957 if (prefixed_path_strv_contains(read_only_paths
, "/home") ||
1958 prefixed_path_strv_contains(inaccessible_paths
, "/home") ||
1959 prefixed_path_strv_contains(empty_directories
, "/home"))
1962 for (size_t i
= 0; i
< n_temporary_filesystems
; i
++)
1963 if (path_equal(temporary_filesystems
[i
].path
, "/home"))
1966 /* If /home is overmounted with some dir from the host it's not writable. */
1967 for (size_t i
= 0; i
< n_bind_mounts
; i
++)
1968 if (path_equal(bind_mounts
[i
].destination
, "/home"))
1974 int setup_namespace(
1975 const char* root_directory
,
1976 const char* root_image
,
1977 const MountOptions
*root_image_mount_options
,
1978 const ImagePolicy
*root_image_policy
,
1979 const NamespaceInfo
*ns_info
,
1980 char** read_write_paths
,
1981 char** read_only_paths
,
1982 char** inaccessible_paths
,
1984 char** no_exec_paths
,
1985 char** empty_directories
,
1986 char** exec_dir_symlinks
,
1987 const BindMount
*bind_mounts
,
1988 size_t n_bind_mounts
,
1989 const TemporaryFileSystem
*temporary_filesystems
,
1990 size_t n_temporary_filesystems
,
1991 const MountImage
*mount_images
,
1992 size_t n_mount_images
,
1993 const ImagePolicy
*mount_image_policy
,
1994 const char* tmp_dir
,
1995 const char* var_tmp_dir
,
1996 const char *creds_path
,
1997 const char *log_namespace
,
1998 unsigned long mount_propagation_flag
,
1999 VeritySettings
*verity
,
2000 const MountImage
*extension_images
,
2001 size_t n_extension_images
,
2002 const ImagePolicy
*extension_image_policy
,
2003 char **extension_directories
,
2004 const char *propagate_dir
,
2005 const char *incoming_dir
,
2006 const char *extension_dir
,
2007 const char *notify_socket
,
2008 char **error_path
) {
2010 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2011 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2012 _cleanup_strv_free_
char **hierarchies
= NULL
;
2013 MountEntry
*m
= NULL
, *mounts
= NULL
;
2014 bool require_prefix
= false, setup_propagate
= false;
2016 DissectImageFlags dissect_image_flags
=
2017 DISSECT_IMAGE_GENERIC_ROOT
|
2018 DISSECT_IMAGE_REQUIRE_ROOT
|
2019 DISSECT_IMAGE_DISCARD_ON_LOOP
|
2020 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2021 DISSECT_IMAGE_FSCK
|
2022 DISSECT_IMAGE_USR_NO_ROOT
|
2023 DISSECT_IMAGE_GROWFS
|
2024 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
2025 DISSECT_IMAGE_PIN_PARTITION_DEVICES
;
2031 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2032 * we configure take effect */
2033 BLOCK_WITH_UMASK(0000);
2035 if (!isempty(propagate_dir
) && !isempty(incoming_dir
))
2036 setup_propagate
= true;
2038 if (mount_propagation_flag
== 0)
2039 mount_propagation_flag
= MS_SHARED
;
2042 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2043 if (root_read_only(read_only_paths
,
2044 ns_info
->protect_system
) &&
2045 home_read_only(read_only_paths
, inaccessible_paths
, empty_directories
,
2046 bind_mounts
, n_bind_mounts
, temporary_filesystems
, n_temporary_filesystems
,
2047 ns_info
->protect_home
) &&
2048 strv_isempty(read_write_paths
))
2049 dissect_image_flags
|= DISSECT_IMAGE_READ_ONLY
;
2051 SET_FLAG(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
, verity
&& verity
->data_path
);
2053 r
= loop_device_make_by_path(
2055 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: -1 /* < 0 means writable if possible, read-only as fallback */,
2056 /* sector_size= */ UINT32_MAX
,
2057 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
2061 return log_debug_errno(r
, "Failed to create loop device for root image: %m");
2063 r
= dissect_loop_device(
2066 root_image_mount_options
,
2068 dissect_image_flags
,
2071 return log_debug_errno(r
, "Failed to dissect image: %m");
2073 r
= dissected_image_load_verity_sig_partition(
2080 r
= dissected_image_decrypt(
2084 dissect_image_flags
);
2086 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
2090 root
= root_directory
;
2092 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2093 * when running tests (test-execute), it might not have been created yet so let's make sure
2094 * we create it if it doesn't already exist. */
2095 (void) mkdir_p_label("/run/systemd", 0755);
2097 /* Always create the mount namespace in a temporary directory, instead of operating directly
2098 * in the root. The temporary directory prevents any mounts from being potentially obscured
2099 * my other mounts we already applied. We use the same mount point for all images, which is
2100 * safe, since they all live in their own namespaces after all, and hence won't see each
2101 * other. (Note: this directory is also created by PID 1 early on, we create it here for
2102 * similar reasons as /run/systemd/ first.) */
2103 root
= "/run/systemd/mount-rootfs";
2104 (void) mkdir_label(root
, 0555);
2106 require_prefix
= true;
2109 if (n_extension_images
> 0 || !strv_isempty(extension_directories
)) {
2110 r
= parse_env_extension_hierarchies(&hierarchies
, "SYSTEMD_SYSEXT_HIERARCHIES");
2115 n_mounts
= namespace_calculate_mounts(
2124 n_temporary_filesystems
,
2127 strv_length(extension_directories
),
2128 strv_length(hierarchies
),
2129 tmp_dir
, var_tmp_dir
,
2136 m
= mounts
= new0(MountEntry
, n_mounts
);
2140 r
= append_access_mounts(&m
, read_write_paths
, READWRITE
, require_prefix
);
2144 r
= append_access_mounts(&m
, read_only_paths
, READONLY
, require_prefix
);
2148 r
= append_access_mounts(&m
, inaccessible_paths
, INACCESSIBLE
, require_prefix
);
2152 r
= append_access_mounts(&m
, exec_paths
, EXEC
, require_prefix
);
2156 r
= append_access_mounts(&m
, no_exec_paths
, NOEXEC
, require_prefix
);
2160 r
= append_empty_dir_mounts(&m
, empty_directories
);
2164 r
= append_bind_mounts(&m
, bind_mounts
, n_bind_mounts
);
2168 r
= append_tmpfs_mounts(&m
, temporary_filesystems
, n_temporary_filesystems
);
2173 bool ro
= streq(tmp_dir
, RUN_SYSTEMD_EMPTY
);
2175 *(m
++) = (MountEntry
) {
2176 .path_const
= "/tmp",
2177 .mode
= ro
? PRIVATE_TMP_READONLY
: PRIVATE_TMP
,
2178 .source_const
= tmp_dir
,
2183 bool ro
= streq(var_tmp_dir
, RUN_SYSTEMD_EMPTY
);
2185 *(m
++) = (MountEntry
) {
2186 .path_const
= "/var/tmp",
2187 .mode
= ro
? PRIVATE_TMP_READONLY
: PRIVATE_TMP
,
2188 .source_const
= var_tmp_dir
,
2192 r
= append_mount_images(&m
, mount_images
, n_mount_images
);
2196 r
= append_extensions(&m
, root
, extension_dir
, hierarchies
, extension_images
, n_extension_images
, extension_directories
);
2200 if (ns_info
->private_dev
)
2201 *(m
++) = (MountEntry
) {
2202 .path_const
= "/dev",
2203 .mode
= PRIVATE_DEV
,
2204 .flags
= DEV_MOUNT_OPTIONS
,
2207 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the
2208 protective mounts to non-pid /proc paths would fail. But the pid only option may have
2209 failed gracefully, so let's try the mounts but it's not fatal if they don't succeed. */
2210 bool ignore_protect_proc
= ns_info
->ignore_protect_paths
|| ns_info
->proc_subset
== PROC_SUBSET_PID
;
2211 if (ns_info
->protect_kernel_tunables
) {
2212 r
= append_static_mounts(&m
,
2213 protect_kernel_tunables_proc_table
,
2214 ELEMENTSOF(protect_kernel_tunables_proc_table
),
2215 ignore_protect_proc
);
2219 r
= append_static_mounts(&m
,
2220 protect_kernel_tunables_sys_table
,
2221 ELEMENTSOF(protect_kernel_tunables_sys_table
),
2222 ns_info
->ignore_protect_paths
);
2227 if (ns_info
->protect_kernel_modules
) {
2228 r
= append_static_mounts(&m
,
2229 protect_kernel_modules_table
,
2230 ELEMENTSOF(protect_kernel_modules_table
),
2231 ns_info
->ignore_protect_paths
);
2236 if (ns_info
->protect_kernel_logs
) {
2237 r
= append_static_mounts(&m
,
2238 protect_kernel_logs_proc_table
,
2239 ELEMENTSOF(protect_kernel_logs_proc_table
),
2240 ignore_protect_proc
);
2244 r
= append_static_mounts(&m
,
2245 protect_kernel_logs_dev_table
,
2246 ELEMENTSOF(protect_kernel_logs_dev_table
),
2247 ns_info
->ignore_protect_paths
);
2252 if (ns_info
->protect_control_groups
)
2253 *(m
++) = (MountEntry
) {
2254 .path_const
= "/sys/fs/cgroup",
2258 r
= append_protect_home(&m
, ns_info
->protect_home
, ns_info
->ignore_protect_paths
);
2262 r
= append_protect_system(&m
, ns_info
->protect_system
, false);
2266 if (namespace_info_mount_apivfs(ns_info
)) {
2267 r
= append_static_mounts(&m
,
2269 ELEMENTSOF(apivfs_table
),
2270 ns_info
->ignore_protect_paths
);
2275 /* Note, if proc is mounted with subset=pid then neither of the
2276 * two paths will exist, i.e. they are implicitly protected by
2277 * the mount option. */
2278 if (ns_info
->protect_hostname
) {
2279 *(m
++) = (MountEntry
) {
2280 .path_const
= "/proc/sys/kernel/hostname",
2282 .ignore
= ignore_protect_proc
,
2284 *(m
++) = (MountEntry
) {
2285 .path_const
= "/proc/sys/kernel/domainname",
2287 .ignore
= ignore_protect_proc
,
2291 if (ns_info
->private_network
)
2292 *(m
++) = (MountEntry
) {
2293 .path_const
= "/sys",
2294 .mode
= PRIVATE_SYSFS
,
2297 if (ns_info
->private_ipc
)
2298 *(m
++) = (MountEntry
) {
2299 .path_const
= "/dev/mqueue",
2301 .flags
= MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
2305 /* If our service has a credentials store configured, then bind that one in, but hide
2306 * everything else. */
2308 *(m
++) = (MountEntry
) {
2309 .path_const
= "/run/credentials",
2312 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
2313 .flags
= MS_NODEV
|MS_STRICTATIME
|MS_NOSUID
|MS_NOEXEC
,
2316 *(m
++) = (MountEntry
) {
2317 .path_const
= creds_path
,
2320 .source_const
= creds_path
,
2324 /* If our service has no credentials store configured, then make the whole
2325 * credentials tree inaccessible wholesale. */
2327 *(m
++) = (MountEntry
) {
2328 .path_const
= "/run/credentials",
2329 .mode
= INACCESSIBLE
,
2334 if (log_namespace
) {
2335 _cleanup_free_
char *q
= NULL
;
2337 q
= strjoin("/run/systemd/journal.", log_namespace
);
2343 *(m
++) = (MountEntry
) {
2344 .path_const
= "/run/systemd/journal",
2345 .mode
= BIND_MOUNT_RECURSIVE
,
2347 .source_malloc
= TAKE_PTR(q
),
2351 /* Will be used to add bind mounts at runtime */
2352 if (setup_propagate
)
2353 *(m
++) = (MountEntry
) {
2354 .source_const
= propagate_dir
,
2355 .path_const
= incoming_dir
,
2361 *(m
++) = (MountEntry
) {
2362 .path_const
= notify_socket
,
2363 .source_const
= notify_socket
,
2368 assert(mounts
+ n_mounts
== m
);
2370 /* Prepend the root directory where that's necessary */
2371 r
= prefix_where_needed(mounts
, n_mounts
, root
);
2375 drop_unused_mounts(root
, mounts
, &n_mounts
);
2378 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
2380 if (unshare(CLONE_NEWNS
) < 0) {
2381 r
= log_debug_errno(errno
, "Failed to unshare the mount namespace: %m");
2382 if (ERRNO_IS_PRIVILEGE(r
) ||
2383 ERRNO_IS_NOT_SUPPORTED(r
))
2384 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
2385 * in place that doesn't allow us to create namespaces (or a missing cap), then
2386 * propagate a recognizable error back, which the caller can use to detect this case
2387 * (and only this) and optionally continue without namespacing applied. */
2393 /* Create the source directory to allow runtime propagation of mounts */
2394 if (setup_propagate
)
2395 (void) mkdir_p(propagate_dir
, 0600);
2397 if (n_extension_images
> 0 || !strv_isempty(extension_directories
))
2398 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
2399 * mounts to create, so have the parent ready */
2400 (void) mkdir_p(extension_dir
, 0600);
2402 /* Remount / as SLAVE so that nothing now mounted in the namespace
2403 * shows up in the parent */
2404 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
) < 0) {
2405 r
= log_debug_errno(errno
, "Failed to remount '/' as SLAVE: %m");
2410 /* A root image is specified, mount it to the right place */
2411 r
= dissected_image_mount(dissected_image
, root
, UID_INVALID
, UID_INVALID
, dissect_image_flags
);
2413 log_debug_errno(r
, "Failed to mount root image: %m");
2417 /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
2419 r
= loop_device_flock(loop_device
, LOCK_UN
);
2421 log_debug_errno(r
, "Failed to release lock on loopback block device: %m");
2425 r
= dissected_image_relinquish(dissected_image
);
2427 log_debug_errno(r
, "Failed to relinquish dissected image: %m");
2431 } else if (root_directory
) {
2433 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
2434 r
= path_is_mount_point(root
, NULL
, AT_SYMLINK_FOLLOW
);
2436 log_debug_errno(r
, "Failed to detect that %s is a mount point or not: %m", root
);
2440 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2446 /* Let's mount the main root directory to the root directory to use */
2447 r
= mount_nofollow_verbose(LOG_DEBUG
, "/", root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2452 /* Try to set up the new root directory before mounting anything else there. */
2453 if (root_image
|| root_directory
)
2454 (void) base_filesystem_create(root
, UID_INVALID
, GID_INVALID
);
2456 /* Now make the magic happen */
2457 r
= apply_mounts(root
, mount_image_policy
, extension_image_policy
, ns_info
, mounts
, &n_mounts
, exec_dir_symlinks
, error_path
);
2461 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
2462 r
= mount_switch_root(root
, /* mount_propagation_flag = */ 0);
2463 if (r
== -EINVAL
&& root_directory
) {
2464 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
2465 * namespace) and the root_directory is already a mount point in the parent namespace,
2466 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
2467 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
2468 * mount point) and try again. */
2469 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2472 r
= mount_switch_root(root
, /* mount_propagation_flag = */ 0);
2475 log_debug_errno(r
, "Failed to mount root with MS_MOVE: %m");
2479 /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
2480 * the host, since what's disconnected is disconnected. */
2481 if (mount(NULL
, "/", NULL
, mount_propagation_flag
| MS_REC
, NULL
) < 0) {
2482 r
= log_debug_errno(errno
, "Failed to remount '/' with desired mount flags: %m");
2486 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only
2487 * supported for non-shared mounts. This needs to happen after remounting / or it will fail. */
2488 if (setup_propagate
) {
2489 r
= mount(NULL
, incoming_dir
, NULL
, MS_SLAVE
, NULL
);
2491 log_error_errno(r
, "Failed to remount %s with MS_SLAVE: %m", incoming_dir
);
2500 for (m
= mounts
; m
< mounts
+ n_mounts
; m
++)
2501 mount_entry_done(m
);
2508 void bind_mount_free_many(BindMount
*b
, size_t n
) {
2509 assert(b
|| n
== 0);
2511 for (size_t i
= 0; i
< n
; i
++) {
2513 free(b
[i
].destination
);
2519 int bind_mount_add(BindMount
**b
, size_t *n
, const BindMount
*item
) {
2520 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2527 s
= strdup(item
->source
);
2531 d
= strdup(item
->destination
);
2535 c
= reallocarray(*b
, *n
+ 1, sizeof(BindMount
));
2541 c
[(*n
) ++] = (BindMount
) {
2542 .source
= TAKE_PTR(s
),
2543 .destination
= TAKE_PTR(d
),
2544 .read_only
= item
->read_only
,
2545 .nosuid
= item
->nosuid
,
2546 .recursive
= item
->recursive
,
2547 .ignore_enoent
= item
->ignore_enoent
,
2553 MountImage
* mount_image_free_many(MountImage
*m
, size_t *n
) {
2555 assert(m
|| *n
== 0);
2557 for (size_t i
= 0; i
< *n
; i
++) {
2559 free(m
[i
].destination
);
2560 mount_options_free_all(m
[i
].mount_options
);
2568 int mount_image_add(MountImage
**m
, size_t *n
, const MountImage
*item
) {
2569 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2570 _cleanup_(mount_options_free_allp
) MountOptions
*options
= NULL
;
2577 s
= strdup(item
->source
);
2581 if (item
->destination
) {
2582 d
= strdup(item
->destination
);
2587 LIST_FOREACH(mount_options
, i
, item
->mount_options
) {
2588 _cleanup_(mount_options_free_allp
) MountOptions
*o
= NULL
;
2590 o
= new(MountOptions
, 1);
2594 *o
= (MountOptions
) {
2595 .partition_designator
= i
->partition_designator
,
2596 .options
= strdup(i
->options
),
2601 LIST_APPEND(mount_options
, options
, TAKE_PTR(o
));
2604 c
= reallocarray(*m
, *n
+ 1, sizeof(MountImage
));
2610 c
[(*n
) ++] = (MountImage
) {
2611 .source
= TAKE_PTR(s
),
2612 .destination
= TAKE_PTR(d
),
2613 .mount_options
= TAKE_PTR(options
),
2614 .ignore_enoent
= item
->ignore_enoent
,
2621 void temporary_filesystem_free_many(TemporaryFileSystem
*t
, size_t n
) {
2622 assert(t
|| n
== 0);
2624 for (size_t i
= 0; i
< n
; i
++) {
2632 int temporary_filesystem_add(
2633 TemporaryFileSystem
**t
,
2636 const char *options
) {
2638 _cleanup_free_
char *p
= NULL
, *o
= NULL
;
2639 TemporaryFileSystem
*c
;
2649 if (!isempty(options
)) {
2650 o
= strdup(options
);
2655 c
= reallocarray(*t
, *n
+ 1, sizeof(TemporaryFileSystem
));
2661 c
[(*n
) ++] = (TemporaryFileSystem
) {
2662 .path
= TAKE_PTR(p
),
2663 .options
= TAKE_PTR(o
),
2669 static int make_tmp_prefix(const char *prefix
) {
2670 _cleanup_free_
char *t
= NULL
;
2671 _cleanup_close_
int fd
= -EBADF
;
2674 /* Don't do anything unless we know the dir is actually missing */
2675 r
= access(prefix
, F_OK
);
2678 if (errno
!= ENOENT
)
2682 r
= mkdir_parents(prefix
, 0755);
2686 r
= tempfn_random(prefix
, NULL
, &t
);
2690 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2691 * the suid bit, below. */
2692 fd
= open_mkdir_at(AT_FDCWD
, t
, O_EXCL
|O_CLOEXEC
, 0777);
2696 r
= RET_NERRNO(fchmod(fd
, 01777));
2702 r
= RET_NERRNO(rename(t
, prefix
));
2705 return r
== -EEXIST
? 0 : r
; /* it's fine if someone else created the dir by now */
2712 static int setup_one_tmp_dir(const char *id
, const char *prefix
, char **path
, char **tmp_path
) {
2713 _cleanup_free_
char *x
= NULL
;
2714 _cleanup_free_
char *y
= NULL
;
2723 /* We include the boot id in the directory so that after a
2724 * reboot we can easily identify obsolete directories. */
2726 r
= sd_id128_get_boot(&boot_id
);
2730 x
= strjoin(prefix
, "/systemd-private-", SD_ID128_TO_STRING(boot_id
), "-", id
, "-XXXXXX");
2734 r
= make_tmp_prefix(prefix
);
2740 if (errno
== EROFS
|| ERRNO_IS_DISK_SPACE(errno
))
2747 y
= strjoin(x
, "/tmp");
2752 if (mkdir(y
, 0777 | S_ISVTX
) < 0)
2755 r
= label_fix_full(AT_FDCWD
, y
, prefix
, 0);
2760 *tmp_path
= TAKE_PTR(y
);
2762 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2763 * read-only. This way the service will get the EROFS result as if it was writing to the real
2766 r
= mkdir_p(RUN_SYSTEMD_EMPTY
, 0500);
2770 r
= free_and_strdup(&x
, RUN_SYSTEMD_EMPTY
);
2775 *path
= TAKE_PTR(x
);
2779 int setup_tmp_dirs(const char *id
, char **tmp_dir
, char **var_tmp_dir
) {
2780 _cleanup_(namespace_cleanup_tmpdirp
) char *a
= NULL
;
2781 _cleanup_(rmdir_and_freep
) char *a_tmp
= NULL
;
2787 assert(var_tmp_dir
);
2789 r
= setup_one_tmp_dir(id
, "/tmp", &a
, &a_tmp
);
2793 r
= setup_one_tmp_dir(id
, "/var/tmp", &b
, NULL
);
2797 a_tmp
= mfree(a_tmp
); /* avoid rmdir */
2798 *tmp_dir
= TAKE_PTR(a
);
2799 *var_tmp_dir
= TAKE_PTR(b
);
2804 int setup_shareable_ns(int ns_storage_socket
[static 2], unsigned long nsflag
) {
2805 _cleanup_close_
int ns
= -EBADF
;
2807 const char *ns_name
, *ns_path
;
2809 assert(ns_storage_socket
);
2810 assert(ns_storage_socket
[0] >= 0);
2811 assert(ns_storage_socket
[1] >= 0);
2813 ns_name
= namespace_single_flag_to_string(nsflag
);
2816 /* We use the passed socketpair as a storage buffer for our
2817 * namespace reference fd. Whatever process runs this first
2818 * shall create a new namespace, all others should just join
2819 * it. To serialize that we use a file lock on the socket
2822 * It's a bit crazy, but hey, works great! */
2824 r
= posix_lock(ns_storage_socket
[0], LOCK_EX
);
2828 CLEANUP_POSIX_UNLOCK(ns_storage_socket
[0]);
2830 ns
= receive_one_fd(ns_storage_socket
[0], MSG_PEEK
|MSG_DONTWAIT
);
2832 /* Yay, found something, so let's join the namespace */
2833 r
= RET_NERRNO(setns(ns
, nsflag
));
2843 /* Nothing stored yet, so let's create a new namespace. */
2845 if (unshare(nsflag
) < 0)
2848 (void) loopback_setup();
2850 ns_path
= strjoina("/proc/self/ns/", ns_name
);
2851 ns
= open(ns_path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2855 r
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2862 int open_shareable_ns_path(int ns_storage_socket
[static 2], const char *path
, unsigned long nsflag
) {
2863 _cleanup_close_
int ns
= -EBADF
;
2866 assert(ns_storage_socket
);
2867 assert(ns_storage_socket
[0] >= 0);
2868 assert(ns_storage_socket
[1] >= 0);
2871 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2872 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2873 * allocate a new anonymous ns if needed. */
2875 r
= posix_lock(ns_storage_socket
[0], LOCK_EX
);
2879 CLEANUP_POSIX_UNLOCK(ns_storage_socket
[0]);
2881 ns
= receive_one_fd(ns_storage_socket
[0], MSG_PEEK
|MSG_DONTWAIT
);
2887 /* Nothing stored yet. Open the file from the file system. */
2889 ns
= open(path
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
2893 r
= fd_is_ns(ns
, nsflag
);
2896 if (r
< 0 && r
!= -EUCLEAN
) /* EUCLEAN: we don't know */
2899 r
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2906 bool ns_type_supported(NamespaceType type
) {
2907 const char *t
, *ns_proc
;
2909 t
= namespace_type_to_string(type
);
2910 if (!t
) /* Don't know how to translate this? Then it's not supported */
2913 ns_proc
= strjoina("/proc/self/ns/", t
);
2914 return access(ns_proc
, F_OK
) == 0;
2917 static const char *const protect_home_table
[_PROTECT_HOME_MAX
] = {
2918 [PROTECT_HOME_NO
] = "no",
2919 [PROTECT_HOME_YES
] = "yes",
2920 [PROTECT_HOME_READ_ONLY
] = "read-only",
2921 [PROTECT_HOME_TMPFS
] = "tmpfs",
2924 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home
, ProtectHome
, PROTECT_HOME_YES
);
2926 static const char *const protect_system_table
[_PROTECT_SYSTEM_MAX
] = {
2927 [PROTECT_SYSTEM_NO
] = "no",
2928 [PROTECT_SYSTEM_YES
] = "yes",
2929 [PROTECT_SYSTEM_FULL
] = "full",
2930 [PROTECT_SYSTEM_STRICT
] = "strict",
2933 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system
, ProtectSystem
, PROTECT_SYSTEM_YES
);
2935 static const char* const namespace_type_table
[] = {
2936 [NAMESPACE_MOUNT
] = "mnt",
2937 [NAMESPACE_CGROUP
] = "cgroup",
2938 [NAMESPACE_UTS
] = "uts",
2939 [NAMESPACE_IPC
] = "ipc",
2940 [NAMESPACE_USER
] = "user",
2941 [NAMESPACE_PID
] = "pid",
2942 [NAMESPACE_NET
] = "net",
2943 [NAMESPACE_TIME
] = "time",
2946 DEFINE_STRING_TABLE_LOOKUP(namespace_type
, NamespaceType
);
2948 static const char* const protect_proc_table
[_PROTECT_PROC_MAX
] = {
2949 [PROTECT_PROC_DEFAULT
] = "default",
2950 [PROTECT_PROC_NOACCESS
] = "noaccess",
2951 [PROTECT_PROC_INVISIBLE
] = "invisible",
2952 [PROTECT_PROC_PTRACEABLE
] = "ptraceable",
2955 DEFINE_STRING_TABLE_LOOKUP(protect_proc
, ProtectProc
);
2957 static const char* const proc_subset_table
[_PROC_SUBSET_MAX
] = {
2958 [PROC_SUBSET_ALL
] = "all",
2959 [PROC_SUBSET_PID
] = "pid",
2962 DEFINE_STRING_TABLE_LOOKUP(proc_subset
, ProcSubset
);