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