Debian Codegraph @

src/core/namespace.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/loop.h>
4 #include <linux/magic.h>
5 #include <sched.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <sys/file.h>
9 #include <sys/mount.h>
10 #include <unistd.h>
11
12 #include "alloc-util.h"
13 #include "base-filesystem.h"
14 #include "bitfield.h"
15 #include "chase.h"
16 #include "cryptsetup-util.h"
17 #include "dev-setup.h"
18 #include "devnum-util.h"
19 #include "dissect-image.h"
20 #include "errno-util.h"
21 #include "escape.h"
22 #include "extension-util.h"
23 #include "extract-word.h"
24 #include "fd-util.h"
25 #include "format-util.h"
26 #include "fs-util.h"
27 #include "glyph-util.h"
28 #include "iovec-util.h"
29 #include "label-util.h"
30 #include "lock-util.h"
31 #include "log.h"
32 #include "loop-util.h"
33 #include "loopback-setup.h"
34 #include "mkdir.h"
35 #include "mount-util.h"
36 #include "mountpoint-util.h"
37 #include "mstack.h"
38 #include "namespace.h"
39 #include "namespace-util.h"
40 #include "nsflags.h"
41 #include "nulstr-util.h"
42 #include "os-util.h"
43 #include "path-util.h"
44 #include "pidref.h"
45 #include "process-util.h"
46 #include "selinux-util.h"
47 #include "socket-util.h"
48 #include "sort-util.h"
49 #include "stat-util.h"
50 #include "string-table.h"
51 #include "string-util.h"
52 #include "strv.h"
53 #include "tmpfile-util.h"
54 #include "umask-util.h"
55 #include "user-util.h"
56 #include "vpick.h"
57
58 #define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
59
60 typedef enum MountMode {
61 /* This is ordered by priority! */
62 MOUNT_INACCESSIBLE,
63 MOUNT_OVERLAY,
64 MOUNT_IMAGE,
65 MOUNT_BIND,
66 MOUNT_BIND_RECURSIVE,
67 MOUNT_PRIVATE_TMP,
68 MOUNT_PRIVATE_DEV,
69 MOUNT_BIND_DEV,
70 MOUNT_EMPTY_DIR,
71 MOUNT_PRIVATE_SYSFS,
72 MOUNT_BIND_SYSFS,
73 MOUNT_PROCFS,
74 MOUNT_PRIVATE_CGROUP2FS,
75 MOUNT_READ_ONLY,
76 MOUNT_READ_WRITE,
77 MOUNT_NOEXEC,
78 MOUNT_EXEC,
79 MOUNT_TMPFS,
80 MOUNT_RUN,
81 MOUNT_PRIVATE_TMPFS, /* Mounted outside the root directory, and used by subsequent mounts */
82 MOUNT_EXTENSION_DIRECTORY, /* Bind-mounted outside the root directory, and used by subsequent mounts */
83 MOUNT_EXTENSION_IMAGE, /* Mounted outside the root directory, and used by subsequent mounts */
84 MOUNT_MQUEUEFS,
85 MOUNT_READ_WRITE_IMPLICIT, /* Should have the lowest priority. */
86 MOUNT_BPFFS, /* Special mount for bpffs, which is mounted with fsmount() and move_mount() */
87 _MOUNT_MODE_MAX,
88 _MOUNT_MODE_INVALID = -EINVAL,
89 } MountMode;
90
91 typedef enum MountEntryState {
92 MOUNT_PENDING,
93 MOUNT_APPLIED,
94 MOUNT_SKIPPED,
95 _MOUNT_ENTRY_STATE_MAX,
96 _MOUNT_ENTRY_STATE_INVALID = -EINVAL,
97 } MountEntryState;
98
99 typedef struct MountEntry {
100 const char *path_const; /* Memory allocated on stack or static */
101 MountMode mode;
102 bool ignore:1; /* Ignore if path does not exist? */
103 bool has_prefix:1; /* Already prefixed by the root dir? */
104 bool read_only:1; /* Shall this mount point be read-only? */
105 bool nosuid:1; /* Shall set MS_NOSUID on the mount itself */
106 bool noexec:1; /* Shall set MS_NOEXEC on the mount itself */
107 bool exec:1; /* Shall clear MS_NOEXEC on the mount itself */
108 bool create_source_dir:1; /* Create the source directory if it doesn't exist - for implicit bind mounts */
109 mode_t source_dir_mode; /* Mode for the source directory, if it is to be created */
110 MountEntryState state; /* Whether it was already processed or skipped */
111 char *path_malloc; /* Use this instead of 'path_const' if we had to allocate memory */
112 const char *unprefixed_path_const; /* If the path was amended with a prefix, these will save the original */
113 char *unprefixed_path_malloc;
114 const char *source_const; /* The source path, for bind mounts or images */
115 char *source_malloc;
116 const char *options_const;/* Mount options for tmpfs */
117 char *options_malloc;
118 unsigned long flags; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
119 unsigned n_followed;
120 MountOptions *image_options_const;
121 char **overlay_layers;
122 VeritySettings verity;
123 ImageClass filter_class; /* Used for live updates to skip inapplicable images */
124 bool idmapped;
125 uid_t idmap_uid;
126 gid_t idmap_gid;
127 } MountEntry;
128
129 typedef struct MountList {
130 MountEntry *mounts;
131 size_t n_mounts;
132 } MountList;
133
134 static const BindMount bind_log_sockets_table[] = {
135 { (char*) "/run/systemd/journal/socket", (char*) "/run/systemd/journal/socket", .read_only = true, .nosuid = true, .noexec = true, .nodev = true, .ignore_enoent = true },
136 { (char*) "/run/systemd/journal/stdout", (char*) "/run/systemd/journal/stdout", .read_only = true, .nosuid = true, .noexec = true, .nodev = true, .ignore_enoent = true },
137 { (char*) "/run/systemd/journal/dev-log", (char*) "/run/systemd/journal/dev-log", .read_only = true, .nosuid = true, .noexec = true, .nodev = true, .ignore_enoent = true },
138 };
139
140 /* If MountAPIVFS= is used, let's mount /proc/, /dev/, /sys/, and /run/, but only as a fallback if the user
141 * hasn't mounted something already. These mounts are hence overridden by any other explicitly configured
142 * mounts. */
143 static const MountEntry apivfs_table[] = {
144 { "/proc", MOUNT_PROCFS, false },
145 { "/dev", MOUNT_BIND_DEV, false },
146 { "/sys", MOUNT_BIND_SYSFS, false },
147 { "/run", MOUNT_RUN, false, .options_const = "mode=0755" TMPFS_LIMITS_RUN, .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME },
148 };
149
150 /* ProtectKernelTunables= option and the related filesystem APIs */
151 static const MountEntry protect_kernel_tunables_proc_table[] = {
152 { "/proc/acpi", MOUNT_READ_ONLY, true },
153 { "/proc/apm", MOUNT_READ_ONLY, true }, /* Obsolete API, there's no point in permitting access to this, ever */
154 { "/proc/asound", MOUNT_READ_ONLY, true },
155 { "/proc/bus", MOUNT_READ_ONLY, true },
156 { "/proc/fs", MOUNT_READ_ONLY, true },
157 { "/proc/irq", MOUNT_READ_ONLY, true },
158 { "/proc/kallsyms", MOUNT_INACCESSIBLE, true },
159 { "/proc/kcore", MOUNT_INACCESSIBLE, true },
160 { "/proc/latency_stats", MOUNT_READ_ONLY, true },
161 { "/proc/mtrr", MOUNT_READ_ONLY, true },
162 { "/proc/scsi", MOUNT_READ_ONLY, true },
163 { "/proc/sys", MOUNT_READ_ONLY, true },
164 { "/proc/sysrq-trigger", MOUNT_READ_ONLY, true },
165 { "/proc/timer_stats", MOUNT_READ_ONLY, true },
166 };
167
168 static const MountEntry protect_kernel_tunables_sys_table[] = {
169 { "/sys", MOUNT_READ_ONLY, false },
170 { "/sys/fs/cgroup", MOUNT_READ_WRITE_IMPLICIT, false }, /* READ_ONLY is set by ProtectControlGroups= option */
171 { "/sys/fs/selinux", MOUNT_READ_WRITE_IMPLICIT, true },
172 { "/sys/kernel/debug", MOUNT_READ_ONLY, true },
173 { "/sys/kernel/tracing", MOUNT_READ_ONLY, true },
174 };
175
176 /* PrivateBPF= option */
177 static const MountEntry private_bpf_no_table[] = {
178 { "/sys/fs/bpf", MOUNT_READ_ONLY, true },
179 };
180
181 /* ProtectKernelModules= option */
182 static const MountEntry protect_kernel_modules_table[] = {
183 { "/usr/lib/modules", MOUNT_INACCESSIBLE, true },
184 };
185
186 /* ProtectKernelLogs= option */
187 static const MountEntry protect_kernel_logs_proc_table[] = {
188 { "/proc/kmsg", MOUNT_INACCESSIBLE, true },
189 };
190
191 static const MountEntry protect_kernel_logs_dev_table[] = {
192 { "/dev/kmsg", MOUNT_INACCESSIBLE, true },
193 };
194
195 /*
196 * ProtectHome=read-only. Protect $HOME and $XDG_RUNTIME_DIR and rest of
197 * system should be protected by ProtectSystem=.
198 */
199 static const MountEntry protect_home_read_only_table[] = {
200 { "/home", MOUNT_READ_ONLY, true },
201 { "/run/user", MOUNT_READ_ONLY, true },
202 { "/root", MOUNT_READ_ONLY, true },
203 };
204
205 /* ProtectHome=tmpfs */
206 static const MountEntry protect_home_tmpfs_table[] = {
207 { "/home", MOUNT_TMPFS, true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
208 { "/run/user", MOUNT_TMPFS, true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
209 { "/root", MOUNT_TMPFS, true, .read_only = true, .options_const = "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
210 };
211
212 /* ProtectHome=yes */
213 static const MountEntry protect_home_yes_table[] = {
214 { "/home", MOUNT_INACCESSIBLE, true },
215 { "/run/user", MOUNT_INACCESSIBLE, true },
216 { "/root", MOUNT_INACCESSIBLE, true },
217 };
218
219 /* ProtectControlGroups=yes */
220 static const MountEntry protect_control_groups_yes_table[] = {
221 { "/sys/fs/cgroup", MOUNT_READ_ONLY, false },
222 };
223
224 /* ProtectControlGroups=private. Note mount_private_apivfs() always use MS_NOSUID|MS_NOEXEC|MS_NODEV so
225 * flags are not set here. */
226 static const MountEntry protect_control_groups_private_table[] = {
227 { "/sys/fs/cgroup", MOUNT_PRIVATE_CGROUP2FS, false, .read_only = false },
228 };
229
230 /* ProtectControlGroups=strict */
231 static const MountEntry protect_control_groups_strict_table[] = {
232 { "/sys/fs/cgroup", MOUNT_PRIVATE_CGROUP2FS, false, .read_only = true },
233 };
234
235 /* ProtectSystem=yes */
236 static const MountEntry protect_system_yes_table[] = {
237 { "/usr", MOUNT_READ_ONLY, false },
238 { "/boot", MOUNT_READ_ONLY, true },
239 { "/efi", MOUNT_READ_ONLY, true },
240 };
241
242 /* ProtectSystem=full includes ProtectSystem=yes */
243 static const MountEntry protect_system_full_table[] = {
244 { "/usr", MOUNT_READ_ONLY, false },
245 { "/boot", MOUNT_READ_ONLY, true },
246 { "/efi", MOUNT_READ_ONLY, true },
247 { "/etc", MOUNT_READ_ONLY, false },
248 };
249
250 /* ProtectSystem=strict. In this strict mode, we mount everything read-only, except for /proc, /dev, and
251 * /sys which are the kernel API VFS and left writable. PrivateDevices= + ProtectKernelTunables=
252 * protect those, and these options should be fully orthogonal. (And of course /home and friends are also
253 * left writable, as ProtectHome= shall manage those, orthogonally).
254 */
255 static const MountEntry protect_system_strict_table[] = {
256 { "/", MOUNT_READ_ONLY, false },
257 { "/proc", MOUNT_READ_WRITE_IMPLICIT, false }, /* ProtectKernelTunables= */
258 { "/sys", MOUNT_READ_WRITE_IMPLICIT, false }, /* ProtectKernelTunables= */
259 { "/dev", MOUNT_READ_WRITE_IMPLICIT, false }, /* PrivateDevices= */
260 { "/home", MOUNT_READ_WRITE_IMPLICIT, true }, /* ProtectHome= */
261 { "/run/user", MOUNT_READ_WRITE_IMPLICIT, true }, /* ProtectHome= */
262 { "/root", MOUNT_READ_WRITE_IMPLICIT, true }, /* ProtectHome= */
263 };
264
265 /* ProtectHostname=yes */
266 static const MountEntry protect_hostname_yes_table[] = {
267 { "/proc/sys/kernel/hostname", MOUNT_READ_ONLY, false },
268 { "/proc/sys/kernel/domainname", MOUNT_READ_ONLY, false },
269 };
270
271 static const char * const mount_mode_table[_MOUNT_MODE_MAX] = {
272 [MOUNT_INACCESSIBLE] = "inaccessible",
273 [MOUNT_OVERLAY] = "overlay",
274 [MOUNT_IMAGE] = "image",
275 [MOUNT_BIND] = "bind",
276 [MOUNT_BIND_RECURSIVE] = "bind-recursive",
277 [MOUNT_PRIVATE_TMP] = "private-tmp",
278 [MOUNT_PRIVATE_DEV] = "private-dev",
279 [MOUNT_BIND_DEV] = "bind-dev",
280 [MOUNT_EMPTY_DIR] = "empty-dir",
281 [MOUNT_PRIVATE_SYSFS] = "private-sysfs",
282 [MOUNT_BIND_SYSFS] = "bind-sysfs",
283 [MOUNT_PRIVATE_CGROUP2FS] = "private-cgroup2fs",
284 [MOUNT_PROCFS] = "procfs",
285 [MOUNT_READ_ONLY] = "read-only",
286 [MOUNT_READ_WRITE] = "read-write",
287 [MOUNT_NOEXEC] = "noexec",
288 [MOUNT_EXEC] = "exec",
289 [MOUNT_TMPFS] = "tmpfs",
290 [MOUNT_RUN] = "run",
291 [MOUNT_PRIVATE_TMPFS] = "private-tmpfs",
292 [MOUNT_EXTENSION_DIRECTORY] = "extension-directory",
293 [MOUNT_EXTENSION_IMAGE] = "extension-image",
294 [MOUNT_MQUEUEFS] = "mqueuefs",
295 [MOUNT_READ_WRITE_IMPLICIT] = "read-write-implicit",
296 };
297
298 /* Helper struct for naming simplicity and reusability */
299 static const struct {
300 const char *level_env;
301 const char *level_env_print;
302 } image_class_info[_IMAGE_CLASS_MAX] = {
303 [IMAGE_SYSEXT] = {
304 .level_env = "SYSEXT_LEVEL",
305 .level_env_print = " SYSEXT_LEVEL=",
306 },
307 [IMAGE_CONFEXT] = {
308 .level_env = "CONFEXT_LEVEL",
309 .level_env_print = " CONFEXT_LEVEL=",
310 }
311 };
312
313 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode, MountMode);
314
315 static const char* mount_entry_path(const MountEntry *p) {
316 assert(p);
317
318 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
319 * otherwise the stack/static ->path field is returned. */
320
321 return p->path_malloc ?: p->path_const;
322 }
323
324 static const char* mount_entry_unprefixed_path(const MountEntry *p) {
325 assert(p);
326
327 /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
328
329 return p->unprefixed_path_malloc ?: p->unprefixed_path_const ?: mount_entry_path(p);
330 }
331
332 static void mount_entry_consume_prefix(MountEntry *p, char *new_path) {
333 assert(p);
334 assert(p->path_malloc || p->path_const);
335 assert(new_path);
336
337 /* Saves current path in unprefixed_ variable, and takes over new_path */
338
339 free_and_replace(p->unprefixed_path_malloc, p->path_malloc);
340 /* If we didn't have a path on the heap, then it's a static one */
341 if (!p->unprefixed_path_malloc)
342 p->unprefixed_path_const = p->path_const;
343 p->path_malloc = new_path;
344 p->has_prefix = true;
345 }
346
347 static bool mount_entry_read_only(const MountEntry *p) {
348 assert(p);
349
350 return p->read_only || IN_SET(p->mode, MOUNT_READ_ONLY, MOUNT_INACCESSIBLE);
351 }
352
353 static bool mount_entry_noexec(const MountEntry *p) {
354 assert(p);
355
356 return p->noexec || IN_SET(p->mode, MOUNT_NOEXEC, MOUNT_INACCESSIBLE, MOUNT_PRIVATE_SYSFS, MOUNT_BIND_SYSFS, MOUNT_PROCFS, MOUNT_PRIVATE_CGROUP2FS);
357 }
358
359 static bool mount_entry_exec(const MountEntry *p) {
360 assert(p);
361
362 return p->exec || p->mode == MOUNT_EXEC;
363 }
364
365 static const char* mount_entry_source(const MountEntry *p) {
366 assert(p);
367
368 return p->source_malloc ?: p->source_const;
369 }
370
371 static const char* mount_entry_options(const MountEntry *p) {
372 assert(p);
373
374 return p->options_malloc ?: p->options_const;
375 }
376
377 static void mount_entry_done(MountEntry *p) {
378 assert(p);
379
380 p->path_malloc = mfree(p->path_malloc);
381 p->unprefixed_path_malloc = mfree(p->unprefixed_path_malloc);
382 p->source_malloc = mfree(p->source_malloc);
383 p->options_malloc = mfree(p->options_malloc);
384 p->overlay_layers = strv_free(p->overlay_layers);
385 verity_settings_done(&p->verity);
386 }
387
388 static void mount_list_done(MountList *ml) {
389 assert(ml);
390
391 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts)
392 mount_entry_done(m);
393
394 ml->mounts = mfree(ml->mounts);
395 ml->n_mounts = 0;
396 }
397
398 static MountEntry* mount_list_extend(MountList *ml) {
399 assert(ml);
400
401 if (!GREEDY_REALLOC0(ml->mounts, ml->n_mounts+1))
402 return NULL;
403
404 return ml->mounts + ml->n_mounts++;
405 }
406
407 static int append_access_mounts(MountList *ml, char **strv, MountMode mode, bool forcibly_require_prefix) {
408 assert(ml);
409
410 /* Adds a list of user-supplied READ_WRITE/READ_WRITE_IMPLICIT/READ_ONLY/INACCESSIBLE entries */
411
412 STRV_FOREACH(i, strv) {
413 bool ignore = false, needs_prefix = false;
414 const char *e = *i;
415
416 /* Look for any prefixes */
417 if (startswith(e, "-")) {
418 e++;
419 ignore = true;
420 }
421 if (startswith(e, "+")) {
422 e++;
423 needs_prefix = true;
424 }
425
426 if (!path_is_absolute(e))
427 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", e);
428
429 MountEntry *me = mount_list_extend(ml);
430 if (!me)
431 return log_oom_debug();
432
433 *me = (MountEntry) {
434 .path_const = e,
435 .mode = mode,
436 .ignore = ignore,
437 .has_prefix = !needs_prefix && !forcibly_require_prefix,
438 };
439 }
440
441 return 0;
442 }
443
444 static int append_empty_dir_mounts(MountList *ml, char **strv) {
445 assert(ml);
446
447 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
448 * "/private/" boundary directories for DynamicUser=1. */
449
450 STRV_FOREACH(i, strv) {
451 MountEntry *me = mount_list_extend(ml);
452 if (!me)
453 return log_oom_debug();
454
455 *me = (MountEntry) {
456 .path_const = *i,
457 .mode = MOUNT_EMPTY_DIR,
458 .ignore = false,
459 .read_only = true,
460 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
461 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
462 };
463 }
464
465 return 0;
466 }
467
468 static int append_bind_mounts(MountList *ml, const BindMount *binds, size_t n) {
469 assert(ml);
470 assert(binds || n == 0);
471
472 FOREACH_ARRAY(b, binds, n) {
473 MountEntry *me = mount_list_extend(ml);
474 if (!me)
475 return log_oom_debug();
476
477 *me = (MountEntry) {
478 .path_const = b->destination,
479 .mode = b->recursive ? MOUNT_BIND_RECURSIVE : MOUNT_BIND,
480 .read_only = b->read_only,
481 .nosuid = b->nosuid,
482 .noexec = b->noexec,
483 .flags = b->nodev ? MS_NODEV : 0,
484 .source_const = b->source,
485 .ignore = b->ignore_enoent,
486 .idmapped = b->idmapped,
487 .idmap_uid = b->uid,
488 .idmap_gid = b->gid,
489 };
490 }
491
492 return 0;
493 }
494
495 static int append_mount_images(MountList *ml, const MountImage *mount_images, size_t n) {
496 int r;
497
498 assert(ml);
499 assert(mount_images || n == 0);
500
501 FOREACH_ARRAY(m, mount_images, n) {
502 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
503 MountEntry *me = mount_list_extend(ml);
504 if (!me)
505 return log_oom_debug();
506
507 r = verity_settings_load(&verity, m->source, /* root_hash_path= */ NULL, /* root_hash_sig_path= */ NULL);
508 if (r < 0)
509 return log_debug_errno(r, "Failed to check verity root hash of %s: %m", m->source);
510
511 *me = (MountEntry) {
512 .path_const = m->destination,
513 .mode = MOUNT_IMAGE,
514 .source_const = m->source,
515 .image_options_const = m->mount_options,
516 .ignore = m->ignore_enoent,
517 .verity = TAKE_GENERIC(verity, VeritySettings, VERITY_SETTINGS_DEFAULT),
518 .filter_class = _IMAGE_CLASS_INVALID,
519 };
520 }
521
522 return 0;
523 }
524
525 static int append_extensions(
526 MountList *ml,
527 const char *root,
528 const char *private_namespace_dir,
529 char **hierarchies,
530 const MountImage *mount_images,
531 size_t n_mount_images,
532 char **extension_directories) {
533
534 char ***overlays = NULL;
535 size_t n_overlays = 0;
536 int r;
537
538 assert(ml);
539
540 if (n_mount_images == 0 && strv_isempty(extension_directories))
541 return 0;
542
543 assert(private_namespace_dir);
544
545 n_overlays = strv_length(hierarchies);
546 if (n_overlays == 0)
547 return 0;
548
549 /* Prepare a list of overlays, that will have as each element a strv containing all the layers that
550 * will later be concatenated as a lowerdir= parameter for the mount operation.
551 * The overlays vector will have the same number of elements and will correspond to the
552 * hierarchies vector, so they can be iterated upon together. */
553 overlays = new0(char**, n_overlays);
554 if (!overlays)
555 return -ENOMEM;
556
557 CLEANUP_ARRAY(overlays, n_overlays, strv_free_many);
558
559 /* First, prepare a mount for each image, but these won't be visible to the unit, instead
560 * they will be mounted in our propagate directory, and used as a source for the overlay. */
561 for (size_t i = 0; i < n_mount_images; i++) {
562 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
563 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
564 _cleanup_free_ char *mount_point = NULL;
565 const MountImage *m = mount_images + i;
566
567 r = path_pick(/* toplevel_path= */ NULL,
568 /* toplevel_fd= */ AT_FDCWD,
569 m->source,
570 pick_filter_image_raw,
571 ELEMENTSOF(pick_filter_image_raw),
572 PICK_ARCHITECTURE|PICK_TRIES,
573 &result);
574 if (r == -ENOENT && m->ignore_enoent)
575 continue;
576 if (r < 0)
577 return r;
578 if (!result.path) {
579 if (m->ignore_enoent)
580 continue;
581
582 return log_debug_errno(
583 SYNTHETIC_ERRNO(ENOENT),
584 "No matching entry in .v/ directory %s found.",
585 m->source);
586 }
587
588 r = verity_settings_load(&verity, result.path, /* root_hash_path= */ NULL, /* root_hash_sig_path= */ NULL);
589 if (r < 0)
590 return log_debug_errno(r, "Failed to check verity root hash of %s: %m", result.path);
591
592 if (asprintf(&mount_point, "%s/unit-extensions/%zu", private_namespace_dir, i) < 0)
593 return -ENOMEM;
594
595 for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
596 char *prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
597 if (!prefixed_hierarchy)
598 return -ENOMEM;
599
600 r = strv_consume(&overlays[j], TAKE_PTR(prefixed_hierarchy));
601 if (r < 0)
602 return r;
603 }
604
605 MountEntry *me = mount_list_extend(ml);
606 if (!me)
607 return -ENOMEM;
608
609 *me = (MountEntry) {
610 .path_malloc = TAKE_PTR(mount_point),
611 .image_options_const = m->mount_options,
612 .ignore = m->ignore_enoent,
613 .source_malloc = TAKE_PTR(result.path),
614 .mode = MOUNT_EXTENSION_IMAGE,
615 .has_prefix = true,
616 .verity = TAKE_GENERIC(verity, VeritySettings, VERITY_SETTINGS_DEFAULT),
617 .filter_class = _IMAGE_CLASS_INVALID,
618 };
619 }
620
621 /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
622 * Bind mount them in the same location as the ExtensionImages, so that we
623 * can check that they are valid trees (extension-release.d). */
624 STRV_FOREACH(extension_directory, extension_directories) {
625 _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
626 _cleanup_free_ char *mount_point = NULL;
627 const char *e = *extension_directory;
628 bool ignore_enoent = false;
629
630 /* Look for any prefixes */
631 if (startswith(e, "-")) {
632 e++;
633 ignore_enoent = true;
634 }
635 /* Ignore this for now */
636 if (startswith(e, "+"))
637 e++;
638
639 r = path_pick(/* toplevel_path= */ NULL,
640 /* toplevel_fd= */ AT_FDCWD,
641 e,
642 pick_filter_image_dir,
643 ELEMENTSOF(pick_filter_image_dir),
644 PICK_ARCHITECTURE|PICK_TRIES,
645 &result);
646 if (r == -ENOENT && ignore_enoent)
647 continue;
648 if (r < 0)
649 return r;
650 if (!result.path) {
651 if (ignore_enoent)
652 continue;
653
654 return log_debug_errno(
655 SYNTHETIC_ERRNO(ENOENT),
656 "No matching entry in .v/ directory %s found.",
657 e);
658 }
659
660 /* Pick up the counter where the ExtensionImages left it. */
661 if (asprintf(&mount_point, "%s/unit-extensions/%zu", private_namespace_dir, n_mount_images++) < 0)
662 return -ENOMEM;
663
664 for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
665 char *prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
666 if (!prefixed_hierarchy)
667 return -ENOMEM;
668
669 r = strv_consume(&overlays[j], TAKE_PTR(prefixed_hierarchy));
670 if (r < 0)
671 return r;
672 }
673
674 MountEntry *me = mount_list_extend(ml);
675 if (!me)
676 return -ENOMEM;
677
678 *me = (MountEntry) {
679 .path_malloc = TAKE_PTR(mount_point),
680 .source_malloc = TAKE_PTR(result.path),
681 .mode = MOUNT_EXTENSION_DIRECTORY,
682 .ignore = ignore_enoent,
683 .has_prefix = true,
684 .read_only = true,
685 .filter_class = _IMAGE_CLASS_INVALID,
686 };
687 }
688
689 /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
690 * set up earlier. */
691 for (size_t i = 0; hierarchies && hierarchies[i]; ++i) {
692 _cleanup_free_ char *prefixed_hierarchy = NULL;
693
694 prefixed_hierarchy = path_join(root, hierarchies[i]);
695 if (!prefixed_hierarchy)
696 return -ENOMEM;
697
698 MountEntry *me = mount_list_extend(ml);
699 if (!me)
700 return -ENOMEM;
701
702 *me = (MountEntry) {
703 .path_malloc = TAKE_PTR(prefixed_hierarchy),
704 .overlay_layers = TAKE_PTR(overlays[i]),
705 .mode = MOUNT_OVERLAY,
706 .has_prefix = true,
707 .ignore = true, /* If the source image doesn't set the ignore bit it will fail earlier. */
708 };
709 }
710
711 return 0;
712 }
713
714 static int append_tmpfs_mounts(MountList *ml, const TemporaryFileSystem *tmpfs, size_t n) {
715 assert(ml);
716 assert(tmpfs || n == 0);
717
718 FOREACH_ARRAY(t, tmpfs, n) {
719 _cleanup_free_ char *o = NULL, *str = NULL;
720 unsigned long flags;
721 bool ro = false;
722 int r;
723
724 if (!path_is_absolute(t->path))
725 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", t->path);
726
727 str = strjoin("mode=0755" NESTED_TMPFS_LIMITS ",", t->options);
728 if (!str)
729 return -ENOMEM;
730
731 r = mount_option_mangle(str, MS_NODEV|MS_STRICTATIME, &flags, &o);
732 if (r < 0)
733 return log_debug_errno(r, "Failed to parse mount option '%s': %m", str);
734
735 ro = flags & MS_RDONLY;
736 flags &= ~MS_RDONLY;
737
738 MountEntry *me = mount_list_extend(ml);
739 if (!me)
740 return log_oom_debug();
741
742 *me = (MountEntry) {
743 .path_const = t->path,
744 .mode = MOUNT_TMPFS,
745 .read_only = ro,
746 .options_malloc = TAKE_PTR(o),
747 .flags = flags,
748 };
749 }
750
751 return 0;
752 }
753
754 static int append_private_tmp_one(
755 MountList *ml,
756 PrivateTmp mode,
757 const char *path,
758 const char *connected_source) {
759
760 assert(ml);
761 assert(mode >= 0 && mode < _PRIVATE_TMP_MAX);
762 assert(path);
763
764 if (mode == PRIVATE_TMP_NO)
765 return 0;
766
767 if (mode == PRIVATE_TMP_CONNECTED && !connected_source)
768 /* Do nothing if the private tmp dir was suppressed as it would be made inaccessible anyways
769 * (see exec_shared_runtime_make()). */
770 return 0;
771
772 MountEntry *me = mount_list_extend(ml);
773 if (!me)
774 return log_oom_debug();
775
776 if (mode == PRIVATE_TMP_CONNECTED)
777 *me = (MountEntry) {
778 .path_const = path,
779 .mode = MOUNT_PRIVATE_TMP,
780 .read_only = streq(connected_source, RUN_SYSTEMD_EMPTY),
781 .source_const = connected_source,
782 };
783 else
784 *me = (MountEntry) {
785 .path_const = path,
786 .mode = MOUNT_PRIVATE_TMPFS,
787 .options_const = "mode=0700" NESTED_TMPFS_LIMITS,
788 .flags = MS_NODEV|MS_STRICTATIME,
789 };
790
791 return 0;
792 }
793
794 static int append_private_tmp(MountList *ml, const NamespaceParameters *p) {
795 int r;
796
797 assert(ml);
798 assert(p);
799 assert(p->private_tmp >= 0 && p->private_tmp < _PRIVATE_TMP_MAX);
800 assert(p->private_var_tmp >= 0 && p->private_var_tmp < _PRIVATE_TMP_MAX);
801
802 if (p->private_tmp != PRIVATE_TMP_DISCONNECTED || p->private_var_tmp != PRIVATE_TMP_DISCONNECTED) {
803 r = append_private_tmp_one(ml, p->private_tmp, "/tmp/", p->tmp_dir);
804 if (r < 0)
805 return r;
806
807 r = append_private_tmp_one(ml, p->private_var_tmp, "/var/tmp/", p->var_tmp_dir);
808 if (r < 0)
809 return r;
810
811 return 0;
812 }
813
814 /* Fully disconnected private tmp: we mount a single tmpfs instance with two subdirs which are
815 * bind mounted to /tmp/ and /var/tmp/. */
816
817 MountEntry *me;
818
819 _cleanup_free_ char *tmpfs_dir = NULL, *tmp_dir = NULL, *var_tmp_dir = NULL;
820 tmpfs_dir = path_join(p->private_namespace_dir, "unit-private-tmp");
821 tmp_dir = path_join(tmpfs_dir, "tmp");
822 var_tmp_dir = path_join(tmpfs_dir, "var-tmp");
823 if (!tmpfs_dir || !tmp_dir || !var_tmp_dir)
824 return log_oom_debug();
825
826 me = mount_list_extend(ml);
827 if (!me)
828 return log_oom_debug();
829 *me = (MountEntry) {
830 .path_malloc = TAKE_PTR(tmpfs_dir),
831 .mode = MOUNT_PRIVATE_TMPFS,
832 .options_const = "mode=0700" NESTED_TMPFS_LIMITS,
833 .flags = MS_NODEV|MS_STRICTATIME,
834 .has_prefix = true,
835 };
836
837 me = mount_list_extend(ml);
838 if (!me)
839 return log_oom_debug();
840 *me = (MountEntry) {
841 .source_malloc = TAKE_PTR(tmp_dir),
842 .path_const = "/tmp/",
843 .mode = MOUNT_BIND,
844 .source_dir_mode = 01777,
845 .create_source_dir = true,
846 };
847
848 me = mount_list_extend(ml);
849 if (!me)
850 return log_oom_debug();
851 *me = (MountEntry) {
852 .source_malloc = TAKE_PTR(var_tmp_dir),
853 .path_const = "/var/tmp/",
854 .mode = MOUNT_BIND,
855 .source_dir_mode = 01777,
856 .create_source_dir = true,
857 };
858
859 return 0;
860 }
861
862 static int append_static_mounts(MountList *ml, const MountEntry *mounts, size_t n, bool ignore_protect) {
863 assert(ml);
864 assert(mounts || n == 0);
865
866 /* Adds a list of static pre-defined entries */
867
868 FOREACH_ARRAY(m, mounts, n) {
869 MountEntry *me = mount_list_extend(ml);
870 if (!me)
871 return log_oom_debug();
872
873 /* No dynamic values allowed. */
874 assert(m->path_const);
875 assert(!m->path_malloc);
876 assert(!m->unprefixed_path_malloc);
877 assert(!m->source_malloc);
878 assert(!m->options_malloc);
879 assert(!m->overlay_layers);
880
881 *me = *m;
882 me->ignore = me->ignore || ignore_protect;
883 }
884
885 return 0;
886 }
887
888 static int append_protect_control_groups(MountList *ml, ProtectControlGroups protect_control_groups, bool ignore_protect) {
889 assert(ml);
890
891 switch (protect_control_groups) {
892
893 case PROTECT_CONTROL_GROUPS_NO:
894 return 0;
895
896 case PROTECT_CONTROL_GROUPS_YES:
897 return append_static_mounts(ml, protect_control_groups_yes_table, ELEMENTSOF(protect_control_groups_yes_table), ignore_protect);
898
899 case PROTECT_CONTROL_GROUPS_PRIVATE:
900 return append_static_mounts(ml, protect_control_groups_private_table, ELEMENTSOF(protect_control_groups_private_table), ignore_protect);
901
902 case PROTECT_CONTROL_GROUPS_STRICT:
903 return append_static_mounts(ml, protect_control_groups_strict_table, ELEMENTSOF(protect_control_groups_strict_table), ignore_protect);
904
905 default:
906 assert_not_reached();
907 }
908 }
909
910 static int append_protect_home(MountList *ml, ProtectHome protect_home, bool ignore_protect) {
911 assert(ml);
912
913 switch (protect_home) {
914
915 case PROTECT_HOME_NO:
916 return 0;
917
918 case PROTECT_HOME_READ_ONLY:
919 return append_static_mounts(ml, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
920
921 case PROTECT_HOME_TMPFS:
922 return append_static_mounts(ml, protect_home_tmpfs_table, ELEMENTSOF(protect_home_tmpfs_table), ignore_protect);
923
924 case PROTECT_HOME_YES:
925 return append_static_mounts(ml, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
926
927 default:
928 assert_not_reached();
929 }
930 }
931
932 static int append_protect_system(MountList *ml, ProtectSystem protect_system, bool ignore_protect) {
933 assert(ml);
934
935 switch (protect_system) {
936
937 case PROTECT_SYSTEM_NO:
938 return 0;
939
940 case PROTECT_SYSTEM_STRICT:
941 return append_static_mounts(ml, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
942
943 case PROTECT_SYSTEM_YES:
944 return append_static_mounts(ml, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
945
946 case PROTECT_SYSTEM_FULL:
947 return append_static_mounts(ml, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
948
949 default:
950 assert_not_reached();
951 }
952 }
953
954 static int append_private_bpf(
955 MountList *ml,
956 PrivateBPF private_bpf,
957 bool protect_kernel_tunables,
958 bool ignore_protect,
959 const NamespaceParameters *p) {
960
961 assert(ml);
962
963 switch (private_bpf) {
964 case PRIVATE_BPF_NO:
965 if (protect_kernel_tunables)
966 return append_static_mounts(ml, private_bpf_no_table, ELEMENTSOF(private_bpf_no_table), ignore_protect);
967 return 0;
968 case PRIVATE_BPF_YES: {
969 MountEntry *me = mount_list_extend(ml);
970 if (!me)
971 return log_oom_debug();
972
973 *me = (MountEntry) {
974 .path_const = "/sys/fs/bpf",
975 .mode = MOUNT_BPFFS,
976 .ignore = !protect_kernel_tunables, /* indicate whether we should fall back to MOUNT_READ_ONLY on failure. */
977 };
978 return 0;
979 }
980 default:
981 assert_not_reached();
982 }
983 }
984
985 static int mount_path_compare(const MountEntry *a, const MountEntry *b) {
986 int d;
987
988 /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
989 * regardless of the prefix - they are set up in the propagate directory anyway */
990 d = -CMP(a->mode == MOUNT_EXTENSION_IMAGE, b->mode == MOUNT_EXTENSION_IMAGE);
991 if (d != 0)
992 return d;
993 d = -CMP(a->mode == MOUNT_EXTENSION_DIRECTORY, b->mode == MOUNT_EXTENSION_DIRECTORY);
994 if (d != 0)
995 return d;
996
997 /* MOUNT_PRIVATE_TMPFS needs to be set up earlier, especially than MOUNT_BIND. */
998 d = -CMP(a->mode == MOUNT_PRIVATE_TMPFS, b->mode == MOUNT_PRIVATE_TMPFS);
999 if (d != 0)
1000 return d;
1001
1002 /* If the paths are not equal, then order prefixes first */
1003 d = path_compare(mount_entry_path(a), mount_entry_path(b));
1004 if (d != 0)
1005 return d;
1006
1007 /* If the paths are equal, check the mode */
1008 return CMP((int) a->mode, (int) b->mode);
1009 }
1010
1011 static int prefix_where_needed(MountList *ml, const char *root_directory) {
1012 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
1013
1014 assert(ml);
1015
1016 FOREACH_ARRAY(me, ml->mounts, ml->n_mounts) {
1017 char *s;
1018
1019 if (me->has_prefix)
1020 continue;
1021
1022 s = path_join(root_directory, mount_entry_path(me));
1023 if (!s)
1024 return -ENOMEM;
1025
1026 mount_entry_consume_prefix(me, s);
1027 }
1028
1029 return 0;
1030 }
1031
1032 static bool verity_has_later_duplicates(MountList *ml, const MountEntry *needle) {
1033
1034 assert(ml);
1035 assert(needle);
1036 assert(needle >= ml->mounts && needle < ml->mounts + ml->n_mounts);
1037 assert(needle->mode == MOUNT_EXTENSION_IMAGE);
1038
1039 if (!iovec_is_set(&needle->verity.root_hash))
1040 return false;
1041
1042 /* Overlayfs rejects supplying the same directory inode twice as determined by filesystem UUID and
1043 * file handle in lowerdir=, even if they are mounted on different paths, as it resolves each mount
1044 * to its source filesystem, so drop duplicates, and keep the last one. This only covers non-DDI
1045 * verity images. Note that the list is ordered, so we only check for the reminder of the list for
1046 * each item, rather than the full list from the beginning, as any earlier duplicates will have
1047 * already been pruned. */
1048
1049 for (const MountEntry *m = needle + 1; m < ml->mounts + ml->n_mounts; m++) {
1050 if (m->mode != MOUNT_EXTENSION_IMAGE)
1051 continue;
1052 if (iovec_equal(&m->verity.root_hash, &needle->verity.root_hash))
1053 return true;
1054 }
1055
1056 return false;
1057 }
1058
1059 static void drop_duplicates(MountList *ml) {
1060 MountEntry *f, *t, *previous;
1061
1062 assert(ml);
1063
1064 /* Drops duplicate entries. Expects that the array is properly ordered already. */
1065
1066 for (f = ml->mounts, t = ml->mounts, previous = NULL; f < ml->mounts + ml->n_mounts; f++) {
1067
1068 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
1069 * above. Note that we only drop duplicates that haven't been mounted yet. */
1070 if (previous &&
1071 path_equal(mount_entry_path(f), mount_entry_path(previous)) &&
1072 f->state == MOUNT_PENDING && previous->state == MOUNT_PENDING) {
1073 log_debug("%s (%s) is duplicate.", mount_entry_path(f), mount_mode_to_string(f->mode));
1074 /* Propagate the flags to the remaining entry */
1075 previous->read_only = previous->read_only || mount_entry_read_only(f);
1076 previous->noexec = previous->noexec || mount_entry_noexec(f);
1077 previous->exec = previous->exec || mount_entry_exec(f);
1078 mount_entry_done(f);
1079 continue;
1080 }
1081
1082 if (f->mode == MOUNT_EXTENSION_IMAGE && verity_has_later_duplicates(ml, f)) {
1083 log_debug("Skipping duplicate extension image %s", mount_entry_source(f));
1084 mount_entry_done(f);
1085 continue;
1086 }
1087
1088 *t = *f;
1089 previous = t;
1090 t++;
1091 }
1092
1093 ml->n_mounts = t - ml->mounts;
1094 }
1095
1096 static void drop_inaccessible(MountList *ml) {
1097 MountEntry *f, *t;
1098 const char *clear = NULL;
1099
1100 assert(ml);
1101
1102 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
1103 * ordered already. */
1104
1105 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
1106
1107 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
1108 * it, as inaccessible paths really should drop the entire subtree. */
1109 if (clear && path_startswith(mount_entry_path(f), clear)) {
1110 log_debug("%s is masked by %s.", mount_entry_path(f), clear);
1111 mount_entry_done(f);
1112 continue;
1113 }
1114
1115 clear = f->mode == MOUNT_INACCESSIBLE ? mount_entry_path(f) : NULL;
1116
1117 *t = *f;
1118 t++;
1119 }
1120
1121 ml->n_mounts = t - ml->mounts;
1122 }
1123
1124 static void drop_nop(MountList *ml) {
1125 MountEntry *f, *t;
1126
1127 assert(ml);
1128
1129 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
1130 * list is ordered by prefixes. */
1131
1132 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
1133
1134 /* Only suppress such subtrees for READ_ONLY, READ_WRITE and READ_WRITE_IMPLICIT entries */
1135 if (IN_SET(f->mode, MOUNT_READ_ONLY, MOUNT_READ_WRITE, MOUNT_READ_WRITE_IMPLICIT)) {
1136 MountEntry *found = NULL;
1137
1138 /* Now let's find the first parent of the entry we are looking at. */
1139 for (MountEntry *p = PTR_SUB1(t, ml->mounts); p; p = PTR_SUB1(p, ml->mounts))
1140 if (path_startswith(mount_entry_path(f), mount_entry_path(p))) {
1141 found = p;
1142 break;
1143 }
1144
1145 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
1146 if (found && found->mode == f->mode) {
1147 log_debug("%s (%s) is made redundant by %s (%s)",
1148 mount_entry_path(f), mount_mode_to_string(f->mode),
1149 mount_entry_path(found), mount_mode_to_string(found->mode));
1150 mount_entry_done(f);
1151 continue;
1152 }
1153 }
1154
1155 *t = *f;
1156 t++;
1157 }
1158
1159 ml->n_mounts = t - ml->mounts;
1160 }
1161
1162 static void drop_outside_root(MountList *ml, const char *root_directory) {
1163 MountEntry *f, *t;
1164
1165 assert(ml);
1166
1167 /* Nothing to do */
1168 if (!root_directory)
1169 return;
1170
1171 /* Drops all mounts that are outside of the root directory. */
1172
1173 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
1174
1175 /* ExtensionImages/Directories bases are opened in /run/[user/xyz/]systemd/unit-extensions
1176 * on the host, and a private (invisible to the guest) tmpfs instance is mounted on
1177 * /run/[user/xyz/]systemd/unit-private-tmp as the storage backend of private /tmp and
1178 * /var/tmp. */
1179 if (!IN_SET(f->mode, MOUNT_EXTENSION_IMAGE, MOUNT_EXTENSION_DIRECTORY, MOUNT_PRIVATE_TMPFS) &&
1180 !path_startswith(mount_entry_path(f), root_directory)) {
1181 log_debug("%s is outside of root directory.", mount_entry_path(f));
1182 mount_entry_done(f);
1183 continue;
1184 }
1185
1186 *t = *f;
1187 t++;
1188 }
1189
1190 ml->n_mounts = t - ml->mounts;
1191 }
1192
1193 static int clone_device_node(const char *node, const char *temporary_mount, bool *make_devnode) {
1194 _cleanup_free_ char *sl = NULL;
1195 const char *dn, *bn;
1196 struct stat st;
1197 int r;
1198
1199 assert(node);
1200 assert(path_is_absolute(node));
1201 assert(temporary_mount);
1202 assert(make_devnode);
1203
1204 if (stat(node, &st) < 0) {
1205 if (errno == ENOENT) {
1206 log_debug_errno(errno, "Device node '%s' to clone does not exist.", node);
1207 return -ENXIO;
1208 }
1209
1210 return log_debug_errno(errno, "Failed to stat() device node '%s' to clone: %m", node);
1211 }
1212
1213 r = stat_verify_device_node(&st);
1214 if (r < 0)
1215 return log_debug_errno(r, "Cannot clone device node '%s': %m", node);
1216
1217 dn = strjoina(temporary_mount, node);
1218
1219 /* First, try to create device node properly */
1220 if (*make_devnode) {
1221 mac_selinux_create_file_prepare(node, st.st_mode);
1222 r = mknod(dn, st.st_mode, st.st_rdev);
1223 mac_selinux_create_file_clear();
1224 if (r >= 0)
1225 goto add_symlink;
1226 if (errno != EPERM)
1227 return log_debug_errno(errno, "Failed to mknod '%s': %m", node);
1228
1229 /* This didn't work, let's not try this again for the next iterations. */
1230 *make_devnode = false;
1231 }
1232
1233 /* We're about to fall back to bind-mounting the device node. So create a dummy bind-mount target.
1234 * Do not prepare device-node SELinux label (see issue 13762) */
1235 r = mknod(dn, S_IFREG, 0);
1236 if (r < 0 && errno != EEXIST)
1237 return log_debug_errno(errno, "Failed to mknod dummy device node for '%s': %m", node);
1238
1239 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
1240 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
1241 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
1242 r = mount_nofollow_verbose(LOG_DEBUG, node, dn, NULL, MS_BIND, NULL);
1243 if (r < 0)
1244 return r;
1245
1246 add_symlink:
1247 bn = path_startswith(node, "/dev/");
1248 if (!bn)
1249 return 0;
1250
1251 /* Create symlinks like /dev/char/1:9 → ../urandom */
1252 if (asprintf(&sl, "%s/dev/%s/" DEVNUM_FORMAT_STR,
1253 temporary_mount,
1254 S_ISCHR(st.st_mode) ? "char" : "block",
1255 DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
1256 return log_oom_debug();
1257
1258 (void) mkdir_parents(sl, 0755);
1259
1260 const char *t = strjoina("../", bn);
1261 if (symlink(t, sl) < 0)
1262 log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, sl);
1263
1264 return 0;
1265 }
1266
1267 static int bind_mount_device_dir(const char *temporary_mount, const char *dir) {
1268 const char *t;
1269
1270 assert(temporary_mount);
1271 assert(dir);
1272 assert(path_is_absolute(dir));
1273
1274 t = strjoina(temporary_mount, dir);
1275
1276 (void) mkdir(t, 0755);
1277 return mount_nofollow_verbose(LOG_DEBUG, dir, t, NULL, MS_BIND, NULL);
1278 }
1279
1280 static char* settle_runtime_dir(RuntimeScope scope) {
1281 char *runtime_dir;
1282
1283 if (scope != RUNTIME_SCOPE_USER)
1284 return strdup("/run/");
1285
1286 if (asprintf(&runtime_dir, "/run/user/" UID_FMT, geteuid()) < 0)
1287 return NULL;
1288
1289 return runtime_dir;
1290 }
1291
1292 static int create_temporary_mount_point(RuntimeScope scope, char **ret) {
1293 _cleanup_free_ char *runtime_dir = NULL, *temporary_mount = NULL;
1294
1295 assert(ret);
1296
1297 runtime_dir = settle_runtime_dir(scope);
1298 if (!runtime_dir)
1299 return log_oom_debug();
1300
1301 temporary_mount = path_join(runtime_dir, "systemd/namespace-XXXXXX");
1302 if (!temporary_mount)
1303 return log_oom_debug();
1304
1305 if (!mkdtemp(temporary_mount))
1306 return log_debug_errno(errno, "Failed to create temporary directory '%s': %m", temporary_mount);
1307
1308 *ret = TAKE_PTR(temporary_mount);
1309 return 0;
1310 }
1311
1312 static int mount_private_dev(const MountEntry *m, const NamespaceParameters *p) {
1313 static const char devnodes[] =
1314 "/dev/null\0"
1315 "/dev/zero\0"
1316 "/dev/full\0"
1317 "/dev/random\0"
1318 "/dev/urandom\0"
1319 "/dev/tty\0";
1320
1321 _cleanup_(rmdir_and_freep) char *temporary_mount = NULL;
1322 _cleanup_(umount_and_rmdir_and_freep) char *dev = NULL;
1323 bool can_mknod = true;
1324 int r;
1325
1326 assert(m);
1327 assert(p);
1328
1329 r = create_temporary_mount_point(p->runtime_scope, &temporary_mount);
1330 if (r < 0)
1331 return r;
1332
1333 dev = path_join(temporary_mount, "dev");
1334 if (!dev)
1335 return -ENOMEM;
1336
1337 (void) mkdir(dev, 0755);
1338 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=0755" TMPFS_LIMITS_PRIVATE_DEV);
1339 if (r < 0)
1340 return r;
1341
1342 r = label_fix_full(AT_FDCWD, dev, "/dev", 0);
1343 if (r < 0)
1344 return log_debug_errno(r, "Failed to fix label of '%s' as /dev/: %m", dev);
1345
1346 r = bind_mount_device_dir(temporary_mount, "/dev/pts");
1347 if (r < 0)
1348 return r;
1349
1350 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
1351 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
1352 * Thus, in that case make a clone.
1353 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
1354 r = is_symlink("/dev/ptmx");
1355 if (r < 0)
1356 return log_debug_errno(r, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
1357 if (r > 0) {
1358 const char *devptmx = strjoina(temporary_mount, "/dev/ptmx");
1359 if (symlink("pts/ptmx", devptmx) < 0)
1360 return log_debug_errno(errno, "Failed to create symlink '%s' to pts/ptmx: %m", devptmx);
1361 } else {
1362 r = clone_device_node("/dev/ptmx", temporary_mount, &can_mknod);
1363 if (r < 0)
1364 return r;
1365 }
1366
1367 r = bind_mount_device_dir(temporary_mount, "/dev/shm");
1368 if (r < 0)
1369 return r;
1370
1371 FOREACH_STRING(d, "/dev/mqueue", "/dev/hugepages")
1372 (void) bind_mount_device_dir(temporary_mount, d);
1373
1374 /* We assume /run/systemd/journal/ is available if not changing root, which isn't entirely accurate
1375 * but shouldn't matter, as either way the user would get ENOENT when accessing /dev/log */
1376 if (!pinned_resource_is_set(p->rootfs) || p->bind_log_sockets) {
1377 const char *devlog = strjoina(temporary_mount, "/dev/log");
1378 if (symlink("/run/systemd/journal/dev-log", devlog) < 0)
1379 log_debug_errno(errno,
1380 "Failed to create symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m",
1381 devlog);
1382 }
1383
1384 NULSTR_FOREACH(d, devnodes) {
1385 r = clone_device_node(d, temporary_mount, &can_mknod);
1386 /* ENXIO means the *source* is not a device file, skip creation in that case */
1387 if (r < 0 && r != -ENXIO)
1388 return r;
1389 }
1390
1391 r = dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
1392 if (r < 0)
1393 log_debug_errno(r, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount);
1394
1395 /* Create the /dev directory if missing. It is more likely to be missing when the service is started
1396 * with RootDirectory. This is consistent with mount units creating the mount points when missing. */
1397 (void) mkdir_p_label(mount_entry_path(m), 0755);
1398
1399 /* Unmount everything in old /dev */
1400 r = umount_recursive(mount_entry_path(m), 0);
1401 if (r < 0)
1402 log_debug_errno(r, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m));
1403
1404 r = mount_nofollow_verbose(LOG_DEBUG, dev, mount_entry_path(m), NULL, MS_MOVE, NULL);
1405 if (r < 0)
1406 return r;
1407 dev = rmdir_and_free(dev); /* Mount is successfully moved, do not umount() */
1408
1409 return 1;
1410 }
1411
1412 static int mount_bind_dev(const MountEntry *m) {
1413 int r;
1414
1415 assert(m);
1416
1417 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the
1418 * service's /dev. This is only used when RootDirectory= is set. */
1419
1420 (void) mkdir_p_label(mount_entry_path(m), 0755);
1421
1422 r = path_is_mount_point(mount_entry_path(m));
1423 if (r < 0)
1424 return log_debug_errno(r, "Unable to determine whether /dev is already mounted: %m");
1425 if (r > 0) /* make this a NOP if /dev is already a mount point */
1426 return 0;
1427
1428 r = mount_nofollow_verbose(LOG_DEBUG, "/dev", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
1429 if (r < 0)
1430 return r;
1431
1432 return 1;
1433 }
1434
1435 static int mount_bind_sysfs(const MountEntry *m) {
1436 int r;
1437
1438 assert(m);
1439
1440 (void) mkdir_p_label(mount_entry_path(m), 0755);
1441
1442 r = path_is_mount_point(mount_entry_path(m));
1443 if (r < 0)
1444 return log_debug_errno(r, "Unable to determine whether /sys is already mounted: %m");
1445 if (r > 0) /* make this a NOP if /sys is already a mount point */
1446 return 0;
1447
1448 /* Bind mount the host's version so that we get all child mounts of it, too. */
1449 r = mount_nofollow_verbose(LOG_DEBUG, "/sys", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
1450 if (r < 0)
1451 return r;
1452
1453 return 1;
1454 }
1455
1456 static int mount_private_apivfs(
1457 const char *fstype,
1458 const char *entry_path,
1459 const char *bind_source,
1460 const char *opts,
1461 RuntimeScope scope) {
1462
1463 _cleanup_(rmdir_and_freep) char *temporary_mount = NULL;
1464 int r;
1465
1466 assert(fstype);
1467 assert(entry_path);
1468 assert(bind_source);
1469
1470 bool noprivs = false;
1471
1472 /* First, check if we have enough privileges to mount a new instance. */
1473 _cleanup_close_ int mount_fd = make_fsmount(
1474 LOG_DEBUG,
1475 /* what= */ fstype,
1476 fstype,
1477 MS_NOSUID|MS_NOEXEC|MS_NODEV,
1478 opts,
1479 /* userns_fd= */ -EBADF);
1480 if (ERRNO_IS_NEG_PRIVILEGE(mount_fd))
1481 noprivs = true;
1482 else if (ERRNO_IS_NEG_NOT_SUPPORTED(mount_fd)) {
1483 /* Fallback for kernels lacking mount_setattr() */
1484
1485 // FIXME: This compatibility code path shall be removed once kernel 5.12
1486 // becomes the new minimal baseline
1487
1488 r = create_temporary_mount_point(scope, &temporary_mount);
1489 if (r < 0)
1490 return r;
1491
1492 r = mount_nofollow_verbose(
1493 LOG_DEBUG,
1494 fstype,
1495 temporary_mount,
1496 fstype,
1497 MS_NOSUID|MS_NOEXEC|MS_NODEV,
1498 opts);
1499 if (ERRNO_IS_NEG_PRIVILEGE(r))
1500 noprivs = true;
1501 else if (r < 0)
1502 return r;
1503 } else if (mount_fd < 0)
1504 return log_debug_errno(mount_fd, "Failed to make file system mount: %m");
1505
1506 (void) mkdir_p_label(entry_path, 0755);
1507
1508 if (noprivs) {
1509 /* When we do not have enough privileges to mount a new instance, fall back to use an
1510 * existing mount. */
1511
1512 r = path_is_mount_point(entry_path);
1513 if (r < 0)
1514 return log_debug_errno(r, "Unable to determine whether '%s' is already mounted: %m", entry_path);
1515 if (r > 0)
1516 return 0; /* Use the current mount as is. */
1517
1518 /* We lack permissions to mount a new instance, and it is not already mounted. But we can
1519 * access the host's, so as a final fallback bind-mount it to the destination, as most likely
1520 * we are inside a user manager in an unprivileged user namespace. */
1521 r = mount_nofollow_verbose(LOG_DEBUG, bind_source, entry_path, /* fstype= */ NULL, MS_BIND|MS_REC, /* options= */ NULL);
1522 if (r < 0)
1523 return r;
1524
1525 return 1;
1526 }
1527
1528 /* OK. We have a new mount instance. Let's clear an existing mount and its submounts. */
1529 r = umount_recursive(entry_path, /* flags= */ 0);
1530 if (r < 0)
1531 log_debug_errno(r, "Failed to unmount directories below '%s', ignoring: %m", entry_path);
1532
1533 /* Then, move the new mount instance. */
1534 if (mount_fd >= 0) {
1535 r = RET_NERRNO(move_mount(mount_fd, "", -EBADF, entry_path, MOVE_MOUNT_F_EMPTY_PATH));
1536 if (r < 0)
1537 return log_debug_errno(r, "Failed to attach '%s' to '%s': %m", fstype, entry_path);
1538 } else if (temporary_mount) {
1539 r = mount_nofollow_verbose(LOG_DEBUG, temporary_mount, entry_path, /* fstype= */ NULL, MS_MOVE, /* options= */ NULL);
1540 if (r < 0)
1541 return r;
1542 } else
1543 assert_not_reached();
1544
1545 /* We mounted a new instance now. Let's bind mount the children over now. This matters for nspawn
1546 * where a bunch of files are overmounted, in particular the boot id. */
1547 (void) bind_mount_submounts(bind_source, entry_path);
1548 return 1;
1549 }
1550
1551 static int mount_private_sysfs(const MountEntry *m, const NamespaceParameters *p) {
1552 assert(m);
1553 assert(p);
1554 return mount_private_apivfs("sysfs", mount_entry_path(m), "/sys", /* opts= */ NULL, p->runtime_scope);
1555 }
1556
1557 static int mount_private_cgroup2fs(const MountEntry *m, const NamespaceParameters *p) {
1558 assert(m);
1559 assert(p);
1560 return mount_private_apivfs("cgroup2", mount_entry_path(m), "/sys/fs/cgroup", /* opts= */ NULL, p->runtime_scope);
1561 }
1562
1563 static int mount_procfs(const MountEntry *m, const NamespaceParameters *p) {
1564 _cleanup_free_ char *opts = NULL;
1565 int r;
1566
1567 assert(m);
1568 assert(p);
1569
1570 if (p->protect_proc != PROTECT_PROC_DEFAULT ||
1571 p->proc_subset != PROC_SUBSET_ALL) {
1572
1573 opts = strjoin("hidepid=",
1574 p->protect_proc == PROTECT_PROC_DEFAULT ? "off" : protect_proc_to_string(p->protect_proc));
1575 if (!opts)
1576 return -ENOMEM;
1577
1578 if (p->proc_subset != PROC_SUBSET_ALL) {
1579 r = strextendf_with_separator(&opts, ",", "subset=%s", proc_subset_to_string(p->proc_subset));
1580 if (r < 0)
1581 return r;
1582 }
1583 }
1584
1585 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
1586 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
1587 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
1588 * mounted on /proc/ first. */
1589 return mount_private_apivfs("proc", mount_entry_path(m), "/proc", opts, p->runtime_scope);
1590 }
1591
1592 static int mount_tmpfs(const MountEntry *m) {
1593 const char *entry_path, *inner_path;
1594 int r;
1595
1596 assert(m);
1597
1598 entry_path = mount_entry_path(m);
1599 inner_path = mount_entry_unprefixed_path(m);
1600
1601 /* First, get rid of everything that is below if there is anything. Then, overmount with our new
1602 * tmpfs */
1603
1604 (void) mkdir_p_label(entry_path, 0755);
1605 (void) umount_recursive(entry_path, 0);
1606
1607 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", entry_path, "tmpfs", m->flags, mount_entry_options(m));
1608 if (r < 0)
1609 return r;
1610
1611 r = label_fix_full(AT_FDCWD, entry_path, inner_path, 0);
1612 if (r < 0)
1613 return log_debug_errno(r, "Failed to fix label of '%s' as '%s': %m", entry_path, inner_path);
1614
1615 return 1;
1616 }
1617
1618 static int mount_run(const MountEntry *m) {
1619 int r;
1620
1621 assert(m);
1622
1623 r = path_is_mount_point(mount_entry_path(m));
1624 if (r < 0 && r != -ENOENT)
1625 return log_debug_errno(r, "Unable to determine whether /run is already mounted: %m");
1626 if (r > 0) /* make this a NOP if /run is already a mount point */
1627 return 0;
1628
1629 return mount_tmpfs(m);
1630 }
1631
1632 static int mount_mqueuefs(const MountEntry *m) {
1633 int r;
1634 const char *entry_path;
1635
1636 assert(m);
1637
1638 entry_path = mount_entry_path(m);
1639
1640 (void) mkdir_p_label(entry_path, 0755);
1641 (void) umount_recursive(entry_path, 0);
1642
1643 r = mount_nofollow_verbose(LOG_DEBUG, "mqueue", entry_path, "mqueue", m->flags, mount_entry_options(m));
1644 if (r < 0)
1645 return r;
1646
1647 return 1;
1648 }
1649
1650 static int mount_image(
1651 MountEntry *m,
1652 const char *root_directory,
1653 const ImagePolicy *image_policy,
1654 RuntimeScope runtime_scope) {
1655
1656 _cleanup_(extension_release_data_done) ExtensionReleaseData rdata = {};
1657 ImageClass required_class = _IMAGE_CLASS_INVALID;
1658 int r;
1659
1660 assert(m);
1661
1662 if (m->mode == MOUNT_EXTENSION_IMAGE) {
1663 r = parse_os_release(
1664 empty_to_root(root_directory),
1665 "ID", &rdata.os_release_id,
1666 "ID_LIKE", &rdata.os_release_id_like,
1667 "VERSION_ID", &rdata.os_release_version_id,
1668 image_class_info[IMAGE_SYSEXT].level_env, &rdata.os_release_sysext_level,
1669 image_class_info[IMAGE_CONFEXT].level_env, &rdata.os_release_confext_level,
1670 NULL);
1671 if (r < 0)
1672 return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1673 if (isempty(rdata.os_release_id))
1674 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'ID' field not found or empty in 'os-release' data of OS tree '%s'.", empty_to_root(root_directory));
1675
1676 required_class = m->filter_class;
1677 }
1678
1679 r = verity_dissect_and_mount(
1680 /* src_fd= */ -EBADF,
1681 mount_entry_source(m),
1682 mount_entry_path(m),
1683 m->image_options_const,
1684 image_policy,
1685 /* image_filter= */ NULL,
1686 &rdata,
1687 required_class,
1688 &m->verity,
1689 runtime_scope,
1690 /* ret_image= */ NULL);
1691 if (r == -ENOENT && m->ignore)
1692 return 0;
1693 if (r == -ESTALE && rdata.os_release_id)
1694 return log_error_errno(r, // FIXME: this should not be logged ad LOG_ERR, as it will result in duplicate logging.
1695 "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s ID_LIKE='%s'%s%s%s%s%s%s",
1696 mount_entry_source(m),
1697 rdata.os_release_id,
1698 strempty(rdata.os_release_id_like),
1699 rdata.os_release_version_id ? " VERSION_ID=" : "",
1700 strempty(rdata.os_release_version_id),
1701 rdata.os_release_sysext_level ? image_class_info[IMAGE_SYSEXT].level_env_print : "",
1702 strempty(rdata.os_release_sysext_level),
1703 rdata.os_release_confext_level ? image_class_info[IMAGE_CONFEXT].level_env_print : "",
1704 strempty(rdata.os_release_confext_level));
1705 if (r == -ENOCSI) {
1706 log_debug("Image %s does not match the expected class, ignoring", mount_entry_source(m));
1707 return 0; /* Nothing to do, wrong class */
1708 }
1709 if (r < 0)
1710 return log_debug_errno(r, "Failed to mount image %s on %s: %m", mount_entry_source(m), mount_entry_path(m));
1711
1712 return 1;
1713 }
1714
1715 static int mount_overlay(const MountEntry *m) {
1716 _cleanup_free_ char *options = NULL, *layers = NULL;
1717 int r;
1718
1719 assert(m);
1720
1721 /* Extension hierarchies are optional (e.g.: confext might not have /opt) so check if they actually
1722 * exist in an image before attempting to create an overlay with them, otherwise the mount will
1723 * fail. We can't check before this, as the images will not be mounted until now. */
1724
1725 /* Note that lowerdir= parameters are in 'reverse' order, so the top-most directory in the overlay
1726 * comes first in the list. */
1727 STRV_FOREACH_BACKWARDS(o, m->overlay_layers) {
1728 _cleanup_free_ char *escaped = NULL;
1729
1730 r = is_dir(*o, /* follow= */ false);
1731 if (r <= 0) {
1732 if (r != -ENOENT)
1733 log_debug_errno(r,
1734 "Failed to check whether overlay layer source path '%s' exists, ignoring: %m",
1735 *o);
1736 continue;
1737 }
1738
1739 escaped = shell_escape(*o, ",:");
1740 if (!escaped)
1741 return log_oom_debug();
1742
1743 if (!strextend_with_separator(&layers, ":", escaped))
1744 return log_oom_debug();
1745 }
1746
1747 if (!layers) {
1748 log_debug("None of the overlays specified in '%s' exist at the source, skipping.",
1749 mount_entry_options(m));
1750 return 0; /* Only the root is set? Then there's nothing to overlay */
1751 }
1752
1753 options = strjoin("lowerdir=", layers, ":", mount_entry_path(m)); /* The root goes in last */
1754 if (!options)
1755 return log_oom_debug();
1756
1757 (void) mkdir_p_label(mount_entry_path(m), 0755);
1758
1759 r = mount_nofollow_verbose(LOG_DEBUG, "systemd-extensions", mount_entry_path(m), "overlay", MS_RDONLY, options);
1760 if (r == -ENOENT && m->ignore)
1761 return 0;
1762 if (r < 0)
1763 return r;
1764
1765 return 1;
1766 }
1767
1768 static int mount_bpffs(const MountEntry *m, PidRef *pidref, int socket_fd, int errno_pipe) {
1769 int r;
1770
1771 assert(m);
1772 assert(pidref_is_set(pidref));
1773 assert(socket_fd >= 0);
1774 assert(errno_pipe >= 0);
1775
1776 _cleanup_close_ int fs_fd = fsopen("bpf", FSOPEN_CLOEXEC);
1777 if (fs_fd < 0)
1778 return log_debug_errno(errno, "Failed to fsopen: %m");
1779
1780 r = send_one_fd(socket_fd, fs_fd, /* flags= */ 0);
1781 if (r < 0)
1782 return log_debug_errno(r, "Failed to send bpffs fd to child: %m");
1783
1784 r = pidref_wait_for_terminate_and_check("(sd-bpffs)", pidref, /* flags= */ 0);
1785 if (r < 0)
1786 return r;
1787
1788 /* If something strange happened with the child, let's consider this fatal, too */
1789 if (r != EXIT_SUCCESS) {
1790 ssize_t ss = read(errno_pipe, &r, sizeof(r));
1791 if (ss < 0)
1792 return log_debug_errno(errno, "Failed to read from the bpffs helper errno pipe: %m");
1793 if (ss != sizeof(r))
1794 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Short read from the bpffs helper errno pipe.");
1795 return log_debug_errno(r, "bpffs helper exited with error: %m");
1796 }
1797
1798 pidref_done(pidref);
1799
1800 _cleanup_close_ int mnt_fd = fsmount(fs_fd, /* flags= */ 0, /* mount_attrs= */ 0);
1801 if (mnt_fd < 0)
1802 return log_debug_errno(errno, "Failed to fsmount bpffs: %m");
1803
1804 r = move_mount(mnt_fd, "", AT_FDCWD, mount_entry_path(m), MOVE_MOUNT_F_EMPTY_PATH);
1805 if (r < 0)
1806 return log_debug_errno(errno, "Failed to move bpffs mount to %s: %m", mount_entry_path(m));
1807
1808 return 1;
1809 }
1810
1811 static int follow_symlink(
1812 const char *root_directory,
1813 MountEntry *m) {
1814
1815 _cleanup_free_ char *target = NULL;
1816 int r;
1817
1818 assert(m);
1819
1820 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1821 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1822 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1823 * end and already have a fully normalized name. */
1824
1825 r = chase(mount_entry_path(m), root_directory, CHASE_STEP|CHASE_NONEXISTENT|CHASE_TRIGGER_AUTOFS, &target, NULL);
1826 if (r < 0)
1827 return log_debug_errno(r, "Failed to chase symlinks '%s': %m", mount_entry_path(m));
1828 if (r > 0) /* Reached the end, nothing more to resolve */
1829 return 1;
1830
1831 if (m->n_followed >= CHASE_MAX) /* put a boundary on things */
1832 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1833 "Symlink loop on '%s'.",
1834 mount_entry_path(m));
1835
1836 log_debug("Followed mount entry path symlink %s %s %s.",
1837 mount_entry_path(m), glyph(GLYPH_ARROW_RIGHT), target);
1838
1839 mount_entry_consume_prefix(m, TAKE_PTR(target));
1840
1841 m->n_followed++;
1842
1843 return 0;
1844 }
1845
1846 static int apply_one_mount(
1847 const char *root_directory,
1848 MountEntry *m,
1849 const NamespaceParameters *p) {
1850
1851 _cleanup_free_ char *inaccessible = NULL;
1852 bool rbind = true, make = false;
1853 const char *what;
1854 int r;
1855
1856 /* Return 1 when the mount should be post-processed (remounted r/o, etc.), 0 otherwise. In most
1857 * cases post-processing is the right thing, the typical exception is when the mount is gracefully
1858 * skipped. */
1859
1860 assert(m);
1861 assert(p);
1862
1863 log_debug("Applying namespace mount on %s", mount_entry_path(m));
1864
1865 if (m->mode == MOUNT_BPFFS) {
1866 r = mount_bpffs(m, p->bpffs_pidref, p->bpffs_socket_fd, p->bpffs_errno_pipe);
1867 if (r >= 0 ||
1868 (!ERRNO_IS_NEG_NOT_SUPPORTED(r) && /* old kernel? */
1869 !ERRNO_IS_NEG_PRIVILEGE(r))) /* ubuntu kernel bug? See issue #38225 */
1870 return r;
1871
1872 if (m->ignore) {
1873 log_debug_errno(r, "Failed to mount new bpffs instance, ignoring: %m");
1874 return 0;
1875 }
1876
1877 log_debug_errno(r, "Failed to mount new bpffs instance at %s, will make read-only, ignoring: %m", mount_entry_path(m));
1878 m->mode = MOUNT_READ_ONLY;
1879 m->ignore = true;
1880 }
1881
1882 switch (m->mode) {
1883
1884 case MOUNT_INACCESSIBLE: {
1885 _cleanup_free_ char *runtime_dir = NULL;
1886 struct stat target;
1887
1888 /* First, get rid of everything that is below if there
1889 * is anything... Then, overmount it with an
1890 * inaccessible path. */
1891 (void) umount_recursive(mount_entry_path(m), 0);
1892
1893 if (lstat(mount_entry_path(m), &target) < 0) {
1894 if (errno == ENOENT && m->ignore)
1895 return 0;
1896
1897 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m",
1898 mount_entry_path(m));
1899 }
1900
1901 /* We don't pass the literal runtime scope through here but one based purely on our UID. This
1902 * means that the root user's --user services will use the host's inaccessible inodes rather
1903 * then root's private ones. This is preferable since it means device nodes that are
1904 * overmounted to make them inaccessible will be overmounted with a device node, rather than
1905 * an AF_UNIX socket inode. */
1906 runtime_dir = settle_runtime_dir(geteuid() == 0 ? RUNTIME_SCOPE_SYSTEM : RUNTIME_SCOPE_USER);
1907 if (!runtime_dir)
1908 return log_oom_debug();
1909
1910 r = mode_to_inaccessible_node(runtime_dir, target.st_mode, &inaccessible);
1911 if (r < 0)
1912 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1913 "File type not supported for inaccessible mounts. Note that symlinks are not allowed.");
1914 what = inaccessible;
1915 break;
1916 }
1917
1918 case MOUNT_READ_ONLY:
1919 case MOUNT_READ_WRITE:
1920 case MOUNT_READ_WRITE_IMPLICIT:
1921 case MOUNT_EXEC:
1922 case MOUNT_NOEXEC:
1923 r = path_is_mount_point_full(mount_entry_path(m), root_directory, /* flags= */ 0);
1924 if (r == -ENOENT && m->ignore)
1925 return 0;
1926 if (r < 0)
1927 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m",
1928 mount_entry_path(m));
1929 if (r > 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
1930 * and MS_NOEXEC bits for the mount point if needed. */
1931 return 1;
1932 /* This isn't a mount point yet, let's make it one. */
1933 what = mount_entry_path(m);
1934 break;
1935
1936 case MOUNT_EXTENSION_DIRECTORY: {
1937 _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_id_like = NULL,
1938 *host_os_release_version_id = NULL, *host_os_release_level = NULL,
1939 *extension_name = NULL;
1940 _cleanup_strv_free_ char **extension_release = NULL;
1941 ImageClass class = IMAGE_SYSEXT;
1942
1943 r = path_extract_filename(mount_entry_source(m), &extension_name);
1944 if (r < 0)
1945 return log_debug_errno(r, "Failed to extract extension name from %s: %m", mount_entry_source(m));
1946
1947 r = load_extension_release_pairs(
1948 mount_entry_source(m),
1949 m->filter_class >= 0 ? m->filter_class : IMAGE_SYSEXT,
1950 extension_name,
1951 /* relax_extension_release_check= */ false,
1952 &extension_release);
1953 if (r == -ENOENT) {
1954 if (m->filter_class >= 0)
1955 return 0; /* Nothing to do, wrong class */
1956
1957 r = load_extension_release_pairs(
1958 mount_entry_source(m),
1959 IMAGE_CONFEXT,
1960 extension_name,
1961 /* relax_extension_release_check= */ false,
1962 &extension_release);
1963 if (r >= 0)
1964 class = IMAGE_CONFEXT;
1965 }
1966 if (r == -ENOENT && m->ignore)
1967 return 0;
1968 if (r < 0)
1969 return log_debug_errno(r, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m));
1970
1971 r = parse_os_release(
1972 empty_to_root(root_directory),
1973 "ID", &host_os_release_id,
1974 "ID_LIKE", &host_os_release_id_like,
1975 "VERSION_ID", &host_os_release_version_id,
1976 image_class_info[class].level_env, &host_os_release_level,
1977 NULL);
1978 if (r < 0)
1979 return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
1980 if (isempty(host_os_release_id))
1981 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'ID' field not found or empty in 'os-release' data of OS tree '%s'.", empty_to_root(root_directory));
1982
1983 r = extension_release_validate(
1984 extension_name,
1985 host_os_release_id,
1986 host_os_release_id_like,
1987 host_os_release_version_id,
1988 host_os_release_level,
1989 /* host_extension_scope= */ NULL, /* Leave empty, we need to accept both system and portable */
1990 extension_release,
1991 class);
1992 if (r < 0)
1993 return log_debug_errno(r, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name);
1994 if (r == 0)
1995 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Directory %s extension-release metadata does not match the root's.", extension_name);
1996
1997 _fallthrough_;
1998 }
1999
2000 case MOUNT_BIND:
2001 rbind = false;
2002
2003 _fallthrough_;
2004 case MOUNT_BIND_RECURSIVE: {
2005 _cleanup_free_ char *chased = NULL;
2006
2007 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
2008 * that bind mount source paths are always relative to the host root, hence we pass NULL as
2009 * root directory to chase() here. */
2010
2011 /* When we create implicit mounts, we might need to create the path ourselves as it is on a
2012 * just-created tmpfs, for example. */
2013 if (m->create_source_dir) {
2014 r = mkdir_p(mount_entry_source(m), m->source_dir_mode);
2015 if (r < 0)
2016 return log_debug_errno(r, "Failed to create source directory %s: %m", mount_entry_source(m));
2017
2018 r = label_fix_full(AT_FDCWD, mount_entry_source(m), mount_entry_unprefixed_path(m), /* flags= */ 0);
2019 if (r < 0)
2020 return log_error_errno(r, "Failed to set label of the source directory %s: %m", mount_entry_source(m));
2021 }
2022
2023 r = chase(mount_entry_source(m), NULL, CHASE_TRAIL_SLASH|CHASE_TRIGGER_AUTOFS, &chased, NULL);
2024 if (r < 0) {
2025 if (m->ignore) {
2026 if (r == -ENOENT) {
2027 log_debug_errno(r, "Path '%s' does not exist, ignoring.", mount_entry_source(m));
2028 return 0;
2029 }
2030 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
2031 log_debug_errno(r, "Path '%s' is not accessible, ignoring: %m", mount_entry_source(m));
2032 return 0;
2033 }
2034 }
2035
2036 return log_debug_errno(r, "Failed to follow symlinks on %s: %m", mount_entry_source(m));
2037 }
2038
2039 log_debug("Followed source symlinks %s %s %s.",
2040 mount_entry_source(m), glyph(GLYPH_ARROW_RIGHT), chased);
2041
2042 free_and_replace(m->source_malloc, chased);
2043
2044 what = mount_entry_source(m);
2045 make = true;
2046 break;
2047 }
2048
2049 case MOUNT_EMPTY_DIR:
2050 case MOUNT_PRIVATE_TMPFS:
2051 case MOUNT_TMPFS:
2052 return mount_tmpfs(m);
2053
2054 case MOUNT_PRIVATE_TMP:
2055 what = mount_entry_source(m);
2056 make = true;
2057 break;
2058
2059 case MOUNT_PRIVATE_DEV:
2060 return mount_private_dev(m, p);
2061
2062 case MOUNT_BIND_DEV:
2063 return mount_bind_dev(m);
2064
2065 case MOUNT_PRIVATE_SYSFS:
2066 return mount_private_sysfs(m, p);
2067
2068 case MOUNT_BIND_SYSFS:
2069 return mount_bind_sysfs(m);
2070
2071 case MOUNT_PROCFS:
2072 return mount_procfs(m, p);
2073
2074 case MOUNT_PRIVATE_CGROUP2FS:
2075 return mount_private_cgroup2fs(m, p);
2076
2077 case MOUNT_RUN:
2078 return mount_run(m);
2079
2080 case MOUNT_MQUEUEFS:
2081 return mount_mqueuefs(m);
2082
2083 case MOUNT_IMAGE:
2084 return mount_image(m, NULL, p->mount_image_policy, p->runtime_scope);
2085
2086 case MOUNT_EXTENSION_IMAGE:
2087 return mount_image(m, root_directory, p->extension_image_policy, p->runtime_scope);
2088
2089 case MOUNT_OVERLAY:
2090 return mount_overlay(m);
2091
2092 default:
2093 assert_not_reached();
2094 }
2095
2096 assert(what);
2097
2098 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
2099 if (r < 0) {
2100 bool try_again = false;
2101
2102 if (r == -ENOENT && make) {
2103 int q;
2104
2105 /* Hmm, either the source or the destination are missing. Let's see if we can create
2106 the destination, then try again. */
2107
2108 q = mkdir_parents(mount_entry_path(m), 0755);
2109 if (q < 0 && q != -EEXIST)
2110 // FIXME: this shouldn't be logged at LOG_WARNING, but be bubbled up, and logged there to avoid duplicate logging
2111 log_warning_errno(q, "Failed to create parent directories of destination mount point node '%s', ignoring: %m",
2112 mount_entry_path(m));
2113 else {
2114 q = make_mount_point_inode_from_path(what, mount_entry_path(m), 0755);
2115 if (q < 0 && q != -EEXIST)
2116 // FIXME: this shouldn't be logged at LOG_WARNING, but be bubbled up, and logged there to avoid duplicate logging
2117 log_warning_errno(q, "Failed to create destination mount point node '%s', ignoring: %m",
2118 mount_entry_path(m));
2119 else
2120 try_again = true;
2121 }
2122 }
2123
2124 if (try_again)
2125 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
2126 if (r < 0)
2127 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
2128 }
2129
2130 log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
2131
2132 /* Take care of id-mapped mounts */
2133 if (m->idmapped && uid_is_valid(m->idmap_uid) && gid_is_valid(m->idmap_gid)) {
2134 _cleanup_close_ int userns_fd = -EBADF;
2135 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
2136
2137 log_debug("Setting an id-mapped mount on %s", mount_entry_path(m));
2138
2139 /* Do mapping from nobody (in setup_exec_directory()) -> this uid */
2140 if (strextendf(&uid_map, UID_FMT " " UID_FMT " 1\n", UID_NOBODY, m->idmap_uid) < 0)
2141 return log_oom();
2142
2143 /* Consider StateDirectory=xxx aaa xxx:aaa/222
2144 * To allow for later symlink creation (by root) in create_symlinks_from_tuples(), map root as well. */
2145 if (m->idmap_uid != 0)
2146 if (!strextend(&uid_map, "0 0 1\n"))
2147 return log_oom();
2148
2149 if (strextendf(&gid_map, GID_FMT " " GID_FMT " 1\n", GID_NOBODY, m->idmap_gid) < 0)
2150 return log_oom();
2151
2152 if (m->idmap_gid != 0)
2153 if (!strextend(&gid_map, "0 0 1\n"))
2154 return log_oom();
2155
2156 userns_fd = userns_acquire(uid_map, gid_map, /* setgroups_deny= */ true);
2157 if (userns_fd < 0)
2158 return log_error_errno(userns_fd, "Failed to allocate user namespace: %m");
2159
2160 /* Drop SUID, add NOEXEC for the mount to avoid root exploits */
2161 r = remount_idmap_fd(STRV_MAKE(mount_entry_path(m)), userns_fd, MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC | MOUNT_ATTR_NODEV);
2162 if (r < 0)
2163 return log_error_errno(r, "Failed to create an id-mapped mount: %m");
2164
2165 log_debug("ID-mapped mount created successfully for %s from " UID_FMT " to " UID_FMT "", mount_entry_path(m), UID_NOBODY, m->idmap_uid);
2166 }
2167
2168 return 1;
2169 }
2170
2171 static bool should_propagate_to_submounts(const MountEntry *m) {
2172 assert(m);
2173 return !IN_SET(m->mode, MOUNT_EMPTY_DIR, MOUNT_TMPFS, MOUNT_PRIVATE_TMPFS);
2174 }
2175
2176 static int make_read_only(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
2177 unsigned long new_flags = 0, flags_mask = 0;
2178 bool submounts;
2179 int r;
2180
2181 assert(m);
2182 assert(proc_self_mountinfo);
2183
2184 if (m->state != MOUNT_APPLIED)
2185 return 0;
2186
2187 if (mount_entry_read_only(m) || m->mode == MOUNT_PRIVATE_DEV) {
2188 new_flags |= MS_RDONLY;
2189 flags_mask |= MS_RDONLY;
2190 }
2191
2192 if (m->nosuid) {
2193 new_flags |= MS_NOSUID;
2194 flags_mask |= MS_NOSUID;
2195 }
2196
2197 if (flags_mask == 0) /* No Change? */
2198 return 0;
2199
2200 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
2201 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
2202 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
2203 * and running Linux <= 4.17. */
2204 submounts = mount_entry_read_only(m) && should_propagate_to_submounts(m);
2205 if (submounts)
2206 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
2207 else
2208 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
2209
2210 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
2211 * read-only already stays this way. This improves compatibility with container managers, where we
2212 * won't attempt to undo read-only mounts already applied. */
2213
2214 if (r == -ENOENT && m->ignore)
2215 return 0;
2216 if (r < 0)
2217 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
2218 submounts ? " and its submounts" : "");
2219 return 0;
2220 }
2221
2222 static int make_noexec(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
2223 unsigned long new_flags = 0, flags_mask = 0;
2224 bool submounts;
2225 int r;
2226
2227 assert(m);
2228 assert(proc_self_mountinfo);
2229
2230 if (m->state != MOUNT_APPLIED)
2231 return 0;
2232
2233 if (mount_entry_noexec(m)) {
2234 new_flags |= MS_NOEXEC;
2235 flags_mask |= MS_NOEXEC;
2236 } else if (mount_entry_exec(m)) {
2237 new_flags &= ~MS_NOEXEC;
2238 flags_mask |= MS_NOEXEC;
2239 }
2240
2241 if (flags_mask == 0) /* No Change? */
2242 return 0;
2243
2244 submounts = should_propagate_to_submounts(m);
2245 if (submounts)
2246 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
2247 else
2248 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
2249
2250 if (r == -ENOENT && m->ignore)
2251 return 0;
2252 if (r < 0)
2253 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
2254 submounts ? " and its submounts" : "");
2255 return 0;
2256 }
2257
2258 static int make_nosuid(const MountEntry *m, FILE *proc_self_mountinfo) {
2259 bool submounts;
2260 int r;
2261
2262 assert(m);
2263 assert(proc_self_mountinfo);
2264
2265 if (m->state != MOUNT_APPLIED)
2266 return 0;
2267
2268 submounts = should_propagate_to_submounts(m);
2269 if (submounts)
2270 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, NULL, proc_self_mountinfo);
2271 else
2272 r = bind_remount_one_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, proc_self_mountinfo);
2273 if (r == -ENOENT && m->ignore)
2274 return 0;
2275 if (r < 0)
2276 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
2277 submounts ? " and its submounts" : "");
2278 return 0;
2279 }
2280
2281 static bool namespace_parameters_mount_apivfs(const NamespaceParameters *p) {
2282 assert(p);
2283
2284 /*
2285 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
2286 * since to protect the API VFS mounts, they need to be around in the
2287 * first place...
2288 */
2289
2290 return p->mount_apivfs ||
2291 p->protect_control_groups != PROTECT_CONTROL_GROUPS_NO ||
2292 p->protect_kernel_tunables ||
2293 p->protect_proc != PROTECT_PROC_DEFAULT ||
2294 p->proc_subset != PROC_SUBSET_ALL ||
2295 p->private_bpf != PRIVATE_BPF_NO ||
2296 p->private_pids != PRIVATE_PIDS_NO;
2297 }
2298
2299 /* Walk all mount entries and dropping any unused mounts. This affects all
2300 * mounts:
2301 * - that are implicitly protected by a path that has been rendered inaccessible
2302 * - whose immediate parent requests the same protection mode as the mount itself
2303 * - that are outside of the relevant root directory
2304 * - which are duplicates
2305 */
2306 static void sort_and_drop_unused_mounts(MountList *ml, const char *root_directory) {
2307 assert(ml);
2308 assert(root_directory);
2309
2310 assert(ml->mounts || ml->n_mounts == 0);
2311
2312 typesafe_qsort(ml->mounts, ml->n_mounts, mount_path_compare);
2313
2314 drop_duplicates(ml);
2315 drop_outside_root(ml, root_directory);
2316 drop_inaccessible(ml);
2317 drop_nop(ml);
2318 }
2319
2320 static int create_symlinks_from_tuples(const char *root, char **strv_symlinks) {
2321 int r;
2322
2323 STRV_FOREACH_PAIR(src, dst, strv_symlinks) {
2324 _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
2325
2326 src_abs = path_join(root, *src);
2327 dst_abs = path_join(root, *dst);
2328 if (!src_abs || !dst_abs)
2329 return -ENOMEM;
2330
2331 r = mkdir_parents_label(dst_abs, 0755);
2332 if (r < 0)
2333 return log_debug_errno(
2334 r,
2335 "Failed to create parent directory for symlink '%s': %m",
2336 dst_abs);
2337
2338 r = symlink_idempotent(src_abs, dst_abs, true);
2339 if (r < 0)
2340 return log_debug_errno(
2341 r,
2342 "Failed to create symlink from '%s' to '%s': %m",
2343 src_abs,
2344 dst_abs);
2345 }
2346
2347 return 0;
2348 }
2349
2350 static void mount_entry_path_debug_string(const char *root, MountEntry *m, char **ret_path) {
2351 assert(m);
2352
2353 /* Create a string suitable for debugging logs, stripping for example the local working directory.
2354 * For example, with a BindPaths=/var/bar that does not exist on the host:
2355 *
2356 * Before:
2357 * foo.service: Failed to set up mount namespacing: /run/systemd/unit-root/var/bar: No such file or directory
2358 * After:
2359 * foo.service: Failed to set up mount namespacing: /var/bar: No such file or directory
2360 *
2361 * Note that this is an error path, so no OOM check is done on purpose. */
2362
2363 if (!ret_path)
2364 return;
2365
2366 if (!mount_entry_path(m)) {
2367 *ret_path = NULL;
2368 return;
2369 }
2370
2371 if (root) {
2372 const char *e = startswith(mount_entry_path(m), root);
2373 if (e) {
2374 *ret_path = strdup(e);
2375 return;
2376 }
2377 }
2378
2379 *ret_path = strdup(mount_entry_path(m));
2380 return;
2381 }
2382
2383 static int apply_mounts(
2384 MountList *ml,
2385 const char *root,
2386 const NamespaceParameters *p,
2387 char **reterr_path) {
2388
2389 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
2390 _cleanup_free_ char **deny_list = NULL;
2391 int r;
2392
2393 assert(ml);
2394 assert(root);
2395 assert(p);
2396
2397 if (ml->n_mounts == 0) /* Shortcut: nothing to do */
2398 return 0;
2399
2400 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
2401 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
2402 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
2403 if (!proc_self_mountinfo) {
2404 r = -errno;
2405
2406 if (reterr_path)
2407 *reterr_path = strdup("/proc/self/mountinfo");
2408
2409 return log_debug_errno(r, "Failed to open %s: %m", "/proc/self/mountinfo");
2410 }
2411
2412 /* First round, establish all mounts we need */
2413 for (;;) {
2414 bool again = false;
2415
2416 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
2417
2418 if (m->state != MOUNT_PENDING)
2419 continue;
2420
2421 /* ExtensionImages/Directories are first opened in the propagate directory, not in
2422 * the root_directory. A private (invisible to the guest) tmpfs instance is mounted
2423 * on /run/[user/xyz/]systemd/unit-private-tmp as the storage backend of private
2424 * /tmp and /var/tmp. */
2425 r = follow_symlink(!IN_SET(m->mode, MOUNT_EXTENSION_IMAGE, MOUNT_EXTENSION_DIRECTORY, MOUNT_PRIVATE_TMPFS) ? root : NULL, m);
2426 if (r < 0) {
2427 mount_entry_path_debug_string(root, m, reterr_path);
2428 return r;
2429 }
2430 if (r == 0) {
2431 /* We hit a symlinked mount point. The entry got rewritten and might
2432 * point to a very different place now. Let's normalize the changed
2433 * list, and start from the beginning. After all to mount the entry
2434 * at the new location we might need some other mounts first */
2435 again = true;
2436 break;
2437 }
2438
2439 /* Returns 1 if the mount should be post-processed, 0 otherwise */
2440 r = apply_one_mount(root, m, p);
2441 if (r < 0) {
2442 mount_entry_path_debug_string(root, m, reterr_path);
2443 return r;
2444 }
2445 m->state = r == 0 ? MOUNT_SKIPPED : MOUNT_APPLIED;
2446 }
2447
2448 if (!again)
2449 break;
2450
2451 sort_and_drop_unused_mounts(ml, root);
2452 }
2453
2454 /* Now that all filesystems have been set up, but before the
2455 * read-only switches are flipped, create the exec dirs and other symlinks.
2456 * Note that when /var/lib is not empty/tmpfs, these symlinks will already
2457 * exist, which means this will be a no-op. */
2458 r = create_symlinks_from_tuples(root, p->symlinks);
2459 if (r < 0)
2460 return log_debug_errno(r, "Failed to set up symlinks inside mount namespace: %m");
2461
2462 /* Create a deny list we can pass to bind_mount_recursive() */
2463 deny_list = new(char*, ml->n_mounts+1);
2464 if (!deny_list)
2465 return -ENOMEM;
2466 for (size_t j = 0; j < ml->n_mounts; j++)
2467 deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
2468 deny_list[ml->n_mounts] = NULL;
2469
2470 /* Second round, flip the ro bits if necessary. */
2471 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
2472 r = make_read_only(m, deny_list, proc_self_mountinfo);
2473 if (r < 0) {
2474 mount_entry_path_debug_string(root, m, reterr_path);
2475 return r;
2476 }
2477 }
2478
2479 /* Third round, flip the noexec bits with a simplified deny list. */
2480 for (size_t j = 0; j < ml->n_mounts; j++)
2481 if (IN_SET((ml->mounts+j)->mode, MOUNT_EXEC, MOUNT_NOEXEC))
2482 deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
2483 deny_list[ml->n_mounts] = NULL;
2484
2485 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
2486 r = make_noexec(m, deny_list, proc_self_mountinfo);
2487 if (r < 0) {
2488 mount_entry_path_debug_string(root, m, reterr_path);
2489 return r;
2490 }
2491 }
2492
2493 /* Fourth round, flip the nosuid bits without a deny list. */
2494 if (p->mount_nosuid)
2495 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
2496 r = make_nosuid(m, proc_self_mountinfo);
2497 if (r < 0) {
2498 mount_entry_path_debug_string(root, m, reterr_path);
2499 return r;
2500 }
2501 }
2502
2503 return 1;
2504 }
2505
2506 static bool root_read_only(
2507 char **read_only_paths,
2508 ProtectSystem protect_system) {
2509
2510 /* Determine whether the root directory is going to be read-only given the configured settings. */
2511
2512 if (protect_system == PROTECT_SYSTEM_STRICT)
2513 return true;
2514
2515 if (prefixed_path_strv_contains(read_only_paths, "/"))
2516 return true;
2517
2518 return false;
2519 }
2520
2521 static bool home_read_only(
2522 char * const *read_only_paths,
2523 char * const *inaccessible_paths,
2524 char * const *empty_directories,
2525 const BindMount *bind_mounts,
2526 size_t n_bind_mounts,
2527 const TemporaryFileSystem *temporary_filesystems,
2528 size_t n_temporary_filesystems,
2529 ProtectHome protect_home) {
2530
2531 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
2532 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
2533 * settings. */
2534
2535 if (protect_home != PROTECT_HOME_NO)
2536 return true;
2537
2538 if (prefixed_path_strv_contains(read_only_paths, "/home") ||
2539 prefixed_path_strv_contains(inaccessible_paths, "/home") ||
2540 prefixed_path_strv_contains(empty_directories, "/home"))
2541 return true;
2542
2543 FOREACH_ARRAY(i, temporary_filesystems, n_temporary_filesystems)
2544 if (path_equal(i->path, "/home"))
2545 return true;
2546
2547 /* If /home is overmounted with some dir from the host it's not writable. */
2548 FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
2549 if (path_equal(i->destination, "/home"))
2550 return true;
2551
2552 return false;
2553 }
2554
2555 static bool namespace_read_only(const NamespaceParameters *p) {
2556 assert(p);
2557
2558 return root_read_only(p->read_only_paths,
2559 p->protect_system) &&
2560 home_read_only(p->read_only_paths, p->inaccessible_paths, p->empty_directories,
2561 p->bind_mounts, p->n_bind_mounts, p->temporary_filesystems, p->n_temporary_filesystems,
2562 p->protect_home) &&
2563 strv_isempty(p->read_write_paths);
2564 }
2565
2566 int setup_namespace(const NamespaceParameters *p, char **reterr_path) {
2567
2568 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2569 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
2570 _cleanup_strv_free_ char **hierarchies = NULL;
2571 _cleanup_(mount_list_done) MountList ml = {};
2572 _cleanup_close_ int userns_fd = -EBADF;
2573 bool require_prefix = false;
2574 const char *root;
2575 DissectImageFlags dissect_image_flags =
2576 DISSECT_IMAGE_GENERIC_ROOT |
2577 DISSECT_IMAGE_REQUIRE_ROOT |
2578 DISSECT_IMAGE_DISCARD_ON_LOOP |
2579 DISSECT_IMAGE_RELAX_VAR_CHECK |
2580 DISSECT_IMAGE_FSCK |
2581 DISSECT_IMAGE_USR_NO_ROOT |
2582 DISSECT_IMAGE_GROWFS |
2583 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
2584 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
2585 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY |
2586 DISSECT_IMAGE_VERITY_SHARE;
2587 MStackFlags mstack_flags = 0;
2588 int r;
2589
2590 assert(p);
2591
2592 /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
2593 * we configure take effect */
2594 BLOCK_WITH_UMASK(0000);
2595
2596 bool setup_propagate = !isempty(p->propagate_dir) && !isempty(p->incoming_dir);
2597 unsigned long mount_propagation_flag = p->mount_propagation_flag != 0 ? p->mount_propagation_flag : MS_SHARED;
2598
2599 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
2600 bool ro = namespace_read_only(p);
2601 if (ro) {
2602 dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
2603 mstack_flags |= MSTACK_RDONLY;
2604 }
2605
2606 _cleanup_close_ int _root_mount_fd = -EBADF;
2607 int root_mount_fd = -EBADF;
2608 if (pinned_resource_is_set(p->rootfs)) {
2609 if (p->rootfs->directory_fd >= 0) {
2610
2611 /* In "managed" mode we need to map from foreign UID/GID space, hence go via mountfsd */
2612 if (p->private_users == PRIVATE_USERS_MANAGED) {
2613 userns_fd = namespace_open_by_type(NAMESPACE_USER);
2614 if (userns_fd < 0)
2615 return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
2616
2617 r = mountfsd_mount_directory_fd(
2618 p->mountfsd_link,
2619 p->rootfs->directory_fd,
2620 userns_fd,
2621 dissect_image_flags,
2622 &_root_mount_fd);
2623 if (r < 0)
2624 return r;
2625
2626 root_mount_fd = _root_mount_fd;
2627 }
2628
2629 /* Try to to clone the directory mount if we have privs to, so that we can apply the
2630 * MS_SLAVE propagation settings right-away. */
2631 if (root_mount_fd < 0) {
2632 _root_mount_fd = open_tree_attr_with_fallback(
2633 p->rootfs->directory_fd,
2634 "",
2635 OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH|AT_RECURSIVE,
2636 &(struct mount_attr) {
2637 /* We just remounted / as slave, but that didn't affect the detached
2638 * mount that we just mounted, so remount that one as slave recursive
2639 * as well now. */
2640 .propagation = MS_SLAVE,
2641 });
2642 if (_root_mount_fd < 0 && !ERRNO_IS_NEG_PRIVILEGE(_root_mount_fd) && _root_mount_fd != -EINVAL)
2643 return log_debug_errno(_root_mount_fd, "Failed to clone specified directory: %m");
2644
2645 root_mount_fd = _root_mount_fd;
2646 }
2647 /* If we have only a root fd (and we couldn't make it ours), and we have no path,
2648 * then try to go on with the literal fd */
2649 if (root_mount_fd < 0 && !p->rootfs->directory)
2650 root_mount_fd = p->rootfs->directory_fd;
2651 }
2652
2653 if (p->rootfs->image_fd >= 0) {
2654 SET_FLAG(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE, p->verity && p->verity->data_path);
2655
2656 if (p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2657 /* In system mode we mount directly */
2658
2659 /* First check if we have a verity device already open and with a fstype pinned by policy. If it
2660 * cannot be found, then fallback to the slow path (full dissect). */
2661 r = dissected_image_new_from_existing_verity(
2662 p->rootfs->image,
2663 p->verity,
2664 p->root_image_options,
2665 p->root_image_policy,
2666 /* image_filter= */ NULL,
2667 p->runtime_scope,
2668 dissect_image_flags,
2669 &dissected_image);
2670 if (r < 0 && !ERRNO_IS_NEG_DEVICE_ABSENT(r) && r != -ENOPKG)
2671 return r;
2672 if (r >= 0)
2673 log_debug("Reusing pre-existing verity-protected root image %s", p->rootfs->image);
2674 else {
2675 r = loop_device_make(
2676 p->rootfs->image_fd,
2677 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : -1 /* < 0 means take access mode from fd */,
2678 /* offset= */ 0,
2679 /* size= */ UINT64_MAX,
2680 /* sector_size= */ UINT32_MAX,
2681 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
2682 LOCK_SH,
2683 &loop_device);
2684 if (r < 0)
2685 return log_debug_errno(r, "Failed to create loop device for root image: %m");
2686
2687 r = dissect_loop_device(
2688 loop_device,
2689 p->verity,
2690 p->root_image_options,
2691 p->root_image_policy,
2692 /* image_filter= */ NULL,
2693 dissect_image_flags,
2694 &dissected_image);
2695 if (r < 0)
2696 return log_debug_errno(r, "Failed to dissect image: %m");
2697
2698 r = dissected_image_load_verity_sig_partition(
2699 dissected_image,
2700 loop_device->fd,
2701 p->verity);
2702 if (r < 0)
2703 return r;
2704
2705 r = dissected_image_guess_verity_roothash(
2706 dissected_image,
2707 p->verity);
2708 if (r < 0)
2709 return r;
2710
2711 r = dissected_image_decrypt(
2712 dissected_image,
2713 /* root= */ NULL,
2714 /* passphrase= */ NULL,
2715 p->verity,
2716 p->root_image_policy,
2717 dissect_image_flags);
2718 if (r < 0)
2719 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
2720 }
2721 } else {
2722 userns_fd = namespace_open_by_type(NAMESPACE_USER);
2723 if (userns_fd < 0)
2724 return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
2725
2726 r = mountfsd_mount_image_fd(
2727 p->mountfsd_link,
2728 p->rootfs->image_fd,
2729 userns_fd,
2730 p->root_image_options,
2731 p->root_image_policy,
2732 p->verity,
2733 dissect_image_flags,
2734 &dissected_image);
2735 if (r < 0)
2736 return r;
2737 }
2738 }
2739
2740 if (p->rootfs->mstack_loaded) {
2741 if (p->runtime_scope != RUNTIME_SCOPE_SYSTEM) {
2742 userns_fd = namespace_open_by_type(NAMESPACE_USER);
2743 if (userns_fd < 0)
2744 return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
2745 }
2746
2747 r = mstack_open_images(
2748 p->rootfs->mstack_loaded,
2749 p->mountfsd_link,
2750 userns_fd,
2751 p->root_image_policy,
2752 /* image_filter= */ NULL,
2753 mstack_flags);
2754 if (r < 0)
2755 return r;
2756 }
2757 }
2758
2759 if (p->rootfs && p->rootfs->directory)
2760 root = p->rootfs->directory;
2761 else {
2762 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
2763 * when running tests (test-execute), it might not have been created yet so let's make sure
2764 * we create it if it doesn't already exist. */
2765 (void) mkdir_p_label("/run/systemd", 0755);
2766
2767 /* Always create the mount namespace in a temporary directory, instead of operating directly
2768 * in the root. The temporary directory prevents any mounts from being potentially obscured
2769 * my other mounts we already applied. We use the same mount point for all images, which is
2770 * safe, since they all live in their own namespaces after all, and hence won't see each
2771 * other. (Note: this directory is also created by PID 1 early on, we create it here for
2772 * similar reasons as /run/systemd/ first.) */
2773 root = "/run/systemd/mount-rootfs";
2774 (void) mkdir_label(root, 0555);
2775
2776 require_prefix = true;
2777 }
2778
2779 if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories)) {
2780 /* Hierarchy population needs to be done for sysext and confext extension images */
2781 r = parse_env_extension_hierarchies(&hierarchies, "SYSTEMD_SYSEXT_AND_CONFEXT_HIERARCHIES");
2782 if (r < 0)
2783 return r;
2784 }
2785
2786 r = append_access_mounts(&ml, p->read_write_paths, MOUNT_READ_WRITE, require_prefix);
2787 if (r < 0)
2788 return r;
2789
2790 r = append_access_mounts(&ml, p->read_only_paths, MOUNT_READ_ONLY, require_prefix);
2791 if (r < 0)
2792 return r;
2793
2794 r = append_access_mounts(&ml, p->inaccessible_paths, MOUNT_INACCESSIBLE, require_prefix);
2795 if (r < 0)
2796 return r;
2797
2798 r = append_access_mounts(&ml, p->exec_paths, MOUNT_EXEC, require_prefix);
2799 if (r < 0)
2800 return r;
2801
2802 r = append_access_mounts(&ml, p->no_exec_paths, MOUNT_NOEXEC, require_prefix);
2803 if (r < 0)
2804 return r;
2805
2806 r = append_empty_dir_mounts(&ml, p->empty_directories);
2807 if (r < 0)
2808 return r;
2809
2810 r = append_bind_mounts(&ml, p->bind_mounts, p->n_bind_mounts);
2811 if (r < 0)
2812 return r;
2813
2814 r = append_tmpfs_mounts(&ml, p->temporary_filesystems, p->n_temporary_filesystems);
2815 if (r < 0)
2816 return r;
2817
2818 r = append_private_tmp(&ml, p);
2819 if (r < 0)
2820 return r;
2821
2822 r = append_mount_images(&ml, p->mount_images, p->n_mount_images);
2823 if (r < 0)
2824 return r;
2825
2826 r = append_extensions(&ml, root, p->private_namespace_dir, hierarchies, p->extension_images, p->n_extension_images, p->extension_directories);
2827 if (r < 0)
2828 return r;
2829
2830 if (p->private_dev) {
2831 MountEntry *me = mount_list_extend(&ml);
2832 if (!me)
2833 return log_oom_debug();
2834
2835 *me = (MountEntry) {
2836 .path_const = "/dev",
2837 .mode = MOUNT_PRIVATE_DEV,
2838 .flags = DEV_MOUNT_OPTIONS,
2839 };
2840 }
2841
2842 /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the protective
2843 mounts to non-pid /proc paths would fail. But the pid only option may have failed gracefully, so
2844 let's try the mounts but it's not fatal if they don't succeed. */
2845 bool ignore_protect_proc = p->ignore_protect_paths || p->proc_subset == PROC_SUBSET_PID;
2846 if (p->protect_kernel_tunables) {
2847 r = append_static_mounts(&ml,
2848 protect_kernel_tunables_proc_table,
2849 ELEMENTSOF(protect_kernel_tunables_proc_table),
2850 ignore_protect_proc);
2851 if (r < 0)
2852 return r;
2853
2854 r = append_static_mounts(&ml,
2855 protect_kernel_tunables_sys_table,
2856 ELEMENTSOF(protect_kernel_tunables_sys_table),
2857 p->ignore_protect_paths);
2858 if (r < 0)
2859 return r;
2860 }
2861
2862 if (p->protect_kernel_modules) {
2863 r = append_static_mounts(&ml,
2864 protect_kernel_modules_table,
2865 ELEMENTSOF(protect_kernel_modules_table),
2866 p->ignore_protect_paths);
2867 if (r < 0)
2868 return r;
2869 }
2870
2871 if (p->protect_kernel_logs) {
2872 r = append_static_mounts(&ml,
2873 protect_kernel_logs_proc_table,
2874 ELEMENTSOF(protect_kernel_logs_proc_table),
2875 ignore_protect_proc);
2876 if (r < 0)
2877 return r;
2878
2879 r = append_static_mounts(&ml,
2880 protect_kernel_logs_dev_table,
2881 ELEMENTSOF(protect_kernel_logs_dev_table),
2882 p->ignore_protect_paths);
2883 if (r < 0)
2884 return r;
2885 }
2886
2887 r = append_protect_control_groups(&ml, p->protect_control_groups, false);
2888 if (r < 0)
2889 return r;
2890
2891 r = append_protect_home(&ml, p->protect_home, p->ignore_protect_paths);
2892 if (r < 0)
2893 return r;
2894
2895 r = append_protect_system(&ml, p->protect_system, false);
2896 if (r < 0)
2897 return r;
2898
2899 r = append_private_bpf(&ml, p->private_bpf, p->protect_kernel_tunables, /* ignore_protect= */ false, p);
2900 if (r < 0)
2901 return r;
2902
2903 if (namespace_parameters_mount_apivfs(p)) {
2904 r = append_static_mounts(&ml,
2905 apivfs_table,
2906 ELEMENTSOF(apivfs_table),
2907 p->ignore_protect_paths);
2908 if (r < 0)
2909 return r;
2910 }
2911
2912 /* Only mount /proc/sys/kernel/hostname and domainname read-only if ProtectHostname=yes. Otherwise,
2913 * ProtectHostname=no allows changing hostname for the host, and ProtectHostname=private allows
2914 * changing the hostname in the unit's UTS namespace. Note, if proc is mounted with subset=pid then
2915 * neither of the two paths will exist, i.e. they are implicitly protected by the mount option. */
2916 if (p->protect_hostname == PROTECT_HOSTNAME_YES) {
2917 r = append_static_mounts(
2918 &ml,
2919 protect_hostname_yes_table,
2920 ELEMENTSOF(protect_hostname_yes_table),
2921 ignore_protect_proc);
2922 if (r < 0)
2923 return r;
2924 }
2925
2926 if (p->private_network) {
2927 MountEntry *me = mount_list_extend(&ml);
2928 if (!me)
2929 return log_oom_debug();
2930
2931 *me = (MountEntry) {
2932 .path_const = "/sys",
2933 .mode = MOUNT_PRIVATE_SYSFS,
2934 };
2935 }
2936
2937 if (p->private_ipc) {
2938 MountEntry *me = mount_list_extend(&ml);
2939 if (!me)
2940 return log_oom_debug();
2941
2942 *me = (MountEntry) {
2943 .path_const = "/dev/mqueue",
2944 .mode = MOUNT_MQUEUEFS,
2945 .flags = MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
2946 };
2947 }
2948
2949 if (p->creds_path) {
2950 /* If our service has a credentials store configured, then bind that one in, but hide
2951 * everything else. */
2952
2953 MountEntry *me = mount_list_extend(&ml);
2954 if (!me)
2955 return log_oom_debug();
2956
2957 *me = (MountEntry) {
2958 .mode = MOUNT_TMPFS,
2959 .read_only = true,
2960 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
2961 .flags = MS_NODEV|MS_STRICTATIME|MS_NOSUID|MS_NOEXEC,
2962 };
2963
2964 if (p->runtime_scope == RUNTIME_SCOPE_SYSTEM)
2965 me->path_const = "/run/credentials";
2966 else {
2967 r = path_extract_directory(p->creds_path, &me->path_malloc);
2968 if (r < 0)
2969 return log_debug_errno(r, "Failed to extract parent directory from '%s': %m",
2970 p->creds_path);
2971 }
2972
2973 me = mount_list_extend(&ml);
2974 if (!me)
2975 return log_oom_debug();
2976
2977 *me = (MountEntry) {
2978 .path_const = p->creds_path,
2979 .mode = MOUNT_BIND,
2980 .read_only = true,
2981 .source_const = p->creds_path,
2982 };
2983 }
2984
2985 if (!p->creds_path || p->runtime_scope != RUNTIME_SCOPE_SYSTEM) {
2986 /* If our service has no credentials store configured, or we're running in user scope, then
2987 * make the system credentials tree inaccessible wholesale. */
2988
2989 MountEntry *me = mount_list_extend(&ml);
2990 if (!me)
2991 return log_oom_debug();
2992
2993 *me = (MountEntry) {
2994 .path_const = "/run/credentials",
2995 .mode = MOUNT_INACCESSIBLE,
2996 .ignore = true,
2997 };
2998 }
2999
3000 if (p->log_namespace) {
3001 _cleanup_free_ char *q = NULL;
3002
3003 q = strjoin("/run/systemd/journal.", p->log_namespace);
3004 if (!q)
3005 return log_oom_debug();
3006
3007 MountEntry *me = mount_list_extend(&ml);
3008 if (!me)
3009 return log_oom_debug();
3010
3011 *me = (MountEntry) {
3012 .path_const = "/run/systemd/journal",
3013 .mode = MOUNT_BIND_RECURSIVE,
3014 .read_only = true,
3015 .source_malloc = TAKE_PTR(q),
3016 };
3017
3018 } else if (p->bind_log_sockets) {
3019 r = append_bind_mounts(&ml, bind_log_sockets_table, ELEMENTSOF(bind_log_sockets_table));
3020 if (r < 0)
3021 return r;
3022 }
3023
3024 /* Will be used to add bind mounts at runtime */
3025 if (setup_propagate) {
3026 MountEntry *me = mount_list_extend(&ml);
3027 if (!me)
3028 return log_oom_debug();
3029
3030 *me = (MountEntry) {
3031 .source_const = p->propagate_dir,
3032 .path_const = p->incoming_dir,
3033 .mode = MOUNT_BIND,
3034 .read_only = true,
3035 };
3036 }
3037
3038 if (p->notify_socket_path) {
3039 MountEntry *me = mount_list_extend(&ml);
3040 if (!me)
3041 return log_oom_debug();
3042
3043 *me = (MountEntry) {
3044 .path_const = p->notify_socket_path,
3045 .source_const = p->host_notify_socket,
3046 .mode = MOUNT_BIND,
3047 .read_only = true,
3048 };
3049 }
3050
3051 if (p->host_os_release_stage) {
3052 MountEntry *me = mount_list_extend(&ml);
3053 if (!me)
3054 return log_oom_debug();
3055
3056 *me = (MountEntry) {
3057 .path_const = "/run/host/.os-release-stage/",
3058 .source_const = p->host_os_release_stage,
3059 .mode = MOUNT_BIND,
3060 .read_only = true,
3061 .ignore = true, /* Live copy, don't hard-fail if it goes missing */
3062 };
3063 }
3064
3065 /* Prepend the root directory where that's necessary */
3066 r = prefix_where_needed(&ml, root);
3067 if (r < 0)
3068 return r;
3069
3070 sort_and_drop_unused_mounts(&ml, root);
3071
3072 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
3073
3074 if (unshare(CLONE_NEWNS) < 0) {
3075 r = log_debug_errno(errno, "Failed to unshare the mount namespace: %m");
3076
3077 if (ERRNO_IS_PRIVILEGE(r) ||
3078 ERRNO_IS_NOT_SUPPORTED(r))
3079 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
3080 * in place that doesn't allow us to create namespaces (or a missing cap), then
3081 * propagate a recognizable error back, which the caller can use to detect this case
3082 * (and only this) and optionally continue without namespacing applied. */
3083 return -ENOANO;
3084
3085 return r;
3086 }
3087
3088 /* Create the source directory to allow runtime propagation of mounts */
3089 if (setup_propagate)
3090 (void) mkdir_p(p->propagate_dir, 0600);
3091
3092 if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories)) {
3093 /* ExtensionImages/Directories mountpoint directories will be created while parsing the
3094 * mounts to create, so have the parent ready */
3095 char *extension_dir = strjoina(p->private_namespace_dir, "/unit-extensions");
3096 (void) mkdir_p(extension_dir, 0600);
3097 }
3098
3099 /* Remount / as SLAVE so that nothing now mounted in the namespace
3100 * shows up in the parent */
3101 r = mount_nofollow_verbose(LOG_DEBUG, /* what= */ NULL, "/", /* fstype= */ NULL, MS_SLAVE|MS_REC, /* options= */ NULL);
3102 if (r < 0)
3103 return r;
3104
3105 if (root_mount_fd >= 0) {
3106 /* If we have root_mount_fd we have a ready-to-use detached mount. Attach it. */
3107
3108 if (move_mount(root_mount_fd, "", AT_FDCWD, root, MOVE_MOUNT_F_EMPTY_PATH) < 0)
3109 return log_debug_errno(errno, "Failed to move detached mount to '%s': %m", root);
3110
3111 r = mount_nofollow_verbose(LOG_DEBUG, /* what= */ NULL, root, /* fstype= */ NULL, MS_SLAVE|MS_REC, /* options= */ NULL);
3112 if (r < 0)
3113 return r;
3114
3115 } else if (p->rootfs && p->rootfs->directory) {
3116
3117 /* If we do not have root_mount_fd, but a directory was specified, then we can use it directly. */
3118
3119 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
3120 r = path_is_mount_point_full(root, /* root = */ NULL, AT_SYMLINK_FOLLOW);
3121 if (r < 0)
3122 return log_debug_errno(r, "Failed to detect that %s is a mount point or not: %m", root);
3123 if (r == 0) {
3124 r = mount_nofollow_verbose(LOG_DEBUG, root, root, /* fstype= */ NULL, MS_BIND|MS_REC, /* options= */ NULL);
3125 if (r < 0)
3126 return r;
3127 }
3128
3129 } else if (dissected_image) {
3130
3131 /* A root image is specified, mount it to the right place */
3132 r = dissected_image_mount(
3133 dissected_image,
3134 root,
3135 /* uid_shift= */ UID_INVALID,
3136 /* uid_range= */ UID_INVALID,
3137 userns_fd,
3138 dissect_image_flags);
3139 if (r < 0)
3140 return log_debug_errno(r, "Failed to mount root image: %m");
3141
3142 /* Now release the block device lock, so that udevd is free to call BLKRRPART on the device
3143 * if it likes. */
3144 if (loop_device) {
3145 r = loop_device_flock(loop_device, LOCK_UN);
3146 if (r < 0)
3147 return log_debug_errno(r, "Failed to release lock on loopback block device: %m");
3148 }
3149
3150 r = dissected_image_relinquish(dissected_image);
3151 if (r < 0)
3152 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
3153
3154 } else if (p->rootfs && p->rootfs->mstack_loaded) {
3155
3156 r = mstack_make_mounts(p->rootfs->mstack_loaded, root, mstack_flags);
3157 if (r < 0)
3158 return r;
3159
3160 r = mstack_bind_mounts(p->rootfs->mstack_loaded, root, /* where_fd= */ -EBADF, mstack_flags, /* ret_root_fd= */ NULL);
3161 if (r < 0)
3162 return r;
3163
3164 } else {
3165 /* Let's mount the main root directory to the root directory to use */
3166 r = mount_nofollow_verbose(LOG_DEBUG, "/", root, NULL, MS_BIND|MS_REC, NULL);
3167 if (r < 0)
3168 return r;
3169 }
3170
3171 /* Try to set up the new root directory before mounting anything else there. */
3172 if (pinned_resource_is_set(p->rootfs))
3173 (void) base_filesystem_create(root, UID_INVALID, GID_INVALID);
3174
3175 /* Now make the magic happen */
3176 r = apply_mounts(&ml, root, p, reterr_path);
3177 if (r < 0)
3178 return r;
3179
3180 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
3181 r = mount_switch_root(root, /* mount_propagation_flag = */ 0);
3182 if (r == -EINVAL && p->rootfs && p->rootfs->directory) {
3183 /* If we are using root_directory and we don't have privileges (ie: user manager in a user
3184 * namespace) and the root_directory is already a mount point in the parent namespace,
3185 * MS_MOVE will fail as we don't have permission to change it (with EINVAL rather than
3186 * EPERM). Attempt to bind-mount it over itself (like we do above if it's not already a
3187 * mount point) and try again. */
3188 r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
3189 if (r < 0)
3190 return r;
3191
3192 r = mount_switch_root(root, /* mount_propagation_flag= */ 0);
3193 }
3194 if (r < 0)
3195 return log_debug_errno(r, "Failed to mount root with MS_MOVE: %m");
3196
3197 /* Remount / as the desired mode. Note that this will not reestablish propagation from our side to
3198 * the host, since what's disconnected is disconnected. */
3199 if (mount(NULL, "/", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
3200 return log_debug_errno(errno, "Failed to remount '/' with desired mount flags: %m");
3201
3202 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only supported for
3203 * non-shared mounts. This needs to happen after remounting / or it will fail. */
3204 if (setup_propagate && mount(NULL, p->incoming_dir, NULL, MS_SLAVE, NULL) < 0)
3205 return log_debug_errno(errno, "Failed to remount %s with MS_SLAVE: %m", p->incoming_dir);
3206
3207 return 0;
3208 }
3209
3210 void bind_mount_free_many(BindMount *b, size_t n) {
3211 assert(b || n == 0);
3212
3213 FOREACH_ARRAY(i, b, n) {
3214 free(i->source);
3215 free(i->destination);
3216 }
3217
3218 free(b);
3219 }
3220
3221 int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
3222 _cleanup_free_ char *s = NULL, *d = NULL;
3223
3224 assert(b);
3225 assert(n);
3226 assert(item);
3227
3228 s = strdup(item->source);
3229 if (!s)
3230 return -ENOMEM;
3231
3232 d = strdup(item->destination);
3233 if (!d)
3234 return -ENOMEM;
3235
3236 if (!GREEDY_REALLOC(*b, *n + 1))
3237 return -ENOMEM;
3238
3239 (*b)[(*n)++] = (BindMount) {
3240 .source = TAKE_PTR(s),
3241 .destination = TAKE_PTR(d),
3242 .read_only = item->read_only,
3243 .nodev = item->nodev,
3244 .nosuid = item->nosuid,
3245 .noexec = item->noexec,
3246 .recursive = item->recursive,
3247 .ignore_enoent = item->ignore_enoent,
3248 };
3249
3250 return 0;
3251 }
3252
3253 static void mount_image_done(MountImage *m) {
3254 assert(m);
3255 m->source = mfree(m->source);
3256 m->destination = mfree(m->destination);
3257 m->mount_options = mount_options_free_all(m->mount_options);
3258 }
3259
3260 DEFINE_ARRAY_FREE_FUNC(mount_image_free_array, MountImage, mount_image_done);
3261
3262 int mount_image_add(MountImage **m, size_t *n, const MountImage *item) {
3263 _cleanup_free_ char *s = NULL, *d = NULL;
3264 _cleanup_(mount_options_free_allp) MountOptions *o = NULL;
3265 int r;
3266
3267 assert(m);
3268 assert(n);
3269 assert(item);
3270
3271 s = strdup(item->source);
3272 if (!s)
3273 return -ENOMEM;
3274
3275 if (item->destination) {
3276 d = strdup(item->destination);
3277 if (!d)
3278 return -ENOMEM;
3279 }
3280
3281 if (item->mount_options) {
3282 r = mount_options_dup(item->mount_options, &o);
3283 if (r < 0)
3284 return r;
3285 }
3286
3287 if (!GREEDY_REALLOC(*m, *n + 1))
3288 return -ENOMEM;
3289
3290 (*m)[(*n)++] = (MountImage) {
3291 .source = TAKE_PTR(s),
3292 .destination = TAKE_PTR(d),
3293 .mount_options = TAKE_PTR(o),
3294 .ignore_enoent = item->ignore_enoent,
3295 .type = item->type,
3296 };
3297
3298 return 0;
3299 }
3300
3301 void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
3302 assert(t || n == 0);
3303
3304 for (size_t i = 0; i < n; i++) {
3305 free(t[i].path);
3306 free(t[i].options);
3307 }
3308
3309 free(t);
3310 }
3311
3312 int temporary_filesystem_add(
3313 TemporaryFileSystem **t,
3314 size_t *n,
3315 const char *path,
3316 const char *options) {
3317
3318 _cleanup_free_ char *p = NULL, *o = NULL;
3319
3320 assert(t);
3321 assert(n);
3322 assert(path);
3323
3324 p = strdup(path);
3325 if (!p)
3326 return -ENOMEM;
3327
3328 if (!isempty(options)) {
3329 o = strdup(options);
3330 if (!o)
3331 return -ENOMEM;
3332 }
3333
3334 if (!GREEDY_REALLOC(*t, *n + 1))
3335 return -ENOMEM;
3336
3337 (*t)[(*n)++] = (TemporaryFileSystem) {
3338 .path = TAKE_PTR(p),
3339 .options = TAKE_PTR(o),
3340 };
3341
3342 return 0;
3343 }
3344
3345 char* namespace_cleanup_tmpdir(char *p) {
3346 if (!p)
3347 return NULL;
3348
3349 if (!streq(p, RUN_SYSTEMD_EMPTY)) {
3350 _cleanup_free_ char *child = path_join(p, "tmp");
3351 if (!child)
3352 log_oom_debug();
3353 else
3354 (void) rmdir(child);
3355
3356 (void) rmdir(p);
3357 }
3358
3359 return mfree(p);
3360 }
3361
3362 static int make_tmp_prefix(const char *prefix) {
3363 _cleanup_free_ char *t = NULL;
3364 _cleanup_close_ int fd = -EBADF;
3365 int r;
3366
3367 assert(prefix);
3368
3369 /* Don't do anything unless we know the dir is actually missing */
3370 r = access(prefix, F_OK);
3371 if (r >= 0)
3372 return 0;
3373 if (errno != ENOENT)
3374 return -errno;
3375
3376 WITH_UMASK(000)
3377 r = mkdir_parents(prefix, 0755);
3378 if (r < 0)
3379 return r;
3380
3381 r = tempfn_random(prefix, NULL, &t);
3382 if (r < 0)
3383 return r;
3384
3385 /* umask will corrupt this access mode, but that doesn't matter, we need to call chmod() anyway for
3386 * the suid bit, below. */
3387 fd = open_mkdir(t, O_EXCL|O_CLOEXEC, 0777);
3388 if (fd < 0)
3389 return fd;
3390
3391 r = RET_NERRNO(fchmod(fd, 01777));
3392 if (r < 0) {
3393 (void) rmdir(t);
3394 return r;
3395 }
3396
3397 r = RET_NERRNO(rename(t, prefix));
3398 if (r < 0) {
3399 (void) rmdir(t);
3400 return IN_SET(r, -EEXIST, -ENOTEMPTY) ? 0 : r; /* it's fine if someone else created the dir by now */
3401 }
3402
3403 return 0;
3404 }
3405
3406 int setup_tmp_dir_one(const char *id, const char *prefix, char **ret_path) {
3407 _cleanup_free_ char *d = NULL;
3408 sd_id128_t boot_id;
3409 bool rw = true;
3410 int r;
3411
3412 assert(id);
3413 assert(prefix);
3414 assert(ret_path);
3415
3416 /* We include the boot id in the directory so that after a
3417 * reboot we can easily identify obsolete directories. */
3418
3419 r = sd_id128_get_boot(&boot_id);
3420 if (r < 0)
3421 return r;
3422
3423 d = strjoin(prefix, "/systemd-private-", SD_ID128_TO_STRING(boot_id), "-", id, "-XXXXXX");
3424 if (!d)
3425 return -ENOMEM;
3426
3427 r = make_tmp_prefix(prefix);
3428 if (r < 0)
3429 return r;
3430
3431 WITH_UMASK(0077)
3432 if (!mkdtemp(d)) {
3433 if (errno == EROFS || ERRNO_IS_DISK_SPACE(errno))
3434 rw = false;
3435 else
3436 return -errno;
3437 }
3438
3439 if (rw) {
3440 _cleanup_free_ char *inner_dir = path_join(d, "tmp");
3441 if (!inner_dir) {
3442 (void) rmdir(d);
3443 return -ENOMEM;
3444 }
3445
3446 WITH_UMASK(0000)
3447 r = RET_NERRNO(mkdir(inner_dir, 0777 | S_ISVTX));
3448 if (r < 0) {
3449 (void) rmdir(d);
3450 return r;
3451 }
3452
3453 r = label_fix_full(AT_FDCWD, inner_dir, prefix, 0);
3454 if (r < 0) {
3455 (void) rmdir(inner_dir);
3456 (void) rmdir(d);
3457 return r;
3458 }
3459 } else {
3460 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
3461 * read-only. This way the service will get the EROFS result as if it was writing to the real
3462 * file system. */
3463 WITH_UMASK(0000)
3464 r = mkdir_p(RUN_SYSTEMD_EMPTY, 0500);
3465 if (r < 0)
3466 return r;
3467
3468 r = free_and_strdup(&d, RUN_SYSTEMD_EMPTY);
3469 if (r < 0)
3470 return r;
3471 }
3472
3473 *ret_path = TAKE_PTR(d);
3474 return 0;
3475 }
3476
3477 int setup_shareable_ns(int ns_storage_socket[static 2], unsigned long nsflag) {
3478 _cleanup_close_ int ns = -EBADF;
3479 const char *ns_name, *ns_path;
3480 int r;
3481
3482 assert(ns_storage_socket);
3483 assert(ns_storage_socket[0] >= 0);
3484 assert(ns_storage_socket[1] >= 0);
3485
3486 ns_name = ASSERT_PTR(namespace_single_flag_to_string(nsflag));
3487
3488 /* We use the passed socketpair as a storage buffer for our namespace reference fd. Whatever process
3489 * runs this first shall create a new namespace, all others should just join it. To serialize that we
3490 * use a file lock on the socket pair.
3491 *
3492 * It's a bit crazy, but hey, works great! */
3493
3494 r = posix_lock(ns_storage_socket[0], LOCK_EX);
3495 if (r < 0)
3496 return r;
3497
3498 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
3499
3500 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
3501 if (ns >= 0) {
3502 /* Yay, found something, so let's join the namespace */
3503 r = RET_NERRNO(setns(ns, nsflag));
3504 if (r < 0)
3505 return r;
3506
3507 return 0;
3508 }
3509
3510 if (ns != -EAGAIN)
3511 return ns;
3512
3513 /* Nothing stored yet, so let's create a new namespace. */
3514
3515 if (unshare(nsflag) < 0)
3516 return -errno;
3517
3518 if (nsflag == CLONE_NEWNET)
3519 (void) loopback_setup();
3520
3521 ns_path = strjoina("/proc/self/ns/", ns_name);
3522 ns = open(ns_path, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3523 if (ns < 0)
3524 return -errno;
3525
3526 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
3527 if (r < 0)
3528 return r;
3529
3530 return 1;
3531 }
3532
3533 int open_shareable_ns_path(int ns_storage_socket[static 2], const char *path, unsigned long nsflag) {
3534 _cleanup_close_ int ns = -EBADF;
3535 NamespaceType type;
3536 int r;
3537
3538 assert(ns_storage_socket);
3539 assert(ns_storage_socket[0] >= 0);
3540 assert(ns_storage_socket[1] >= 0);
3541 assert(path);
3542
3543 /* If the storage socket doesn't contain a ns fd yet, open one via the file system and store it in
3544 * it. This is supposed to be called ahead of time, i.e. before setup_shareable_ns() which will
3545 * allocate a new anonymous ns if needed. */
3546
3547 type = clone_flag_to_namespace_type(nsflag);
3548 assert(type >= 0);
3549
3550 r = posix_lock(ns_storage_socket[0], LOCK_EX);
3551 if (r < 0)
3552 return r;
3553
3554 CLEANUP_POSIX_UNLOCK(ns_storage_socket[0]);
3555
3556 ns = receive_one_fd(ns_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
3557 if (ns >= 0)
3558 return 0;
3559 if (ns != -EAGAIN)
3560 return ns;
3561
3562 /* Nothing stored yet. Open the file from the file system. */
3563
3564 ns = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
3565 if (ns < 0)
3566 return -errno;
3567
3568 r = fd_is_namespace(ns, type);
3569 if (r < 0)
3570 return r;
3571 if (r == 0)
3572 return -EINVAL;
3573
3574 r = send_one_fd(ns_storage_socket[1], ns, MSG_DONTWAIT);
3575 if (r < 0)
3576 return r;
3577
3578 return 1;
3579 }
3580
3581 static int is_extension_overlay(const char *path, int fd) {
3582 _cleanup_free_ char *source = NULL;
3583 _cleanup_close_ int dfd = -EBADF;
3584 int r;
3585
3586 assert(path);
3587
3588 if (fd < 0) {
3589 r = chase(path, /* root= */ NULL, CHASE_TRAIL_SLASH|CHASE_MUST_BE_DIRECTORY|CHASE_TRIGGER_AUTOFS, /* ret_path= */ NULL, &dfd);
3590 if (r < 0)
3591 return r;
3592 fd = dfd;
3593 }
3594
3595 r = is_mount_point_at(fd, /* path= */ NULL, /* flags= */ 0);
3596 if (r < 0)
3597 return log_debug_errno(r, "Unable to determine whether '%s' is a mount point: %m", path);
3598 if (r == 0)
3599 return 0;
3600
3601 r = fd_is_fs_type(fd, OVERLAYFS_SUPER_MAGIC);
3602 if (r < 0)
3603 return log_debug_errno(r, "Failed to check if %s is an overlayfs: %m", path);
3604 if (r == 0)
3605 return 0;
3606
3607 /* Check the 'source' field of the mount on mount_path */
3608 r = path_get_mount_info_at(fd, /* path= */ NULL, /* ret_fstype= */ NULL, /* ret_options= */ NULL, &source);
3609 if (r < 0)
3610 return log_debug_errno(r, "Failed to get mount info for %s: %m", path);
3611 if (!streq_ptr(source, "systemd-extensions"))
3612 return 0;
3613
3614 return 1;
3615 }
3616
3617 static int unpeel_get_fd(const char *mount_path, int *ret_fd) {
3618 _cleanup_close_pair_ int pipe_fds[2] = EBADF_PAIR;
3619 _cleanup_close_ int fs_fd = -EBADF;
3620 int r;
3621
3622 assert(mount_path);
3623 assert(ret_fd);
3624
3625 r = socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pipe_fds);
3626 if (r < 0)
3627 return log_debug_errno(errno, "Failed to create socket pair: %m");
3628
3629 /* Clone mount namespace here to unpeel without affecting live process */
3630 r = pidref_safe_fork("(sd-ns-unpeel)", FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, /* ret= */ NULL);
3631 if (r < 0)
3632 return r;
3633 if (r == 0) {
3634 _cleanup_close_ int dir_fd = -EBADF;
3635
3636 pipe_fds[0] = safe_close(pipe_fds[0]);
3637
3638 /* Opportunistically unmount any overlay at this path */
3639 r = is_extension_overlay(mount_path, /* fd= */ -EBADF);
3640 if (r < 0) {
3641 log_debug_errno(r, "Unable to determine whether '%s' is an extension overlay: %m", mount_path);
3642 _exit(EXIT_FAILURE);
3643 }
3644 if (r > 0) {
3645 r = umount_recursive(mount_path, MNT_DETACH);
3646 if (r < 0)
3647 _exit(EXIT_FAILURE);
3648 if (r == 0) /* no umounts done, possible if a previous reload deleted all extensions */
3649 log_debug("No overlay layer unmountable from %s", mount_path);
3650 }
3651
3652 /* Now that /mount_path is exposed, get an FD for it and pass back */
3653 dir_fd = open_tree(-EBADF, mount_path, AT_SYMLINK_NOFOLLOW|OPEN_TREE_CLONE);
3654 if (dir_fd < 0) {
3655 log_debug_errno(errno, "Failed to clone mount %s: %m", mount_path);
3656 _exit(EXIT_FAILURE);
3657 }
3658
3659 r = fd_is_fs_type(dir_fd, OVERLAYFS_SUPER_MAGIC);
3660 if (r < 0) {
3661 log_debug_errno(r, "Unable to determine whether '%s' is an overlay after opening mount tree: %m", mount_path);
3662 _exit(EXIT_FAILURE);
3663 }
3664 if (r > 0) {
3665 log_debug("'%s' is still an overlay after opening mount tree", mount_path);
3666 _exit(EXIT_FAILURE);
3667 }
3668
3669 r = send_one_fd(pipe_fds[1], dir_fd, 0);
3670 if (r < 0) {
3671 log_debug_errno(r, "Failed to send mount fd: %m");
3672 _exit(EXIT_FAILURE);
3673 }
3674
3675 _exit(EXIT_SUCCESS);
3676 }
3677
3678 pipe_fds[1] = safe_close(pipe_fds[1]);
3679
3680 r = receive_one_fd(pipe_fds[0], 0);
3681 if (r < 0)
3682 return log_debug_errno(r, "Failed to receive mount fd: %m");
3683 fs_fd = r;
3684
3685 r = fd_is_fs_type(fs_fd, OVERLAYFS_SUPER_MAGIC);
3686 if (r < 0)
3687 return log_debug_errno(r, "Unable to determine if unpeeled directory refers to overlayfs: %m");
3688 if (r > 0)
3689 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unpeeled mount is still an overlayfs, something is weird, refusing.");
3690
3691 *ret_fd = TAKE_FD(fs_fd);
3692 return 0;
3693 }
3694
3695 /* In target namespace, unmounts an existing overlayfs at mount_path (if one exists), grabs FD from the
3696 * underlying directory, and sets up a new overlayfs mount. Coordinates with parent process over pair_fd:
3697 * 1. Creates and sends new overlay fs fd to parent
3698 * 2. Fake-unmounts overlay at mount_path to obtain underlying directory fd to build new overlay
3699 * 3. Waits for parent to configure layers
3700 * 4. Performs final mount at mount_path
3701 *
3702 * This is used by refresh_extensions_in_namespace() to peel back any existing overlays and reapply them.
3703 */
3704 static int unpeel_mount_and_setup_overlay(int pair_fd, const char *mount_path) {
3705 _cleanup_close_ int dir_unpeeled_fd = -EBADF, overlay_fs_fd = -EBADF, mount_fd = -EBADF;
3706 int r;
3707
3708 assert(pair_fd >= 0);
3709 assert(mount_path);
3710
3711 /* Create new OverlayFS and send to parent */
3712 overlay_fs_fd = fsopen("overlay", FSOPEN_CLOEXEC);
3713 if (overlay_fs_fd < 0)
3714 return log_debug_errno(errno, "Failed to create overlay fs for %s: %m", mount_path);
3715
3716 r = send_one_fd(pair_fd, overlay_fs_fd, /* flags= */ 0);
3717 if (r < 0)
3718 return log_debug_errno(r, "Failed to send overlay fs fd to parent: %m");
3719
3720 /* Unpeel in cloned mount namespace to get underlying directory fd */
3721 r = unpeel_get_fd(mount_path, &dir_unpeeled_fd);
3722 if (r < 0)
3723 return log_debug_errno(r, "Failed to unpeel mount %s: %m", mount_path);
3724
3725 /* Send the fd to the parent */
3726 r = send_one_fd(pair_fd, dir_unpeeled_fd, /* flags= */ 0);
3727 if (r < 0)
3728 return log_debug_errno(r, "Failed to send %s fd to parent: %m", mount_path);
3729
3730 /* Wait for parent to signal overlay configuration completion */
3731 log_debug("Waiting for configured overlay fs for %s", mount_path);
3732 r = receive_one_fd(pair_fd, 0);
3733 if (r < 0)
3734 return log_debug_errno(r, "Failed to receive configured overlay: %m");
3735
3736 /* Create the mount */
3737 mount_fd = fsmount(overlay_fs_fd, FSMOUNT_CLOEXEC, /* flags= */ 0);
3738 if (mount_fd < 0)
3739 return log_debug_errno(errno, "Failed to create overlay mount: %m");
3740
3741 /* Move mount to final location */
3742 r = mount_exchange_graceful(mount_fd, mount_path, /* mount_beneath= */ true);
3743 if (r < 0)
3744 return log_debug_errno(r, "Failed to move overlay to %s: %m", mount_path);
3745
3746 return 0;
3747 }
3748
3749 static int refresh_grandchild_proc(
3750 const PidRef *target,
3751 MountList *ml,
3752 const char *overlay_prefix,
3753 int pidns_fd,
3754 int mntns_fd,
3755 int root_fd,
3756 int pipe_fd) {
3757
3758 int r;
3759
3760 assert(pidref_is_set(target));
3761 assert(ml);
3762 assert(overlay_prefix);
3763 assert(pidns_fd >= 0);
3764 assert(mntns_fd >= 0);
3765 assert(root_fd >= 0);
3766 assert(pipe_fd >= 0);
3767
3768 r = namespace_enter(pidns_fd, mntns_fd, /* netns_fd= */ -EBADF, /* userns_fd= */ -EBADF, root_fd);
3769 if (r < 0)
3770 return log_debug_errno(r, "Failed to enter namespace: %m");
3771
3772 /* Handle each overlay mount path */
3773 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
3774 if (m->mode != MOUNT_OVERLAY)
3775 continue;
3776
3777 /* Need an absolute path under the child namespace, rather than the root's */
3778 _cleanup_free_ char *mount_path = NULL;
3779 mount_path = path_join("/",
3780 path_startswith(mount_entry_unprefixed_path(m), overlay_prefix) ?:
3781 mount_entry_unprefixed_path(m));
3782 if (!mount_path)
3783 return log_oom_debug();
3784
3785 /* If there are no extensions mounted for this overlay layer, instead of setting everything
3786 * up, the correct behavior is to unmount the existing overlay in the target namespace to
3787 * expose the original files. */
3788 if (strv_isempty(m->overlay_layers)) {
3789 r = is_extension_overlay(mount_path, /* fd= */ -EBADF);
3790 if (r < 0)
3791 return log_debug_errno(r, "Unable to determine whether '%s' is an extension overlay: %m", mount_path);
3792 if (r == 0)
3793 continue;
3794
3795 log_debug("No extensions for %s, undoing existing mount", mount_path);
3796 (void) umount_recursive(mount_path, MNT_DETACH);
3797
3798 continue;
3799 }
3800
3801 r = unpeel_mount_and_setup_overlay(pipe_fd, mount_path);
3802 if (r < 0)
3803 return log_debug_errno(r, "Failed to setup overlay mount for %s: %m", mount_path);
3804 }
3805
3806 return 0;
3807 }
3808
3809 static int handle_mount_from_grandchild(
3810 MountEntry *m,
3811 const char *overlay_prefix,
3812 int **fd_layers,
3813 size_t *n_fd_layers,
3814 int pipe_fd) {
3815
3816 _cleanup_free_ char *layers = NULL, *options = NULL, *hierarchy_path_moved_mount = NULL;
3817 _cleanup_close_ int hierarchy_path_fd = -EBADF, overlay_fs_fd = -EBADF;
3818 _cleanup_strv_free_ char **new_layers = NULL;
3819 int r;
3820
3821 assert(m);
3822 assert(overlay_prefix);
3823 assert(fd_layers);
3824 assert(n_fd_layers);
3825 assert(pipe_fd >= 0);
3826
3827 if (m->mode != MOUNT_OVERLAY)
3828 return 0;
3829
3830 const char *mount_path = path_startswith(mount_entry_unprefixed_path(m), overlay_prefix);
3831 if (!mount_path)
3832 mount_path = mount_entry_unprefixed_path(m);
3833
3834 /* If there are no extensions mounted for this overlay layer, we only need to
3835 * unmount the existing overlay (this is handled in the grandchild process) and
3836 * would skip the usual cooperative processing here.
3837 */
3838 if (strv_isempty(m->overlay_layers)) {
3839 log_debug("No layers for %s, skip setting up overlay", mount_path);
3840 return 0;
3841 }
3842
3843 /* Receive the fds from grandchild */
3844 overlay_fs_fd = receive_one_fd(pipe_fd, 0);
3845 if (overlay_fs_fd < 0)
3846 return log_debug_errno(overlay_fs_fd, "Failed to receive overlay fs fd from grandchild: %m");
3847
3848 hierarchy_path_fd = receive_one_fd(pipe_fd, 0);
3849 if (hierarchy_path_fd < 0)
3850 return log_debug_errno(hierarchy_path_fd, "Failed to receive fd from grandchild for %s: %m", mount_path);
3851
3852 /* move_mount so that it is visible on our end. */
3853 hierarchy_path_moved_mount = path_join(overlay_prefix, mount_path);
3854 if (!hierarchy_path_moved_mount)
3855 return log_oom_debug();
3856
3857 (void) mkdir_p_label(hierarchy_path_moved_mount, 0555);
3858 r = move_mount(hierarchy_path_fd, "", AT_FDCWD, hierarchy_path_moved_mount, MOVE_MOUNT_F_EMPTY_PATH);
3859 if (r < 0)
3860 return log_debug_errno(r, "Failed to move mount for %s: %m", mount_path);
3861
3862 /* Turn all overlay layer directories into FD-based references */
3863 if (!GREEDY_REALLOC(*fd_layers, *n_fd_layers + strv_length(m->overlay_layers)))
3864 return log_oom_debug();
3865
3866 STRV_FOREACH(ol, m->overlay_layers) {
3867 _cleanup_close_ int tree_fd = -EBADF;
3868
3869 tree_fd = open_tree(-EBADF, *ol, /* flags= */ 0);
3870 if (tree_fd < 0)
3871 return log_debug_errno(errno, "Failed to open_tree overlay layer '%s': %m", *ol);
3872
3873 r = strv_extend(&new_layers, FORMAT_PROC_FD_PATH(tree_fd));
3874 if (r < 0)
3875 return log_oom_debug();
3876
3877 (*fd_layers)[(*n_fd_layers)++] = TAKE_FD(tree_fd);
3878 }
3879 m->overlay_layers = strv_free(m->overlay_layers);
3880 m->overlay_layers = TAKE_PTR(new_layers);
3881
3882 layers = strv_join(m->overlay_layers, ":");
3883 if (!layers)
3884 return log_oom_debug();
3885
3886 /* Append the underlying hierarchy path as the last lowerdir */
3887 options = strjoin(layers, ":", FORMAT_PROC_FD_PATH(hierarchy_path_fd));
3888 if (!options)
3889 return log_oom_debug();
3890
3891 if (fsconfig(overlay_fs_fd, FSCONFIG_SET_STRING, "lowerdir", options, 0) < 0)
3892 return log_debug_errno(errno, "Failed to set lowerdir=%s: %m", options);
3893
3894 if (fsconfig(overlay_fs_fd, FSCONFIG_SET_STRING, "source", "systemd-extensions", 0) < 0)
3895 return log_debug_errno(errno, "Failed to set source=systemd-extensions: %m");
3896
3897 /* Create the superblock */
3898 if (fsconfig(overlay_fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
3899 return log_debug_errno(errno, "Failed to create overlay superblock: %m");
3900
3901 /* Signal completion to grandchild */
3902 r = send_one_fd(pipe_fd, overlay_fs_fd, 0);
3903 if (r < 0)
3904 return log_debug_errno(r, "Failed to signal overlay configuration complete for %s: %m", mount_path);
3905
3906 return 0;
3907 }
3908
3909 static int refresh_apply_and_prune(const NamespaceParameters *p, MountList *ml) {
3910 int r;
3911
3912 assert(p);
3913 assert(ml);
3914
3915 /* Open all extensions on the host, drop all sysexts since they won't have /etc/. The list of
3916 * overlays also need to be updated, so that if it's empty after a confext has been removed, the
3917 * child process can correctly undo the overlay in the target namespace, rather than attempting to
3918 * mount an empty overlay which the kernel does not allow, so this pruning has to be done here and
3919 * not later (nor earlier, as we don't know if an image is a confext until this point). */
3920 MountEntry *f, *t;
3921 for (f = ml->mounts, t = ml->mounts; f < ml->mounts + ml->n_mounts; f++) {
3922 if (IN_SET(f->mode, MOUNT_EXTENSION_DIRECTORY, MOUNT_EXTENSION_IMAGE)) {
3923 f->filter_class = IMAGE_CONFEXT;
3924
3925 r = apply_one_mount("/", f, p);
3926 if (r < 0)
3927 return r;
3928 /* Nothing happened? Then it is not a confext, prune it from the lists */
3929 if (r == 0) {
3930 FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
3931 if (m->mode != MOUNT_OVERLAY)
3932 continue;
3933
3934 _cleanup_strv_free_ char **pruned = NULL;
3935
3936 STRV_FOREACH(ol, m->overlay_layers)
3937 if (!path_startswith(*ol, mount_entry_path(f))) {
3938 r = strv_extend(&pruned, *ol);
3939 if (r < 0)
3940 return log_oom_debug();
3941 }
3942 strv_free(m->overlay_layers);
3943 m->overlay_layers = TAKE_PTR(pruned);
3944 }
3945 mount_entry_done(f);
3946 continue;
3947 }
3948 }
3949
3950 *t = *f;
3951 t++;
3952 }
3953
3954 ml->n_mounts = t - ml->mounts;
3955
3956 return 0;
3957 }
3958
3959 int refresh_extensions_in_namespace(
3960 const PidRef *target,
3961 const char *hierarchy_env,
3962 const NamespaceParameters *p) {
3963
3964 _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF;
3965 const char *overlay_prefix = "/run/systemd/mount-rootfs";
3966 _cleanup_(mount_list_done) MountList ml = {};
3967 _cleanup_free_ char *extension_dir = NULL;
3968 _cleanup_strv_free_ char **hierarchies = NULL;
3969 int r;
3970
3971 assert(pidref_is_set(target));
3972 assert(hierarchy_env);
3973 assert(p);
3974
3975 log_debug("Refreshing extensions in-namespace for hierarchy '%s'", hierarchy_env);
3976
3977 r = pidref_namespace_open(target, &pidns_fd, &mntns_fd, /* ret_netns_fd= */ NULL, /* ret_userns_fd= */ NULL, &root_fd);
3978 if (r < 0)
3979 return log_debug_errno(r, "Failed to open namespace: %m");
3980
3981 r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
3982 if (r < 0)
3983 return log_debug_errno(r, "Failed to check if target namespace is separate: %m");
3984 if (r > 0)
3985 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Target namespace is not separate, cannot reload extensions");
3986
3987 (void) DLOPEN_CRYPTSETUP(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
3988
3989 extension_dir = path_join(p->private_namespace_dir, "unit-extensions");
3990 if (!extension_dir)
3991 return log_oom_debug();
3992
3993 r = parse_env_extension_hierarchies(&hierarchies, hierarchy_env);
3994 if (r < 0)
3995 return r;
3996
3997 r = append_extensions(
3998 &ml,
3999 overlay_prefix,
4000 p->private_namespace_dir,
4001 hierarchies,
4002 p->extension_images,
4003 p->n_extension_images,
4004 p->extension_directories);
4005 if (r < 0)
4006 return r;
4007
4008 sort_and_drop_unused_mounts(&ml, overlay_prefix);
4009 if (ml.n_mounts == 0)
4010 return 0;
4011
4012 /**
4013 * There are three main steps:
4014 * 1. In child, set up the extension images and directories in a slave mountns, so that we have
4015 * access to their FDs
4016 * 2. Fork into a grandchild, which will enter the target namespace and attempt to "unpeel" the
4017 * overlays to obtain FDs the underlying directories, over which we will reapply the overlays
4018 * 3. In the child again, receive the FDs and reapply the overlays
4019 */
4020 r = pidref_safe_fork(
4021 "(sd-ns-refresh-exts)",
4022 FORK_DEATHSIG_SIGTERM|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE,
4023 /* ret= */ NULL);
4024 if (r < 0)
4025 return r;
4026 if (r == 0) {
4027 /* Child (host namespace) */
4028 _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
4029 _cleanup_(pidref_done_sigkill_wait) PidRef grandchild = PIDREF_NULL;
4030
4031 (void) mkdir_p_label(overlay_prefix, 0555);
4032
4033 r = refresh_apply_and_prune(p, &ml);
4034 if (r < 0) {
4035 log_debug_errno(r, "Failed to apply extensions for refreshing: %m");
4036 _exit(EXIT_FAILURE);
4037 }
4038
4039 /* Create a grandchild process to handle the unmounting and reopening of hierarchy */
4040 r = socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair);
4041 if (r < 0) {
4042 log_debug_errno(errno, "Failed to create socket pair: %m");
4043 _exit(EXIT_FAILURE);
4044 }
4045
4046 r = pidref_safe_fork("(sd-ns-refresh-exts-grandchild)", FORK_LOG|FORK_DEATHSIG_SIGKILL, &grandchild);
4047 if (r < 0)
4048 _exit(EXIT_FAILURE);
4049 if (r == 0) {
4050 /* Grandchild (target service namespace) */
4051 pair[0] = safe_close(pair[0]);
4052
4053 r = refresh_grandchild_proc(target, &ml, overlay_prefix, pidns_fd, mntns_fd, root_fd, pair[1]);
4054 if (r < 0) {
4055 pair[1] = safe_close(pair[1]);
4056 _exit(EXIT_FAILURE);
4057 }
4058
4059 _exit(EXIT_SUCCESS);
4060 }
4061
4062 pair[1] = safe_close(pair[1]);
4063
4064 /* Until kernel 6.15, the FDs to the individual layers used to set up the OverlayFS via
4065 * lowerdir=/proc/self/fd/X need to remain open until the OverlayFS mount is _attached_
4066 * (as opposed to merely created) to its mount point, hence we need to ensure these FDs
4067 * stay open until the grandchild has attached the mount and exited. */
4068 // TODO: once the kernel baseline is >= 6.15, move the FD array into the helper function
4069 // and close them immediately
4070 int *fd_layers = NULL;
4071 size_t n_fd_layers = 0;
4072 CLEANUP_ARRAY(fd_layers, n_fd_layers, close_many_and_free);
4073
4074 FOREACH_ARRAY(m, ml.mounts, ml.n_mounts) {
4075 r = handle_mount_from_grandchild(m, overlay_prefix, &fd_layers, &n_fd_layers, pair[0]);
4076 if (r < 0)
4077 _exit(EXIT_FAILURE);
4078 }
4079
4080 r = pidref_wait_for_terminate_and_check("(sd-ns-refresh-exts-grandchild)", &grandchild, 0);
4081 if (r < 0) {
4082 log_debug_errno(r, "Failed to wait for target namespace process to finish: %m");
4083 _exit(EXIT_FAILURE);
4084 }
4085
4086 pidref_done(&grandchild);
4087
4088 if (r != EXIT_SUCCESS) {
4089 log_debug("Target namespace fork did not succeed");
4090 _exit(EXIT_FAILURE);
4091 }
4092
4093 _exit(EXIT_SUCCESS);
4094 }
4095
4096 return 0;
4097 }
4098
4099 static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
4100 [PROTECT_HOME_NO] = "no",
4101 [PROTECT_HOME_YES] = "yes",
4102 [PROTECT_HOME_READ_ONLY] = "read-only",
4103 [PROTECT_HOME_TMPFS] = "tmpfs",
4104 };
4105
4106 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home, ProtectHome, PROTECT_HOME_YES);
4107
4108 static const char *const protect_hostname_table[_PROTECT_HOSTNAME_MAX] = {
4109 [PROTECT_HOSTNAME_NO] = "no",
4110 [PROTECT_HOSTNAME_YES] = "yes",
4111 [PROTECT_HOSTNAME_PRIVATE] = "private",
4112 };
4113
4114 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_hostname, ProtectHostname, PROTECT_HOSTNAME_YES);
4115
4116 static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
4117 [PROTECT_SYSTEM_NO] = "no",
4118 [PROTECT_SYSTEM_YES] = "yes",
4119 [PROTECT_SYSTEM_FULL] = "full",
4120 [PROTECT_SYSTEM_STRICT] = "strict",
4121 };
4122
4123 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system, ProtectSystem, PROTECT_SYSTEM_YES);
4124
4125 static const char *const protect_control_groups_table[_PROTECT_CONTROL_GROUPS_MAX] = {
4126 [PROTECT_CONTROL_GROUPS_NO] = "no",
4127 [PROTECT_CONTROL_GROUPS_YES] = "yes",
4128 [PROTECT_CONTROL_GROUPS_PRIVATE] = "private",
4129 [PROTECT_CONTROL_GROUPS_STRICT] = "strict",
4130 };
4131
4132 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_control_groups, ProtectControlGroups, PROTECT_CONTROL_GROUPS_YES);
4133
4134 static const char* const protect_proc_table[_PROTECT_PROC_MAX] = {
4135 [PROTECT_PROC_DEFAULT] = "default",
4136 [PROTECT_PROC_NOACCESS] = "noaccess",
4137 [PROTECT_PROC_INVISIBLE] = "invisible",
4138 [PROTECT_PROC_PTRACEABLE] = "ptraceable",
4139 };
4140
4141 DEFINE_STRING_TABLE_LOOKUP(protect_proc, ProtectProc);
4142
4143 static const char* const proc_subset_table[_PROC_SUBSET_MAX] = {
4144 [PROC_SUBSET_ALL] = "all",
4145 [PROC_SUBSET_PID] = "pid",
4146 };
4147
4148 DEFINE_STRING_TABLE_LOOKUP(proc_subset, ProcSubset);
4149
4150 static const char* const private_bpf_table[_PRIVATE_BPF_MAX] = {
4151 [PRIVATE_BPF_NO] = "no",
4152 [PRIVATE_BPF_YES] = "yes",
4153 };
4154
4155 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(private_bpf, PrivateBPF, PRIVATE_BPF_YES);
4156
4157 #include "bpf-delegate-configs.inc"
4158
4159 DEFINE_STRING_TABLE_LOOKUP(bpf_delegate_cmd, uint64_t);
4160 DEFINE_STRING_TABLE_LOOKUP(bpf_delegate_map_type, uint64_t);
4161 DEFINE_STRING_TABLE_LOOKUP(bpf_delegate_prog_type, uint64_t);
4162 DEFINE_STRING_TABLE_LOOKUP(bpf_delegate_attach_type, uint64_t);
4163
4164 char* bpf_delegate_to_string(uint64_t u, const char * (*parser)(uint64_t) _const_ ) {
4165 assert(parser);
4166
4167 if (u == UINT64_MAX)
4168 return strdup("any");
4169
4170 _cleanup_free_ char *buf = NULL;
4171
4172 BIT_FOREACH(i, u) {
4173 const char *s = parser(i);
4174 if (s) {
4175 if (!strextend_with_separator(&buf, ",", s))
4176 return NULL;
4177 } else {
4178 if (strextendf_with_separator(&buf, ",", "%d", i) < 0)
4179 return NULL;
4180 }
4181 }
4182
4183 return TAKE_PTR(buf) ?: strdup("");
4184 }
4185
4186 int bpf_delegate_from_string(const char *s, uint64_t *ret, uint64_t (*parser)(const char *)) {
4187 int r;
4188
4189 assert(s);
4190 assert(ret);
4191 assert(parser);
4192
4193 if (streq(s, "any")) {
4194 *ret = UINT64_MAX;
4195 return 0;
4196 }
4197
4198 uint64_t mask = 0;
4199 for (;;) {
4200 _cleanup_free_ char *word = NULL;
4201
4202 r = extract_first_word(&s, &word, ",", /* flags= */ 0);
4203 if (r < 0)
4204 return log_warning_errno(r, "Failed to parse delegate options \"%s\": %m", s);
4205 if (r == 0)
4206 break;
4207
4208 r = parser(word);
4209 if (r < 0)
4210 log_warning_errno(r, "Unknown BPF delegate option, ignoring: %s", word);
4211 else
4212 mask |= UINT64_C(1) << r;
4213 }
4214
4215 *ret = mask;
4216
4217 return 0;
4218 }
4219
4220 static const char* const private_tmp_table[_PRIVATE_TMP_MAX] = {
4221 [PRIVATE_TMP_NO] = "no",
4222 [PRIVATE_TMP_CONNECTED] = "connected",
4223 [PRIVATE_TMP_DISCONNECTED] = "disconnected",
4224 };
4225
4226 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(private_tmp, PrivateTmp, PRIVATE_TMP_CONNECTED);
4227
4228 static const char* const private_users_table[_PRIVATE_USERS_MAX] = {
4229 [PRIVATE_USERS_NO] = "no",
4230 [PRIVATE_USERS_SELF] = "self",
4231 [PRIVATE_USERS_IDENTITY] = "identity",
4232 [PRIVATE_USERS_FULL] = "full",
4233 [PRIVATE_USERS_MANAGED] = "managed",
4234 };
4235
4236 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(private_users, PrivateUsers, PRIVATE_USERS_SELF);
4237
4238 static const char* const private_pids_table[_PRIVATE_PIDS_MAX] = {
4239 [PRIVATE_PIDS_NO] = "no",
4240 [PRIVATE_PIDS_YES] = "yes",
4241 };
4242
4243 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(private_pids, PrivatePIDs, PRIVATE_PIDS_YES);
4244
4245 void pinned_resource_done(PinnedResource *p) {
4246 assert(p);
4247
4248 p->directory_fd = safe_close(p->directory_fd);
4249 p->directory = mfree(p->directory);
4250 p->image_fd = safe_close(p->image_fd);
4251 p->image = mfree(p->image);
4252 p->mstack_loaded = mstack_free(p->mstack_loaded);
4253 p->mstack = mfree(p->mstack);
4254 }
4255
4256 bool pinned_resource_is_set(const PinnedResource *p) {
4257 if (!p)
4258 return false;
4259
4260 return p->directory_fd >= 0 ||
4261 p->directory ||
4262 p->image_fd >= 0 ||
4263 p->image ||
4264 p->mstack_loaded ||
4265 p->mstack;
4266 }