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