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