]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/mount-util.c
Merge pull request #31531 from poettering/verity-userspace-optional
[thirdparty/systemd.git] / src / shared / mount-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <stdlib.h>
5 #include <sys/mount.h>
6 #include <sys/stat.h>
7 #include <sys/statvfs.h>
8 #include <unistd.h>
9 #include <linux/loop.h>
10 #if WANT_LINUX_FS_H
11 #include <linux/fs.h>
12 #endif
13
14 #include "alloc-util.h"
15 #include "chase.h"
16 #include "dissect-image.h"
17 #include "exec-util.h"
18 #include "extract-word.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 #include "fs-util.h"
22 #include "glyph-util.h"
23 #include "hashmap.h"
24 #include "initrd-util.h"
25 #include "label-util.h"
26 #include "libmount-util.h"
27 #include "missing_mount.h"
28 #include "missing_syscall.h"
29 #include "mkdir-label.h"
30 #include "mount-util.h"
31 #include "mountpoint-util.h"
32 #include "namespace-util.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "process-util.h"
36 #include "set.h"
37 #include "sort-util.h"
38 #include "stat-util.h"
39 #include "stdio-util.h"
40 #include "string-table.h"
41 #include "string-util.h"
42 #include "strv.h"
43 #include "tmpfile-util.h"
44 #include "user-util.h"
45
46 int umount_recursive_full(const char *prefix, int flags, char **keep) {
47 _cleanup_fclose_ FILE *f = NULL;
48 int n = 0, r;
49
50 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
51 * keep unmounting them until they are gone. */
52
53 f = fopen("/proc/self/mountinfo", "re"); /* Pin the file, in case we unmount /proc/ as part of the logic here */
54 if (!f)
55 return log_debug_errno(errno, "Failed to open /proc/self/mountinfo: %m");
56
57 for (;;) {
58 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
59 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
60 bool again = false;
61
62 r = libmount_parse("/proc/self/mountinfo", f, &table, &iter);
63 if (r < 0)
64 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
65
66 for (;;) {
67 bool shall_keep = false;
68 struct libmnt_fs *fs;
69 const char *path;
70
71 r = mnt_table_next_fs(table, iter, &fs);
72 if (r == 1)
73 break;
74 if (r < 0)
75 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
76
77 path = mnt_fs_get_target(fs);
78 if (!path)
79 continue;
80
81 if (prefix && !path_startswith(path, prefix)) {
82 log_trace("Not unmounting %s, outside of prefix: %s", path, prefix);
83 continue;
84 }
85
86 STRV_FOREACH(k, keep)
87 /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
88 if (path_startswith(path, *k) || path_startswith(*k, path)) {
89 shall_keep = true;
90 break;
91 }
92 if (shall_keep) {
93 log_debug("Not unmounting %s, referenced by keep list.", path);
94 continue;
95 }
96
97 if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
98 log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
99 continue;
100 }
101
102 log_trace("Successfully unmounted %s", path);
103
104 again = true;
105 n++;
106
107 break;
108 }
109
110 if (!again)
111 break;
112
113 rewind(f);
114 }
115
116 return n;
117 }
118
119 #define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
120
121 static uint64_t ms_flags_to_mount_attr(unsigned long a) {
122 uint64_t f = 0;
123
124 if (FLAGS_SET(a, MS_RDONLY))
125 f |= MOUNT_ATTR_RDONLY;
126
127 if (FLAGS_SET(a, MS_NOSUID))
128 f |= MOUNT_ATTR_NOSUID;
129
130 if (FLAGS_SET(a, MS_NODEV))
131 f |= MOUNT_ATTR_NODEV;
132
133 if (FLAGS_SET(a, MS_NOEXEC))
134 f |= MOUNT_ATTR_NOEXEC;
135
136 if (FLAGS_SET(a, MS_NOSYMFOLLOW))
137 f |= MOUNT_ATTR_NOSYMFOLLOW;
138
139 return f;
140 }
141
142 static bool skip_mount_set_attr = false;
143
144 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
145 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
146 int bind_remount_recursive_with_mountinfo(
147 const char *prefix,
148 unsigned long new_flags,
149 unsigned long flags_mask,
150 char **deny_list,
151 FILE *proc_self_mountinfo) {
152
153 _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
154 _cleanup_set_free_ Set *done = NULL;
155 unsigned n_tries = 0;
156 int r;
157
158 assert(prefix);
159
160 if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && strv_isempty(deny_list) && !skip_mount_set_attr) {
161 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
162
163 if (mount_setattr(AT_FDCWD, prefix, AT_SYMLINK_NOFOLLOW|AT_RECURSIVE,
164 &(struct mount_attr) {
165 .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
166 .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
167 }, MOUNT_ATTR_SIZE_VER0) < 0) {
168
169 log_debug_errno(errno, "mount_setattr() failed, falling back to classic remounting: %m");
170
171 /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
172 * also do this for all other kinds of errors since they are so many different, and
173 * mount_setattr() has no graceful mode where it continues despite seeing errors one
174 * some mounts, but we want that. Moreover mount_setattr() only works on the mount
175 * point inode itself, not a non-mount point inode, and we want to support arbitrary
176 * prefixes here. */
177
178 if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
179 skip_mount_set_attr = true;
180 } else
181 return 0; /* Nice, this worked! */
182 }
183
184 if (!proc_self_mountinfo) {
185 r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened);
186 if (r < 0)
187 return r;
188
189 proc_self_mountinfo = proc_self_mountinfo_opened;
190 }
191
192 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
193 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
194 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
195 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
196 * access, too. When mounts are stacked on the same mount point we only care for each individual
197 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
198 * not have any effect on future submounts that might get propagated, they might be writable
199 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
200 * operate atomically here. Mounts established while we process the tree might or might not get
201 * noticed and thus might or might not be covered.
202 *
203 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
204 * remount operation. Note that we'll ignore the deny list for the top-level path. */
205
206 for (;;) {
207 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
208 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
209 _cleanup_hashmap_free_ Hashmap *todo = NULL;
210 bool top_autofs = false;
211
212 if (n_tries++ >= 32) /* Let's not retry this loop forever */
213 return -EBUSY;
214
215 rewind(proc_self_mountinfo);
216
217 r = libmount_parse("/proc/self/mountinfo", proc_self_mountinfo, &table, &iter);
218 if (r < 0)
219 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
220
221 for (;;) {
222 _cleanup_free_ char *d = NULL;
223 const char *path, *type, *opts;
224 unsigned long flags = 0;
225 struct libmnt_fs *fs;
226
227 r = mnt_table_next_fs(table, iter, &fs);
228 if (r == 1) /* EOF */
229 break;
230 if (r < 0)
231 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
232
233 path = mnt_fs_get_target(fs);
234 if (!path)
235 continue;
236
237 if (!path_startswith(path, prefix))
238 continue;
239
240 type = mnt_fs_get_fstype(fs);
241 if (!type)
242 continue;
243
244 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
245 * triggering them, as we don't make any guarantees for future submounts anyway. If
246 * they are already triggered, then we will find another entry for this. */
247 if (streq(type, "autofs")) {
248 top_autofs = top_autofs || path_equal(path, prefix);
249 continue;
250 }
251
252 if (set_contains(done, path))
253 continue;
254
255 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
256 * we shall operate on. */
257 if (!path_equal(path, prefix)) {
258 bool deny_listed = false;
259
260 STRV_FOREACH(i, deny_list) {
261 if (path_equal(*i, prefix))
262 continue;
263
264 if (!path_startswith(*i, prefix))
265 continue;
266
267 if (path_startswith(path, *i)) {
268 deny_listed = true;
269 log_trace("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
270 break;
271 }
272 }
273
274 if (deny_listed)
275 continue;
276 }
277
278 opts = mnt_fs_get_vfs_options(fs);
279 if (opts) {
280 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
281 if (r < 0)
282 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
283 }
284
285 d = strdup(path);
286 if (!d)
287 return -ENOMEM;
288
289 r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
290 if (r == -EEXIST)
291 /* If the same path was recorded, but with different mount flags, update it:
292 * it means a mount point is overmounted, and libmount returns the "bottom" (or
293 * older one) first, but we want to reapply the flags from the "top" (or newer
294 * one). See: https://github.com/systemd/systemd/issues/20032
295 * Note that this shouldn't really fail, as we were just told that the key
296 * exists, and it's an update so we want 'd' to be freed immediately. */
297 r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
298 if (r < 0)
299 return r;
300 if (r > 0)
301 TAKE_PTR(d);
302 }
303
304 /* Check if the top-level directory was among what we have seen so far. For that check both
305 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
306 * not include it in either set but will set this bool. */
307 if (!set_contains(done, prefix) &&
308 !(top_autofs || hashmap_contains(todo, prefix))) {
309
310 /* The prefix directory itself is not yet a mount, make it one. */
311 r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
312 if (r < 0)
313 return r;
314
315 /* Immediately rescan, so that we pick up the new mount's flags */
316 continue;
317 }
318
319 /* If we have no submounts to process anymore, we are done */
320 if (hashmap_isempty(todo))
321 return 0;
322
323 for (;;) {
324 unsigned long flags;
325 char *x = NULL;
326
327 /* Take the first mount from our list of mounts to still process */
328 flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
329 if (!x)
330 break;
331
332 r = set_ensure_consume(&done, &path_hash_ops_free, x);
333 if (IN_SET(r, 0, -EEXIST))
334 continue; /* Already done */
335 if (r < 0)
336 return r;
337
338 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
339 * the default anyway, thus redundant, and in userns we'll get an error if we try to
340 * explicitly enable it) */
341 r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
342 if (r < 0) {
343 int q;
344
345 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
346 * almost all cases (there are simply so many reasons why this can fail,
347 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
348 * the very least. */
349
350 q = path_is_mount_point(x);
351 if (IN_SET(q, 0, -ENOENT)) {
352 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
353 * it is either obstructed by a later mount or somebody has been
354 * racing against us and removed it. Either way the mount point
355 * doesn't matter to us, let's ignore it hence. */
356 log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
357 continue;
358 }
359 if (q < 0) /* Any other error on this? Just log and continue */
360 log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
361
362 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
363 log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
364 continue;
365 }
366
367 /* Make this fatal if this is the top-level mount */
368 if (path_equal(x, prefix))
369 return r;
370
371 /* If this is not the top-level mount, then handle this gracefully: log but
372 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
373 * this might fail without a chance for us to do anything about it, let's
374 * hence be strict on the top-level mount and lenient on the inner ones. */
375 log_debug_errno(r, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x);
376 continue;
377 }
378
379 log_trace("Remounted %s.", x);
380 }
381 }
382 }
383
384 int bind_remount_one_with_mountinfo(
385 const char *path,
386 unsigned long new_flags,
387 unsigned long flags_mask,
388 FILE *proc_self_mountinfo) {
389
390 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
391 unsigned long flags = 0;
392 struct libmnt_fs *fs;
393 const char *opts;
394 int r;
395
396 assert(path);
397 assert(proc_self_mountinfo);
398
399 if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && !skip_mount_set_attr) {
400 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
401
402 if (mount_setattr(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW,
403 &(struct mount_attr) {
404 .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
405 .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
406 }, MOUNT_ATTR_SIZE_VER0) < 0) {
407
408 log_debug_errno(errno, "mount_setattr() didn't work, falling back to classic remounting: %m");
409
410 if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
411 skip_mount_set_attr = true;
412 } else
413 return 0; /* Nice, this worked! */
414 }
415
416 rewind(proc_self_mountinfo);
417
418 table = mnt_new_table();
419 if (!table)
420 return -ENOMEM;
421
422 r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
423 if (r < 0)
424 return r;
425
426 fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
427 if (!fs) {
428 if (laccess(path, F_OK) < 0) /* Hmm, it's not in the mount table, but does it exist at all? */
429 return -errno;
430
431 return -EINVAL; /* Not a mount point we recognize */
432 }
433
434 opts = mnt_fs_get_vfs_options(fs);
435 if (opts) {
436 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
437 if (r < 0)
438 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
439 }
440
441 r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
442 if (r < 0) {
443 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
444 * since kernel adds it in
445 * everywhere, because it's the
446 * default. */
447 return r;
448
449 /* Let's handle redundant remounts gracefully */
450 log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
451 }
452
453 return 0;
454 }
455
456 int bind_remount_one(const char *path, unsigned long new_flags, unsigned long flags_mask) {
457 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
458
459 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
460 if (!proc_self_mountinfo)
461 return log_debug_errno(errno, "Failed to open /proc/self/mountinfo: %m");
462
463 return bind_remount_one_with_mountinfo(path, new_flags, flags_mask, proc_self_mountinfo);
464 }
465
466 static int mount_switch_root_pivot(int fd_newroot, const char *path) {
467 assert(fd_newroot >= 0);
468 assert(path);
469
470 /* Let the kernel tuck the new root under the old one. */
471 if (pivot_root(".", ".") < 0)
472 return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
473
474 /* Get rid of the old root and reveal our brand new root. (This will always operate on the top-most
475 * mount on our cwd, regardless what our current directory actually points to.) */
476 if (umount2(".", MNT_DETACH) < 0)
477 return log_debug_errno(errno, "Failed to unmount old rootfs: %m");
478
479 return 0;
480 }
481
482 static int mount_switch_root_move(int fd_newroot, const char *path) {
483 assert(fd_newroot >= 0);
484 assert(path);
485
486 /* Move the new root fs */
487 if (mount(".", "/", NULL, MS_MOVE, NULL) < 0)
488 return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
489
490 /* Also change root dir */
491 if (chroot(".") < 0)
492 return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
493
494 return 0;
495 }
496
497 int mount_switch_root_full(const char *path, unsigned long mount_propagation_flag, bool force_ms_move) {
498 _cleanup_close_ int fd_newroot = -EBADF;
499 int r, is_current_root;
500
501 assert(path);
502 assert(mount_propagation_flag_is_valid(mount_propagation_flag));
503
504 fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
505 if (fd_newroot < 0)
506 return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
507
508 is_current_root = path_is_root_at(fd_newroot, NULL);
509 if (is_current_root < 0)
510 return log_debug_errno(is_current_root, "Failed to determine if target dir is our root already: %m");
511
512 /* Change into the new rootfs. */
513 if (fchdir(fd_newroot) < 0)
514 return log_debug_errno(errno, "Failed to chdir into new rootfs '%s': %m", path);
515
516 /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
517 * and MS_MOVE don't like that. */
518 if (!is_current_root) {
519 if (!force_ms_move) {
520 r = mount_switch_root_pivot(fd_newroot, path);
521 if (r < 0) {
522 log_debug_errno(r, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path);
523 force_ms_move = true;
524 }
525 }
526 if (force_ms_move) {
527 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
528 * an initramfs in which case pivot_root() isn't supported. */
529 r = mount_switch_root_move(fd_newroot, path);
530 if (r < 0)
531 return log_debug_errno(r, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path);
532 }
533 }
534
535 /* Finally, let's establish the requested propagation flags. */
536 if (mount_propagation_flag == 0)
537 return 0;
538
539 if (mount(NULL, ".", NULL, mount_propagation_flag | MS_REC, 0) < 0)
540 return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
541 mount_propagation_flag_to_string(mount_propagation_flag), path);
542
543 return 0;
544 }
545
546 int repeat_unmount(const char *path, int flags) {
547 bool done = false;
548
549 assert(path);
550
551 /* If there are multiple mounts on a mount point, this
552 * removes them all */
553
554 for (;;) {
555 if (umount2(path, flags) < 0) {
556
557 if (errno == EINVAL)
558 return done;
559
560 return -errno;
561 }
562
563 done = true;
564 }
565 }
566
567 int mode_to_inaccessible_node(
568 const char *runtime_dir,
569 mode_t mode,
570 char **ret) {
571
572 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
573 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
574 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
575 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
576 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
577 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
578 * file nodes, and that's the most important thing that matters.
579 *
580 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
581 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
582
583 _cleanup_free_ char *d = NULL;
584 const char *node;
585
586 assert(ret);
587
588 if (!runtime_dir)
589 runtime_dir = "/run";
590
591 if (S_ISLNK(mode))
592 return -EINVAL;
593
594 node = inode_type_to_string(mode);
595 if (!node)
596 return -EINVAL;
597
598 d = path_join(runtime_dir, "systemd/inaccessible", node);
599 if (!d)
600 return -ENOMEM;
601
602 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
603 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
604 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
605 * inaccessible block device node let's see if the block device node actually exists, and if not,
606 * fall back to the character device node. From there fall back to the socket device node. This means
607 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
608 * device node at all. */
609
610 if (S_ISBLK(mode) &&
611 access(d, F_OK) < 0 && errno == ENOENT) {
612 free(d);
613 d = path_join(runtime_dir, "/systemd/inaccessible/chr");
614 if (!d)
615 return -ENOMEM;
616 }
617
618 if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
619 access(d, F_OK) < 0 && errno == ENOENT) {
620 free(d);
621 d = path_join(runtime_dir, "/systemd/inaccessible/sock");
622 if (!d)
623 return -ENOMEM;
624 }
625
626 *ret = TAKE_PTR(d);
627 return 0;
628 }
629
630 int mount_flags_to_string(unsigned long flags, char **ret) {
631 static const struct {
632 unsigned long flag;
633 const char *name;
634 } map[] = {
635 { .flag = MS_RDONLY, .name = "MS_RDONLY", },
636 { .flag = MS_NOSUID, .name = "MS_NOSUID", },
637 { .flag = MS_NODEV, .name = "MS_NODEV", },
638 { .flag = MS_NOEXEC, .name = "MS_NOEXEC", },
639 { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
640 { .flag = MS_REMOUNT, .name = "MS_REMOUNT", },
641 { .flag = MS_MANDLOCK, .name = "MS_MANDLOCK", },
642 { .flag = MS_DIRSYNC, .name = "MS_DIRSYNC", },
643 { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
644 { .flag = MS_NOATIME, .name = "MS_NOATIME", },
645 { .flag = MS_NODIRATIME, .name = "MS_NODIRATIME", },
646 { .flag = MS_BIND, .name = "MS_BIND", },
647 { .flag = MS_MOVE, .name = "MS_MOVE", },
648 { .flag = MS_REC, .name = "MS_REC", },
649 { .flag = MS_SILENT, .name = "MS_SILENT", },
650 { .flag = MS_POSIXACL, .name = "MS_POSIXACL", },
651 { .flag = MS_UNBINDABLE, .name = "MS_UNBINDABLE", },
652 { .flag = MS_PRIVATE, .name = "MS_PRIVATE", },
653 { .flag = MS_SLAVE, .name = "MS_SLAVE", },
654 { .flag = MS_SHARED, .name = "MS_SHARED", },
655 { .flag = MS_RELATIME, .name = "MS_RELATIME", },
656 { .flag = MS_KERNMOUNT, .name = "MS_KERNMOUNT", },
657 { .flag = MS_I_VERSION, .name = "MS_I_VERSION", },
658 { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
659 { .flag = MS_LAZYTIME, .name = "MS_LAZYTIME", },
660 };
661 _cleanup_free_ char *str = NULL;
662
663 assert(ret);
664
665 for (size_t i = 0; i < ELEMENTSOF(map); i++)
666 if (flags & map[i].flag) {
667 if (!strextend_with_separator(&str, "|", map[i].name))
668 return -ENOMEM;
669 flags &= ~map[i].flag;
670 }
671
672 if (!str || flags != 0)
673 if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
674 return -ENOMEM;
675
676 *ret = TAKE_PTR(str);
677 return 0;
678 }
679
680 int mount_verbose_full(
681 int error_log_level,
682 const char *what,
683 const char *where,
684 const char *type,
685 unsigned long flags,
686 const char *options,
687 bool follow_symlink) {
688
689 _cleanup_free_ char *fl = NULL, *o = NULL;
690 unsigned long f;
691 int r;
692
693 r = mount_option_mangle(options, flags, &f, &o);
694 if (r < 0)
695 return log_full_errno(error_log_level, r,
696 "Failed to mangle mount options %s: %m",
697 strempty(options));
698
699 (void) mount_flags_to_string(f, &fl);
700
701 if (FLAGS_SET(f, MS_REMOUNT|MS_BIND))
702 log_debug("Changing mount flags %s (%s \"%s\")...",
703 where, strnull(fl), strempty(o));
704 else if (f & MS_REMOUNT)
705 log_debug("Remounting superblock %s (%s \"%s\")...",
706 where, strnull(fl), strempty(o));
707 else if (f & (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE))
708 log_debug("Changing mount propagation %s (%s \"%s\")",
709 where, strnull(fl), strempty(o));
710 else if (f & MS_BIND)
711 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
712 what, where, strnull(fl), strempty(o));
713 else if (f & MS_MOVE)
714 log_debug("Moving mount %s %s %s (%s \"%s\")...",
715 what, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
716 else
717 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
718 strna(what), strna(type), where, strnull(fl), strempty(o));
719
720 if (follow_symlink)
721 r = RET_NERRNO(mount(what, where, type, f, o));
722 else
723 r = mount_nofollow(what, where, type, f, o);
724 if (r < 0)
725 return log_full_errno(error_log_level, r,
726 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
727 strna(what), strna(type), where, strnull(fl), strempty(o));
728 return 0;
729 }
730
731 int umount_verbose(
732 int error_log_level,
733 const char *what,
734 int flags) {
735
736 assert(what);
737
738 log_debug("Umounting %s...", what);
739
740 if (umount2(what, flags) < 0)
741 return log_full_errno(error_log_level, errno,
742 "Failed to unmount %s: %m", what);
743
744 return 0;
745 }
746
747 int mount_exchange_graceful(int fsmount_fd, const char *dest, bool mount_beneath) {
748 int r;
749
750 assert(fsmount_fd >= 0);
751 assert(dest);
752
753 /* First, try to mount beneath an existing mount point, and if that works, umount the old mount,
754 * which is now at the top. This will ensure we can atomically replace a mount. Note that this works
755 * also in the case where there are submounts down the tree. Mount propagation is allowed but
756 * restricted to layouts that don't end up propagation the new mount on top of the mount stack. If
757 * this is not supported (minimum kernel v6.5), or if there is no mount on the mountpoint, we get
758 * -EINVAL and then we fallback to normal mounting. */
759
760 r = RET_NERRNO(move_mount(
761 fsmount_fd,
762 /* from_path= */ "",
763 /* to_fd= */ -EBADF,
764 dest,
765 MOVE_MOUNT_F_EMPTY_PATH | (mount_beneath ? MOVE_MOUNT_BENEATH : 0)));
766 if (mount_beneath) {
767 if (r == -EINVAL) { /* Fallback if mount_beneath is not supported */
768 log_debug_errno(r,
769 "Failed to mount beneath '%s', falling back to overmount",
770 dest);
771 return RET_NERRNO(move_mount(
772 fsmount_fd,
773 /* from_path= */ "",
774 /* to_fd= */ -EBADF,
775 dest,
776 MOVE_MOUNT_F_EMPTY_PATH));
777 }
778
779 if (r >= 0) /* If it is, now remove the old mount */
780 return umount_verbose(LOG_DEBUG, dest, UMOUNT_NOFOLLOW|MNT_DETACH);
781 }
782
783 return r;
784 }
785
786 int mount_option_mangle(
787 const char *options,
788 unsigned long mount_flags,
789 unsigned long *ret_mount_flags,
790 char **ret_remaining_options) {
791
792 const struct libmnt_optmap *map;
793 _cleanup_free_ char *ret = NULL;
794 int r;
795
796 /* This extracts mount flags from the mount options, and stores
797 * non-mount-flag options to '*ret_remaining_options'.
798 * E.g.,
799 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
800 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
801 * "size=1630748k,mode=0700,uid=1000,gid=1000".
802 * See more examples in test-mount-util.c.
803 *
804 * If 'options' does not contain any non-mount-flag options,
805 * then '*ret_remaining_options' is set to NULL instead of empty string.
806 * The validity of options stored in '*ret_remaining_options' is not checked.
807 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
808
809 assert(ret_mount_flags);
810 assert(ret_remaining_options);
811
812 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
813 if (!map)
814 return -EINVAL;
815
816 for (const char *p = options;;) {
817 _cleanup_free_ char *word = NULL;
818 const struct libmnt_optmap *ent;
819
820 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
821 if (r < 0)
822 return r;
823 if (r == 0)
824 break;
825
826 for (ent = map; ent->name; ent++) {
827 /* All entries in MNT_LINUX_MAP do not take any argument.
828 * Thus, ent->name does not contain "=" or "[=]". */
829 if (!streq(word, ent->name))
830 continue;
831
832 if (!(ent->mask & MNT_INVERT))
833 mount_flags |= ent->id;
834 else
835 mount_flags &= ~ent->id;
836
837 break;
838 }
839
840 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
841 if (!ent->name &&
842 !startswith_no_case(word, "x-") &&
843 !strextend_with_separator(&ret, ",", word))
844 return -ENOMEM;
845 }
846
847 *ret_mount_flags = mount_flags;
848 *ret_remaining_options = TAKE_PTR(ret);
849
850 return 0;
851 }
852
853 static int mount_in_namespace_legacy(
854 const char *chased_src_path,
855 int chased_src_fd,
856 struct stat *chased_src_st,
857 const char *propagate_path,
858 const char *incoming_path,
859 const char *dest,
860 int pidns_fd,
861 int mntns_fd,
862 int root_fd,
863 bool read_only,
864 bool make_file_or_directory,
865 const MountOptions *options,
866 const ImagePolicy *image_policy,
867 bool is_image) {
868
869 _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
870 char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
871 bool mount_slave_created = false, mount_slave_mounted = false,
872 mount_tmp_created = false, mount_tmp_mounted = false,
873 mount_outside_created = false, mount_outside_mounted = false;
874 pid_t child;
875 int r;
876
877 assert(chased_src_path);
878 assert(chased_src_fd >= 0);
879 assert(chased_src_st);
880 assert(propagate_path);
881 assert(incoming_path);
882 assert(dest);
883 assert(pidns_fd >= 0);
884 assert(mntns_fd >= 0);
885 assert(root_fd >= 0);
886 assert(!options || is_image);
887
888 p = strjoina(propagate_path, "/");
889 r = laccess(p, F_OK);
890 if (r < 0)
891 return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
892
893 /* Our goal is to install a new bind mount into the container,
894 possibly read-only. This is irritatingly complex
895 unfortunately, currently.
896
897 First, we start by creating a private playground in /tmp,
898 that we can mount MS_SLAVE. (Which is necessary, since
899 MS_MOVE cannot be applied to mounts with MS_SHARED parent
900 mounts.) */
901
902 if (!mkdtemp(mount_slave))
903 return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
904
905 mount_slave_created = true;
906
907 r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
908 if (r < 0)
909 goto finish;
910
911 mount_slave_mounted = true;
912
913 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
914 if (r < 0)
915 goto finish;
916
917 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
918 mount_tmp = strjoina(mount_slave, "/mount");
919 if (is_image)
920 r = mkdir_p(mount_tmp, 0700);
921 else
922 r = make_mount_point_inode_from_stat(chased_src_st, mount_tmp, 0700);
923 if (r < 0) {
924 log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
925 goto finish;
926 }
927
928 mount_tmp_created = true;
929
930 if (is_image)
931 r = verity_dissect_and_mount(
932 chased_src_fd,
933 chased_src_path,
934 mount_tmp,
935 options,
936 image_policy,
937 /* required_host_os_release_id= */ NULL,
938 /* required_host_os_release_version_id= */ NULL,
939 /* required_host_os_release_sysext_level= */ NULL,
940 /* required_host_os_release_confext_level= */ NULL,
941 /* required_sysext_scope= */ NULL,
942 /* ret_image= */ NULL);
943 else
944 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
945 if (r < 0)
946 goto finish;
947
948 mount_tmp_mounted = true;
949
950 /* Third, we remount the new bind mount read-only if requested. */
951 if (read_only) {
952 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
953 if (r < 0)
954 goto finish;
955 }
956
957 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
958 * right-away. */
959
960 mount_outside = strjoina(propagate_path, "/XXXXXX");
961 if (is_image || S_ISDIR(chased_src_st->st_mode))
962 r = mkdtemp(mount_outside) ? 0 : -errno;
963 else {
964 r = mkostemp_safe(mount_outside);
965 safe_close(r);
966 }
967 if (r < 0) {
968 log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
969 goto finish;
970 }
971
972 mount_outside_created = true;
973
974 r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
975 if (r < 0)
976 goto finish;
977
978 mount_outside_mounted = true;
979 mount_tmp_mounted = false;
980
981 if (is_image || S_ISDIR(chased_src_st->st_mode))
982 (void) rmdir(mount_tmp);
983 else
984 (void) unlink(mount_tmp);
985 mount_tmp_created = false;
986
987 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
988 mount_slave_mounted = false;
989
990 (void) rmdir(mount_slave);
991 mount_slave_created = false;
992
993 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
994 log_debug_errno(errno, "Failed to create pipe: %m");
995 goto finish;
996 }
997
998 r = namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
999 pidns_fd, mntns_fd, -1, -1, root_fd, &child);
1000 if (r < 0)
1001 goto finish;
1002 if (r == 0) {
1003 _cleanup_free_ char *mount_outside_fn = NULL, *mount_inside = NULL;
1004
1005 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
1006
1007 if (make_file_or_directory) {
1008 if (!is_image) {
1009 (void) mkdir_parents(dest, 0755);
1010 (void) make_mount_point_inode_from_stat(chased_src_st, dest, 0700);
1011 } else
1012 (void) mkdir_p(dest, 0755);
1013 }
1014
1015 /* Fifth, move the mount to the right place inside */
1016 r = path_extract_filename(mount_outside, &mount_outside_fn);
1017 if (r < 0) {
1018 log_debug_errno(r, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside);
1019 goto child_fail;
1020 }
1021
1022 mount_inside = path_join(incoming_path, mount_outside_fn);
1023 if (!mount_inside) {
1024 r = log_oom_debug();
1025 goto child_fail;
1026 }
1027
1028 r = mount_nofollow_verbose(LOG_DEBUG, mount_inside, dest, NULL, MS_MOVE, NULL);
1029 if (r < 0)
1030 goto child_fail;
1031
1032 _exit(EXIT_SUCCESS);
1033
1034 child_fail:
1035 (void) write(errno_pipe_fd[1], &r, sizeof(r));
1036 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1037
1038 _exit(EXIT_FAILURE);
1039 }
1040
1041 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1042
1043 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
1044 if (r < 0) {
1045 log_debug_errno(r, "Failed to wait for child: %m");
1046 goto finish;
1047 }
1048 if (r != EXIT_SUCCESS) {
1049 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
1050 log_debug_errno(r, "Failed to mount: %m");
1051 else
1052 log_debug("Child failed.");
1053 goto finish;
1054 }
1055
1056 finish:
1057 if (mount_outside_mounted)
1058 (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
1059 if (mount_outside_created) {
1060 if (is_image || S_ISDIR(chased_src_st->st_mode))
1061 (void) rmdir(mount_outside);
1062 else
1063 (void) unlink(mount_outside);
1064 }
1065
1066 if (mount_tmp_mounted)
1067 (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
1068 if (mount_tmp_created) {
1069 if (is_image || S_ISDIR(chased_src_st->st_mode))
1070 (void) rmdir(mount_tmp);
1071 else
1072 (void) unlink(mount_tmp);
1073 }
1074
1075 if (mount_slave_mounted)
1076 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
1077 if (mount_slave_created)
1078 (void) rmdir(mount_slave);
1079
1080 return r;
1081 }
1082
1083 static int mount_in_namespace(
1084 const PidRef *target,
1085 const char *propagate_path,
1086 const char *incoming_path,
1087 const char *src,
1088 const char *dest,
1089 bool read_only,
1090 bool make_file_or_directory,
1091 const MountOptions *options,
1092 const ImagePolicy *image_policy,
1093 bool is_image) {
1094
1095 _cleanup_(dissected_image_unrefp) DissectedImage *img = NULL;
1096 _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
1097 _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF,
1098 new_mount_fd = -EBADF;
1099 _cleanup_free_ char *chased_src_path = NULL;
1100 struct stat st;
1101 pid_t child;
1102 int r;
1103
1104 assert(propagate_path);
1105 assert(incoming_path);
1106 assert(src);
1107 assert(dest);
1108 assert(!options || is_image);
1109
1110 if (!pidref_is_set(target))
1111 return -ESRCH;
1112
1113 r = namespace_open(target->pid, &pidns_fd, &mntns_fd, /* ret_netns_fd = */ NULL, /* ret_userns_fd = */ NULL, &root_fd);
1114 if (r < 0)
1115 return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
1116
1117 r = in_same_namespace(target->pid, 0, NAMESPACE_MOUNT);
1118 if (r < 0)
1119 return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
1120 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1121 if (r > 0)
1122 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace");
1123
1124 r = pidref_verify(target);
1125 if (r < 0)
1126 return log_debug_errno(r, "Failed to verify target process '" PID_FMT "': %m", target->pid);
1127
1128 r = chase(src, NULL, 0, &chased_src_path, &chased_src_fd);
1129 if (r < 0)
1130 return log_debug_errno(r, "Failed to resolve source path of %s: %m", src);
1131 log_debug("Chased source path of %s to %s", src, chased_src_path);
1132
1133 if (fstat(chased_src_fd, &st) < 0)
1134 return log_debug_errno(errno, "Failed to stat() resolved source path %s: %m", src);
1135 if (S_ISLNK(st.st_mode)) /* This shouldn't really happen, given that we just chased the symlinks above, but let's better be safe… */
1136 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Source directory %s can't be a symbolic link", src);
1137
1138 if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
1139 return mount_in_namespace_legacy(
1140 chased_src_path,
1141 chased_src_fd,
1142 &st,
1143 propagate_path,
1144 incoming_path,
1145 dest,
1146 pidns_fd,
1147 mntns_fd,
1148 root_fd,
1149 read_only,
1150 make_file_or_directory,
1151 options,
1152 image_policy,
1153 is_image);
1154
1155 if (is_image) {
1156 r = verity_dissect_and_mount(
1157 chased_src_fd,
1158 chased_src_path,
1159 /* dest= */ NULL,
1160 options,
1161 image_policy,
1162 /* required_host_os_release_id= */ NULL,
1163 /* required_host_os_release_version_id= */ NULL,
1164 /* required_host_os_release_sysext_level= */ NULL,
1165 /* required_host_os_release_confext_level= */ NULL,
1166 /* required_sysext_scope= */ NULL,
1167 &img);
1168 if (r < 0)
1169 return log_debug_errno(
1170 r,
1171 "Failed to dissect and mount image %s: %m",
1172 chased_src_path);
1173 } else {
1174 new_mount_fd = open_tree(
1175 chased_src_fd,
1176 "",
1177 OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
1178 if (new_mount_fd < 0)
1179 return log_debug_errno(
1180 errno,
1181 "Failed to open mount point \"%s\": %m",
1182 chased_src_path);
1183
1184 if (read_only && mount_setattr(new_mount_fd, "", AT_EMPTY_PATH,
1185 &(struct mount_attr) {
1186 .attr_set = MOUNT_ATTR_RDONLY,
1187 }, MOUNT_ATTR_SIZE_VER0) < 0)
1188 return log_debug_errno(
1189 errno,
1190 "Failed to set mount flags for \"%s\": %m",
1191 chased_src_path);
1192 }
1193
1194 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0)
1195 return log_debug_errno(errno, "Failed to create pipe: %m");
1196
1197 r = namespace_fork("(sd-bindmnt)",
1198 "(sd-bindmnt-inner)",
1199 /* except_fds= */ NULL,
1200 /* n_except_fds= */ 0,
1201 FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1202 pidns_fd,
1203 mntns_fd,
1204 /* netns_fd= */ -1,
1205 /* userns_fd= */ -1,
1206 root_fd,
1207 &child);
1208 if (r < 0)
1209 return log_debug_errno(r, "Failed to fork off: %m");
1210 if (r == 0) {
1211 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
1212
1213 if (make_file_or_directory)
1214 (void) mkdir_parents(dest, 0755);
1215
1216 if (img) {
1217 DissectImageFlags f =
1218 DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE |
1219 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
1220
1221 if (make_file_or_directory)
1222 f |= DISSECT_IMAGE_MKDIR;
1223
1224 if (read_only)
1225 f |= DISSECT_IMAGE_READ_ONLY;
1226
1227 r = dissected_image_mount(
1228 img,
1229 dest,
1230 /* uid_shift= */ UID_INVALID,
1231 /* uid_range= */ UID_INVALID,
1232 /* userns_fd= */ -EBADF,
1233 f);
1234 } else {
1235 if (make_file_or_directory)
1236 (void) make_mount_point_inode_from_stat(&st, dest, 0700);
1237
1238 r = mount_exchange_graceful(new_mount_fd, dest, /* mount_beneath= */ true);
1239 }
1240 if (r < 0) {
1241 (void) write(errno_pipe_fd[1], &r, sizeof(r));
1242 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1243
1244 _exit(EXIT_FAILURE);
1245 }
1246
1247 _exit(EXIT_SUCCESS);
1248 }
1249
1250 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1251
1252 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
1253 if (r < 0)
1254 return log_debug_errno(r, "Failed to wait for child: %m");
1255 if (r != EXIT_SUCCESS) {
1256 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
1257 return log_debug_errno(r, "Failed to mount: %m");
1258
1259 return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Child failed.");
1260 }
1261
1262 return 0;
1263 }
1264
1265 int bind_mount_in_namespace(
1266 PidRef * target,
1267 const char *propagate_path,
1268 const char *incoming_path,
1269 const char *src,
1270 const char *dest,
1271 bool read_only,
1272 bool make_file_or_directory) {
1273
1274 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, /* options= */ NULL, /* image_policy= */ NULL, /* is_image= */ false);
1275 }
1276
1277 int mount_image_in_namespace(
1278 PidRef * target,
1279 const char *propagate_path,
1280 const char *incoming_path,
1281 const char *src,
1282 const char *dest,
1283 bool read_only,
1284 bool make_file_or_directory,
1285 const MountOptions *options,
1286 const ImagePolicy *image_policy) {
1287
1288 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, options, image_policy, /* is_image=*/ true);
1289 }
1290
1291 int make_mount_point(const char *path) {
1292 int r;
1293
1294 assert(path);
1295
1296 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1297
1298 r = path_is_mount_point(path);
1299 if (r < 0)
1300 return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
1301 if (r > 0)
1302 return 0;
1303
1304 r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
1305 if (r < 0)
1306 return r;
1307
1308 return 1;
1309 }
1310
1311 int fd_make_mount_point(int fd) {
1312 int r;
1313
1314 assert(fd >= 0);
1315
1316 r = fd_is_mount_point(fd, NULL, 0);
1317 if (r < 0)
1318 return log_debug_errno(r, "Failed to determine whether file descriptor is a mount point: %m");
1319 if (r > 0)
1320 return 0;
1321
1322 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(fd), FORMAT_PROC_FD_PATH(fd), NULL, MS_BIND|MS_REC, NULL);
1323 if (r < 0)
1324 return r;
1325
1326 return 1;
1327 }
1328
1329 int make_userns(uid_t uid_shift, uid_t uid_range, uid_t source_owner, uid_t dest_owner, RemountIdmapping idmapping) {
1330 _cleanup_close_ int userns_fd = -EBADF;
1331 _cleanup_free_ char *line = NULL;
1332
1333 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1334 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1335
1336 if (!userns_shift_range_valid(uid_shift, uid_range))
1337 return -EINVAL;
1338
1339 if (IN_SET(idmapping, REMOUNT_IDMAPPING_NONE, REMOUNT_IDMAPPING_HOST_ROOT)) {
1340 if (asprintf(&line, UID_FMT " " UID_FMT " " UID_FMT "\n", 0u, uid_shift, uid_range) < 0)
1341 return log_oom_debug();
1342
1343 /* If requested we'll include an entry in the mapping so that the host root user can make
1344 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1345 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1346 * to create various missing inodes in the OS tree before booting into it, and this becomes
1347 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1348 * that in that case the container's runtime uidmap (i.e. the one the container payload
1349 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1350 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1351 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1352 * to the container's own UID range, but it's good to have a safety net, in case we
1353 * forget it.) */
1354 if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
1355 if (strextendf(&line,
1356 UID_FMT " " UID_FMT " " UID_FMT "\n",
1357 UID_MAPPED_ROOT, 0u, 1u) < 0)
1358 return log_oom_debug();
1359 }
1360
1361 if (idmapping == REMOUNT_IDMAPPING_HOST_OWNER) {
1362 /* Remap the owner of the bind mounted directory to the root user within the container. This
1363 * way every file written by root within the container to the bind-mounted directory will
1364 * be owned by the original user from the host. All other users will remain unmapped. */
1365 if (asprintf(&line, UID_FMT " " UID_FMT " " UID_FMT "\n", source_owner, uid_shift, 1u) < 0)
1366 return log_oom_debug();
1367 }
1368
1369 if (idmapping == REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER) {
1370 /* Remap the owner of the bind mounted directory to the owner of the target directory
1371 * within the container. This way every file written by target directory owner within the
1372 * container to the bind-mounted directory will be owned by the original host user.
1373 * All other users will remain unmapped. */
1374 if (asprintf(
1375 &line,
1376 UID_FMT " " UID_FMT " " UID_FMT "\n",
1377 source_owner, dest_owner, 1u) < 0)
1378 return log_oom_debug();
1379 }
1380
1381 /* We always assign the same UID and GID ranges */
1382 userns_fd = userns_acquire(line, line);
1383 if (userns_fd < 0)
1384 return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
1385
1386 return TAKE_FD(userns_fd);
1387 }
1388
1389 int remount_idmap_fd(
1390 char **paths,
1391 int userns_fd) {
1392
1393 int r;
1394
1395 assert(userns_fd >= 0);
1396
1397 /* This remounts all specified paths with the specified userns as idmap. It will do so in in the
1398 * order specified in the strv: the expectation is that the top-level directories are at the
1399 * beginning, and nested directories in the right, so that the tree can be built correctly from left
1400 * to right. */
1401
1402 size_t n = strv_length(paths);
1403 if (n == 0) /* Nothing to do? */
1404 return 0;
1405
1406 int *mount_fds = NULL;
1407 size_t n_mounts_fds = 0;
1408
1409 mount_fds = new(int, n);
1410 if (!mount_fds)
1411 return log_oom_debug();
1412
1413 CLEANUP_ARRAY(mount_fds, n_mounts_fds, close_many_and_free);
1414
1415 for (size_t i = 0; i < n; i++) {
1416 int mntfd;
1417
1418 /* Clone the mount point */
1419 mntfd = mount_fds[n_mounts_fds] = open_tree(-EBADF, paths[i], OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
1420 if (mount_fds[n_mounts_fds] < 0)
1421 return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", paths[i]);
1422
1423 n_mounts_fds++;
1424
1425 /* Set the user namespace mapping attribute on the cloned mount point */
1426 if (mount_setattr(mntfd, "", AT_EMPTY_PATH,
1427 &(struct mount_attr) {
1428 .attr_set = MOUNT_ATTR_IDMAP,
1429 .userns_fd = userns_fd,
1430 }, sizeof(struct mount_attr)) < 0)
1431 return log_debug_errno(errno, "Failed to change bind mount attributes for clone of '%s': %m", paths[i]);
1432 }
1433
1434 for (size_t i = n; i > 0; i--) { /* Unmount the paths right-to-left */
1435 /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1436 r = umount_verbose(LOG_DEBUG, paths[i-1], UMOUNT_NOFOLLOW);
1437 if (r < 0)
1438 return r;
1439 }
1440
1441 for (size_t i = 0; i < n; i++) { /* Mount the replacement mounts left-to-right */
1442 /* And place the cloned version in its place */
1443 log_debug("Mounting idmapped fs to '%s'", paths[i]);
1444 if (move_mount(mount_fds[i], "", -EBADF, paths[i], MOVE_MOUNT_F_EMPTY_PATH) < 0)
1445 return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", paths[i]);
1446 }
1447
1448 return 0;
1449 }
1450
1451 int remount_idmap(char **p, uid_t uid_shift, uid_t uid_range, uid_t source_owner, uid_t dest_owner,RemountIdmapping idmapping) {
1452 _cleanup_close_ int userns_fd = -EBADF;
1453
1454 userns_fd = make_userns(uid_shift, uid_range, source_owner, dest_owner, idmapping);
1455 if (userns_fd < 0)
1456 return userns_fd;
1457
1458 return remount_idmap_fd(p, userns_fd);
1459 }
1460
1461 typedef struct SubMount {
1462 char *path;
1463 int mount_fd;
1464 } SubMount;
1465
1466 static void sub_mount_clear(SubMount *s) {
1467 assert(s);
1468
1469 s->path = mfree(s->path);
1470 s->mount_fd = safe_close(s->mount_fd);
1471 }
1472
1473 static void sub_mount_array_free(SubMount *s, size_t n) {
1474 assert(s || n == 0);
1475
1476 for (size_t i = 0; i < n; i++)
1477 sub_mount_clear(s + i);
1478
1479 free(s);
1480 }
1481
1482 static int sub_mount_compare(const SubMount *a, const SubMount *b) {
1483 assert(a);
1484 assert(b);
1485 assert(a->path);
1486 assert(b->path);
1487
1488 return path_compare(a->path, b->path);
1489 }
1490
1491 static void sub_mount_drop(SubMount *s, size_t n) {
1492 assert(s || n == 0);
1493
1494 for (size_t m = 0, i = 1; i < n; i++) {
1495 if (path_startswith(s[i].path, s[m].path))
1496 sub_mount_clear(s + i);
1497 else
1498 m = i;
1499 }
1500 }
1501
1502 static int get_sub_mounts(
1503 const char *prefix,
1504 SubMount **ret_mounts,
1505 size_t *ret_n_mounts) {
1506 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1507 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1508 SubMount *mounts = NULL;
1509 size_t n = 0;
1510 int r;
1511
1512 CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1513
1514 assert(prefix);
1515 assert(ret_mounts);
1516 assert(ret_n_mounts);
1517
1518 r = libmount_parse("/proc/self/mountinfo", NULL, &table, &iter);
1519 if (r < 0)
1520 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
1521
1522 for (;;) {
1523 _cleanup_close_ int mount_fd = -EBADF;
1524 _cleanup_free_ char *p = NULL;
1525 struct libmnt_fs *fs;
1526 const char *path;
1527 int id1, id2;
1528
1529 r = mnt_table_next_fs(table, iter, &fs);
1530 if (r == 1)
1531 break; /* EOF */
1532 if (r < 0)
1533 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
1534
1535 path = mnt_fs_get_target(fs);
1536 if (!path)
1537 continue;
1538
1539 if (isempty(path_startswith(path, prefix)))
1540 continue;
1541
1542 id1 = mnt_fs_get_id(fs);
1543 r = path_get_mnt_id(path, &id2);
1544 if (r < 0) {
1545 log_debug_errno(r, "Failed to get mount ID of '%s', ignoring: %m", path);
1546 continue;
1547 }
1548 if (id1 != id2) {
1549 /* The path may be hidden by another over-mount or already remounted. */
1550 log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
1551 path, id1, id2);
1552 continue;
1553 }
1554
1555 mount_fd = open(path, O_CLOEXEC|O_PATH);
1556 if (mount_fd < 0) {
1557 if (errno == ENOENT) /* The path may be hidden by another over-mount or already unmounted. */
1558 continue;
1559
1560 return log_debug_errno(errno, "Failed to open subtree of mounted filesystem '%s': %m", path);
1561 }
1562
1563 p = strdup(path);
1564 if (!p)
1565 return log_oom_debug();
1566
1567 if (!GREEDY_REALLOC(mounts, n + 1))
1568 return log_oom_debug();
1569
1570 mounts[n++] = (SubMount) {
1571 .path = TAKE_PTR(p),
1572 .mount_fd = TAKE_FD(mount_fd),
1573 };
1574 }
1575
1576 typesafe_qsort(mounts, n, sub_mount_compare);
1577 sub_mount_drop(mounts, n);
1578
1579 *ret_mounts = TAKE_PTR(mounts);
1580 *ret_n_mounts = n;
1581 return 0;
1582 }
1583
1584 int bind_mount_submounts(
1585 const char *source,
1586 const char *target) {
1587
1588 SubMount *mounts = NULL;
1589 size_t n = 0;
1590 int ret = 0, r;
1591
1592 /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
1593 * with new mount options to copy the original submounts over. */
1594
1595 assert(source);
1596 assert(target);
1597
1598 CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1599
1600 r = get_sub_mounts(source, &mounts, &n);
1601 if (r < 0)
1602 return r;
1603
1604 FOREACH_ARRAY(m, mounts, n) {
1605 _cleanup_free_ char *t = NULL;
1606 const char *suffix;
1607
1608 if (isempty(m->path))
1609 continue;
1610
1611 assert_se(suffix = path_startswith(m->path, source));
1612
1613 t = path_join(target, suffix);
1614 if (!t)
1615 return -ENOMEM;
1616
1617 r = path_is_mount_point(t);
1618 if (r < 0) {
1619 log_debug_errno(r, "Failed to detect if '%s' already is a mount point, ignoring: %m", t);
1620 continue;
1621 }
1622 if (r > 0) {
1623 log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix, source, target);
1624 continue;
1625 }
1626
1627 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(m->mount_fd), t, NULL, MS_BIND|MS_REC, NULL);
1628 if (r < 0 && ret == 0)
1629 ret = r;
1630 }
1631
1632 return ret;
1633 }
1634
1635 int make_mount_point_inode_from_stat(const struct stat *st, const char *dest, mode_t mode) {
1636 assert(st);
1637 assert(dest);
1638
1639 if (S_ISDIR(st->st_mode))
1640 return mkdir_label(dest, mode);
1641 else
1642 return RET_NERRNO(mknod(dest, S_IFREG|(mode & ~0111), 0));
1643 }
1644
1645 int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t mode) {
1646 struct stat st;
1647
1648 assert(source);
1649 assert(dest);
1650
1651 if (stat(source, &st) < 0)
1652 return -errno;
1653
1654 return make_mount_point_inode_from_stat(&st, dest, mode);
1655 }
1656
1657 int trigger_automount_at(int dir_fd, const char *path) {
1658 _cleanup_free_ char *nested = NULL;
1659
1660 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1661
1662 nested = path_join(path, "a");
1663 if (!nested)
1664 return -ENOMEM;
1665
1666 (void) faccessat(dir_fd, nested, F_OK, 0);
1667
1668 return 0;
1669 }
1670
1671 unsigned long credentials_fs_mount_flags(bool ro) {
1672 /* A tight set of mount flags for credentials mounts */
1673 return MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported()|(ro ? MS_RDONLY : 0);
1674 }
1675
1676 int mount_credentials_fs(const char *path, size_t size, bool ro) {
1677 _cleanup_free_ char *opts = NULL;
1678 int r, noswap_supported;
1679
1680 /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1681 * beginning, and ideally swapping turned off. In order of preference:
1682 *
1683 * 1. tmpfs if it supports "noswap"
1684 * 2. ramfs
1685 * 3. tmpfs if it doesn't support "noswap"
1686 */
1687
1688 noswap_supported = mount_option_supported("tmpfs", "noswap", NULL); /* Check explicitly to avoid kmsg noise */
1689 if (noswap_supported > 0) {
1690 _cleanup_free_ char *noswap_opts = NULL;
1691
1692 if (asprintf(&noswap_opts, "mode=0700,nr_inodes=1024,size=%zu,noswap", size) < 0)
1693 return -ENOMEM;
1694
1695 /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1696
1697 r = mount_nofollow_verbose(
1698 LOG_DEBUG,
1699 "tmpfs",
1700 path,
1701 "tmpfs",
1702 credentials_fs_mount_flags(ro),
1703 noswap_opts);
1704 if (r >= 0)
1705 return r;
1706 }
1707
1708 r = mount_nofollow_verbose(
1709 LOG_DEBUG,
1710 "ramfs",
1711 path,
1712 "ramfs",
1713 credentials_fs_mount_flags(ro),
1714 "mode=0700");
1715 if (r >= 0)
1716 return r;
1717
1718 if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%zu", size) < 0)
1719 return -ENOMEM;
1720
1721 return mount_nofollow_verbose(
1722 LOG_DEBUG,
1723 "tmpfs",
1724 path,
1725 "tmpfs",
1726 credentials_fs_mount_flags(ro),
1727 opts);
1728 }
1729
1730 int make_fsmount(
1731 int error_log_level,
1732 const char *what,
1733 const char *type,
1734 unsigned long flags,
1735 const char *options,
1736 int userns_fd) {
1737
1738 _cleanup_close_ int fs_fd = -EBADF, mnt_fd = -EBADF;
1739 _cleanup_free_ char *o = NULL;
1740 unsigned long f;
1741 int r;
1742
1743 assert(type);
1744 assert(what);
1745
1746 r = mount_option_mangle(options, flags, &f, &o);
1747 if (r < 0)
1748 return log_full_errno(
1749 error_log_level, r, "Failed to mangle mount options %s: %m",
1750 strempty(options));
1751
1752 if (DEBUG_LOGGING) {
1753 _cleanup_free_ char *fl = NULL;
1754 (void) mount_flags_to_string(f, &fl);
1755
1756 log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
1757 strna(what), strna(type), strnull(fl), strempty(o));
1758 }
1759
1760 fs_fd = fsopen(type, FSOPEN_CLOEXEC);
1761 if (fs_fd < 0)
1762 return log_full_errno(error_log_level, errno, "Failed to open superblock for \"%s\": %m", type);
1763
1764 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "source", what, 0) < 0)
1765 return log_full_errno(error_log_level, errno, "Failed to set mount source for \"%s\" to \"%s\": %m", type, what);
1766
1767 if (FLAGS_SET(f, MS_RDONLY))
1768 if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, "ro", NULL, 0) < 0)
1769 return log_full_errno(error_log_level, errno, "Failed to set read only mount flag for \"%s\": %m", type);
1770
1771 for (const char *p = o;;) {
1772 _cleanup_free_ char *word = NULL;
1773 char *eq;
1774
1775 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
1776 if (r < 0)
1777 return log_full_errno(error_log_level, r, "Failed to parse mount option string \"%s\": %m", o);
1778 if (r == 0)
1779 break;
1780
1781 eq = strchr(word, '=');
1782 if (eq) {
1783 *eq = 0;
1784 eq++;
1785
1786 if (fsconfig(fs_fd, FSCONFIG_SET_STRING, word, eq, 0) < 0)
1787 return log_full_errno(error_log_level, errno, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word, eq, type);
1788 } else {
1789 if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, word, NULL, 0) < 0)
1790 return log_full_errno(error_log_level, errno, "Failed to set mount flag \"%s\" for \"%s\": %m", word, type);
1791 }
1792 }
1793
1794 if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
1795 return log_full_errno(error_log_level, errno, "Failed to realize fs fd for \"%s\" (\"%s\"): %m", what, type);
1796
1797 mnt_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0);
1798 if (mnt_fd < 0)
1799 return log_full_errno(error_log_level, errno, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what, type);
1800
1801 if (mount_setattr(mnt_fd, "", AT_EMPTY_PATH|AT_RECURSIVE,
1802 &(struct mount_attr) {
1803 .attr_set = ms_flags_to_mount_attr(f) | (userns_fd >= 0 ? MOUNT_ATTR_IDMAP : 0),
1804 .userns_fd = userns_fd,
1805 }, MOUNT_ATTR_SIZE_VER0) < 0)
1806 return log_full_errno(error_log_level,
1807 errno,
1808 "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1809 what,
1810 type);
1811
1812 return TAKE_FD(mnt_fd);
1813 }