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"
52 #define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
54 typedef enum MountMode
{
55 /* This is ordered by priority! */
62 MOUNT_PRIVATE_TMP_READ_ONLY
,
75 MOUNT_EXTENSION_DIRECTORY
, /* Bind-mounted outside the root directory, and used by subsequent mounts */
76 MOUNT_EXTENSION_IMAGE
, /* Mounted outside the root directory, and used by subsequent mounts */
78 MOUNT_READ_WRITE_IMPLICIT
, /* Should have the lowest priority. */
80 _MOUNT_MODE_INVALID
= -EINVAL
,
83 typedef enum MountEntryState
{
87 _MOUNT_ENTRY_STATE_MAX
,
88 _MOUNT_ENTRY_STATE_INVALID
= -EINVAL
,
91 typedef struct MountEntry
{
92 const char *path_const
; /* Memory allocated on stack or static */
94 bool ignore
:1; /* Ignore if path does not exist? */
95 bool has_prefix
:1; /* Already is prefixed by the root dir? */
96 bool read_only
:1; /* Shall this mount point be read-only? */
97 bool nosuid
:1; /* Shall set MS_NOSUID on the mount itself */
98 bool noexec
:1; /* Shall set MS_NOEXEC on the mount itself */
99 bool exec
:1; /* Shall clear MS_NOEXEC on the mount itself */
100 MountEntryState state
; /* Whether it was already processed or skipped */
101 char *path_malloc
; /* Use this instead of 'path_const' if we had to allocate memory */
102 const char *unprefixed_path_const
; /* If the path was amended with a prefix, these will save the original */
103 char *unprefixed_path_malloc
;
104 const char *source_const
; /* The source path, for bind mounts or images */
106 const char *options_const
;/* Mount options for tmpfs */
107 char *options_malloc
;
108 unsigned long flags
; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
110 LIST_HEAD(MountOptions
, image_options_const
);
111 char **overlay_layers
;
114 typedef struct MountList
{
119 /* 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
120 * something there already. These mounts are hence overridden by any other explicitly configured mounts. */
121 static const MountEntry apivfs_table
[] = {
122 { "/proc", MOUNT_PROCFS
, false },
123 { "/dev", MOUNT_BIND_DEV
, false },
124 { "/sys", MOUNT_BIND_SYSFS
, false },
125 { "/run", MOUNT_RUN
, false, .options_const
= "mode=0755" TMPFS_LIMITS_RUN
, .flags
= MS_NOSUID
|MS_NODEV
|MS_STRICTATIME
},
128 /* ProtectKernelTunables= option and the related filesystem APIs */
129 static const MountEntry protect_kernel_tunables_proc_table
[] = {
130 { "/proc/acpi", MOUNT_READ_ONLY
, true },
131 { "/proc/apm", MOUNT_READ_ONLY
, true }, /* Obsolete API, there's no point in permitting access to this, ever */
132 { "/proc/asound", MOUNT_READ_ONLY
, true },
133 { "/proc/bus", MOUNT_READ_ONLY
, true },
134 { "/proc/fs", MOUNT_READ_ONLY
, true },
135 { "/proc/irq", MOUNT_READ_ONLY
, true },
136 { "/proc/kallsyms", MOUNT_INACCESSIBLE
, true },
137 { "/proc/kcore", MOUNT_INACCESSIBLE
, true },
138 { "/proc/latency_stats", MOUNT_READ_ONLY
, true },
139 { "/proc/mtrr", MOUNT_READ_ONLY
, true },
140 { "/proc/scsi", MOUNT_READ_ONLY
, true },
141 { "/proc/sys", MOUNT_READ_ONLY
, true },
142 { "/proc/sysrq-trigger", MOUNT_READ_ONLY
, true },
143 { "/proc/timer_stats", MOUNT_READ_ONLY
, true },
146 static const MountEntry protect_kernel_tunables_sys_table
[] = {
147 { "/sys", MOUNT_READ_ONLY
, false },
148 { "/sys/fs/bpf", MOUNT_READ_ONLY
, true },
149 { "/sys/fs/cgroup", MOUNT_READ_WRITE_IMPLICIT
, false }, /* READ_ONLY is set by ProtectControlGroups= option */
150 { "/sys/fs/selinux", MOUNT_READ_WRITE_IMPLICIT
, true },
151 { "/sys/kernel/debug", MOUNT_READ_ONLY
, true },
152 { "/sys/kernel/tracing", MOUNT_READ_ONLY
, true },
155 /* ProtectKernelModules= option */
156 static const MountEntry protect_kernel_modules_table
[] = {
157 { "/usr/lib/modules", MOUNT_INACCESSIBLE
, true },
160 /* ProtectKernelLogs= option */
161 static const MountEntry protect_kernel_logs_proc_table
[] = {
162 { "/proc/kmsg", MOUNT_INACCESSIBLE
, true },
165 static const MountEntry protect_kernel_logs_dev_table
[] = {
166 { "/dev/kmsg", MOUNT_INACCESSIBLE
, true },
170 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
171 * system should be protected by ProtectSystem=
173 static const MountEntry protect_home_read_only_table
[] = {
174 { "/home", MOUNT_READ_ONLY
, true },
175 { "/run/user", MOUNT_READ_ONLY
, true },
176 { "/root", MOUNT_READ_ONLY
, true },
179 /* ProtectHome=tmpfs table */
180 static const MountEntry protect_home_tmpfs_table
[] = {
181 { "/home", MOUNT_TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
182 { "/run/user", MOUNT_TMPFS
, true, .read_only
= true, .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
183 { "/root", MOUNT_TMPFS
, true, .read_only
= true, .options_const
= "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST
, .flags
= MS_NODEV
|MS_STRICTATIME
},
186 /* ProtectHome=yes table */
187 static const MountEntry protect_home_yes_table
[] = {
188 { "/home", MOUNT_INACCESSIBLE
, true },
189 { "/run/user", MOUNT_INACCESSIBLE
, true },
190 { "/root", MOUNT_INACCESSIBLE
, true },
193 /* ProtectSystem=yes table */
194 static const MountEntry protect_system_yes_table
[] = {
195 { "/usr", MOUNT_READ_ONLY
, false },
196 { "/boot", MOUNT_READ_ONLY
, true },
197 { "/efi", MOUNT_READ_ONLY
, true },
200 /* ProtectSystem=full includes ProtectSystem=yes */
201 static const MountEntry protect_system_full_table
[] = {
202 { "/usr", MOUNT_READ_ONLY
, false },
203 { "/boot", MOUNT_READ_ONLY
, true },
204 { "/efi", MOUNT_READ_ONLY
, true },
205 { "/etc", MOUNT_READ_ONLY
, false },
208 /* ProtectSystem=strict table. In this strict mode, we mount everything read-only, except for /proc, /dev,
209 * /sys which are the kernel API VFS, which are left writable, but PrivateDevices= + ProtectKernelTunables=
210 * protect those, and these options should be fully orthogonal. (And of course /home and friends are also
211 * left writable, as ProtectHome= shall manage those, orthogonally).
213 static const MountEntry protect_system_strict_table
[] = {
214 { "/", MOUNT_READ_ONLY
, false },
215 { "/proc", MOUNT_READ_WRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
216 { "/sys", MOUNT_READ_WRITE_IMPLICIT
, false }, /* ProtectKernelTunables= */
217 { "/dev", MOUNT_READ_WRITE_IMPLICIT
, false }, /* PrivateDevices= */
218 { "/home", MOUNT_READ_WRITE_IMPLICIT
, true }, /* ProtectHome= */
219 { "/run/user", MOUNT_READ_WRITE_IMPLICIT
, true }, /* ProtectHome= */
220 { "/root", MOUNT_READ_WRITE_IMPLICIT
, true }, /* ProtectHome= */
223 /* ProtectHostname=yes able */
224 static const MountEntry protect_hostname_table
[] = {
225 { "/proc/sys/kernel/hostname", MOUNT_READ_ONLY
, false },
226 { "/proc/sys/kernel/domainname", MOUNT_READ_ONLY
, false },
229 static const char * const mount_mode_table
[_MOUNT_MODE_MAX
] = {
230 [MOUNT_INACCESSIBLE
] = "inaccessible",
231 [MOUNT_OVERLAY
] = "overlay",
232 [MOUNT_IMAGE
] = "image",
233 [MOUNT_BIND
] = "bind",
234 [MOUNT_BIND_RECURSIVE
] = "bind-recursive",
235 [MOUNT_PRIVATE_TMP
] = "private-tmp",
236 [MOUNT_PRIVATE_TMP_READ_ONLY
] = "private-tmp-read-only",
237 [MOUNT_PRIVATE_DEV
] = "private-dev",
238 [MOUNT_BIND_DEV
] = "bind-dev",
239 [MOUNT_EMPTY_DIR
] = "empty-dir",
240 [MOUNT_PRIVATE_SYSFS
] = "private-sysfs",
241 [MOUNT_BIND_SYSFS
] = "bind-sysfs",
242 [MOUNT_PROCFS
] = "procfs",
243 [MOUNT_READ_ONLY
] = "read-only",
244 [MOUNT_READ_WRITE
] = "read-write",
245 [MOUNT_NOEXEC
] = "noexec",
246 [MOUNT_EXEC
] = "exec",
247 [MOUNT_TMPFS
] = "tmpfs",
249 [MOUNT_EXTENSION_DIRECTORY
] = "extension-directory",
250 [MOUNT_EXTENSION_IMAGE
] = "extension-image",
251 [MOUNT_MQUEUEFS
] = "mqueuefs",
252 [MOUNT_READ_WRITE_IMPLICIT
] = "read-write-implicit",
255 /* Helper struct for naming simplicity and reusability */
256 static const struct {
257 const char *level_env
;
258 const char *level_env_print
;
259 } image_class_info
[_IMAGE_CLASS_MAX
] = {
261 .level_env
= "SYSEXT_LEVEL",
262 .level_env_print
= " SYSEXT_LEVEL=",
265 .level_env
= "CONFEXT_LEVEL",
266 .level_env_print
= " CONFEXT_LEVEL=",
270 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode
, MountMode
);
272 static const char *mount_entry_path(const MountEntry
*p
) {
275 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
276 * otherwise the stack/static ->path field is returned. */
278 return p
->path_malloc
?: p
->path_const
;
281 static const char *mount_entry_unprefixed_path(const MountEntry
*p
) {
284 /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
286 return p
->unprefixed_path_malloc
?: p
->unprefixed_path_const
?: mount_entry_path(p
);
289 static void mount_entry_consume_prefix(MountEntry
*p
, char *new_path
) {
291 assert(p
->path_malloc
|| p
->path_const
);
294 /* Saves current path in unprefixed_ variable, and takes over new_path */
296 free_and_replace(p
->unprefixed_path_malloc
, p
->path_malloc
);
297 /* If we didn't have a path on the heap, then it's a static one */
298 if (!p
->unprefixed_path_malloc
)
299 p
->unprefixed_path_const
= p
->path_const
;
300 p
->path_malloc
= new_path
;
301 p
->has_prefix
= true;
304 static bool mount_entry_read_only(const MountEntry
*p
) {
307 return p
->read_only
|| IN_SET(p
->mode
, MOUNT_READ_ONLY
, MOUNT_INACCESSIBLE
, MOUNT_PRIVATE_TMP_READ_ONLY
);
310 static bool mount_entry_noexec(const MountEntry
*p
) {
313 return p
->noexec
|| IN_SET(p
->mode
, MOUNT_NOEXEC
, MOUNT_INACCESSIBLE
, MOUNT_PRIVATE_SYSFS
, MOUNT_BIND_SYSFS
, MOUNT_PROCFS
);
316 static bool mount_entry_exec(const MountEntry
*p
) {
319 return p
->exec
|| p
->mode
== MOUNT_EXEC
;
322 static const char *mount_entry_source(const MountEntry
*p
) {
325 return p
->source_malloc
?: p
->source_const
;
328 static const char *mount_entry_options(const MountEntry
*p
) {
331 return p
->options_malloc
?: p
->options_const
;
334 static void mount_entry_done(MountEntry
*p
) {
337 p
->path_malloc
= mfree(p
->path_malloc
);
338 p
->unprefixed_path_malloc
= mfree(p
->unprefixed_path_malloc
);
339 p
->source_malloc
= mfree(p
->source_malloc
);
340 p
->options_malloc
= mfree(p
->options_malloc
);
341 p
->overlay_layers
= strv_free(p
->overlay_layers
);
344 static void mount_list_done(MountList
*ml
) {
347 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
)
350 ml
->mounts
= mfree(ml
->mounts
);
354 static MountEntry
*mount_list_extend(MountList
*ml
) {
357 if (!GREEDY_REALLOC0(ml
->mounts
, ml
->n_mounts
+1))
360 return ml
->mounts
+ ml
->n_mounts
++;
363 static int append_access_mounts(MountList
*ml
, char **strv
, MountMode mode
, bool forcibly_require_prefix
) {
366 /* Adds a list of user-supplied READ_WRITE/READ_WRITE_IMPLICIT/READ_ONLY/INACCESSIBLE entries */
368 STRV_FOREACH(i
, strv
) {
369 bool ignore
= false, needs_prefix
= false;
372 /* Look for any prefixes */
373 if (startswith(e
, "-")) {
377 if (startswith(e
, "+")) {
382 if (!path_is_absolute(e
))
383 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Path is not absolute: %s", e
);
385 MountEntry
*me
= mount_list_extend(ml
);
387 return log_oom_debug();
393 .has_prefix
= !needs_prefix
&& !forcibly_require_prefix
,
400 static int append_empty_dir_mounts(MountList
*ml
, char **strv
) {
403 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
404 * "/private/" boundary directories for DynamicUser=1. */
406 STRV_FOREACH(i
, strv
) {
407 MountEntry
*me
= mount_list_extend(ml
);
409 return log_oom_debug();
413 .mode
= MOUNT_EMPTY_DIR
,
416 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
417 .flags
= MS_NOSUID
|MS_NOEXEC
|MS_NODEV
|MS_STRICTATIME
,
424 static int append_bind_mounts(MountList
*ml
, const BindMount
*binds
, size_t n
) {
426 assert(binds
|| n
== 0);
428 FOREACH_ARRAY(b
, binds
, n
) {
429 MountEntry
*me
= mount_list_extend(ml
);
431 return log_oom_debug();
434 .path_const
= b
->destination
,
435 .mode
= b
->recursive
? MOUNT_BIND_RECURSIVE
: MOUNT_BIND
,
436 .read_only
= b
->read_only
,
438 .source_const
= b
->source
,
439 .ignore
= b
->ignore_enoent
,
446 static int append_mount_images(MountList
*ml
, const MountImage
*mount_images
, size_t n
) {
448 assert(mount_images
|| n
== 0);
450 FOREACH_ARRAY(m
, mount_images
, n
) {
451 MountEntry
*me
= mount_list_extend(ml
);
453 return log_oom_debug();
456 .path_const
= m
->destination
,
458 .source_const
= m
->source
,
459 .image_options_const
= m
->mount_options
,
460 .ignore
= m
->ignore_enoent
,
467 static int append_extensions(
470 const char *extension_dir
,
472 const MountImage
*mount_images
,
474 char **extension_directories
) {
476 char ***overlays
= NULL
;
477 size_t n_overlays
= 0;
482 if (n
== 0 && strv_isempty(extension_directories
))
485 assert(extension_dir
);
487 n_overlays
= strv_length(hierarchies
);
491 /* Prepare a list of overlays, that will have as each element a strv containing all the layers that
492 * will later be concatenated as a lowerdir= parameter for the mount operation.
493 * The overlays vector will have the same number of elements and will correspond to the
494 * hierarchies vector, so they can be iterated upon together. */
495 overlays
= new0(char**, n_overlays
);
499 CLEANUP_ARRAY(overlays
, n_overlays
, strv_free_many
);
501 /* First, prepare a mount for each image, but these won't be visible to the unit, instead
502 * they will be mounted in our propagate directory, and used as a source for the overlay. */
503 for (size_t i
= 0; i
< n
; i
++) {
504 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
505 _cleanup_free_
char *mount_point
= NULL
;
506 const MountImage
*m
= mount_images
+ i
;
508 r
= path_pick(/* toplevel_path= */ NULL
,
509 /* toplevel_fd= */ AT_FDCWD
,
511 &pick_filter_image_raw
,
512 PICK_ARCHITECTURE
|PICK_TRIES
,
517 return log_debug_errno(
518 SYNTHETIC_ERRNO(ENOENT
),
519 "No matching entry in .v/ directory %s found.",
522 if (asprintf(&mount_point
, "%s/%zu", extension_dir
, i
) < 0)
525 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
526 char *prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
527 if (!prefixed_hierarchy
)
530 r
= strv_consume(&overlays
[j
], TAKE_PTR(prefixed_hierarchy
));
535 MountEntry
*me
= mount_list_extend(ml
);
540 .path_malloc
= TAKE_PTR(mount_point
),
541 .image_options_const
= m
->mount_options
,
542 .ignore
= m
->ignore_enoent
,
543 .source_malloc
= TAKE_PTR(result
.path
),
544 .mode
= MOUNT_EXTENSION_IMAGE
,
549 /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
550 * Bind mount them in the same location as the ExtensionImages, so that we
551 * can check that they are valid trees (extension-release.d). */
552 STRV_FOREACH(extension_directory
, extension_directories
) {
553 _cleanup_(pick_result_done
) PickResult result
= PICK_RESULT_NULL
;
554 _cleanup_free_
char *mount_point
= NULL
;
555 const char *e
= *extension_directory
;
556 bool ignore_enoent
= false;
558 /* Pick up the counter where the ExtensionImages left it. */
559 if (asprintf(&mount_point
, "%s/%zu", extension_dir
, n
++) < 0)
562 /* Look for any prefixes */
563 if (startswith(e
, "-")) {
565 ignore_enoent
= true;
567 /* Ignore this for now */
568 if (startswith(e
, "+"))
571 r
= path_pick(/* toplevel_path= */ NULL
,
572 /* toplevel_fd= */ AT_FDCWD
,
574 &pick_filter_image_dir
,
575 PICK_ARCHITECTURE
|PICK_TRIES
,
580 return log_debug_errno(
581 SYNTHETIC_ERRNO(ENOENT
),
582 "No matching entry in .v/ directory %s found.",
585 for (size_t j
= 0; hierarchies
&& hierarchies
[j
]; ++j
) {
586 char *prefixed_hierarchy
= path_join(mount_point
, hierarchies
[j
]);
587 if (!prefixed_hierarchy
)
590 r
= strv_consume(&overlays
[j
], TAKE_PTR(prefixed_hierarchy
));
595 MountEntry
*me
= mount_list_extend(ml
);
600 .path_malloc
= TAKE_PTR(mount_point
),
601 .source_malloc
= TAKE_PTR(result
.path
),
602 .mode
= MOUNT_EXTENSION_DIRECTORY
,
603 .ignore
= ignore_enoent
,
609 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
611 for (size_t i
= 0; hierarchies
&& hierarchies
[i
]; ++i
) {
612 _cleanup_free_
char *prefixed_hierarchy
= NULL
;
614 prefixed_hierarchy
= path_join(root
, hierarchies
[i
]);
615 if (!prefixed_hierarchy
)
618 MountEntry
*me
= mount_list_extend(ml
);
623 .path_malloc
= TAKE_PTR(prefixed_hierarchy
),
624 .overlay_layers
= TAKE_PTR(overlays
[i
]),
625 .mode
= MOUNT_OVERLAY
,
627 .ignore
= true, /* If the source image doesn't set the ignore bit it will fail earlier. */
634 static int append_tmpfs_mounts(MountList
*ml
, const TemporaryFileSystem
*tmpfs
, size_t n
) {
636 assert(tmpfs
|| n
== 0);
638 FOREACH_ARRAY(t
, tmpfs
, n
) {
639 _cleanup_free_
char *o
= NULL
, *str
= NULL
;
644 if (!path_is_absolute(t
->path
))
645 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Path is not absolute: %s", t
->path
);
647 str
= strjoin("mode=0755" NESTED_TMPFS_LIMITS
",", t
->options
);
651 r
= mount_option_mangle(str
, MS_NODEV
|MS_STRICTATIME
, &flags
, &o
);
653 return log_debug_errno(r
, "Failed to parse mount option '%s': %m", str
);
655 ro
= flags
& MS_RDONLY
;
658 MountEntry
*me
= mount_list_extend(ml
);
660 return log_oom_debug();
663 .path_const
= t
->path
,
666 .options_malloc
= TAKE_PTR(o
),
674 static int append_static_mounts(MountList
*ml
, const MountEntry
*mounts
, size_t n
, bool ignore_protect
) {
676 assert(mounts
|| n
== 0);
678 /* Adds a list of static pre-defined entries */
680 FOREACH_ARRAY(m
, mounts
, n
) {
681 MountEntry
*me
= mount_list_extend(ml
);
683 return log_oom_debug();
686 .path_const
= mount_entry_path(m
),
688 .ignore
= m
->ignore
|| ignore_protect
,
695 static int append_protect_home(MountList
*ml
, ProtectHome protect_home
, bool ignore_protect
) {
698 switch (protect_home
) {
700 case PROTECT_HOME_NO
:
703 case PROTECT_HOME_READ_ONLY
:
704 return append_static_mounts(ml
, protect_home_read_only_table
, ELEMENTSOF(protect_home_read_only_table
), ignore_protect
);
706 case PROTECT_HOME_TMPFS
:
707 return append_static_mounts(ml
, protect_home_tmpfs_table
, ELEMENTSOF(protect_home_tmpfs_table
), ignore_protect
);
709 case PROTECT_HOME_YES
:
710 return append_static_mounts(ml
, protect_home_yes_table
, ELEMENTSOF(protect_home_yes_table
), ignore_protect
);
713 assert_not_reached();
717 static int append_protect_system(MountList
*ml
, ProtectSystem protect_system
, bool ignore_protect
) {
720 switch (protect_system
) {
722 case PROTECT_SYSTEM_NO
:
725 case PROTECT_SYSTEM_STRICT
:
726 return append_static_mounts(ml
, protect_system_strict_table
, ELEMENTSOF(protect_system_strict_table
), ignore_protect
);
728 case PROTECT_SYSTEM_YES
:
729 return append_static_mounts(ml
, protect_system_yes_table
, ELEMENTSOF(protect_system_yes_table
), ignore_protect
);
731 case PROTECT_SYSTEM_FULL
:
732 return append_static_mounts(ml
, protect_system_full_table
, ELEMENTSOF(protect_system_full_table
), ignore_protect
);
735 assert_not_reached();
739 static int mount_path_compare(const MountEntry
*a
, const MountEntry
*b
) {
742 /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
743 * regardless of the prefix - they are set up in the propagate directory anyway */
744 d
= -CMP(a
->mode
== MOUNT_EXTENSION_IMAGE
, b
->mode
== MOUNT_EXTENSION_IMAGE
);
747 d
= -CMP(a
->mode
== MOUNT_EXTENSION_DIRECTORY
, b
->mode
== MOUNT_EXTENSION_DIRECTORY
);
751 /* If the paths are not equal, then order prefixes first */
752 d
= path_compare(mount_entry_path(a
), mount_entry_path(b
));
756 /* If the paths are equal, check the mode */
757 return CMP((int) a
->mode
, (int) b
->mode
);
760 static int prefix_where_needed(MountList
*ml
, const char *root_directory
) {
761 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
765 FOREACH_ARRAY(me
, ml
->mounts
, ml
->n_mounts
) {
771 s
= path_join(root_directory
, mount_entry_path(me
));
775 mount_entry_consume_prefix(me
, s
);
781 static void drop_duplicates(MountList
*ml
) {
782 MountEntry
*f
, *t
, *previous
;
786 /* Drops duplicate entries. Expects that the array is properly ordered already. */
788 for (f
= ml
->mounts
, t
= ml
->mounts
, previous
= NULL
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
790 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
791 * above. Note that we only drop duplicates that haven't been mounted yet. */
793 path_equal(mount_entry_path(f
), mount_entry_path(previous
)) &&
794 f
->state
== MOUNT_PENDING
&& previous
->state
== MOUNT_PENDING
) {
795 log_debug("%s (%s) is duplicate.", mount_entry_path(f
), mount_mode_to_string(f
->mode
));
796 /* Propagate the flags to the remaining entry */
797 previous
->read_only
= previous
->read_only
|| mount_entry_read_only(f
);
798 previous
->noexec
= previous
->noexec
|| mount_entry_noexec(f
);
799 previous
->exec
= previous
->exec
|| mount_entry_exec(f
);
809 ml
->n_mounts
= t
- ml
->mounts
;
812 static void drop_inaccessible(MountList
*ml
) {
814 const char *clear
= NULL
;
818 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
819 * ordered already. */
821 for (f
= ml
->mounts
, t
= ml
->mounts
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
823 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
824 * it, as inaccessible paths really should drop the entire subtree. */
825 if (clear
&& path_startswith(mount_entry_path(f
), clear
)) {
826 log_debug("%s is masked by %s.", mount_entry_path(f
), clear
);
831 clear
= f
->mode
== MOUNT_INACCESSIBLE
? mount_entry_path(f
) : NULL
;
837 ml
->n_mounts
= t
- ml
->mounts
;
840 static void drop_nop(MountList
*ml
) {
845 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
846 * list is ordered by prefixes. */
848 for (f
= ml
->mounts
, t
= ml
->mounts
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
850 /* Only suppress such subtrees for READ_ONLY, READ_WRITE and READ_WRITE_IMPLICIT entries */
851 if (IN_SET(f
->mode
, MOUNT_READ_ONLY
, MOUNT_READ_WRITE
, MOUNT_READ_WRITE_IMPLICIT
)) {
852 MountEntry
*found
= NULL
;
854 /* Now let's find the first parent of the entry we are looking at. */
855 for (MountEntry
*p
= PTR_SUB1(t
, ml
->mounts
); p
; p
= PTR_SUB1(p
, ml
->mounts
))
856 if (path_startswith(mount_entry_path(f
), mount_entry_path(p
))) {
861 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
862 if (found
&& found
->mode
== f
->mode
) {
863 log_debug("%s (%s) is made redundant by %s (%s)",
864 mount_entry_path(f
), mount_mode_to_string(f
->mode
),
865 mount_entry_path(found
), mount_mode_to_string(found
->mode
));
875 ml
->n_mounts
= t
- ml
->mounts
;
878 static void drop_outside_root(MountList
*ml
, const char *root_directory
) {
887 /* Drops all mounts that are outside of the root directory. */
889 for (f
= ml
->mounts
, t
= ml
->mounts
; f
< ml
->mounts
+ ml
->n_mounts
; f
++) {
891 /* ExtensionImages/Directories bases are opened in /run/systemd/unit-extensions on the host */
892 if (!IN_SET(f
->mode
, MOUNT_EXTENSION_IMAGE
, MOUNT_EXTENSION_DIRECTORY
) && !path_startswith(mount_entry_path(f
), root_directory
)) {
893 log_debug("%s is outside of root directory.", mount_entry_path(f
));
902 ml
->n_mounts
= t
- ml
->mounts
;
905 static int clone_device_node(
907 const char *temporary_mount
,
908 bool *make_devnode
) {
910 _cleanup_free_
char *sl
= NULL
;
911 const char *dn
, *bn
, *t
;
915 if (stat(d
, &st
) < 0) {
916 if (errno
== ENOENT
) {
917 log_debug_errno(errno
, "Device node '%s' to clone does not exist, ignoring.", d
);
921 return log_debug_errno(errno
, "Failed to stat() device node '%s' to clone, ignoring: %m", d
);
924 if (!S_ISBLK(st
.st_mode
) &&
925 !S_ISCHR(st
.st_mode
))
926 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
927 "Device node '%s' to clone is not a device node, ignoring.",
930 dn
= strjoina(temporary_mount
, d
);
932 /* First, try to create device node properly */
934 mac_selinux_create_file_prepare(d
, st
.st_mode
);
935 r
= mknod(dn
, st
.st_mode
, st
.st_rdev
);
936 mac_selinux_create_file_clear();
940 return log_debug_errno(errno
, "mknod failed for %s: %m", d
);
942 /* This didn't work, let's not try this again for the next iterations. */
943 *make_devnode
= false;
946 /* We're about to fall back to bind-mounting the device node. So create a dummy bind-mount target.
947 * Do not prepare device-node SELinux label (see issue 13762) */
948 r
= mknod(dn
, S_IFREG
, 0);
949 if (r
< 0 && errno
!= EEXIST
)
950 return log_debug_errno(errno
, "mknod() fallback failed for '%s': %m", d
);
952 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
953 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
954 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
955 r
= mount_nofollow_verbose(LOG_DEBUG
, d
, dn
, NULL
, MS_BIND
, NULL
);
960 bn
= path_startswith(d
, "/dev/");
964 /* Create symlinks like /dev/char/1:9 → ../urandom */
965 if (asprintf(&sl
, "%s/dev/%s/" DEVNUM_FORMAT_STR
,
967 S_ISCHR(st
.st_mode
) ? "char" : "block",
968 DEVNUM_FORMAT_VAL(st
.st_rdev
)) < 0)
969 return log_oom_debug();
971 (void) mkdir_parents(sl
, 0755);
973 t
= strjoina("../", bn
);
974 if (symlink(t
, sl
) < 0)
975 log_debug_errno(errno
, "Failed to symlink '%s' to '%s', ignoring: %m", t
, sl
);
980 static char *settle_runtime_dir(RuntimeScope scope
) {
983 if (scope
!= RUNTIME_SCOPE_USER
)
984 return strdup("/run/");
986 if (asprintf(&runtime_dir
, "/run/user/" UID_FMT
, geteuid()) < 0)
992 static int create_temporary_mount_point(RuntimeScope scope
, char **ret
) {
993 _cleanup_free_
char *runtime_dir
= NULL
, *temporary_mount
= NULL
;
997 runtime_dir
= settle_runtime_dir(scope
);
999 return log_oom_debug();
1001 temporary_mount
= path_join(runtime_dir
, "systemd/namespace-XXXXXX");
1002 if (!temporary_mount
)
1003 return log_oom_debug();
1005 if (!mkdtemp(temporary_mount
))
1006 return log_debug_errno(errno
, "Failed to create temporary directory '%s': %m", temporary_mount
);
1008 *ret
= TAKE_PTR(temporary_mount
);
1012 static int mount_private_dev(MountEntry
*m
, RuntimeScope scope
) {
1013 static const char devnodes
[] =
1021 _cleanup_free_
char *temporary_mount
= NULL
;
1022 const char *dev
= NULL
, *devpts
= NULL
, *devshm
= NULL
, *devhugepages
= NULL
, *devmqueue
= NULL
, *devlog
= NULL
, *devptmx
= NULL
;
1023 bool can_mknod
= true;
1028 r
= create_temporary_mount_point(scope
, &temporary_mount
);
1032 dev
= strjoina(temporary_mount
, "/dev");
1033 (void) mkdir(dev
, 0755);
1034 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", dev
, "tmpfs", DEV_MOUNT_OPTIONS
, "mode=0755" TMPFS_LIMITS_PRIVATE_DEV
);
1038 r
= label_fix_full(AT_FDCWD
, dev
, "/dev", 0);
1040 log_debug_errno(r
, "Failed to fix label of '%s' as /dev: %m", dev
);
1044 devpts
= strjoina(temporary_mount
, "/dev/pts");
1045 (void) mkdir(devpts
, 0755);
1046 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/pts", devpts
, NULL
, MS_BIND
, NULL
);
1050 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
1051 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
1052 * Thus, in that case make a clone.
1053 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
1054 r
= is_symlink("/dev/ptmx");
1056 log_debug_errno(r
, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
1059 devptmx
= strjoina(temporary_mount
, "/dev/ptmx");
1060 if (symlink("pts/ptmx", devptmx
) < 0) {
1061 r
= log_debug_errno(errno
, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx
);
1065 r
= clone_device_node("/dev/ptmx", temporary_mount
, &can_mknod
);
1070 devshm
= strjoina(temporary_mount
, "/dev/shm");
1071 (void) mkdir(devshm
, 0755);
1072 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev/shm", devshm
, NULL
, MS_BIND
, NULL
);
1076 devmqueue
= strjoina(temporary_mount
, "/dev/mqueue");
1077 (void) mkdir(devmqueue
, 0755);
1078 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/mqueue", devmqueue
, NULL
, MS_BIND
, NULL
);
1080 devhugepages
= strjoina(temporary_mount
, "/dev/hugepages");
1081 (void) mkdir(devhugepages
, 0755);
1082 (void) mount_nofollow_verbose(LOG_DEBUG
, "/dev/hugepages", devhugepages
, NULL
, MS_BIND
, NULL
);
1084 devlog
= strjoina(temporary_mount
, "/dev/log");
1085 if (symlink("/run/systemd/journal/dev-log", devlog
) < 0)
1086 log_debug_errno(errno
, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog
);
1088 NULSTR_FOREACH(d
, devnodes
) {
1089 r
= clone_device_node(d
, temporary_mount
, &can_mknod
);
1090 /* ENXIO means the *source* is not a device file, skip creation in that case */
1091 if (r
< 0 && r
!= -ENXIO
)
1095 r
= dev_setup(temporary_mount
, UID_INVALID
, GID_INVALID
);
1097 log_debug_errno(r
, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount
);
1099 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
1100 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
1101 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1103 /* Unmount everything in old /dev */
1104 r
= umount_recursive(mount_entry_path(m
), 0);
1106 log_debug_errno(r
, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m
));
1108 r
= mount_nofollow_verbose(LOG_DEBUG
, dev
, mount_entry_path(m
), NULL
, MS_MOVE
, NULL
);
1113 (void) rmdir(temporary_mount
);
1119 (void) umount_verbose(LOG_DEBUG
, devpts
, UMOUNT_NOFOLLOW
);
1122 (void) umount_verbose(LOG_DEBUG
, devshm
, UMOUNT_NOFOLLOW
);
1125 (void) umount_verbose(LOG_DEBUG
, devhugepages
, UMOUNT_NOFOLLOW
);
1128 (void) umount_verbose(LOG_DEBUG
, devmqueue
, UMOUNT_NOFOLLOW
);
1130 (void) umount_verbose(LOG_DEBUG
, dev
, UMOUNT_NOFOLLOW
);
1132 (void) rmdir(temporary_mount
);
1137 static int mount_bind_dev(const MountEntry
*m
) {
1142 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1143 * service's /dev. This is only used when RootDirectory= is set. */
1145 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1147 r
= path_is_mount_point(mount_entry_path(m
));
1149 return log_debug_errno(r
, "Unable to determine whether /dev is already mounted: %m");
1150 if (r
> 0) /* make this a NOP if /dev is already a mount point */
1153 r
= mount_nofollow_verbose(LOG_DEBUG
, "/dev", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1160 static int mount_bind_sysfs(const MountEntry
*m
) {
1165 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1167 r
= path_is_mount_point(mount_entry_path(m
));
1169 return log_debug_errno(r
, "Unable to determine whether /sys is already mounted: %m");
1170 if (r
> 0) /* make this a NOP if /sys is already a mount point */
1173 /* Bind mount the host's version so that we get all child mounts of it, too. */
1174 r
= mount_nofollow_verbose(LOG_DEBUG
, "/sys", mount_entry_path(m
), NULL
, MS_BIND
|MS_REC
, NULL
);
1181 static int mount_private_apivfs(
1183 const char *entry_path
,
1184 const char *bind_source
,
1186 RuntimeScope scope
) {
1188 _cleanup_(rmdir_and_freep
) char *temporary_mount
= NULL
;
1193 assert(bind_source
);
1195 (void) mkdir_p_label(entry_path
, 0755);
1197 /* First, check if we have enough privileges to mount a new instance. Note, a new sysfs instance
1198 * cannot be mounted on an already existing mount. Let's use a temporary place. */
1199 r
= create_temporary_mount_point(scope
, &temporary_mount
);
1203 r
= mount_nofollow_verbose(LOG_DEBUG
, fstype
, temporary_mount
, fstype
, MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, opts
);
1204 if (r
== -EINVAL
&& opts
)
1205 /* If this failed with EINVAL then this likely means the textual hidepid= stuff for procfs is
1206 * not supported by the kernel, and thus the per-instance hidepid= neither, which means we
1207 * really don't want to use it, since it would affect our host's /proc mount. Hence let's
1208 * gracefully fallback to a classic, unrestricted version. */
1209 r
= mount_nofollow_verbose(LOG_DEBUG
, fstype
, temporary_mount
, fstype
, MS_NOSUID
|MS_NOEXEC
|MS_NODEV
, /* opts = */ NULL
);
1210 if (ERRNO_IS_NEG_PRIVILEGE(r
)) {
1211 /* When we do not have enough privileges to mount a new instance, fall back to use an
1212 * existing mount. */
1214 r
= path_is_mount_point(entry_path
);
1216 return log_debug_errno(r
, "Unable to determine whether '%s' is already mounted: %m", entry_path
);
1218 return 0; /* Use the current mount as is. */
1220 /* We lack permissions to mount a new instance, and it is not already mounted. But we can
1221 * access the host's, so as a final fallback bind-mount it to the destination, as most likely
1222 * we are inside a user manager in an unprivileged user namespace. */
1223 r
= mount_nofollow_verbose(LOG_DEBUG
, bind_source
, entry_path
, /* fstype = */ NULL
, MS_BIND
|MS_REC
, /* opts = */ NULL
);
1232 /* OK. We have a new mount instance. Let's clear an existing mount and its submounts. */
1233 r
= umount_recursive(entry_path
, /* flags = */ 0);
1235 log_debug_errno(r
, "Failed to unmount directories below '%s', ignoring: %m", entry_path
);
1237 /* Then, move the new mount instance. */
1238 r
= mount_nofollow_verbose(LOG_DEBUG
, temporary_mount
, entry_path
, /* fstype = */ NULL
, MS_MOVE
, /* opts = */ NULL
);
1242 /* We mounted a new instance now. Let's bind mount the children over now. This matters for nspawn
1243 * where a bunch of files are overmounted, in particular the boot id. */
1244 (void) bind_mount_submounts(bind_source
, entry_path
);
1248 static int mount_private_sysfs(const MountEntry
*m
, const NamespaceParameters
*p
) {
1251 return mount_private_apivfs("sysfs", mount_entry_path(m
), "/sys", /* opts = */ NULL
, p
->runtime_scope
);
1254 static int mount_procfs(const MountEntry
*m
, const NamespaceParameters
*p
) {
1255 _cleanup_free_
char *opts
= NULL
;
1260 if (p
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1261 p
->proc_subset
!= PROC_SUBSET_ALL
) {
1263 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
1264 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
1265 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
1266 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
1267 * added in the same commit: if it's supported it is thus also per-instance. */
1269 const char *hpv
= p
->protect_proc
== PROTECT_PROC_DEFAULT
?
1271 protect_proc_to_string(p
->protect_proc
);
1273 /* hidepid= support was added in 5.8, so we can use fsconfig()/fsopen() (which were added in
1274 * 5.2) to check if hidepid= is supported. This avoids a noisy dmesg log by the kernel when
1275 * trying to use hidepid= on systems where it isn't supported. The same applies for subset=.
1276 * fsopen()/fsconfig() was also backported on some distros which allows us to detect
1277 * hidepid=/subset= support in even more scenarios. */
1279 if (mount_option_supported("proc", "hidepid", hpv
) != 0) {
1280 opts
= strjoin("hidepid=", hpv
);
1285 if (p
->proc_subset
== PROC_SUBSET_PID
&&
1286 mount_option_supported("proc", "subset", "pid") != 0)
1287 if (!strextend_with_separator(&opts
, ",", "subset=pid"))
1291 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1292 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1293 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1294 * mounted on /proc/ first. */
1295 return mount_private_apivfs("proc", mount_entry_path(m
), "/proc", opts
, p
->runtime_scope
);
1298 static int mount_tmpfs(const MountEntry
*m
) {
1299 const char *entry_path
, *inner_path
;
1304 entry_path
= mount_entry_path(m
);
1305 inner_path
= mount_entry_unprefixed_path(m
);
1307 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1310 (void) mkdir_p_label(entry_path
, 0755);
1311 (void) umount_recursive(entry_path
, 0);
1313 r
= mount_nofollow_verbose(LOG_DEBUG
, "tmpfs", entry_path
, "tmpfs", m
->flags
, mount_entry_options(m
));
1317 r
= label_fix_full(AT_FDCWD
, entry_path
, inner_path
, 0);
1319 return log_debug_errno(r
, "Failed to fix label of '%s' as '%s': %m", entry_path
, inner_path
);
1324 static int mount_run(const MountEntry
*m
) {
1329 r
= path_is_mount_point(mount_entry_path(m
));
1330 if (r
< 0 && r
!= -ENOENT
)
1331 return log_debug_errno(r
, "Unable to determine whether /run is already mounted: %m");
1332 if (r
> 0) /* make this a NOP if /run is already a mount point */
1335 return mount_tmpfs(m
);
1338 static int mount_mqueuefs(const MountEntry
*m
) {
1340 const char *entry_path
;
1344 entry_path
= mount_entry_path(m
);
1346 (void) mkdir_p_label(entry_path
, 0755);
1347 (void) umount_recursive(entry_path
, 0);
1349 r
= mount_nofollow_verbose(LOG_DEBUG
, "mqueue", entry_path
, "mqueue", m
->flags
, mount_entry_options(m
));
1356 static int mount_image(
1357 const MountEntry
*m
,
1358 const char *root_directory
,
1359 const ImagePolicy
*image_policy
) {
1361 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1362 *host_os_release_sysext_level
= NULL
, *host_os_release_confext_level
= NULL
,
1363 *extension_name
= NULL
;
1368 r
= path_extract_filename(mount_entry_source(m
), &extension_name
);
1370 return log_debug_errno(r
, "Failed to extract extension name from %s: %m", mount_entry_source(m
));
1372 if (m
->mode
== MOUNT_EXTENSION_IMAGE
) {
1373 r
= parse_os_release(
1374 empty_to_root(root_directory
),
1375 "ID", &host_os_release_id
,
1376 "VERSION_ID", &host_os_release_version_id
,
1377 image_class_info
[IMAGE_SYSEXT
].level_env
, &host_os_release_sysext_level
,
1378 image_class_info
[IMAGE_CONFEXT
].level_env
, &host_os_release_confext_level
,
1381 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1382 if (isempty(host_os_release_id
))
1383 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'ID' field not found or empty in 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1386 r
= verity_dissect_and_mount(
1388 mount_entry_source(m
),
1389 mount_entry_path(m
),
1390 m
->image_options_const
,
1393 host_os_release_version_id
,
1394 host_os_release_sysext_level
,
1395 host_os_release_confext_level
,
1396 /* required_sysext_scope= */ NULL
,
1397 /* ret_image= */ NULL
);
1398 if (r
== -ENOENT
&& m
->ignore
)
1400 if (r
== -ESTALE
&& host_os_release_id
)
1401 return log_error_errno(r
, // FIXME: this should not be logged ad LOG_ERR, as it will result in duplicate logging.
1402 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s%s%s",
1403 mount_entry_source(m
),
1405 host_os_release_version_id
? " VERSION_ID=" : "",
1406 strempty(host_os_release_version_id
),
1407 host_os_release_sysext_level
? image_class_info
[IMAGE_SYSEXT
].level_env_print
: "",
1408 strempty(host_os_release_sysext_level
),
1409 host_os_release_confext_level
? image_class_info
[IMAGE_CONFEXT
].level_env_print
: "",
1410 strempty(host_os_release_confext_level
));
1412 return log_debug_errno(r
, "Failed to mount image %s on %s: %m", mount_entry_source(m
), mount_entry_path(m
));
1417 static int mount_overlay(const MountEntry
*m
) {
1418 _cleanup_free_
char *options
= NULL
, *layers
= NULL
;
1423 /* Extension hierarchies are optional (e.g.: confext might not have /opt) so check if they actually
1424 * exist in an image before attempting to create an overlay with them, otherwise the mount will
1425 * fail. We can't check before this, as the images will not be mounted until now. */
1427 /* Note that lowerdir= parameters are in 'reverse' order, so the top-most directory in the overlay
1428 * comes first in the list. */
1429 STRV_FOREACH_BACKWARDS(o
, m
->overlay_layers
) {
1430 _cleanup_free_
char *escaped
= NULL
;
1432 r
= is_dir(*o
, /* follow= */ false);
1436 "Failed to check whether overlay layer source path '%s' exists, ignoring: %m",
1441 escaped
= shell_escape(*o
, ",:");
1443 return log_oom_debug();
1445 if (!strextend_with_separator(&layers
, ":", escaped
))
1446 return log_oom_debug();
1450 log_debug("None of the overlays specified in '%s' exist at the source, skipping.",
1451 mount_entry_options(m
));
1452 return 0; /* Only the root is set? Then there's nothing to overlay */
1455 options
= strjoin("lowerdir=", layers
, ":", mount_entry_path(m
)); /* The root goes in last */
1457 return log_oom_debug();
1459 (void) mkdir_p_label(mount_entry_path(m
), 0755);
1461 r
= mount_nofollow_verbose(LOG_DEBUG
, "overlay", mount_entry_path(m
), "overlay", MS_RDONLY
, options
);
1462 if (r
== -ENOENT
&& m
->ignore
)
1470 static int follow_symlink(
1471 const char *root_directory
,
1474 _cleanup_free_
char *target
= NULL
;
1477 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1478 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1479 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1480 * end and already have a fully normalized name. */
1482 r
= chase(mount_entry_path(m
), root_directory
, CHASE_STEP
|CHASE_NONEXISTENT
, &target
, NULL
);
1484 return log_debug_errno(r
, "Failed to chase symlinks '%s': %m", mount_entry_path(m
));
1485 if (r
> 0) /* Reached the end, nothing more to resolve */
1488 if (m
->n_followed
>= CHASE_MAX
) /* put a boundary on things */
1489 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1490 "Symlink loop on '%s'.",
1491 mount_entry_path(m
));
1493 log_debug("Followed mount entry path symlink %s %s %s.",
1494 mount_entry_path(m
), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), target
);
1496 mount_entry_consume_prefix(m
, TAKE_PTR(target
));
1503 static int apply_one_mount(
1504 const char *root_directory
,
1506 const NamespaceParameters
*p
) {
1508 _cleanup_free_
char *inaccessible
= NULL
;
1509 bool rbind
= true, make
= false;
1513 /* Return 1 when the mount should be post-processed (remounted r/o, etc.), 0 otherwise. In most
1514 * cases post-processing is the right thing, the typical exception is when the mount is gracefully
1520 log_debug("Applying namespace mount on %s", mount_entry_path(m
));
1524 case MOUNT_INACCESSIBLE
: {
1525 _cleanup_free_
char *runtime_dir
= NULL
;
1528 /* First, get rid of everything that is below if there
1529 * is anything... Then, overmount it with an
1530 * inaccessible path. */
1531 (void) umount_recursive(mount_entry_path(m
), 0);
1533 if (lstat(mount_entry_path(m
), &target
) < 0) {
1534 if (errno
== ENOENT
&& m
->ignore
)
1537 return log_debug_errno(errno
, "Failed to lstat() %s to determine what to mount over it: %m",
1538 mount_entry_path(m
));
1541 /* We don't pass the literal runtime scope through here but one based purely on our UID. This
1542 * means that the root user's --user services will use the host's inaccessible inodes rather
1543 * then root's private ones. This is preferable since it means device nodes that are
1544 * overmounted to make them inaccessible will be overmounted with a device node, rather than
1545 * an AF_UNIX socket inode. */
1546 runtime_dir
= settle_runtime_dir(geteuid() == 0 ? RUNTIME_SCOPE_SYSTEM
: RUNTIME_SCOPE_USER
);
1548 return log_oom_debug();
1550 r
= mode_to_inaccessible_node(runtime_dir
, target
.st_mode
, &inaccessible
);
1552 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP
),
1553 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
1554 what
= inaccessible
;
1558 case MOUNT_READ_ONLY
:
1559 case MOUNT_READ_WRITE
:
1560 case MOUNT_READ_WRITE_IMPLICIT
:
1563 r
= path_is_mount_point_full(mount_entry_path(m
), root_directory
, /* flags = */ 0);
1564 if (r
== -ENOENT
&& m
->ignore
)
1567 return log_debug_errno(r
, "Failed to determine whether %s is already a mount point: %m",
1568 mount_entry_path(m
));
1569 if (r
> 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1570 * and MS_NOEXEC bits for the mount point if needed. */
1572 /* This isn't a mount point yet, let's make it one. */
1573 what
= mount_entry_path(m
);
1576 case MOUNT_EXTENSION_DIRECTORY
: {
1577 _cleanup_free_
char *host_os_release_id
= NULL
, *host_os_release_version_id
= NULL
,
1578 *host_os_release_level
= NULL
, *extension_name
= NULL
;
1579 _cleanup_strv_free_
char **extension_release
= NULL
;
1580 ImageClass
class = IMAGE_SYSEXT
;
1582 r
= path_extract_filename(mount_entry_source(m
), &extension_name
);
1584 return log_debug_errno(r
, "Failed to extract extension name from %s: %m", mount_entry_source(m
));
1586 r
= load_extension_release_pairs(mount_entry_source(m
), IMAGE_SYSEXT
, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1588 r
= load_extension_release_pairs(mount_entry_source(m
), IMAGE_CONFEXT
, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1590 class = IMAGE_CONFEXT
;
1593 return log_debug_errno(r
, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m
));
1595 r
= parse_os_release(
1596 empty_to_root(root_directory
),
1597 "ID", &host_os_release_id
,
1598 "VERSION_ID", &host_os_release_version_id
,
1599 image_class_info
[class].level_env
, &host_os_release_level
,
1602 return log_debug_errno(r
, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory
));
1603 if (isempty(host_os_release_id
))
1604 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
));
1606 r
= load_extension_release_pairs(mount_entry_source(m
), class, extension_name
, /* relax_extension_release_check= */ false, &extension_release
);
1607 if (r
== -ENOENT
&& m
->ignore
)
1610 return log_debug_errno(r
, "Failed to parse directory %s extension-release metadata: %m", extension_name
);
1612 r
= extension_release_validate(
1615 host_os_release_version_id
,
1616 host_os_release_level
,
1617 /* host_extension_scope */ NULL
, /* Leave empty, we need to accept both system and portable */
1621 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Directory %s extension-release metadata does not match the root's", extension_name
);
1623 return log_debug_errno(r
, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name
);
1632 case MOUNT_BIND_RECURSIVE
: {
1633 _cleanup_free_
char *chased
= NULL
;
1635 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1636 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1637 * root directory to chase() here. */
1639 r
= chase(mount_entry_source(m
), NULL
, CHASE_TRAIL_SLASH
, &chased
, NULL
);
1640 if (r
== -ENOENT
&& m
->ignore
) {
1641 log_debug_errno(r
, "Path %s does not exist, ignoring.", mount_entry_source(m
));
1645 return log_debug_errno(r
, "Failed to follow symlinks on %s: %m", mount_entry_source(m
));
1647 log_debug("Followed source symlinks %s %s %s.",
1648 mount_entry_source(m
), special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), chased
);
1650 free_and_replace(m
->source_malloc
, chased
);
1652 what
= mount_entry_source(m
);
1657 case MOUNT_EMPTY_DIR
:
1659 return mount_tmpfs(m
);
1661 case MOUNT_PRIVATE_TMP
:
1662 case MOUNT_PRIVATE_TMP_READ_ONLY
:
1663 what
= mount_entry_source(m
);
1667 case MOUNT_PRIVATE_DEV
:
1668 return mount_private_dev(m
, p
->runtime_scope
);
1670 case MOUNT_BIND_DEV
:
1671 return mount_bind_dev(m
);
1673 case MOUNT_PRIVATE_SYSFS
:
1674 return mount_private_sysfs(m
, p
);
1676 case MOUNT_BIND_SYSFS
:
1677 return mount_bind_sysfs(m
);
1680 return mount_procfs(m
, p
);
1683 return mount_run(m
);
1685 case MOUNT_MQUEUEFS
:
1686 return mount_mqueuefs(m
);
1689 return mount_image(m
, NULL
, p
->mount_image_policy
);
1691 case MOUNT_EXTENSION_IMAGE
:
1692 return mount_image(m
, root_directory
, p
->extension_image_policy
);
1695 return mount_overlay(m
);
1698 assert_not_reached();
1703 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1705 bool try_again
= false;
1707 if (r
== -ENOENT
&& make
) {
1710 /* Hmm, either the source or the destination are missing. Let's see if we can create
1711 the destination, then try again. */
1713 (void) mkdir_parents(mount_entry_path(m
), 0755);
1715 q
= make_mount_point_inode_from_path(what
, mount_entry_path(m
), 0755);
1717 if (q
!= -EEXIST
) // FIXME: this shouldn't be logged at LOG_WARNING, but be bubbled up, and logged there to avoid duplicate logging
1718 log_warning_errno(q
, "Failed to create destination mount point node '%s', ignoring: %m",
1719 mount_entry_path(m
));
1725 r
= mount_nofollow_verbose(LOG_DEBUG
, what
, mount_entry_path(m
), NULL
, MS_BIND
|(rbind
? MS_REC
: 0), NULL
);
1727 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
1730 log_debug("Successfully mounted %s to %s", what
, mount_entry_path(m
));
1734 static int make_read_only(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1735 unsigned long new_flags
= 0, flags_mask
= 0;
1740 assert(proc_self_mountinfo
);
1742 if (m
->state
!= MOUNT_APPLIED
)
1745 if (mount_entry_read_only(m
) || m
->mode
== MOUNT_PRIVATE_DEV
) {
1746 new_flags
|= MS_RDONLY
;
1747 flags_mask
|= MS_RDONLY
;
1751 new_flags
|= MS_NOSUID
;
1752 flags_mask
|= MS_NOSUID
;
1755 if (flags_mask
== 0) /* No Change? */
1758 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1759 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1760 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1761 * and running Linux <= 4.17. */
1763 mount_entry_read_only(m
) &&
1764 !IN_SET(m
->mode
, MOUNT_EMPTY_DIR
, MOUNT_TMPFS
);
1766 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1768 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1770 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
1771 * read-only already stays this way. This improves compatibility with container managers, where we
1772 * won't attempt to undo read-only mounts already applied. */
1774 if (r
== -ENOENT
&& m
->ignore
)
1777 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1778 submounts
? " and its submounts" : "");
1782 static int make_noexec(const MountEntry
*m
, char **deny_list
, FILE *proc_self_mountinfo
) {
1783 unsigned long new_flags
= 0, flags_mask
= 0;
1788 assert(proc_self_mountinfo
);
1790 if (m
->state
!= MOUNT_APPLIED
)
1793 if (mount_entry_noexec(m
)) {
1794 new_flags
|= MS_NOEXEC
;
1795 flags_mask
|= MS_NOEXEC
;
1796 } else if (mount_entry_exec(m
)) {
1797 new_flags
&= ~MS_NOEXEC
;
1798 flags_mask
|= MS_NOEXEC
;
1801 if (flags_mask
== 0) /* No Change? */
1804 submounts
= !IN_SET(m
->mode
, MOUNT_EMPTY_DIR
, MOUNT_TMPFS
);
1807 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, deny_list
, proc_self_mountinfo
);
1809 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), new_flags
, flags_mask
, proc_self_mountinfo
);
1811 if (r
== -ENOENT
&& m
->ignore
)
1814 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1815 submounts
? " and its submounts" : "");
1819 static int make_nosuid(const MountEntry
*m
, FILE *proc_self_mountinfo
) {
1824 assert(proc_self_mountinfo
);
1826 if (m
->state
!= MOUNT_APPLIED
)
1829 submounts
= !IN_SET(m
->mode
, MOUNT_EMPTY_DIR
, MOUNT_TMPFS
);
1831 r
= bind_remount_recursive_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, NULL
, proc_self_mountinfo
);
1833 r
= bind_remount_one_with_mountinfo(mount_entry_path(m
), MS_NOSUID
, MS_NOSUID
, proc_self_mountinfo
);
1834 if (r
== -ENOENT
&& m
->ignore
)
1837 return log_debug_errno(r
, "Failed to re-mount '%s'%s: %m", mount_entry_path(m
),
1838 submounts
? " and its submounts" : "");
1842 static bool namespace_parameters_mount_apivfs(const NamespaceParameters
*p
) {
1846 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1847 * since to protect the API VFS mounts, they need to be around in the
1851 return p
->mount_apivfs
||
1852 p
->protect_control_groups
||
1853 p
->protect_kernel_tunables
||
1854 p
->protect_proc
!= PROTECT_PROC_DEFAULT
||
1855 p
->proc_subset
!= PROC_SUBSET_ALL
;
1858 /* Walk all mount entries and dropping any unused mounts. This affects all
1860 * - that are implicitly protected by a path that has been rendered inaccessible
1861 * - whose immediate parent requests the same protection mode as the mount itself
1862 * - that are outside of the relevant root directory
1863 * - which are duplicates
1865 static void drop_unused_mounts(MountList
*ml
, const char *root_directory
) {
1867 assert(root_directory
);
1869 assert(ml
->mounts
|| ml
->n_mounts
== 0);
1871 typesafe_qsort(ml
->mounts
, ml
->n_mounts
, mount_path_compare
);
1873 drop_duplicates(ml
);
1874 drop_outside_root(ml
, root_directory
);
1875 drop_inaccessible(ml
);
1879 static int create_symlinks_from_tuples(const char *root
, char **strv_symlinks
) {
1882 STRV_FOREACH_PAIR(src
, dst
, strv_symlinks
) {
1883 _cleanup_free_
char *src_abs
= NULL
, *dst_abs
= NULL
;
1885 src_abs
= path_join(root
, *src
);
1886 dst_abs
= path_join(root
, *dst
);
1887 if (!src_abs
|| !dst_abs
)
1890 r
= mkdir_parents_label(dst_abs
, 0755);
1892 return log_debug_errno(
1894 "Failed to create parent directory for symlink '%s': %m",
1897 r
= symlink_idempotent(src_abs
, dst_abs
, true);
1899 return log_debug_errno(
1901 "Failed to create symlink from '%s' to '%s': %m",
1909 static void mount_entry_path_debug_string(const char *root
, MountEntry
*m
, char **error_path
) {
1912 /* Create a string suitable for debugging logs, stripping for example the local working directory.
1913 * For example, with a BindPaths=/var/bar that does not exist on the host:
1916 * foo.service: Failed to set up mount namespacing: /run/systemd/unit-root/var/bar: No such file or directory
1918 * foo.service: Failed to set up mount namespacing: /var/bar: No such file or directory
1920 * Note that this is an error path, so no OOM check is done on purpose. */
1925 if (!mount_entry_path(m
)) {
1931 const char *e
= startswith(mount_entry_path(m
), root
);
1933 *error_path
= strdup(e
);
1938 *error_path
= strdup(mount_entry_path(m
));
1942 static int apply_mounts(
1945 const NamespaceParameters
*p
,
1946 char **error_path
) {
1948 _cleanup_fclose_
FILE *proc_self_mountinfo
= NULL
;
1949 _cleanup_free_
char **deny_list
= NULL
;
1956 if (ml
->n_mounts
== 0) /* Shortcut: nothing to do */
1959 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1960 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
1961 proc_self_mountinfo
= fopen("/proc/self/mountinfo", "re");
1962 if (!proc_self_mountinfo
) {
1966 *error_path
= strdup("/proc/self/mountinfo");
1968 return log_debug_errno(r
, "Failed to open /proc/self/mountinfo: %m");
1971 /* First round, establish all mounts we need */
1975 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
1977 if (m
->state
!= MOUNT_PENDING
)
1980 /* ExtensionImages/Directories are first opened in the propagate directory, not in the root_directory */
1981 r
= follow_symlink(!IN_SET(m
->mode
, MOUNT_EXTENSION_IMAGE
, MOUNT_EXTENSION_DIRECTORY
) ? root
: NULL
, m
);
1983 mount_entry_path_debug_string(root
, m
, error_path
);
1987 /* We hit a symlinked mount point. The entry got rewritten and might
1988 * point to a very different place now. Let's normalize the changed
1989 * list, and start from the beginning. After all to mount the entry
1990 * at the new location we might need some other mounts first */
1995 /* Returns 1 if the mount should be post-processed, 0 otherwise */
1996 r
= apply_one_mount(root
, m
, p
);
1998 mount_entry_path_debug_string(root
, m
, error_path
);
2001 m
->state
= r
== 0 ? MOUNT_SKIPPED
: MOUNT_APPLIED
;
2007 drop_unused_mounts(ml
, root
);
2010 /* Now that all filesystems have been set up, but before the
2011 * read-only switches are flipped, create the exec dirs and other symlinks.
2012 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
2013 * exist, which means this will be a no-op. */
2014 r
= create_symlinks_from_tuples(root
, p
->symlinks
);
2016 return log_debug_errno(r
, "Failed to set up symlinks inside mount namespace: %m");
2018 /* Create a deny list we can pass to bind_mount_recursive() */
2019 deny_list
= new(char*, ml
->n_mounts
+1);
2022 for (size_t j
= 0; j
< ml
->n_mounts
; j
++)
2023 deny_list
[j
] = (char*) mount_entry_path(ml
->mounts
+j
);
2024 deny_list
[ml
->n_mounts
] = NULL
;
2026 /* Second round, flip the ro bits if necessary. */
2027 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
2028 r
= make_read_only(m
, deny_list
, proc_self_mountinfo
);
2030 mount_entry_path_debug_string(root
, m
, error_path
);
2035 /* Third round, flip the noexec bits with a simplified deny list. */
2036 for (size_t j
= 0; j
< ml
->n_mounts
; j
++)
2037 if (IN_SET((ml
->mounts
+j
)->mode
, MOUNT_EXEC
, MOUNT_NOEXEC
))
2038 deny_list
[j
] = (char*) mount_entry_path(ml
->mounts
+j
);
2039 deny_list
[ml
->n_mounts
] = NULL
;
2041 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
2042 r
= make_noexec(m
, deny_list
, proc_self_mountinfo
);
2044 mount_entry_path_debug_string(root
, m
, error_path
);
2049 /* Fourth round, flip the nosuid bits without a deny list. */
2050 if (p
->mount_nosuid
)
2051 FOREACH_ARRAY(m
, ml
->mounts
, ml
->n_mounts
) {
2052 r
= make_nosuid(m
, proc_self_mountinfo
);
2054 mount_entry_path_debug_string(root
, m
, error_path
);
2062 static bool root_read_only(
2063 char **read_only_paths
,
2064 ProtectSystem protect_system
) {
2066 /* Determine whether the root directory is going to be read-only given the configured settings. */
2068 if (protect_system
== PROTECT_SYSTEM_STRICT
)
2071 if (prefixed_path_strv_contains(read_only_paths
, "/"))
2077 static bool home_read_only(
2078 char** read_only_paths
,
2079 char** inaccessible_paths
,
2080 char** empty_directories
,
2081 const BindMount
*bind_mounts
,
2082 size_t n_bind_mounts
,
2083 const TemporaryFileSystem
*temporary_filesystems
,
2084 size_t n_temporary_filesystems
,
2085 ProtectHome protect_home
) {
2087 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
2088 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
2091 if (protect_home
!= PROTECT_HOME_NO
)
2094 if (prefixed_path_strv_contains(read_only_paths
, "/home") ||
2095 prefixed_path_strv_contains(inaccessible_paths
, "/home") ||
2096 prefixed_path_strv_contains(empty_directories
, "/home"))
2099 for (size_t i
= 0; i
< n_temporary_filesystems
; i
++)
2100 if (path_equal(temporary_filesystems
[i
].path
, "/home"))
2103 /* If /home is overmounted with some dir from the host it's not writable. */
2104 for (size_t i
= 0; i
< n_bind_mounts
; i
++)
2105 if (path_equal(bind_mounts
[i
].destination
, "/home"))
2111 int setup_namespace(const NamespaceParameters
*p
, char **error_path
) {
2113 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2114 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2115 _cleanup_strv_free_
char **hierarchies
= NULL
;
2116 _cleanup_(mount_list_done
) MountList ml
= {};
2117 bool require_prefix
= false;
2119 DissectImageFlags dissect_image_flags
=
2120 DISSECT_IMAGE_GENERIC_ROOT
|
2121 DISSECT_IMAGE_REQUIRE_ROOT
|
2122 DISSECT_IMAGE_DISCARD_ON_LOOP
|
2123 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2124 DISSECT_IMAGE_FSCK
|
2125 DISSECT_IMAGE_USR_NO_ROOT
|
2126 DISSECT_IMAGE_GROWFS
|
2127 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
2128 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
2129 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
2134 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2135 * we configure take effect */
2136 BLOCK_WITH_UMASK(0000);
2138 bool setup_propagate
= !isempty(p
->propagate_dir
) && !isempty(p
->incoming_dir
);
2139 unsigned long mount_propagation_flag
= p
->mount_propagation_flag
!= 0 ? p
->mount_propagation_flag
: MS_SHARED
;
2141 if (p
->root_image
) {
2142 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2143 if (root_read_only(p
->read_only_paths
,
2144 p
->protect_system
) &&
2145 home_read_only(p
->read_only_paths
, p
->inaccessible_paths
, p
->empty_directories
,
2146 p
->bind_mounts
, p
->n_bind_mounts
, p
->temporary_filesystems
, p
->n_temporary_filesystems
,
2148 strv_isempty(p
->read_write_paths
))
2149 dissect_image_flags
|= DISSECT_IMAGE_READ_ONLY
;
2151 SET_FLAG(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
, p
->verity
&& p
->verity
->data_path
);
2153 r
= loop_device_make_by_path(
2155 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: -1 /* < 0 means writable if possible, read-only as fallback */,
2156 /* sector_size= */ UINT32_MAX
,
2157 FLAGS_SET(dissect_image_flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
2161 return log_debug_errno(r
, "Failed to create loop device for root image: %m");
2163 r
= dissect_loop_device(
2166 p
->root_image_options
,
2167 p
->root_image_policy
,
2168 dissect_image_flags
,
2171 return log_debug_errno(r
, "Failed to dissect image: %m");
2173 r
= dissected_image_load_verity_sig_partition(
2180 r
= dissected_image_decrypt(
2184 dissect_image_flags
);
2186 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
2189 if (p
->root_directory
)
2190 root
= p
->root_directory
;
2192 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2193 * when running tests (test-execute), it might not have been created yet so let's make sure
2194 * we create it if it doesn't already exist. */
2195 (void) mkdir_p_label("/run/systemd", 0755);
2197 /* Always create the mount namespace in a temporary directory, instead of operating directly
2198 * in the root. The temporary directory prevents any mounts from being potentially obscured
2199 * my other mounts we already applied. We use the same mount point for all images, which is
2200 * safe, since they all live in their own namespaces after all, and hence won't see each
2201 * other. (Note: this directory is also created by PID 1 early on, we create it here for
2202 * similar reasons as /run/systemd/ first.) */
2203 root
= "/run/systemd/mount-rootfs";
2204 (void) mkdir_label(root
, 0555);
2206 require_prefix
= true;
2209 if (p
->n_extension_images
> 0 || !strv_isempty(p
->extension_directories
)) {
2210 /* Hierarchy population needs to be done for sysext and confext extension images */
2211 r
= parse_env_extension_hierarchies(&hierarchies
, "SYSTEMD_SYSEXT_AND_CONFEXT_HIERARCHIES");
2216 r
= append_access_mounts(&ml
, p
->read_write_paths
, MOUNT_READ_WRITE
, require_prefix
);
2220 r
= append_access_mounts(&ml
, p
->read_only_paths
, MOUNT_READ_ONLY
, require_prefix
);
2224 r
= append_access_mounts(&ml
, p
->inaccessible_paths
, MOUNT_INACCESSIBLE
, require_prefix
);
2228 r
= append_access_mounts(&ml
, p
->exec_paths
, MOUNT_EXEC
, require_prefix
);
2232 r
= append_access_mounts(&ml
, p
->no_exec_paths
, MOUNT_NOEXEC
, require_prefix
);
2236 r
= append_empty_dir_mounts(&ml
, p
->empty_directories
);
2240 r
= append_bind_mounts(&ml
, p
->bind_mounts
, p
->n_bind_mounts
);
2244 r
= append_tmpfs_mounts(&ml
, p
->temporary_filesystems
, p
->n_temporary_filesystems
);
2249 bool ro
= streq(p
->tmp_dir
, RUN_SYSTEMD_EMPTY
);
2251 MountEntry
*me
= mount_list_extend(&ml
);
2253 return log_oom_debug();
2255 *me
= (MountEntry
) {
2256 .path_const
= "/tmp",
2257 .mode
= ro
? MOUNT_PRIVATE_TMP_READ_ONLY
: MOUNT_PRIVATE_TMP
,
2258 .source_const
= p
->tmp_dir
,
2262 if (p
->var_tmp_dir
) {
2263 bool ro
= streq(p
->var_tmp_dir
, RUN_SYSTEMD_EMPTY
);
2265 MountEntry
*me
= mount_list_extend(&ml
);
2267 return log_oom_debug();
2269 *me
= (MountEntry
) {
2270 .path_const
= "/var/tmp",
2271 .mode
= ro
? MOUNT_PRIVATE_TMP_READ_ONLY
: MOUNT_PRIVATE_TMP
,
2272 .source_const
= p
->var_tmp_dir
,
2276 r
= append_mount_images(&ml
, p
->mount_images
, p
->n_mount_images
);
2280 r
= append_extensions(&ml
, root
, p
->extension_dir
, hierarchies
, p
->extension_images
, p
->n_extension_images
, p
->extension_directories
);
2284 if (p
->private_dev
) {
2285 MountEntry
*me
= mount_list_extend(&ml
);
2287 return log_oom_debug();
2289 *me
= (MountEntry
) {
2290 .path_const
= "/dev",
2291 .mode
= MOUNT_PRIVATE_DEV
,
2292 .flags
= DEV_MOUNT_OPTIONS
,
2296 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the protective
2297 mounts to non-pid /proc paths would fail. But the pid only option may have failed gracefully, so
2298 let's try the mounts but it's not fatal if they don't succeed. */
2299 bool ignore_protect_proc
= p
->ignore_protect_paths
|| p
->proc_subset
== PROC_SUBSET_PID
;
2300 if (p
->protect_kernel_tunables
) {
2301 r
= append_static_mounts(&ml
,
2302 protect_kernel_tunables_proc_table
,
2303 ELEMENTSOF(protect_kernel_tunables_proc_table
),
2304 ignore_protect_proc
);
2308 r
= append_static_mounts(&ml
,
2309 protect_kernel_tunables_sys_table
,
2310 ELEMENTSOF(protect_kernel_tunables_sys_table
),
2311 p
->ignore_protect_paths
);
2316 if (p
->protect_kernel_modules
) {
2317 r
= append_static_mounts(&ml
,
2318 protect_kernel_modules_table
,
2319 ELEMENTSOF(protect_kernel_modules_table
),
2320 p
->ignore_protect_paths
);
2325 if (p
->protect_kernel_logs
) {
2326 r
= append_static_mounts(&ml
,
2327 protect_kernel_logs_proc_table
,
2328 ELEMENTSOF(protect_kernel_logs_proc_table
),
2329 ignore_protect_proc
);
2333 r
= append_static_mounts(&ml
,
2334 protect_kernel_logs_dev_table
,
2335 ELEMENTSOF(protect_kernel_logs_dev_table
),
2336 p
->ignore_protect_paths
);
2341 if (p
->protect_control_groups
) {
2342 MountEntry
*me
= mount_list_extend(&ml
);
2344 return log_oom_debug();
2346 *me
= (MountEntry
) {
2347 .path_const
= "/sys/fs/cgroup",
2348 .mode
= MOUNT_READ_ONLY
,
2352 r
= append_protect_home(&ml
, p
->protect_home
, p
->ignore_protect_paths
);
2356 r
= append_protect_system(&ml
, p
->protect_system
, false);
2360 if (namespace_parameters_mount_apivfs(p
)) {
2361 r
= append_static_mounts(&ml
,
2363 ELEMENTSOF(apivfs_table
),
2364 p
->ignore_protect_paths
);
2369 /* Note, if proc is mounted with subset=pid then neither of the two paths will exist, i.e. they are
2370 * implicitly protected by the mount option. */
2371 if (p
->protect_hostname
) {
2372 r
= append_static_mounts(
2374 protect_hostname_table
,
2375 ELEMENTSOF(protect_hostname_table
),
2376 ignore_protect_proc
);
2381 if (p
->private_network
) {
2382 MountEntry
*me
= mount_list_extend(&ml
);
2384 return log_oom_debug();
2386 *me
= (MountEntry
) {
2387 .path_const
= "/sys",
2388 .mode
= MOUNT_PRIVATE_SYSFS
,
2392 if (p
->private_ipc
) {
2393 MountEntry
*me
= mount_list_extend(&ml
);
2395 return log_oom_debug();
2397 *me
= (MountEntry
) {
2398 .path_const
= "/dev/mqueue",
2399 .mode
= MOUNT_MQUEUEFS
,
2400 .flags
= MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
2404 if (p
->creds_path
) {
2405 /* If our service has a credentials store configured, then bind that one in, but hide
2406 * everything else. */
2408 MountEntry
*me
= mount_list_extend(&ml
);
2410 return log_oom_debug();
2412 *me
= (MountEntry
) {
2413 .path_const
= "/run/credentials",
2414 .mode
= MOUNT_TMPFS
,
2416 .options_const
= "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST
,
2417 .flags
= MS_NODEV
|MS_STRICTATIME
|MS_NOSUID
|MS_NOEXEC
,
2420 me
= mount_list_extend(&ml
);
2422 return log_oom_debug();
2424 *me
= (MountEntry
) {
2425 .path_const
= p
->creds_path
,
2428 .source_const
= p
->creds_path
,
2432 /* If our service has no credentials store configured, then make the whole credentials tree
2433 * inaccessible wholesale. */
2435 MountEntry
*me
= mount_list_extend(&ml
);
2437 return log_oom_debug();
2439 *me
= (MountEntry
) {
2440 .path_const
= "/run/credentials",
2441 .mode
= MOUNT_INACCESSIBLE
,
2446 if (p
->log_namespace
) {
2447 _cleanup_free_
char *q
= NULL
;
2449 q
= strjoin("/run/systemd/journal.", p
->log_namespace
);
2451 return log_oom_debug();
2453 MountEntry
*me
= mount_list_extend(&ml
);
2455 return log_oom_debug();
2457 *me
= (MountEntry
) {
2458 .path_const
= "/run/systemd/journal",
2459 .mode
= MOUNT_BIND_RECURSIVE
,
2461 .source_malloc
= TAKE_PTR(q
),
2465 /* Will be used to add bind mounts at runtime */
2466 if (setup_propagate
) {
2467 MountEntry
*me
= mount_list_extend(&ml
);
2469 return log_oom_debug();
2471 *me
= (MountEntry
) {
2472 .source_const
= p
->propagate_dir
,
2473 .path_const
= p
->incoming_dir
,
2479 if (p
->notify_socket
) {
2480 MountEntry
*me
= mount_list_extend(&ml
);
2482 return log_oom_debug();
2484 *me
= (MountEntry
) {
2485 .path_const
= p
->notify_socket
,
2486 .source_const
= p
->notify_socket
,
2492 if (p
->host_os_release_stage
) {
2493 MountEntry
*me
= mount_list_extend(&ml
);
2495 return log_oom_debug();
2497 *me
= (MountEntry
) {
2498 .path_const
= "/run/host/.os-release-stage/",
2499 .source_const
= p
->host_os_release_stage
,
2502 .ignore
= true, /* Live copy, don't hard-fail if it goes missing */
2506 /* Prepend the root directory where that's necessary */
2507 r
= prefix_where_needed(&ml
, root
);
2511 drop_unused_mounts(&ml
, root
);
2513 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
2515 if (unshare(CLONE_NEWNS
) < 0) {
2516 r
= log_debug_errno(errno
, "Failed to unshare the mount namespace: %m");
2518 if (ERRNO_IS_PRIVILEGE(r
) ||
2519 ERRNO_IS_NOT_SUPPORTED(r
))
2520 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
2521 * in place that doesn't allow us to create namespaces (or a missing cap), then
2522 * propagate a recognizable error back, which the caller can use to detect this case
2523 * (and only this) and optionally continue without namespacing applied. */
2529 /* Create the source directory to allow runtime propagation of mounts */
2530 if (setup_propagate
)
2531 (void) mkdir_p(p
->propagate_dir
, 0600);
2533 if (p
->n_extension_images
> 0 || !strv_isempty(p
->extension_directories
))
2534 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
2535 * mounts to create, so have the parent ready */
2536 (void) mkdir_p(p
->extension_dir
, 0600);
2538 /* Remount / as SLAVE so that nothing now mounted in the namespace
2539 * shows up in the parent */
2540 if (mount(NULL
, "/", NULL
, MS_SLAVE
|MS_REC
, NULL
) < 0)
2541 return log_debug_errno(errno
, "Failed to remount '/' as SLAVE: %m");
2543 if (p
->root_image
) {
2544 /* A root image is specified, mount it to the right place */
2545 r
= dissected_image_mount(
2548 /* uid_shift= */ UID_INVALID
,
2549 /* uid_range= */ UID_INVALID
,
2550 /* userns_fd= */ -EBADF
,
2551 dissect_image_flags
);
2553 return log_debug_errno(r
, "Failed to mount root image: %m");
2555 /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
2557 r
= loop_device_flock(loop_device
, LOCK_UN
);
2559 return log_debug_errno(r
, "Failed to release lock on loopback block device: %m");
2561 r
= dissected_image_relinquish(dissected_image
);
2563 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
2565 } else if (p
->root_directory
) {
2567 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
2568 r
= path_is_mount_point_full(root
, /* root = */ NULL
, AT_SYMLINK_FOLLOW
);
2570 return log_debug_errno(r
, "Failed to detect that %s is a mount point or not: %m", root
);
2572 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2578 /* Let's mount the main root directory to the root directory to use */
2579 r
= mount_nofollow_verbose(LOG_DEBUG
, "/", root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2584 /* Try to set up the new root directory before mounting anything else there. */
2585 if (p
->root_image
|| p
->root_directory
)
2586 (void) base_filesystem_create(root
, UID_INVALID
, GID_INVALID
);
2588 /* Now make the magic happen */
2589 r
= apply_mounts(&ml
, root
, p
, error_path
);
2593 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
2594 r
= mount_switch_root(root
, /* mount_propagation_flag = */ 0);
2595 if (r
== -EINVAL
&& p
->root_directory
) {
2596 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
2597 * namespace) and the root_directory is already a mount point in the parent namespace,
2598 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
2599 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
2600 * mount point) and try again. */
2601 r
= mount_nofollow_verbose(LOG_DEBUG
, root
, root
, NULL
, MS_BIND
|MS_REC
, NULL
);
2604 r
= mount_switch_root(root
, /* mount_propagation_flag = */ 0);
2607 return log_debug_errno(r
, "Failed to mount root with MS_MOVE: %m");
2609 /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
2610 * the host, since what's disconnected is disconnected. */
2611 if (mount(NULL
, "/", NULL
, mount_propagation_flag
| MS_REC
, NULL
) < 0)
2612 return log_debug_errno(errno
, "Failed to remount '/' with desired mount flags: %m");
2614 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only supported for
2615 * non-shared mounts. This needs to happen after remounting / or it will fail. */
2616 if (setup_propagate
&& mount(NULL
, p
->incoming_dir
, NULL
, MS_SLAVE
, NULL
) < 0)
2617 return log_debug_errno(errno
, "Failed to remount %s with MS_SLAVE: %m", p
->incoming_dir
);
2622 void bind_mount_free_many(BindMount
*b
, size_t n
) {
2623 assert(b
|| n
== 0);
2625 for (size_t i
= 0; i
< n
; i
++) {
2627 free(b
[i
].destination
);
2633 int bind_mount_add(BindMount
**b
, size_t *n
, const BindMount
*item
) {
2634 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2641 s
= strdup(item
->source
);
2645 d
= strdup(item
->destination
);
2649 c
= reallocarray(*b
, *n
+ 1, sizeof(BindMount
));
2655 c
[(*n
)++] = (BindMount
) {
2656 .source
= TAKE_PTR(s
),
2657 .destination
= TAKE_PTR(d
),
2658 .read_only
= item
->read_only
,
2659 .nosuid
= item
->nosuid
,
2660 .recursive
= item
->recursive
,
2661 .ignore_enoent
= item
->ignore_enoent
,
2667 MountImage
* mount_image_free_many(MountImage
*m
, size_t *n
) {
2669 assert(m
|| *n
== 0);
2671 for (size_t i
= 0; i
< *n
; i
++) {
2673 free(m
[i
].destination
);
2674 mount_options_free_all(m
[i
].mount_options
);
2682 int mount_image_add(MountImage
**m
, size_t *n
, const MountImage
*item
) {
2683 _cleanup_free_
char *s
= NULL
, *d
= NULL
;
2684 _cleanup_(mount_options_free_allp
) MountOptions
*options
= NULL
;
2691 s
= strdup(item
->source
);
2695 if (item
->destination
) {
2696 d
= strdup(item
->destination
);
2701 LIST_FOREACH(mount_options
, i
, item
->mount_options
) {
2702 _cleanup_(mount_options_free_allp
) MountOptions
*o
= NULL
;
2704 o
= new(MountOptions
, 1);
2708 *o
= (MountOptions
) {
2709 .partition_designator
= i
->partition_designator
,
2710 .options
= strdup(i
->options
),
2715 LIST_APPEND(mount_options
, options
, TAKE_PTR(o
));
2718 c
= reallocarray(*m
, *n
+ 1, sizeof(MountImage
));
2724 c
[(*n
)++] = (MountImage
) {
2725 .source
= TAKE_PTR(s
),
2726 .destination
= TAKE_PTR(d
),
2727 .mount_options
= TAKE_PTR(options
),
2728 .ignore_enoent
= item
->ignore_enoent
,
2735 void temporary_filesystem_free_many(TemporaryFileSystem
*t
, size_t n
) {
2736 assert(t
|| n
== 0);
2738 for (size_t i
= 0; i
< n
; i
++) {
2746 int temporary_filesystem_add(
2747 TemporaryFileSystem
**t
,
2750 const char *options
) {
2752 _cleanup_free_
char *p
= NULL
, *o
= NULL
;
2753 TemporaryFileSystem
*c
;
2763 if (!isempty(options
)) {
2764 o
= strdup(options
);
2769 c
= reallocarray(*t
, *n
+ 1, sizeof(TemporaryFileSystem
));
2775 c
[(*n
)++] = (TemporaryFileSystem
) {
2776 .path
= TAKE_PTR(p
),
2777 .options
= TAKE_PTR(o
),
2783 static int make_tmp_prefix(const char *prefix
) {
2784 _cleanup_free_
char *t
= NULL
;
2785 _cleanup_close_
int fd
= -EBADF
;
2788 /* Don't do anything unless we know the dir is actually missing */
2789 r
= access(prefix
, F_OK
);
2792 if (errno
!= ENOENT
)
2796 r
= mkdir_parents(prefix
, 0755);
2800 r
= tempfn_random(prefix
, NULL
, &t
);
2804 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
2805 * the suid bit, below. */
2806 fd
= open_mkdir_at(AT_FDCWD
, t
, O_EXCL
|O_CLOEXEC
, 0777);
2810 r
= RET_NERRNO(fchmod(fd
, 01777));
2816 r
= RET_NERRNO(rename(t
, prefix
));
2819 return r
== -EEXIST
? 0 : r
; /* it's fine if someone else created the dir by now */
2826 static int setup_one_tmp_dir(const char *id
, const char *prefix
, char **path
, char **tmp_path
) {
2827 _cleanup_free_
char *x
= NULL
;
2828 _cleanup_free_
char *y
= NULL
;
2837 /* We include the boot id in the directory so that after a
2838 * reboot we can easily identify obsolete directories. */
2840 r
= sd_id128_get_boot(&boot_id
);
2844 x
= strjoin(prefix
, "/systemd-private-", SD_ID128_TO_STRING(boot_id
), "-", id
, "-XXXXXX");
2848 r
= make_tmp_prefix(prefix
);
2854 if (errno
== EROFS
|| ERRNO_IS_DISK_SPACE(errno
))
2861 y
= strjoin(x
, "/tmp");
2866 if (mkdir(y
, 0777 | S_ISVTX
) < 0)
2869 r
= label_fix_full(AT_FDCWD
, y
, prefix
, 0);
2874 *tmp_path
= TAKE_PTR(y
);
2876 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2877 * read-only. This way the service will get the EROFS result as if it was writing to the real
2880 r
= mkdir_p(RUN_SYSTEMD_EMPTY
, 0500);
2884 r
= free_and_strdup(&x
, RUN_SYSTEMD_EMPTY
);
2889 *path
= TAKE_PTR(x
);
2893 int setup_tmp_dirs(const char *id
, char **tmp_dir
, char **var_tmp_dir
) {
2894 _cleanup_(namespace_cleanup_tmpdirp
) char *a
= NULL
;
2895 _cleanup_(rmdir_and_freep
) char *a_tmp
= NULL
;
2901 assert(var_tmp_dir
);
2903 r
= setup_one_tmp_dir(id
, "/tmp", &a
, &a_tmp
);
2907 r
= setup_one_tmp_dir(id
, "/var/tmp", &b
, NULL
);
2911 a_tmp
= mfree(a_tmp
); /* avoid rmdir */
2912 *tmp_dir
= TAKE_PTR(a
);
2913 *var_tmp_dir
= TAKE_PTR(b
);
2918 int setup_shareable_ns(int ns_storage_socket
[static 2], unsigned long nsflag
) {
2919 _cleanup_close_
int ns
= -EBADF
;
2920 const char *ns_name
, *ns_path
;
2923 assert(ns_storage_socket
);
2924 assert(ns_storage_socket
[0] >= 0);
2925 assert(ns_storage_socket
[1] >= 0);
2927 ns_name
= ASSERT_PTR(namespace_single_flag_to_string(nsflag
));
2929 /* We use the passed socketpair as a storage buffer for our namespace reference fd. Whatever process
2930 * runs this first shall create a new namespace, all others should just join it. To serialize that we
2931 * use a file lock on the socket pair.
2933 * It's a bit crazy, but hey, works great! */
2935 r
= posix_lock(ns_storage_socket
[0], LOCK_EX
);
2939 CLEANUP_POSIX_UNLOCK(ns_storage_socket
[0]);
2941 ns
= receive_one_fd(ns_storage_socket
[0], MSG_PEEK
|MSG_DONTWAIT
);
2943 /* Yay, found something, so let's join the namespace */
2944 r
= RET_NERRNO(setns(ns
, nsflag
));
2954 /* Nothing stored yet, so let's create a new namespace. */
2956 if (unshare(nsflag
) < 0)
2959 if (nsflag
== CLONE_NEWNET
)
2960 (void) loopback_setup();
2962 ns_path
= strjoina("/proc/self/ns/", ns_name
);
2963 ns
= open(ns_path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
2967 r
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
2974 int open_shareable_ns_path(int ns_storage_socket
[static 2], const char *path
, unsigned long nsflag
) {
2975 _cleanup_close_
int ns
= -EBADF
;
2978 assert(ns_storage_socket
);
2979 assert(ns_storage_socket
[0] >= 0);
2980 assert(ns_storage_socket
[1] >= 0);
2983 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
2984 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
2985 * allocate a new anonymous ns if needed. */
2987 r
= posix_lock(ns_storage_socket
[0], LOCK_EX
);
2991 CLEANUP_POSIX_UNLOCK(ns_storage_socket
[0]);
2993 ns
= receive_one_fd(ns_storage_socket
[0], MSG_PEEK
|MSG_DONTWAIT
);
2999 /* Nothing stored yet. Open the file from the file system. */
3001 ns
= open(path
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
3005 r
= fd_is_ns(ns
, nsflag
);
3008 if (r
< 0 && r
!= -EUCLEAN
) /* EUCLEAN: we don't know */
3011 r
= send_one_fd(ns_storage_socket
[1], ns
, MSG_DONTWAIT
);
3018 bool ns_type_supported(NamespaceType type
) {
3019 const char *t
, *ns_proc
;
3021 t
= namespace_type_to_string(type
);
3022 if (!t
) /* Don't know how to translate this? Then it's not supported */
3025 ns_proc
= strjoina("/proc/self/ns/", t
);
3026 return access(ns_proc
, F_OK
) == 0;
3029 static const char *const protect_home_table
[_PROTECT_HOME_MAX
] = {
3030 [PROTECT_HOME_NO
] = "no",
3031 [PROTECT_HOME_YES
] = "yes",
3032 [PROTECT_HOME_READ_ONLY
] = "read-only",
3033 [PROTECT_HOME_TMPFS
] = "tmpfs",
3036 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home
, ProtectHome
, PROTECT_HOME_YES
);
3038 static const char *const protect_system_table
[_PROTECT_SYSTEM_MAX
] = {
3039 [PROTECT_SYSTEM_NO
] = "no",
3040 [PROTECT_SYSTEM_YES
] = "yes",
3041 [PROTECT_SYSTEM_FULL
] = "full",
3042 [PROTECT_SYSTEM_STRICT
] = "strict",
3045 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system
, ProtectSystem
, PROTECT_SYSTEM_YES
);
3047 static const char* const namespace_type_table
[] = {
3048 [NAMESPACE_MOUNT
] = "mnt",
3049 [NAMESPACE_CGROUP
] = "cgroup",
3050 [NAMESPACE_UTS
] = "uts",
3051 [NAMESPACE_IPC
] = "ipc",
3052 [NAMESPACE_USER
] = "user",
3053 [NAMESPACE_PID
] = "pid",
3054 [NAMESPACE_NET
] = "net",
3055 [NAMESPACE_TIME
] = "time",
3058 DEFINE_STRING_TABLE_LOOKUP(namespace_type
, NamespaceType
);
3060 static const char* const protect_proc_table
[_PROTECT_PROC_MAX
] = {
3061 [PROTECT_PROC_DEFAULT
] = "default",
3062 [PROTECT_PROC_NOACCESS
] = "noaccess",
3063 [PROTECT_PROC_INVISIBLE
] = "invisible",
3064 [PROTECT_PROC_PTRACEABLE
] = "ptraceable",
3067 DEFINE_STRING_TABLE_LOOKUP(protect_proc
, ProtectProc
);
3069 static const char* const proc_subset_table
[_PROC_SUBSET_MAX
] = {
3070 [PROC_SUBSET_ALL
] = "all",
3071 [PROC_SUBSET_PID
] = "pid",
3074 DEFINE_STRING_TABLE_LOOKUP(proc_subset
, ProcSubset
);