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