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_const
);
103 typedef struct MountList
{
108 /* 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
109 * something there already. These mounts are hence overridden by any other explicitly configured mounts. */
110 static const MountEntry apivfs_table
[] = {
111 { "/proc", PROCFS
, false },
112 { "/dev", BIND_DEV
, false },
113 { "/sys", BIND_SYSFS
, false },
114 { "/run", RUN
, false, .options_const
= "mode=0755" TMPFS_LIMITS_RUN
, .flags
= MS_NOSUID
|MS_NODEV
|MS_STRICTATIME
},
117 /* ProtectKernelTunables= option and the related filesystem APIs */
118 static const MountEntry protect_kernel_tunables_proc_table
[] = {
119 { "/proc/acpi", READONLY
, true },
120 { "/proc/apm", READONLY
, true }, /* Obsolete API, there's no point in permitting access to this, ever */
121 { "/proc/asound", READONLY
, true },
122 { "/proc/bus", READONLY
, true },
123 { "/proc/fs", READONLY
, true },
124 { "/proc/irq", READONLY
, true },
125 { "/proc/kallsyms", INACCESSIBLE
, true },
126 { "/proc/kcore", INACCESSIBLE
, true },
127 { "/proc/latency_stats", READONLY
, true },
128 { "/proc/mtrr", READONLY
, true },
129 { "/proc/scsi", READONLY
, true },
130 { "/proc/sys", READONLY
, true },
131 { "/proc/sysrq-trigger", READONLY
, true },
132 { "/proc/timer_stats", READONLY
, true },
135 static const MountEntry protect_kernel_tunables_sys_table
[] = {
136 { "/sys", READONLY
, false },
137 { "/sys/fs/bpf", READONLY
, true },
138 { "/sys/fs/cgroup", READWRITE_IMPLICIT
, false }, /* READONLY is set by ProtectControlGroups= option */
139 { "/sys/fs/selinux", READWRITE_IMPLICIT
, true },
140 { "/sys/kernel/debug", READONLY
, true },
141 { "/sys/kernel/tracing", READONLY
, true },
144 /* ProtectKernelModules= option */
145 static const MountEntry protect_kernel_modules_table
[] = {
146 { "/usr/lib/modules", INACCESSIBLE
, true },
149 /* ProtectKernelLogs= option */
150 static const MountEntry protect_kernel_logs_proc_table
[] = {
151 { "/proc/kmsg", INACCESSIBLE
, true },
154 static const MountEntry protect_kernel_logs_dev_table
[] = {
155 { "/dev/kmsg", INACCESSIBLE
, true },
159 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
160 * system should be protected by ProtectSystem=
162 static const MountEntry protect_home_read_only_table
[] = {
163 { "/home", READONLY
, true },
164 { "/run/user", READONLY
, true },
165 { "/root", READONLY
, true },
168 /* ProtectHome=tmpfs table */
169 static const MountEntry protect_home_tmpfs_table
[] = {
170 { "/home", TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
171 { "/run/user", TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
172 { "/root", TMPFS
, true, .read_only
= true, .options_const
= "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
175 /* ProtectHome=yes table */
176 static const MountEntry protect_home_yes_table
[] = {
177 { "/home", INACCESSIBLE
, true },
178 { "/run/user", INACCESSIBLE
, true },
179 { "/root", INACCESSIBLE
, true },
182 /* ProtectSystem=yes table */
183 static const MountEntry protect_system_yes_table
[] = {
184 { "/usr", READONLY
, false },
185 { "/boot", READONLY
, true },
186 { "/efi", READONLY
, true },
189 /* ProtectSystem=full includes ProtectSystem=yes */
190 static const MountEntry protect_system_full_table
[] = {
191 { "/usr", READONLY
, false },
192 { "/boot", READONLY
, true },
193 { "/efi", READONLY
, true },
194 { "/etc", READONLY
, false },
197 /* ProtectSystem=strict table. In this strict mode, we mount everything read-only, except for /proc, /dev,
198 * /sys which are the kernel API VFS, which are left writable, but PrivateDevices= + ProtectKernelTunables=
199 * protect those, and these options should be fully orthogonal. (And of course /home and friends are also
200 * left writable, as ProtectHome= shall manage those, orthogonally).
202 static const MountEntry protect_system_strict_table
[] = {
203 { "/", READONLY
, false },
204 { "/proc", READWRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
205 { "/sys", READWRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
206 { "/dev", READWRITE_IMPLICIT
, false }, /* PrivateDevices= */
207 { "/home", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
208 { "/run/user", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
209 { "/root", READWRITE_IMPLICIT
, true }, /* ProtectHome= */
212 /* ProtectHostname=yes able */
213 static const MountEntry protect_hostname_table
[] = {
214 { "/proc/sys/kernel/hostname", READONLY
, false },
215 { "/proc/sys/kernel/domainname", READONLY
, false },
218 static const char * const mount_mode_table
[_MOUNT_MODE_MAX
] = {
219 [INACCESSIBLE
] = "inaccessible",
220 [OVERLAY_MOUNT
] = "overlay",
221 [MOUNT_IMAGES
] = "mount-images",
222 [BIND_MOUNT
] = "bind",
223 [BIND_MOUNT_RECURSIVE
] = "rbind",
224 [PRIVATE_TMP
] = "private-tmp",
225 [PRIVATE_TMP_READONLY
] = "private-tmp-read-only",
226 [PRIVATE_DEV
] = "private-dev",
227 [BIND_DEV
] = "bind-dev",
228 [EMPTY_DIR
] = "empty",
229 [PRIVATE_SYSFS
] = "private-sysfs",
230 [BIND_SYSFS
] = "bind-sysfs",
232 [READONLY
] = "read-only",
233 [READWRITE
] = "read-write",
238 [EXTENSION_DIRECTORIES
] = "extension-directories",
239 [EXTENSION_IMAGES
] = "extension-images",
240 [MQUEUEFS
] = "mqueuefs",
241 [READWRITE_IMPLICIT
] = "read-write-implicit",
244 /* Helper struct for naming simplicity and reusability */
245 static const struct {
246 const char *level_env
;
247 const char *level_env_print
;
248 } image_class_info
[_IMAGE_CLASS_MAX
] = {
250 .level_env
= "SYSEXT_LEVEL",
251 .level_env_print
= " SYSEXT_LEVEL=",
254 .level_env
= "CONFEXT_LEVEL",
255 .level_env_print
= " CONFEXT_LEVEL=",
259 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode
, MountMode
);
261 static const char *mount_entry_path(const MountEntry
*p
) {
264 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
265 * otherwise the stack/static ->path field is returned. */
267 return p
->path_malloc
?: p
->path_const
;
270 static const char *mount_entry_unprefixed_path(const MountEntry
*p
) {
273 /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
275 return p
->unprefixed_path_malloc
?: p
->unprefixed_path_const
?: mount_entry_path(p
);
278 static void mount_entry_consume_prefix(MountEntry
*p
, char *new_path
) {
280 assert(p
->path_malloc
|| p
->path_const
);
283 /* Saves current path in unprefixed_ variable, and takes over new_path */
285 free_and_replace(p
->unprefixed_path_malloc
, p
->path_malloc
);
286 /* If we didn't have a path on the heap, then it's a static one */
287 if (!p
->unprefixed_path_malloc
)
288 p
->unprefixed_path_const
= p
->path_const
;
289 p
->path_malloc
= new_path
;
290 p
->has_prefix
= true;
293 static bool mount_entry_read_only(const MountEntry
*p
) {
296 return p
->read_only
|| IN_SET(p
->mode
, READONLY
, INACCESSIBLE
, PRIVATE_TMP_READONLY
);
299 static bool mount_entry_noexec(const MountEntry
*p
) {
302 return p
->noexec
|| IN_SET(p
->mode
, NOEXEC
, INACCESSIBLE
, PRIVATE_SYSFS
, BIND_SYSFS
, PROCFS
);
305 static bool mount_entry_exec(const MountEntry
*p
) {
308 return p
->exec
|| p
->mode
== EXEC
;
311 static const char *mount_entry_source(const MountEntry
*p
) {
314 return p
->source_malloc
?: p
->source_const
;
317 static const char *mount_entry_options(const MountEntry
*p
) {
320 return p
->options_malloc
?: p
->options_const
;
323 static void mount_entry_done(MountEntry
*p
) {
326 p
->path_malloc
= mfree(p
->path_malloc
);
327 p
->unprefixed_path_malloc
= mfree(p
->unprefixed_path_malloc
);
328 p
->source_malloc
= mfree(p
->source_malloc
);
329 p
->options_malloc
= mfree(p
->options_malloc
);
332 static void mount_list_done(MountList
*ml
) {
335 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
)
338 ml
->mounts
= mfree(ml
->mounts
);
342 static MountEntry
*mount_list_extend(MountList
*ml
) {
345 if (!GREEDY_REALLOC0(ml
->mounts
, ml
->n_mounts
+1))
348 return ml
->mounts
+ ml
->n_mounts
++;
351 static int append_access_mounts(MountList
*ml
, char **strv
, MountMode mode
, bool forcibly_require_prefix
) {
354 /* Adds a list of user-supplied READWRITE/READWRITE_IMPLICIT/READONLY/INACCESSIBLE entries */
356 STRV_FOREACH(i
, strv
) {
357 bool ignore
= false, needs_prefix
= false;
360 /* Look for any prefixes */
361 if (startswith(e
, "-")) {
365 if (startswith(e
, "+")) {
370 if (!path_is_absolute(e
))
371 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Path is not absolute: %s", e
);
373 MountEntry
*me
= mount_list_extend(ml
);
375 return log_oom_debug();
381 .has_prefix
= !needs_prefix
&& !forcibly_require_prefix
,
388 static int append_empty_dir_mounts(MountList
*ml
, char **strv
) {
391 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
392 * "/private/" boundary directories for DynamicUser=1. */
394 STRV_FOREACH(i
, strv
) {
395 MountEntry
*me
= mount_list_extend(ml
);
397 return log_oom_debug();
404 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
405 .flags
= MS_NOSUID
|MS_NOEXEC
|MS_NODEV
|MS_STRICTATIME
,
412 static int append_bind_mounts(MountList
*ml
, const BindMount
*binds
, size_t n
) {
414 assert(binds
|| n
== 0);
416 FOREACH_ARRAY(b
, binds
, n
) {
417 MountEntry
*me
= mount_list_extend(ml
);
419 return log_oom_debug();
422 .path_const
= b
->destination
,
423 .mode
= b
->recursive
? BIND_MOUNT_RECURSIVE
: BIND_MOUNT
,
424 .read_only
= b
->read_only
,
426 .source_const
= b
->source
,
427 .ignore
= b
->ignore_enoent
,
434 static int append_mount_images(MountList
*ml
, const MountImage
*mount_images
, size_t n
) {
436 assert(mount_images
|| n
== 0);
438 FOREACH_ARRAY(m
, mount_images
, n
) {
439 MountEntry
*me
= mount_list_extend(ml
);
441 return log_oom_debug();
444 .path_const
= m
->destination
,
445 .mode
= MOUNT_IMAGES
,
446 .source_const
= m
->source
,
447 .image_options_const
= m
->mount_options
,
448 .ignore
= m
->ignore_enoent
,
455 static int append_extensions(
458 const char *extension_dir
,
460 const MountImage
*mount_images
,
462 char **extension_directories
) {
464 _cleanup_strv_free_
char **overlays
= NULL
;
469 if (n
== 0 && strv_isempty(extension_directories
))
472 assert(extension_dir
);
474 /* Prepare a list of overlays, that will have as each element a string suitable for being
475 * passed as a lowerdir= parameter, so start with the hierarchy on the root.
476 * The overlays vector will have the same number of elements and will correspond to the
477 * hierarchies vector, so they can be iterated upon together. */
478 STRV_FOREACH(hierarchy
, hierarchies
) {
479 _cleanup_free_
char *prefixed_hierarchy
= NULL
;
481 prefixed_hierarchy
= path_join(root
, *hierarchy
);
482 if (!prefixed_hierarchy
)
485 r
= strv_consume(&overlays
, TAKE_PTR(prefixed_hierarchy
));
490 /* First, prepare a mount for each image, but these won't be visible to the unit, instead
491 * they will be mounted in our propagate directory, and used as a source for the overlay. */
492 for (size_t i
= 0; i
< n
; i
++) {
493 _cleanup_free_
char *mount_point
= NULL
;
494 const MountImage
*m
= mount_images
+ i
;
496 if (asprintf(&mount_point
, "%s/%zu", extension_dir
, i
) < 0)
499 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
500 _cleanup_free_
char *prefixed_hierarchy
= NULL
, *escaped
= NULL
, *lowerdir
= NULL
;
502 prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
503 if (!prefixed_hierarchy
)
506 escaped
= shell_escape(prefixed_hierarchy
, ",:");
510 /* Note that lowerdir= parameters are in 'reverse' order, so the
511 * top-most directory in the overlay comes first in the list. */
512 lowerdir
= strjoin(escaped
, ":", overlays
[j
]);
516 free_and_replace(overlays
[j
], lowerdir
);
519 MountEntry
*me
= mount_list_extend(ml
);
521 return log_oom_debug();
524 .path_malloc
= TAKE_PTR(mount_point
),
525 .image_options_const
= m
->mount_options
,
526 .ignore
= m
->ignore_enoent
,
527 .source_const
= m
->source
,
528 .mode
= EXTENSION_IMAGES
,
533 /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
534 * Bind mount them in the same location as the ExtensionImages, so that we
535 * can check that they are valid trees (extension-release.d). */
536 STRV_FOREACH(extension_directory
, extension_directories
) {
537 _cleanup_free_
char *mount_point
= NULL
, *source
= NULL
;
538 const char *e
= *extension_directory
;
539 bool ignore_enoent
= false;
541 /* Pick up the counter where the ExtensionImages left it. */
542 if (asprintf(&mount_point
, "%s/%zu", extension_dir
, n
++) < 0)
545 /* Look for any prefixes */
546 if (startswith(e
, "-")) {
548 ignore_enoent
= true;
550 /* Ignore this for now */
551 if (startswith(e
, "+"))
558 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
559 _cleanup_free_
char *prefixed_hierarchy
= NULL
, *escaped
= NULL
, *lowerdir
= NULL
;
561 prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
562 if (!prefixed_hierarchy
)
565 escaped
= shell_escape(prefixed_hierarchy
, ",:");
569 /* Note that lowerdir= parameters are in 'reverse' order, so the
570 * top-most directory in the overlay comes first in the list. */
571 lowerdir
= strjoin(escaped
, ":", overlays
[j
]);
575 free_and_replace(overlays
[j
], lowerdir
);
578 MountEntry
*me
= mount_list_extend(ml
);
580 return log_oom_debug();
583 .path_malloc
= TAKE_PTR(mount_point
),
584 .source_malloc
= TAKE_PTR(source
),
585 .mode
= EXTENSION_DIRECTORIES
,
586 .ignore
= ignore_enoent
,
592 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
594 for (size_t i
= 0; hierarchies
&& hierarchies
[i
]; ++i
) {
595 _cleanup_free_
char *prefixed_hierarchy
= NULL
;
597 prefixed_hierarchy
= path_join(root
, hierarchies
[i
]);
598 if (!prefixed_hierarchy
)
601 MountEntry
*me
= mount_list_extend(ml
);
603 return log_oom_debug();
606 .path_malloc
= TAKE_PTR(prefixed_hierarchy
),
607 .options_malloc
= TAKE_PTR(overlays
[i
]),
608 .mode
= OVERLAY_MOUNT
,
610 .ignore
= true, /* If the source image doesn't set the ignore bit it will fail earlier. */
617 static int append_tmpfs_mounts(MountList
*ml
, const TemporaryFileSystem
*tmpfs
, size_t n
) {
619 assert(tmpfs
|| n
== 0);
621 FOREACH_ARRAY(t
, tmpfs
, n
) {
622 _cleanup_free_
char *o
= NULL
, *str
= NULL
;
627 if (!path_is_absolute(t
->path
))
628 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Path is not absolute: %s", t
->path
);
630 str
= strjoin("mode=0755" NESTED_TMPFS_LIMITS
",", t
->options
);
634 r
= mount_option_mangle(str
, MS_NODEV
|MS_STRICTATIME
, &flags
, &o
);
636 return log_debug_errno(r
, "Failed to parse mount option '%s': %m", str
);
638 ro
= flags
& MS_RDONLY
;
642 MountEntry
*me
= mount_list_extend(ml
);
644 return log_oom_debug();
647 .path_const
= t
->path
,
650 .options_malloc
= TAKE_PTR(o
),
658 static int append_static_mounts(MountList
*ml
, const MountEntry
*mounts
, size_t n
, bool ignore_protect
) {
660 assert(mounts
|| n
== 0);
662 /* Adds a list of static pre-defined entries */
664 FOREACH_ARRAY(m
, mounts
, n
) {
665 MountEntry
*me
= mount_list_extend(ml
);
667 return log_oom_debug();
670 .path_const
= mount_entry_path(m
),
672 .ignore
= m
->ignore
|| ignore_protect
,
679 static int append_protect_home(MountList
*ml
, ProtectHome protect_home
, bool ignore_protect
) {
682 switch (protect_home
) {
684 case PROTECT_HOME_NO
:
687 case PROTECT_HOME_READ_ONLY
:
688 return append_static_mounts(ml
, protect_home_read_only_table
, ELEMENTSOF(protect_home_read_only_table
), ignore_protect
);
690 case PROTECT_HOME_TMPFS
:
691 return append_static_mounts(ml
, protect_home_tmpfs_table
, ELEMENTSOF(protect_home_tmpfs_table
), ignore_protect
);
693 case PROTECT_HOME_YES
:
694 return append_static_mounts(ml
, protect_home_yes_table
, ELEMENTSOF(protect_home_yes_table
), ignore_protect
);
697 assert_not_reached();
701 static int append_protect_system(MountList
*ml
, ProtectSystem protect_system
, bool ignore_protect
) {
704 switch (protect_system
) {
706 case PROTECT_SYSTEM_NO
:
709 case PROTECT_SYSTEM_STRICT
:
710 return append_static_mounts(ml
, protect_system_strict_table
, ELEMENTSOF(protect_system_strict_table
), ignore_protect
);
712 case PROTECT_SYSTEM_YES
:
713 return append_static_mounts(ml
, protect_system_yes_table
, ELEMENTSOF(protect_system_yes_table
), ignore_protect
);
715 case PROTECT_SYSTEM_FULL
:
716 return append_static_mounts(ml
, protect_system_full_table
, ELEMENTSOF(protect_system_full_table
), ignore_protect
);
719 assert_not_reached();
723 static int mount_path_compare(const MountEntry
*a
, const MountEntry
*b
) {
726 /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
727 * regardless of the prefix - they are set up in the propagate directory anyway */
728 d
= -CMP(a
->mode
== EXTENSION_IMAGES
, b
->mode
== EXTENSION_IMAGES
);
731 d
= -CMP(a
->mode
== EXTENSION_DIRECTORIES
, b
->mode
== EXTENSION_DIRECTORIES
);
735 /* If the paths are not equal, then order prefixes first */
736 d
= path_compare(mount_entry_path(a
), mount_entry_path(b
));
740 /* If the paths are equal, check the mode */
741 return CMP((int) a
->mode
, (int) b
->mode
);
744 static int prefix_where_needed(MountList
*ml
, const char *root_directory
) {
745 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
749 FOREACH_ARRAY(me
, ml
->mounts
, ml
->n_mounts
) {
755 s
= path_join(root_directory
, mount_entry_path(me
));
759 mount_entry_consume_prefix(me
, s
);
765 static void drop_duplicates(MountList
*ml
) {
766 MountEntry
*f
, *t
, *previous
;
770 /* Drops duplicate entries. Expects that the array is properly ordered already. */
772 for (f
= ml
->mounts
, t
= ml
->mounts
, previous
= NULL
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
774 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
775 * above. Note that we only drop duplicates that haven't been mounted yet. */
777 path_equal(mount_entry_path(f
), mount_entry_path(previous
)) &&
778 !f
->applied
&& !previous
->applied
) {
779 log_debug("%s (%s) is duplicate.", mount_entry_path(f
), mount_mode_to_string(f
->mode
));
780 /* Propagate the flags to the remaining entry */
781 previous
->read_only
= previous
->read_only
|| mount_entry_read_only(f
);
782 previous
->noexec
= previous
->noexec
|| mount_entry_noexec(f
);
783 previous
->exec
= previous
->exec
|| mount_entry_exec(f
);
793 ml
->n_mounts
= t
- ml
->mounts
;
796 static void drop_inaccessible(MountList
*ml
) {
798 const char *clear
= NULL
;
802 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
803 * ordered already. */
805 for (f
= ml
->mounts
, t
= ml
->mounts
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
807 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
808 * it, as inaccessible paths really should drop the entire subtree. */
809 if (clear
&& path_startswith(mount_entry_path(f
), clear
)) {
810 log_debug("%s is masked by %s.", mount_entry_path(f
), clear
);
815 clear
= f
->mode
== INACCESSIBLE
? mount_entry_path(f
) : NULL
;
821 ml
->n_mounts
= t
- ml
->mounts
;
824 static void drop_nop(MountList
*ml
) {
829 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
830 * list is ordered by prefixes. */
832 for (f
= ml
->mounts
, t
= ml
->mounts
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
834 /* Only suppress such subtrees for READONLY, READWRITE and READWRITE_IMPLICIT entries */
835 if (IN_SET(f
->mode
, READONLY
, READWRITE
, READWRITE_IMPLICIT
)) {
836 MountEntry
*found
= NULL
;
838 /* Now let's find the first parent of the entry we are looking at. */
839 for (MountEntry
*p
= PTR_SUB1(t
, ml
->mounts
); p
; p
= PTR_SUB1(p
, ml
->mounts
))
840 if (path_startswith(mount_entry_path(f
), mount_entry_path(p
))) {
845 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
846 if (found
&& found
->mode
== f
->mode
) {
847 log_debug("%s (%s) is made redundant by %s (%s)",
848 mount_entry_path(f
), mount_mode_to_string(f
->mode
),
849 mount_entry_path(found
), mount_mode_to_string(found
->mode
));
859 ml
->n_mounts
= t
- ml
->mounts
;
862 static void drop_outside_root(MountList
*ml
, const char *root_directory
) {
871 /* Drops all mounts that are outside of the root directory. */
873 for (f
= ml
->mounts
, t
= ml
->mounts
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
875 /* ExtensionImages/Directories bases are opened in /run/systemd/unit-extensions on the host */
876 if (!IN_SET(f
->mode
, EXTENSION_IMAGES
, EXTENSION_DIRECTORIES
) && !path_startswith(mount_entry_path(f
), root_directory
)) {
877 log_debug("%s is outside of root directory.", mount_entry_path(f
));
886 ml
->n_mounts
= t
- ml
->mounts
;
889 static int clone_device_node(
891 const char *temporary_mount
,
892 bool *make_devnode
) {
894 _cleanup_free_
char *sl
= NULL
;
895 const char *dn
, *bn
, *t
;
899 if (stat(d
, &st
) < 0) {
900 if (errno
== ENOENT
) {
901 log_debug_errno(errno
, "Device node '%s' to clone does not exist, ignoring.", d
);
905 return log_debug_errno(errno
, "Failed to stat() device node '%s' to clone, ignoring: %m", d
);
908 if (!S_ISBLK(st
.st_mode
) &&
909 !S_ISCHR(st
.st_mode
))
910 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
911 "Device node '%s' to clone is not a device node, ignoring.",
914 dn
= strjoina(temporary_mount
, d
);
916 /* First, try to create device node properly */
918 mac_selinux_create_file_prepare(d
, st
.st_mode
);
919 r
= mknod(dn
, st
.st_mode
, st
.st_rdev
);
920 mac_selinux_create_file_clear();
924 return log_debug_errno(errno
, "mknod failed for %s: %m", d
);
926 /* This didn't work, let's not try this again for the next iterations. */
927 *make_devnode
= false;
930 /* We're about to fall back to bind-mounting the device node. So create a dummy bind-mount target.
931 * Do not prepare device-node SELinux label (see issue 13762) */
932 r
= mknod(dn
, S_IFREG
, 0);
933 if (r
< 0 && errno
!= EEXIST
)
934 return log_debug_errno(errno
, "mknod() fallback failed for '%s': %m", d
);
936 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
937 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
938 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
939 r
= mount_nofollow_verbose(LOG_DEBUG
, d
, dn
, NULL
, MS_BIND
, NULL
);
944 bn
= path_startswith(d
, "/dev/");
948 /* Create symlinks like /dev/char/1:9 → ../urandom */
949 if (asprintf(&sl
, "%s/dev/%s/" DEVNUM_FORMAT_STR
,
951 S_ISCHR(st
.st_mode
) ? "char" : "block",
952 DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
953 return log_oom_debug();
955 (void) mkdir_parents(sl
, 0755);
957 t
= strjoina("../", bn
);
958 if (symlink(t
, sl
) < 0)
959 log_debug_errno(errno
, "Failed to symlink '%s' to '%s', ignoring: %m", t
, sl
);
964 static char *settle_runtime_dir(RuntimeScope scope
) {
967 if (scope
!= RUNTIME_SCOPE_USER
)
968 return strdup("/run/");
970 if (asprintf(&runtime_dir
, "/run/user/" UID_FMT
, geteuid()) < 0)
976 static int mount_private_dev(MountEntry
*m
, RuntimeScope scope
) {
977 static const char devnodes
[] =
985 _cleanup_free_
char *runtime_dir
= NULL
, *temporary_mount
= NULL
;
986 const char *dev
= NULL
, *devpts
= NULL
, *devshm
= NULL
, *devhugepages
= NULL
, *devmqueue
= NULL
, *devlog
= NULL
, *devptmx
= NULL
;
987 bool can_mknod
= true;
992 runtime_dir
= settle_runtime_dir(scope
);
994 return log_oom_debug();
996 temporary_mount
= path_join(runtime_dir
, "systemd/namespace-dev-XXXXXX");
997 if (!temporary_mount
)
998 return log_oom_debug();
1000 if (!mkdtemp(temporary_mount
))
1001 return log_debug_errno(errno
, "Failed to create temporary directory '%s': %m", temporary_mount
);
1003 dev
= strjoina(temporary_mount
, "/dev");
1004 (void) mkdir(dev
, 0755);
1005 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", dev
, "tmpfs", DEV_MOUNT_OPTIONS
, "mode=0755" TMPFS_LIMITS_PRIVATE_DEV
);
1009 r
= label_fix_full(AT_FDCWD
, dev
, "/dev", 0);
1011 log_debug_errno(r
, "Failed to fix label of '%s' as /dev: %m", dev
);
1015 devpts
= strjoina(temporary_mount
, "/dev/pts");
1016 (void) mkdir(devpts
, 0755);
1017 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/pts", devpts
, NULL
, MS_BIND
, NULL
);
1021 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
1022 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
1023 * Thus, in that case make a clone.
1024 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
1025 r
= is_symlink("/dev/ptmx");
1027 log_debug_errno(r
, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
1030 devptmx
= strjoina(temporary_mount
, "/dev/ptmx");
1031 if (symlink("pts/ptmx", devptmx
) < 0) {
1032 r
= log_debug_errno(errno
, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx
);
1036 r
= clone_device_node("/dev/ptmx", temporary_mount
, &can_mknod
);
1041 devshm
= strjoina(temporary_mount
, "/dev/shm");
1042 (void) mkdir(devshm
, 0755);
1043 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/shm", devshm
, NULL
, MS_BIND
, NULL
);
1047 devmqueue
= strjoina(temporary_mount
, "/dev/mqueue");
1048 (void) mkdir(devmqueue
, 0755);
1049 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/mqueue", devmqueue
, NULL
, MS_BIND
, NULL
);
1051 devhugepages
= strjoina(temporary_mount
, "/dev/hugepages");
1052 (void) mkdir(devhugepages
, 0755);
1053 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/hugepages", devhugepages
, NULL
, MS_BIND
, NULL
);
1055 devlog
= strjoina(temporary_mount
, "/dev/log");
1056 if (symlink("/run/systemd/journal/dev-log", devlog
) < 0)
1057 log_debug_errno(errno
, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog
);
1059 NULSTR_FOREACH(d
, devnodes
) {
1060 r
= clone_device_node(d
, temporary_mount
, &can_mknod
);
1061 /* ENXIO means the *source* is not a device file, skip creation in that case */
1062 if (r
< 0 && r
!= -ENXIO
)
1066 r
= dev_setup(temporary_mount
, UID_INVALID
, GID_INVALID
);
1068 log_debug_errno(r
, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount
);
1070 /* Make the bind mount read-only. */
1071 r
= mount_nofollow_verbose(LOG_DEBUG
, NULL
, dev
, NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
);
1075 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
1076 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
1077 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1079 /* Unmount everything in old /dev */
1080 r
= umount_recursive(mount_entry_path(m
), 0);
1082 log_debug_errno(r
, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m
));
1084 r
= mount_nofollow_verbose(LOG_DEBUG
, dev
, mount_entry_path(m
), NULL
, MS_MOVE
, NULL
);
1089 (void) rmdir(temporary_mount
);
1095 (void) umount_verbose(LOG_DEBUG
, devpts
, UMOUNT_NOFOLLOW
);
1098 (void) umount_verbose(LOG_DEBUG
, devshm
, UMOUNT_NOFOLLOW
);
1101 (void) umount_verbose(LOG_DEBUG
, devhugepages
, UMOUNT_NOFOLLOW
);
1104 (void) umount_verbose(LOG_DEBUG
, devmqueue
, UMOUNT_NOFOLLOW
);
1106 (void) umount_verbose(LOG_DEBUG
, dev
, UMOUNT_NOFOLLOW
);
1108 (void) rmdir(temporary_mount
);
1113 static int mount_bind_dev(const MountEntry
*m
) {
1118 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1119 * service's /dev. This is only used when RootDirectory= is set. */
1121 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1123 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1125 return log_debug_errno(r
, "Unable to determine whether /dev is already mounted: %m");
1126 if (r
> 0) /* make this a NOP if /dev is already a mount point */
1129 return mount_nofollow_verbose(LOG_DEBUG
, "/dev", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1132 static int mount_bind_sysfs(const MountEntry
*m
) {
1137 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1139 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1141 return log_debug_errno(r
, "Unable to determine whether /sys is already mounted: %m");
1142 if (r
> 0) /* make this a NOP if /sys is already a mount point */
1145 /* Bind mount the host's version so that we get all child mounts of it, too. */
1146 return mount_nofollow_verbose(LOG_DEBUG
, "/sys", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1149 static int mount_private_sysfs(const MountEntry
*m
) {
1150 const char *entry_path
= mount_entry_path(ASSERT_PTR(m
));
1153 (void) mkdir_p_label(entry_path
, 0755);
1155 n
= umount_recursive(entry_path
, 0);
1157 r
= mount_nofollow_verbose(LOG_DEBUG
, "sysfs", entry_path
, "sysfs", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, NULL
);
1158 if (ERRNO_IS_NEG_PRIVILEGE(r
)) {
1159 /* When we do not have enough privileges to mount sysfs, fall back to use existing /sys. */
1162 /* /sys or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1163 * Propagate the original error code returned by mount() in the above. */
1166 return mount_bind_sysfs(m
);
1171 /* We mounted a new instance now. Let's bind mount the children over now. */
1172 (void) bind_mount_submounts("/sys", entry_path
);
1176 static int mount_procfs(const MountEntry
*m
, const NamespaceParameters
*p
) {
1177 _cleanup_free_
char *opts
= NULL
;
1178 const char *entry_path
;
1184 if (p
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1185 p
->proc_subset
!= PROC_SUBSET_ALL
) {
1187 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
1188 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
1189 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
1190 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
1191 * added in the same commit: if it's supported it is thus also per-instance. */
1193 const char *hpv
= p
->protect_proc
== PROTECT_PROC_DEFAULT
?
1195 protect_proc_to_string(p
->protect_proc
);
1197 /* hidepid= support was added in 5.8, so we can use fsconfig()/fsopen() (which were added in
1198 * 5.2) to check if hidepid= is supported. This avoids a noisy dmesg log by the kernel when
1199 * trying to use hidepid= on systems where it isn't supported. The same applies for subset=.
1200 * fsopen()/fsconfig() was also backported on some distros which allows us to detect
1201 * hidepid=/subset= support in even more scenarios. */
1203 if (mount_option_supported("proc", "hidepid", hpv
) != 0) {
1204 opts
= strjoin("hidepid=", hpv
);
1209 if (p
->proc_subset
== PROC_SUBSET_PID
&&
1210 mount_option_supported("proc", "subset", "pid") != 0)
1211 if (!strextend_with_separator(&opts
, ",", "subset=pid"))
1215 entry_path
= mount_entry_path(m
);
1216 (void) mkdir_p_label(entry_path
, 0755);
1218 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1219 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1220 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1221 * mounted on /proc/ first. */
1223 n
= umount_recursive(entry_path
, 0);
1225 r
= mount_nofollow_verbose(LOG_DEBUG
, "proc", entry_path
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, opts
);
1226 if (r
== -EINVAL
&& opts
)
1227 /* If this failed with EINVAL then this likely means the textual hidepid= stuff is
1228 * not supported by the kernel, and thus the per-instance hidepid= neither, which
1229 * means we really don't want to use it, since it would affect our host's /proc
1230 * mount. Hence let's gracefully fallback to a classic, unrestricted version. */
1231 r
= mount_nofollow_verbose(LOG_DEBUG
, "proc", entry_path
, "proc", MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, NULL
);
1232 if (ERRNO_IS_NEG_PRIVILEGE(r
)) {
1233 /* When we do not have enough privileges to mount /proc, fall back to use existing /proc. */
1236 /* /proc or some of sub-mounts are umounted in the above. Refuse incomplete tree.
1237 * Propagate the original error code returned by mount() in the above. */
1240 r
= path_is_mount_point(entry_path
, NULL
, 0);
1242 return log_debug_errno(r
, "Unable to determine whether /proc is already mounted: %m");
1246 /* We lack permissions to mount a new instance of /proc, and it is not already mounted. But
1247 * we can access the host's, so as a final fallback bind-mount it to the destination, as most
1248 * likely we are inside a user manager in an unprivileged user namespace. */
1249 return mount_nofollow_verbose(LOG_DEBUG
, "/proc", entry_path
, NULL
, MS_BIND
|MS_REC
, NULL
);
1254 /* We mounted a new instance now. Let's bind mount the children over now. This matters for nspawn
1255 * where a bunch of files are overmounted, in particular the boot id */
1256 (void) bind_mount_submounts("/proc", entry_path
);
1260 static int mount_tmpfs(const MountEntry
*m
) {
1261 const char *entry_path
, *inner_path
;
1266 entry_path
= mount_entry_path(m
);
1267 inner_path
= mount_entry_unprefixed_path(m
);
1269 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1272 (void) mkdir_p_label(entry_path
, 0755);
1273 (void) umount_recursive(entry_path
, 0);
1275 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", entry_path
, "tmpfs", m
->flags
, mount_entry_options(m
));
1279 r
= label_fix_full(AT_FDCWD
, entry_path
, inner_path
, 0);
1281 return log_debug_errno(r
, "Failed to fix label of '%s' as '%s': %m", entry_path
, inner_path
);
1286 static int mount_run(const MountEntry
*m
) {
1291 r
= path_is_mount_point(mount_entry_path(m
), NULL
, 0);
1292 if (r
< 0 && r
!= -ENOENT
)
1293 return log_debug_errno(r
, "Unable to determine whether /run is already mounted: %m");
1294 if (r
> 0) /* make this a NOP if /run is already a mount point */
1297 return mount_tmpfs(m
);
1300 static int mount_mqueuefs(const MountEntry
*m
) {
1302 const char *entry_path
;
1306 entry_path
= mount_entry_path(m
);
1308 (void) mkdir_p_label(entry_path
, 0755);
1309 (void) umount_recursive(entry_path
, 0);
1311 r
= mount_nofollow_verbose(LOG_DEBUG
, "mqueue", entry_path
, "mqueue", m
->flags
, mount_entry_options(m
));
1318 static int mount_image(
1319 const MountEntry
*m
,
1320 const char *root_directory
,
1321 const ImagePolicy
*image_policy
) {
1323 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1324 *host_os_release_sysext_level
= NULL
, *host_os_release_confext_level
= NULL
,
1325 *extension_name
= NULL
;
1330 r
= path_extract_filename(mount_entry_source(m
), &extension_name
);
1332 return log_debug_errno(r
, "Failed to extract extension name from %s: %m", mount_entry_source(m
));
1334 if (m
->mode
== EXTENSION_IMAGES
) {
1335 r
= parse_os_release(
1336 empty_to_root(root_directory
),
1337 "ID", &host_os_release_id
,
1338 "VERSION_ID", &host_os_release_version_id
,
1339 image_class_info
[IMAGE_SYSEXT
].level_env
, &host_os_release_sysext_level
,
1340 image_class_info
[IMAGE_CONFEXT
].level_env
, &host_os_release_confext_level
,
1343 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1344 if (isempty(host_os_release_id
))
1345 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
));
1348 r
= verity_dissect_and_mount(
1350 mount_entry_source(m
),
1351 mount_entry_path(m
),
1352 m
->image_options_const
,
1355 host_os_release_version_id
,
1356 host_os_release_sysext_level
,
1357 host_os_release_confext_level
,
1358 /* required_sysext_scope= */ NULL
,
1359 /* ret_image= */ NULL
);
1360 if (r
== -ENOENT
&& m
->ignore
)
1362 if (r
== -ESTALE
&& host_os_release_id
)
1363 return log_error_errno(r
, // FIXME: this should not be logged ad LOG_ERR, as it will result in duplicate logging.
1364 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s%s%s",
1365 mount_entry_source(m
),
1367 host_os_release_version_id
? " VERSION_ID=" : "",
1368 strempty(host_os_release_version_id
),
1369 host_os_release_sysext_level
? image_class_info
[IMAGE_SYSEXT
].level_env_print
: "",
1370 strempty(host_os_release_sysext_level
),
1371 host_os_release_confext_level
? image_class_info
[IMAGE_CONFEXT
].level_env_print
: "",
1372 strempty(host_os_release_confext_level
));
1374 return log_debug_errno(r
, "Failed to mount image %s on %s: %m", mount_entry_source(m
), mount_entry_path(m
));
1379 static int mount_overlay(const MountEntry
*m
) {
1380 const char *options
;
1385 options
= strjoina("lowerdir=", mount_entry_options(m
));
1387 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1389 r
= mount_nofollow_verbose(LOG_DEBUG
, "overlay", mount_entry_path(m
), "overlay", MS_RDONLY
, options
);
1390 if (r
== -ENOENT
&& m
->ignore
)
1396 static int follow_symlink(
1397 const char *root_directory
,
1400 _cleanup_free_
char *target
= NULL
;
1403 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1404 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1405 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1406 * end and already have a fully normalized name. */
1408 r
= chase(mount_entry_path(m
), root_directory
, CHASE_STEP
|CHASE_NONEXISTENT
, &target
, NULL
);
1410 return log_debug_errno(r
, "Failed to chase symlinks '%s': %m", mount_entry_path(m
));
1411 if (r
> 0) /* Reached the end, nothing more to resolve */
1414 if (m
->n_followed
>= CHASE_MAX
) /* put a boundary on things */
1415 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1416 "Symlink loop on '%s'.",
1417 mount_entry_path(m
));
1419 log_debug("Followed mount entry path symlink %s %s %s.",
1420 mount_entry_path(m
), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), target
);
1422 mount_entry_consume_prefix(m
, TAKE_PTR(target
));
1429 static int apply_one_mount(
1430 const char *root_directory
,
1432 const NamespaceParameters
*p
) {
1434 _cleanup_free_
char *inaccessible
= NULL
;
1435 bool rbind
= true, make
= false;
1442 log_debug("Applying namespace mount on %s", mount_entry_path(m
));
1446 case INACCESSIBLE
: {
1447 _cleanup_free_
char *runtime_dir
= NULL
;
1450 /* First, get rid of everything that is below if there
1451 * is anything... Then, overmount it with an
1452 * inaccessible path. */
1453 (void) umount_recursive(mount_entry_path(m
), 0);
1455 if (lstat(mount_entry_path(m
), &target
) < 0) {
1456 if (errno
== ENOENT
&& m
->ignore
)
1459 return log_debug_errno(errno
, "Failed to lstat() %s to determine what to mount over it: %m",
1460 mount_entry_path(m
));
1463 /* We don't pass the literal runtime scope through here but one based purely on our UID. This
1464 * means that the root user's --user services will use the host's inaccessible inodes rather
1465 * then root's private ones. This is preferable since it means device nodes that are
1466 * overmounted to make them inaccessible will be overmounted with a device node, rather than
1467 * an AF_UNIX socket inode. */
1468 runtime_dir
= settle_runtime_dir(geteuid() == 0 ? RUNTIME_SCOPE_SYSTEM
: RUNTIME_SCOPE_USER
);
1470 return log_oom_debug();
1472 r
= mode_to_inaccessible_node(runtime_dir
, target
.st_mode
, &inaccessible
);
1474 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1475 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
1476 what
= inaccessible
;
1482 case READWRITE_IMPLICIT
:
1485 r
= path_is_mount_point(mount_entry_path(m
), root_directory
, 0);
1486 if (r
== -ENOENT
&& m
->ignore
)
1489 return log_debug_errno(r
, "Failed to determine whether %s is already a mount point: %m",
1490 mount_entry_path(m
));
1491 if (r
> 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1492 * and MS_NOEXEC bits for the mount point if needed. */
1494 /* This isn't a mount point yet, let's make it one. */
1495 what
= mount_entry_path(m
);
1498 case EXTENSION_DIRECTORIES
: {
1499 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1500 *host_os_release_level
= NULL
, *extension_name
= NULL
;
1501 _cleanup_strv_free_
char **extension_release
= NULL
;
1502 ImageClass
class = IMAGE_SYSEXT
;
1504 r
= path_extract_filename(mount_entry_source(m
), &extension_name
);
1506 return log_debug_errno(r
, "Failed to extract extension name from %s: %m", mount_entry_source(m
));
1508 r
= load_extension_release_pairs(mount_entry_source(m
), IMAGE_SYSEXT
, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1510 r
= load_extension_release_pairs(mount_entry_source(m
), IMAGE_CONFEXT
, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1512 class = IMAGE_CONFEXT
;
1515 return log_debug_errno(r
, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m
));
1517 r
= parse_os_release(
1518 empty_to_root(root_directory
),
1519 "ID", &host_os_release_id
,
1520 "VERSION_ID", &host_os_release_version_id
,
1521 image_class_info
[class].level_env
, &host_os_release_level
,
1524 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1525 if (isempty(host_os_release_id
))
1526 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
));
1528 r
= load_extension_release_pairs(mount_entry_source(m
), class, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1529 if (r
== -ENOENT
&& m
->ignore
)
1532 return log_debug_errno(r
, "Failed to parse directory %s extension-release metadata: %m", extension_name
);
1534 r
= extension_release_validate(
1537 host_os_release_version_id
,
1538 host_os_release_level
,
1539 /* host_extension_scope */ NULL
, /* Leave empty, we need to accept both system and portable */
1543 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Directory %s extension-release metadata does not match the root's", extension_name
);
1545 return log_debug_errno(r
, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name
);
1554 case BIND_MOUNT_RECURSIVE
: {
1555 _cleanup_free_
char *chased
= NULL
;
1557 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1558 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1559 * root directory to chase() here. */
1561 r
= chase(mount_entry_source(m
), NULL
, CHASE_TRAIL_SLASH
, &chased
, NULL
);
1562 if (r
== -ENOENT
&& m
->ignore
) {
1563 log_debug_errno(r
, "Path %s does not exist, ignoring.", mount_entry_source(m
));
1567 return log_debug_errno(r
, "Failed to follow symlinks on %s: %m", mount_entry_source(m
));
1569 log_debug("Followed source symlinks %s %s %s.",
1570 mount_entry_source(m
), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), chased
);
1572 free_and_replace(m
->source_malloc
, chased
);
1574 what
= mount_entry_source(m
);
1581 return mount_tmpfs(m
);
1584 case PRIVATE_TMP_READONLY
:
1585 what
= mount_entry_source(m
);
1590 return mount_private_dev(m
, p
->runtime_scope
);
1593 return mount_bind_dev(m
);
1596 return mount_private_sysfs(m
);
1599 return mount_bind_sysfs(m
);
1602 return mount_procfs(m
, p
);
1605 return mount_run(m
);
1608 return mount_mqueuefs(m
);
1611 return mount_image(m
, NULL
, p
->mount_image_policy
);
1613 case EXTENSION_IMAGES
:
1614 return mount_image(m
, root_directory
, p
->extension_image_policy
);
1617 return mount_overlay(m
);
1620 assert_not_reached();
1625 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1627 bool try_again
= false;
1629 if (r
== -ENOENT
&& make
) {
1632 /* Hmm, either the source or the destination are missing. Let's see if we can create
1633 the destination, then try again. */
1635 (void) mkdir_parents(mount_entry_path(m
), 0755);
1637 q
= make_mount_point_inode_from_path(what
, mount_entry_path(m
), 0755);
1639 if (q
!= -EEXIST
) // FIXME: this shouldn't be logged at LOG_WARNING, but be bubbled up, and logged there to avoid duplicate logging
1640 log_warning_errno(q
, "Failed to create destination mount point node '%s', ignoring: %m",
1641 mount_entry_path(m
));
1647 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1649 return log_error_errno(r
, "Failed to mount %s to %s: %m", what
, mount_entry_path(m
)); // FIXME: this should not be logged here, but be bubbled up, to avoid duplicate logging
1652 log_debug("Successfully mounted %s to %s", what
, mount_entry_path(m
));
1656 static int make_read_only(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1657 unsigned long new_flags
= 0, flags_mask
= 0;
1662 assert(proc_self_mountinfo
);
1664 if (mount_entry_read_only(m
) || m
->mode
== PRIVATE_DEV
) {
1665 new_flags
|= MS_RDONLY
;
1666 flags_mask
|= MS_RDONLY
;
1670 new_flags
|= MS_NOSUID
;
1671 flags_mask
|= MS_NOSUID
;
1674 if (flags_mask
== 0) /* No Change? */
1677 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1678 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1679 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1680 * and running Linux <= 4.17. */
1682 mount_entry_read_only(m
) &&
1683 !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1685 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1687 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1689 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
1690 * read-only already stays this way. This improves compatibility with container managers, where we
1691 * won't attempt to undo read-only mounts already applied. */
1693 if (r
== -ENOENT
&& m
->ignore
)
1696 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1697 submounts
? " and its submounts" : "");
1701 static int make_noexec(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1702 unsigned long new_flags
= 0, flags_mask
= 0;
1707 assert(proc_self_mountinfo
);
1709 if (mount_entry_noexec(m
)) {
1710 new_flags
|= MS_NOEXEC
;
1711 flags_mask
|= MS_NOEXEC
;
1712 } else if (mount_entry_exec(m
)) {
1713 new_flags
&= ~MS_NOEXEC
;
1714 flags_mask
|= MS_NOEXEC
;
1717 if (flags_mask
== 0) /* No Change? */
1720 submounts
= !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1723 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1725 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1727 if (r
== -ENOENT
&& m
->ignore
)
1730 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1731 submounts
? " and its submounts" : "");
1735 static int make_nosuid(const MountEntry
*m
, FILE *proc_self_mountinfo
) {
1740 assert(proc_self_mountinfo
);
1742 submounts
= !IN_SET(m
->mode
, EMPTY_DIR
, TMPFS
);
1745 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, NULL
, proc_self_mountinfo
);
1747 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, proc_self_mountinfo
);
1748 if (r
== -ENOENT
&& m
->ignore
)
1751 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1752 submounts
? " and its submounts" : "");
1756 static bool namespace_parameters_mount_apivfs(const NamespaceParameters
*p
) {
1760 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1761 * since to protect the API VFS mounts, they need to be around in the
1765 return p
->mount_apivfs
||
1766 p
->protect_control_groups
||
1767 p
->protect_kernel_tunables
||
1768 p
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1769 p
->proc_subset
!= PROC_SUBSET_ALL
;
1772 /* Walk all mount entries and dropping any unused mounts. This affects all
1774 * - that are implicitly protected by a path that has been rendered inaccessible
1775 * - whose immediate parent requests the same protection mode as the mount itself
1776 * - that are outside of the relevant root directory
1777 * - which are duplicates
1779 static void drop_unused_mounts(MountList
*ml
, const char *root_directory
) {
1781 assert(root_directory
);
1783 assert(ml
->mounts
|| ml
->n_mounts
== 0);
1785 typesafe_qsort(ml
->mounts
, ml
->n_mounts
, mount_path_compare
);
1787 drop_duplicates(ml
);
1788 drop_outside_root(ml
, root_directory
);
1789 drop_inaccessible(ml
);
1793 static int create_symlinks_from_tuples(const char *root
, char **strv_symlinks
) {
1796 STRV_FOREACH_PAIR(src
, dst
, strv_symlinks
) {
1797 _cleanup_free_
char *src_abs
= NULL
, *dst_abs
= NULL
;
1799 src_abs
= path_join(root
, *src
);
1800 dst_abs
= path_join(root
, *dst
);
1801 if (!src_abs
|| !dst_abs
)
1804 r
= mkdir_parents_label(dst_abs
, 0755);
1806 return log_debug_errno(
1808 "Failed to create parent directory for symlink '%s': %m",
1811 r
= symlink_idempotent(src_abs
, dst_abs
, true);
1813 return log_debug_errno(
1815 "Failed to create symlink from '%s' to '%s': %m",
1823 static void mount_entry_path_debug_string(const char *root
, MountEntry
*m
, char **error_path
) {
1826 /* Create a string suitable for debugging logs, stripping for example the local working directory.
1827 * For example, with a BindPaths=/var/bar that does not exist on the host:
1830 * foo.service: Failed to set up mount namespacing: /run/systemd/unit-root/var/bar: No such file or directory
1832 * foo.service: Failed to set up mount namespacing: /var/bar: No such file or directory
1834 * Note that this is an error path, so no OOM check is done on purpose. */
1839 if (!mount_entry_path(m
)) {
1845 const char *e
= startswith(mount_entry_path(m
), root
);
1847 *error_path
= strdup(e
);
1852 *error_path
= strdup(mount_entry_path(m
));
1856 static int apply_mounts(
1859 const NamespaceParameters
*p
,
1860 char **error_path
) {
1862 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
1863 _cleanup_free_
char **deny_list
= NULL
;
1870 if (ml
->n_mounts
== 0) /* Shortcut: nothing to do */
1873 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1874 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
1875 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
1876 if (!proc_self_mountinfo
) {
1880 *error_path
= strdup("/proc/self/mountinfo");
1882 return log_debug_errno(r
, "Failed to open /proc/self/mountinfo: %m");
1885 /* First round, establish all mounts we need */
1889 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
1894 /* ExtensionImages/Directories are first opened in the propagate directory, not in the root_directory */
1895 r
= follow_symlink(!IN_SET(m
->mode
, EXTENSION_IMAGES
, EXTENSION_DIRECTORIES
) ? root
: NULL
, m
);
1897 mount_entry_path_debug_string(root
, m
, error_path
);
1901 /* We hit a symlinked mount point. The entry got rewritten and might
1902 * point to a very different place now. Let's normalize the changed
1903 * list, and start from the beginning. After all to mount the entry
1904 * at the new location we might need some other mounts first */
1909 r
= apply_one_mount(root
, m
, p
);
1911 mount_entry_path_debug_string(root
, m
, error_path
);
1921 drop_unused_mounts(ml
, root
);
1924 /* Now that all filesystems have been set up, but before the
1925 * read-only switches are flipped, create the exec dirs and other symlinks.
1926 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
1927 * exist, which means this will be a no-op. */
1928 r
= create_symlinks_from_tuples(root
, p
->symlinks
);
1930 return log_debug_errno(r
, "Failed to set up symlinks inside mount namespace: %m");
1932 /* Create a deny list we can pass to bind_mount_recursive() */
1933 deny_list
= new(char*, ml
->n_mounts
+1);
1936 for (size_t j
= 0; j
< ml
->n_mounts
; j
++)
1937 deny_list
[j
] = (char*) mount_entry_path(ml
->mounts
+j
);
1938 deny_list
[ml
->n_mounts
] = NULL
;
1940 /* Second round, flip the ro bits if necessary. */
1941 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
1942 r
= make_read_only(m
, deny_list
, proc_self_mountinfo
);
1944 mount_entry_path_debug_string(root
, m
, error_path
);
1949 /* Third round, flip the noexec bits with a simplified deny list. */
1950 for (size_t j
= 0; j
< ml
->n_mounts
; j
++)
1951 if (IN_SET((ml
->mounts
+j
)->mode
, EXEC
, NOEXEC
))
1952 deny_list
[j
] = (char*) mount_entry_path(ml
->mounts
+j
);
1953 deny_list
[ml
->n_mounts
] = NULL
;
1955 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
1956 r
= make_noexec(m
, deny_list
, proc_self_mountinfo
);
1958 mount_entry_path_debug_string(root
, m
, error_path
);
1963 /* Fourth round, flip the nosuid bits without a deny list. */
1964 if (p
->mount_nosuid
)
1965 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
1966 r
= make_nosuid(m
, proc_self_mountinfo
);
1968 mount_entry_path_debug_string(root
, m
, error_path
);
1976 static bool root_read_only(
1977 char **read_only_paths
,
1978 ProtectSystem protect_system
) {
1980 /* Determine whether the root directory is going to be read-only given the configured settings. */
1982 if (protect_system
== PROTECT_SYSTEM_STRICT
)
1985 if (prefixed_path_strv_contains(read_only_paths
, "/"))
1991 static bool home_read_only(
1992 char** read_only_paths
,
1993 char** inaccessible_paths
,
1994 char** empty_directories
,
1995 const BindMount
*bind_mounts
,
1996 size_t n_bind_mounts
,
1997 const TemporaryFileSystem
*temporary_filesystems
,
1998 size_t n_temporary_filesystems
,
1999 ProtectHome protect_home
) {
2001 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
2002 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
2005 if (protect_home
!= PROTECT_HOME_NO
)
2008 if (prefixed_path_strv_contains(read_only_paths
, "/home") ||
2009 prefixed_path_strv_contains(inaccessible_paths
, "/home") ||
2010 prefixed_path_strv_contains(empty_directories
, "/home"))
2013 for (size_t i
= 0; i
< n_temporary_filesystems
; i
++)
2014 if (path_equal(temporary_filesystems
[i
].path
, "/home"))
2017 /* If /home is overmounted with some dir from the host it's not writable. */
2018 for (size_t i
= 0; i
< n_bind_mounts
; i
++)
2019 if (path_equal(bind_mounts
[i
].destination
, "/home"))
2025 int setup_namespace(const NamespaceParameters
*p
, char **error_path
) {
2027 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2028 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2029 _cleanup_strv_free_
char **hierarchies
= NULL
;
2030 _cleanup_(mount_list_done
) MountList ml
= {};
2031 bool require_prefix
= false;
2033 DissectImageFlags dissect_image_flags
=
2034 DISSECT_IMAGE_GENERIC_ROOT
|
2035 DISSECT_IMAGE_REQUIRE_ROOT
|
2036 DISSECT_IMAGE_DISCARD_ON_LOOP
|
2037 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2038 DISSECT_IMAGE_FSCK
|
2039 DISSECT_IMAGE_USR_NO_ROOT
|
2040 DISSECT_IMAGE_GROWFS
|
2041 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
2042 DISSECT_IMAGE_PIN_PARTITION_DEVICES
;
2047 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2048 * we configure take effect */
2049 BLOCK_WITH_UMASK(0000);
2051 bool setup_propagate
= !isempty(p
->propagate_dir
) && !isempty(p
->incoming_dir
);
2052 unsigned long mount_propagation_flag
= p
->mount_propagation_flag
!= 0 ? p
->mount_propagation_flag
: MS_SHARED
;
2054 if (p
->root_image
) {
2055 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2056 if (root_read_only(p
->read_only_paths
,
2057 p
->protect_system
) &&
2058 home_read_only(p
->read_only_paths
, p
->inaccessible_paths
, p
->empty_directories
,
2059 p
->bind_mounts
, p
->n_bind_mounts
, p
->temporary_filesystems
, p
->n_temporary_filesystems
,
2061 strv_isempty(p
->read_write_paths
))
2062 dissect_image_flags
|= DISSECT_IMAGE_READ_ONLY
;
2064 SET_FLAG(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
, p
->verity
&& p
->verity
->data_path
);
2066 r
= loop_device_make_by_path(
2068 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: -1 /* < 0 means writable if possible, read-only as fallback */,
2069 /* sector_size= */ UINT32_MAX
,
2070 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
2074 return log_debug_errno(r
, "Failed to create loop device for root image: %m");
2076 r
= dissect_loop_device(
2079 p
->root_image_options
,
2080 p
->root_image_policy
,
2081 dissect_image_flags
,
2084 return log_debug_errno(r
, "Failed to dissect image: %m");
2086 r
= dissected_image_load_verity_sig_partition(
2093 r
= dissected_image_decrypt(
2097 dissect_image_flags
);
2099 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
2102 if (p
->root_directory
)
2103 root
= p
->root_directory
;
2105 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2106 * when running tests (test-execute), it might not have been created yet so let's make sure
2107 * we create it if it doesn't already exist. */
2108 (void) mkdir_p_label("/run/systemd", 0755);
2110 /* Always create the mount namespace in a temporary directory, instead of operating directly
2111 * in the root. The temporary directory prevents any mounts from being potentially obscured
2112 * my other mounts we already applied. We use the same mount point for all images, which is
2113 * safe, since they all live in their own namespaces after all, and hence won't see each
2114 * other. (Note: this directory is also created by PID 1 early on, we create it here for
2115 * similar reasons as /run/systemd/ first.) */
2116 root
= "/run/systemd/mount-rootfs";
2117 (void) mkdir_label(root
, 0555);
2119 require_prefix
= true;
2122 if (p
->n_extension_images
> 0 || !strv_isempty(p
->extension_directories
)) {
2123 /* Hierarchy population needs to be done for sysext and confext extension images */
2124 r
= parse_env_extension_hierarchies(&hierarchies
, "SYSTEMD_SYSEXT_AND_CONFEXT_HIERARCHIES");
2129 r
= append_access_mounts(&ml
, p
->read_write_paths
, READWRITE
, require_prefix
);
2133 r
= append_access_mounts(&ml
, p
->read_only_paths
, READONLY
, require_prefix
);
2137 r
= append_access_mounts(&ml
, p
->inaccessible_paths
, INACCESSIBLE
, require_prefix
);
2141 r
= append_access_mounts(&ml
, p
->exec_paths
, EXEC
, require_prefix
);
2145 r
= append_access_mounts(&ml
, p
->no_exec_paths
, NOEXEC
, require_prefix
);
2149 r
= append_empty_dir_mounts(&ml
, p
->empty_directories
);
2153 r
= append_bind_mounts(&ml
, p
->bind_mounts
, p
->n_bind_mounts
);
2157 r
= append_tmpfs_mounts(&ml
, p
->temporary_filesystems
, p
->n_temporary_filesystems
);
2162 bool ro
= streq(p
->tmp_dir
, RUN_SYSTEMD_EMPTY
);
2164 MountEntry
*me
= mount_list_extend(&ml
);
2166 return log_oom_debug();
2168 *me
= (MountEntry
) {
2169 .path_const
= "/tmp",
2170 .mode
= ro
? PRIVATE_TMP_READONLY
: PRIVATE_TMP
,
2171 .source_const
= p
->tmp_dir
,
2175 if (p
->var_tmp_dir
) {
2176 bool ro
= streq(p
->var_tmp_dir
, RUN_SYSTEMD_EMPTY
);
2178 MountEntry
*me
= mount_list_extend(&ml
);
2180 return log_oom_debug();
2182 *me
= (MountEntry
) {
2183 .path_const
= "/var/tmp",
2184 .mode
= ro
? PRIVATE_TMP_READONLY
: PRIVATE_TMP
,
2185 .source_const
= p
->var_tmp_dir
,
2189 r
= append_mount_images(&ml
, p
->mount_images
, p
->n_mount_images
);
2193 r
= append_extensions(&ml
, root
, p
->extension_dir
, hierarchies
, p
->extension_images
, p
->n_extension_images
, p
->extension_directories
);
2197 if (p
->private_dev
) {
2198 MountEntry
*me
= mount_list_extend(&ml
);
2200 return log_oom_debug();
2202 *me
= (MountEntry
) {
2203 .path_const
= "/dev",
2204 .mode
= PRIVATE_DEV
,
2205 .flags
= DEV_MOUNT_OPTIONS
,
2209 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the protective
2210 mounts to non-pid /proc paths would fail. But the pid only option may have failed gracefully, so
2211 let's try the mounts but it's not fatal if they don't succeed. */
2212 bool ignore_protect_proc
= p
->ignore_protect_paths
|| p
->proc_subset
== PROC_SUBSET_PID
;
2213 if (p
->protect_kernel_tunables
) {
2214 r
= append_static_mounts(&ml
,
2215 protect_kernel_tunables_proc_table
,
2216 ELEMENTSOF(protect_kernel_tunables_proc_table
),
2217 ignore_protect_proc
);
2221 r
= append_static_mounts(&ml
,
2222 protect_kernel_tunables_sys_table
,
2223 ELEMENTSOF(protect_kernel_tunables_sys_table
),
2224 p
->ignore_protect_paths
);
2229 if (p
->protect_kernel_modules
) {
2230 r
= append_static_mounts(&ml
,
2231 protect_kernel_modules_table
,
2232 ELEMENTSOF(protect_kernel_modules_table
),
2233 p
->ignore_protect_paths
);
2238 if (p
->protect_kernel_logs
) {
2239 r
= append_static_mounts(&ml
,
2240 protect_kernel_logs_proc_table
,
2241 ELEMENTSOF(protect_kernel_logs_proc_table
),
2242 ignore_protect_proc
);
2246 r
= append_static_mounts(&ml
,
2247 protect_kernel_logs_dev_table
,
2248 ELEMENTSOF(protect_kernel_logs_dev_table
),
2249 p
->ignore_protect_paths
);
2254 if (p
->protect_control_groups
) {
2255 MountEntry
*me
= mount_list_extend(&ml
);
2257 return log_oom_debug();
2259 *me
= (MountEntry
) {
2260 .path_const
= "/sys/fs/cgroup",
2265 r
= append_protect_home(&ml
, p
->protect_home
, p
->ignore_protect_paths
);
2269 r
= append_protect_system(&ml
, p
->protect_system
, false);
2273 if (namespace_parameters_mount_apivfs(p
)) {
2274 r
= append_static_mounts(&ml
,
2276 ELEMENTSOF(apivfs_table
),
2277 p
->ignore_protect_paths
);
2282 /* Note, if proc is mounted with subset=pid then neither of the two paths will exist, i.e. they are
2283 * implicitly protected by the mount option. */
2284 if (p
->protect_hostname
) {
2285 r
= append_static_mounts(
2287 protect_hostname_table
,
2288 ELEMENTSOF(protect_hostname_table
),
2289 ignore_protect_proc
);
2294 if (p
->private_network
) {
2295 MountEntry
*me
= mount_list_extend(&ml
);
2297 return log_oom_debug();
2299 *me
= (MountEntry
) {
2300 .path_const
= "/sys",
2301 .mode
= PRIVATE_SYSFS
,
2305 if (p
->private_ipc
) {
2306 MountEntry
*me
= mount_list_extend(&ml
);
2308 return log_oom_debug();
2310 *me
= (MountEntry
) {
2311 .path_const
= "/dev/mqueue",
2313 .flags
= MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
2317 if (p
->creds_path
) {
2318 /* If our service has a credentials store configured, then bind that one in, but hide
2319 * everything else. */
2321 MountEntry
*me
= mount_list_extend(&ml
);
2323 return log_oom_debug();
2325 *me
= (MountEntry
) {
2326 .path_const
= "/run/credentials",
2329 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
2330 .flags
= MS_NODEV
|MS_STRICTATIME
|MS_NOSUID
|MS_NOEXEC
,
2333 me
= mount_list_extend(&ml
);
2335 return log_oom_debug();
2337 *me
= (MountEntry
) {
2338 .path_const
= p
->creds_path
,
2341 .source_const
= p
->creds_path
,
2345 /* If our service has no credentials store configured, then make the whole credentials tree
2346 * inaccessible wholesale. */
2348 MountEntry
*me
= mount_list_extend(&ml
);
2350 return log_oom_debug();
2352 *me
= (MountEntry
) {
2353 .path_const
= "/run/credentials",
2354 .mode
= INACCESSIBLE
,
2359 if (p
->log_namespace
) {
2360 _cleanup_free_
char *q
= NULL
;
2362 q
= strjoin("/run/systemd/journal.", p
->log_namespace
);
2364 return log_oom_debug();
2366 MountEntry
*me
= mount_list_extend(&ml
);
2368 return log_oom_debug();
2370 *me
= (MountEntry
) {
2371 .path_const
= "/run/systemd/journal",
2372 .mode
= BIND_MOUNT_RECURSIVE
,
2374 .source_malloc
= TAKE_PTR(q
),
2378 /* Will be used to add bind mounts at runtime */
2379 if (setup_propagate
) {
2380 MountEntry
*me
= mount_list_extend(&ml
);
2382 return log_oom_debug();
2384 *me
= (MountEntry
) {
2385 .source_const
= p
->propagate_dir
,
2386 .path_const
= p
->incoming_dir
,
2392 if (p
->notify_socket
) {
2393 MountEntry
*me
= mount_list_extend(&ml
);
2395 return log_oom_debug();
2397 *me
= (MountEntry
) {
2398 .path_const
= p
->notify_socket
,
2399 .source_const
= p
->notify_socket
,
2405 if (p
->host_os_release_stage
) {
2406 MountEntry
*me
= mount_list_extend(&ml
);
2408 return log_oom_debug();
2410 *me
= (MountEntry
) {
2411 .path_const
= "/run/host/.os-release-stage/",
2412 .source_const
= p
->host_os_release_stage
,
2415 .ignore
= true, /* Live copy, don't hard-fail if it goes missing */
2419 /* Prepend the root directory where that's necessary */
2420 r
= prefix_where_needed(&ml
, root
);
2424 drop_unused_mounts(&ml
, root
);
2426 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
2428 if (unshare(CLONE_NEWNS
) < 0) {
2429 r
= log_debug_errno(errno
, "Failed to unshare the mount namespace: %m");
2431 if (ERRNO_IS_PRIVILEGE(r
) ||
2432 ERRNO_IS_NOT_SUPPORTED(r
))
2433 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
2434 * in place that doesn't allow us to create namespaces (or a missing cap), then
2435 * propagate a recognizable error back, which the caller can use to detect this case
2436 * (and only this) and optionally continue without namespacing applied. */
2442 /* Create the source directory to allow runtime propagation of mounts */
2443 if (setup_propagate
)
2444 (void) mkdir_p(p
->propagate_dir
, 0600);
2446 if (p
->n_extension_images
> 0 || !strv_isempty(p
->extension_directories
))
2447 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
2448 * mounts to create, so have the parent ready */
2449 (void) mkdir_p(p
->extension_dir
, 0600);
2451 /* Remount / as SLAVE so that nothing now mounted in the namespace
2452 * shows up in the parent */
2453 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
) < 0)
2454 return log_debug_errno(errno
, "Failed to remount '/' as SLAVE: %m");
2456 if (p
->root_image
) {
2457 /* A root image is specified, mount it to the right place */
2458 r
= dissected_image_mount(
2461 /* uid_shift= */ UID_INVALID
,
2462 /* uid_range= */ UID_INVALID
,
2463 /* userns_fd= */ -EBADF
,
2464 dissect_image_flags
);
2466 return log_debug_errno(r
, "Failed to mount root image: %m");
2468 /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
2470 r
= loop_device_flock(loop_device
, LOCK_UN
);
2472 return log_debug_errno(r
, "Failed to release lock on loopback block device: %m");
2474 r
= dissected_image_relinquish(dissected_image
);
2476 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
2478 } else if (p
->root_directory
) {
2480 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
2481 r
= path_is_mount_point(root
, NULL
, AT_SYMLINK_FOLLOW
);
2483 return log_debug_errno(r
, "Failed to detect that %s is a mount point or not: %m", root
);
2485 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2491 /* Let's mount the main root directory to the root directory to use */
2492 r
= mount_nofollow_verbose(LOG_DEBUG
, "/", root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2497 /* Try to set up the new root directory before mounting anything else there. */
2498 if (p
->root_image
|| p
->root_directory
)
2499 (void) base_filesystem_create(root
, UID_INVALID
, GID_INVALID
);
2501 /* Now make the magic happen */
2502 r
= apply_mounts(&ml
, root
, p
, error_path
);
2506 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
2507 r
= mount_switch_root(root
, /* mount_propagation_flag = */ 0);
2508 if (r
== -EINVAL
&& p
->root_directory
) {
2509 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
2510 * namespace) and the root_directory is already a mount point in the parent namespace,
2511 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
2512 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
2513 * mount point) and try again. */
2514 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2517 r
= mount_switch_root(root
, /* mount_propagation_flag = */ 0);
2520 return log_debug_errno(r
, "Failed to mount root with MS_MOVE: %m");
2522 /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
2523 * the host, since what's disconnected is disconnected. */
2524 if (mount(NULL
, "/", NULL
, mount_propagation_flag
| MS_REC
, NULL
) < 0)
2525 return log_debug_errno(errno
, "Failed to remount '/' with desired mount flags: %m");
2527 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only supported for
2528 * non-shared mounts. This needs to happen after remounting / or it will fail. */
2529 if (setup_propagate
&& mount(NULL
, p
->incoming_dir
, NULL
, MS_SLAVE
, NULL
) < 0)
2530 return log_debug_errno(errno
, "Failed to remount %s with MS_SLAVE: %m", p
->incoming_dir
);
2535 void bind_mount_free_many(BindMount
*b
, size_t n
) {
2536 assert(b
|| n
== 0);
2538 for (size_t i
= 0; i
< n
; i
++) {
2540 free(b
[i
].destination
);
2546 int bind_mount_add(BindMount
**b
, size_t *n
, const BindMount
*item
) {
2547 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2554 s
= strdup(item
->source
);
2558 d
= strdup(item
->destination
);
2562 c
= reallocarray(*b
, *n
+ 1, sizeof(BindMount
));
2568 c
[(*n
) ++] = (BindMount
) {
2569 .source
= TAKE_PTR(s
),
2570 .destination
= TAKE_PTR(d
),
2571 .read_only
= item
->read_only
,
2572 .nosuid
= item
->nosuid
,
2573 .recursive
= item
->recursive
,
2574 .ignore_enoent
= item
->ignore_enoent
,
2580 MountImage
* mount_image_free_many(MountImage
*m
, size_t *n
) {
2582 assert(m
|| *n
== 0);
2584 for (size_t i
= 0; i
< *n
; i
++) {
2586 free(m
[i
].destination
);
2587 mount_options_free_all(m
[i
].mount_options
);
2595 int mount_image_add(MountImage
**m
, size_t *n
, const MountImage
*item
) {
2596 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2597 _cleanup_(mount_options_free_allp
) MountOptions
*options
= NULL
;
2604 s
= strdup(item
->source
);
2608 if (item
->destination
) {
2609 d
= strdup(item
->destination
);
2614 LIST_FOREACH(mount_options
, i
, item
->mount_options
) {
2615 _cleanup_(mount_options_free_allp
) MountOptions
*o
= NULL
;
2617 o
= new(MountOptions
, 1);
2621 *o
= (MountOptions
) {
2622 .partition_designator
= i
->partition_designator
,
2623 .options
= strdup(i
->options
),
2628 LIST_APPEND(mount_options
, options
, TAKE_PTR(o
));
2631 c
= reallocarray(*m
, *n
+ 1, sizeof(MountImage
));
2637 c
[(*n
) ++] = (MountImage
) {
2638 .source
= TAKE_PTR(s
),
2639 .destination
= TAKE_PTR(d
),
2640 .mount_options
= TAKE_PTR(options
),
2641 .ignore_enoent
= item
->ignore_enoent
,
2648 void temporary_filesystem_free_many(TemporaryFileSystem
*t
, size_t n
) {
2649 assert(t
|| n
== 0);
2651 for (size_t i
= 0; i
< n
; i
++) {
2659 int temporary_filesystem_add(
2660 TemporaryFileSystem
**t
,
2663 const char *options
) {
2665 _cleanup_free_
char *p
= NULL
, *o
= NULL
;
2666 TemporaryFileSystem
*c
;
2676 if (!isempty(options
)) {
2677 o
= strdup(options
);
2682 c
= reallocarray(*t
, *n
+ 1, sizeof(TemporaryFileSystem
));
2688 c
[(*n
) ++] = (TemporaryFileSystem
) {
2689 .path
= TAKE_PTR(p
),
2690 .options
= TAKE_PTR(o
),
2696 static int make_tmp_prefix(const char *prefix
) {
2697 _cleanup_free_
char *t
= NULL
;
2698 _cleanup_close_
int fd
= -EBADF
;
2701 /* Don't do anything unless we know the dir is actually missing */
2702 r
= access(prefix
, F_OK
);
2705 if (errno
!= ENOENT
)
2709 r
= mkdir_parents(prefix
, 0755);
2713 r
= tempfn_random(prefix
, NULL
, &t
);
2717 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2718 * the suid bit, below. */
2719 fd
= open_mkdir_at(AT_FDCWD
, t
, O_EXCL
|O_CLOEXEC
, 0777);
2723 r
= RET_NERRNO(fchmod(fd
, 01777));
2729 r
= RET_NERRNO(rename(t
, prefix
));
2732 return r
== -EEXIST
? 0 : r
; /* it's fine if someone else created the dir by now */
2739 static int setup_one_tmp_dir(const char *id
, const char *prefix
, char **path
, char **tmp_path
) {
2740 _cleanup_free_
char *x
= NULL
;
2741 _cleanup_free_
char *y
= NULL
;
2750 /* We include the boot id in the directory so that after a
2751 * reboot we can easily identify obsolete directories. */
2753 r
= sd_id128_get_boot(&boot_id
);
2757 x
= strjoin(prefix
, "/systemd-private-", SD_ID128_TO_STRING(boot_id
), "-", id
, "-XXXXXX");
2761 r
= make_tmp_prefix(prefix
);
2767 if (errno
== EROFS
|| ERRNO_IS_DISK_SPACE(errno
))
2774 y
= strjoin(x
, "/tmp");
2779 if (mkdir(y
, 0777 | S_ISVTX
) < 0)
2782 r
= label_fix_full(AT_FDCWD
, y
, prefix
, 0);
2787 *tmp_path
= TAKE_PTR(y
);
2789 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2790 * read-only. This way the service will get the EROFS result as if it was writing to the real
2793 r
= mkdir_p(RUN_SYSTEMD_EMPTY
, 0500);
2797 r
= free_and_strdup(&x
, RUN_SYSTEMD_EMPTY
);
2802 *path
= TAKE_PTR(x
);
2806 int setup_tmp_dirs(const char *id
, char **tmp_dir
, char **var_tmp_dir
) {
2807 _cleanup_(namespace_cleanup_tmpdirp
) char *a
= NULL
;
2808 _cleanup_(rmdir_and_freep
) char *a_tmp
= NULL
;
2814 assert(var_tmp_dir
);
2816 r
= setup_one_tmp_dir(id
, "/tmp", &a
, &a_tmp
);
2820 r
= setup_one_tmp_dir(id
, "/var/tmp", &b
, NULL
);
2824 a_tmp
= mfree(a_tmp
); /* avoid rmdir */
2825 *tmp_dir
= TAKE_PTR(a
);
2826 *var_tmp_dir
= TAKE_PTR(b
);
2831 int setup_shareable_ns(int ns_storage_socket
[static 2], unsigned long nsflag
) {
2832 _cleanup_close_
int ns
= -EBADF
;
2834 const char *ns_name
, *ns_path
;
2836 assert(ns_storage_socket
);
2837 assert(ns_storage_socket
[0] >= 0);
2838 assert(ns_storage_socket
[1] >= 0);
2840 ns_name
= namespace_single_flag_to_string(nsflag
);
2843 /* We use the passed socketpair as a storage buffer for our
2844 * namespace reference fd. Whatever process runs this first
2845 * shall create a new namespace, all others should just join
2846 * it. To serialize that we use a file lock on the socket
2849 * It's a bit crazy, but hey, works great! */
2851 r
= posix_lock(ns_storage_socket
[0], LOCK_EX
);
2855 CLEANUP_POSIX_UNLOCK(ns_storage_socket
[0]);
2857 ns
= receive_one_fd(ns_storage_socket
[0], MSG_PEEK
|MSG_DONTWAIT
);
2859 /* Yay, found something, so let's join the namespace */
2860 r
= RET_NERRNO(setns(ns
, nsflag
));
2870 /* Nothing stored yet, so let's create a new namespace. */
2872 if (unshare(nsflag
) < 0)
2875 (void) loopback_setup();
2877 ns_path
= strjoina("/proc/self/ns/", ns_name
);
2878 ns
= open(ns_path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2882 r
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2889 int open_shareable_ns_path(int ns_storage_socket
[static 2], const char *path
, unsigned long nsflag
) {
2890 _cleanup_close_
int ns
= -EBADF
;
2893 assert(ns_storage_socket
);
2894 assert(ns_storage_socket
[0] >= 0);
2895 assert(ns_storage_socket
[1] >= 0);
2898 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2899 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2900 * allocate a new anonymous ns if needed. */
2902 r
= posix_lock(ns_storage_socket
[0], LOCK_EX
);
2906 CLEANUP_POSIX_UNLOCK(ns_storage_socket
[0]);
2908 ns
= receive_one_fd(ns_storage_socket
[0], MSG_PEEK
|MSG_DONTWAIT
);
2914 /* Nothing stored yet. Open the file from the file system. */
2916 ns
= open(path
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
2920 r
= fd_is_ns(ns
, nsflag
);
2923 if (r
< 0 && r
!= -EUCLEAN
) /* EUCLEAN: we don't know */
2926 r
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2933 bool ns_type_supported(NamespaceType type
) {
2934 const char *t
, *ns_proc
;
2936 t
= namespace_type_to_string(type
);
2937 if (!t
) /* Don't know how to translate this? Then it's not supported */
2940 ns_proc
= strjoina("/proc/self/ns/", t
);
2941 return access(ns_proc
, F_OK
) == 0;
2944 static const char *const protect_home_table
[_PROTECT_HOME_MAX
] = {
2945 [PROTECT_HOME_NO
] = "no",
2946 [PROTECT_HOME_YES
] = "yes",
2947 [PROTECT_HOME_READ_ONLY
] = "read-only",
2948 [PROTECT_HOME_TMPFS
] = "tmpfs",
2951 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home
, ProtectHome
, PROTECT_HOME_YES
);
2953 static const char *const protect_system_table
[_PROTECT_SYSTEM_MAX
] = {
2954 [PROTECT_SYSTEM_NO
] = "no",
2955 [PROTECT_SYSTEM_YES
] = "yes",
2956 [PROTECT_SYSTEM_FULL
] = "full",
2957 [PROTECT_SYSTEM_STRICT
] = "strict",
2960 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system
, ProtectSystem
, PROTECT_SYSTEM_YES
);
2962 static const char* const namespace_type_table
[] = {
2963 [NAMESPACE_MOUNT
] = "mnt",
2964 [NAMESPACE_CGROUP
] = "cgroup",
2965 [NAMESPACE_UTS
] = "uts",
2966 [NAMESPACE_IPC
] = "ipc",
2967 [NAMESPACE_USER
] = "user",
2968 [NAMESPACE_PID
] = "pid",
2969 [NAMESPACE_NET
] = "net",
2970 [NAMESPACE_TIME
] = "time",
2973 DEFINE_STRING_TABLE_LOOKUP(namespace_type
, NamespaceType
);
2975 static const char* const protect_proc_table
[_PROTECT_PROC_MAX
] = {
2976 [PROTECT_PROC_DEFAULT
] = "default",
2977 [PROTECT_PROC_NOACCESS
] = "noaccess",
2978 [PROTECT_PROC_INVISIBLE
] = "invisible",
2979 [PROTECT_PROC_PTRACEABLE
] = "ptraceable",
2982 DEFINE_STRING_TABLE_LOOKUP(protect_proc
, ProtectProc
);
2984 static const char* const proc_subset_table
[_PROC_SUBSET_MAX
] = {
2985 [PROC_SUBSET_ALL
] = "all",
2986 [PROC_SUBSET_PID
] = "pid",
2989 DEFINE_STRING_TABLE_LOOKUP(proc_subset
, ProcSubset
);