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