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