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