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