]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/mount-util.c
tree-wide: introduce PIPE_EBADF macro
[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-symlinks.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.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 "stat-util.h"
38 #include "stdio-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
41 #include "strv.h"
42 #include "tmpfile-util.h"
43 #include "user-util.h"
44
45 int umount_recursive(const char *prefix, int flags) {
46 int n = 0, r;
47 bool again;
48
49 /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
50 * keep unmounting them until they are gone. */
51
52 do {
53 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
54 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
55
56 again = false;
57
58 r = libmount_parse("/proc/self/mountinfo", NULL, &table, &iter);
59 if (r < 0)
60 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
61
62 for (;;) {
63 struct libmnt_fs *fs;
64 const char *path;
65
66 r = mnt_table_next_fs(table, iter, &fs);
67 if (r == 1)
68 break;
69 if (r < 0)
70 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
71
72 path = mnt_fs_get_target(fs);
73 if (!path)
74 continue;
75
76 if (!path_startswith(path, prefix))
77 continue;
78
79 if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
80 log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
81 continue;
82 }
83
84 log_debug("Successfully unmounted %s", path);
85
86 again = true;
87 n++;
88
89 break;
90 }
91 } while (again);
92
93 return n;
94 }
95
96 #define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
97
98 static uint64_t ms_flags_to_mount_attr(unsigned long a) {
99 uint64_t f = 0;
100
101 if (FLAGS_SET(a, MS_RDONLY))
102 f |= MOUNT_ATTR_RDONLY;
103
104 if (FLAGS_SET(a, MS_NOSUID))
105 f |= MOUNT_ATTR_NOSUID;
106
107 if (FLAGS_SET(a, MS_NODEV))
108 f |= MOUNT_ATTR_NODEV;
109
110 if (FLAGS_SET(a, MS_NOEXEC))
111 f |= MOUNT_ATTR_NOEXEC;
112
113 if (FLAGS_SET(a, MS_NOSYMFOLLOW))
114 f |= MOUNT_ATTR_NOSYMFOLLOW;
115
116 return f;
117 }
118
119 static bool skip_mount_set_attr = false;
120
121 /* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
122 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
123 int bind_remount_recursive_with_mountinfo(
124 const char *prefix,
125 unsigned long new_flags,
126 unsigned long flags_mask,
127 char **deny_list,
128 FILE *proc_self_mountinfo) {
129
130 _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
131 _cleanup_set_free_ Set *done = NULL;
132 unsigned n_tries = 0;
133 int r;
134
135 assert(prefix);
136
137 if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && strv_isempty(deny_list) && !skip_mount_set_attr) {
138 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
139
140 if (mount_setattr(AT_FDCWD, prefix, AT_SYMLINK_NOFOLLOW|AT_RECURSIVE,
141 &(struct mount_attr) {
142 .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
143 .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
144 }, MOUNT_ATTR_SIZE_VER0) < 0) {
145
146 log_debug_errno(errno, "mount_setattr() failed, falling back to classic remounting: %m");
147
148 /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
149 * also do this for all other kinds of errors since they are so many different, and
150 * mount_setattr() has no graceful mode where it continues despite seeing errors one
151 * some mounts, but we want that. Moreover mount_setattr() only works on the mount
152 * point inode itself, not a non-mount point inode, and we want to support arbitrary
153 * prefixes here. */
154
155 if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
156 skip_mount_set_attr = true;
157 } else
158 return 0; /* Nice, this worked! */
159 }
160
161 if (!proc_self_mountinfo) {
162 r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened);
163 if (r < 0)
164 return r;
165
166 proc_self_mountinfo = proc_self_mountinfo_opened;
167 }
168
169 /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
170 * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
171 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
172 * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
173 * access, too. When mounts are stacked on the same mount point we only care for each individual
174 * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
175 * not have any effect on future submounts that might get propagated, they might be writable
176 * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
177 * operate atomically here. Mounts established while we process the tree might or might not get
178 * noticed and thus might or might not be covered.
179 *
180 * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
181 * remount operation. Note that we'll ignore the deny list for the top-level path. */
182
183 for (;;) {
184 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
185 _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
186 _cleanup_hashmap_free_ Hashmap *todo = NULL;
187 bool top_autofs = false;
188
189 if (n_tries++ >= 32) /* Let's not retry this loop forever */
190 return -EBUSY;
191
192 rewind(proc_self_mountinfo);
193
194 r = libmount_parse("/proc/self/mountinfo", proc_self_mountinfo, &table, &iter);
195 if (r < 0)
196 return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
197
198 for (;;) {
199 _cleanup_free_ char *d = NULL;
200 const char *path, *type, *opts;
201 unsigned long flags = 0;
202 struct libmnt_fs *fs;
203
204 r = mnt_table_next_fs(table, iter, &fs);
205 if (r == 1) /* EOF */
206 break;
207 if (r < 0)
208 return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
209
210 path = mnt_fs_get_target(fs);
211 if (!path)
212 continue;
213
214 if (!path_startswith(path, prefix))
215 continue;
216
217 type = mnt_fs_get_fstype(fs);
218 if (!type)
219 continue;
220
221 /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
222 * triggering them, as we don't make any guarantees for future submounts anyway. If
223 * they are already triggered, then we will find another entry for this. */
224 if (streq(type, "autofs")) {
225 top_autofs = top_autofs || path_equal(path, prefix);
226 continue;
227 }
228
229 if (set_contains(done, path))
230 continue;
231
232 /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
233 * we shall operate on. */
234 if (!path_equal(path, prefix)) {
235 bool deny_listed = false;
236
237 STRV_FOREACH(i, deny_list) {
238 if (path_equal(*i, prefix))
239 continue;
240
241 if (!path_startswith(*i, prefix))
242 continue;
243
244 if (path_startswith(path, *i)) {
245 deny_listed = true;
246 log_debug("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
247 break;
248 }
249 }
250
251 if (deny_listed)
252 continue;
253 }
254
255 opts = mnt_fs_get_vfs_options(fs);
256 if (opts) {
257 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
258 if (r < 0)
259 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
260 }
261
262 d = strdup(path);
263 if (!d)
264 return -ENOMEM;
265
266 r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
267 if (r == -EEXIST)
268 /* If the same path was recorded, but with different mount flags, update it:
269 * it means a mount point is overmounted, and libmount returns the "bottom" (or
270 * older one) first, but we want to reapply the flags from the "top" (or newer
271 * one). See: https://github.com/systemd/systemd/issues/20032
272 * Note that this shouldn't really fail, as we were just told that the key
273 * exists, and it's an update so we want 'd' to be freed immediately. */
274 r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
275 if (r < 0)
276 return r;
277 if (r > 0)
278 TAKE_PTR(d);
279 }
280
281 /* Check if the top-level directory was among what we have seen so far. For that check both
282 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
283 * not include it in either set but will set this bool. */
284 if (!set_contains(done, prefix) &&
285 !(top_autofs || hashmap_contains(todo, prefix))) {
286
287 /* The prefix directory itself is not yet a mount, make it one. */
288 r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
289 if (r < 0)
290 return r;
291
292 /* Immediately rescan, so that we pick up the new mount's flags */
293 continue;
294 }
295
296 /* If we have no submounts to process anymore, we are done */
297 if (hashmap_isempty(todo))
298 return 0;
299
300 for (;;) {
301 unsigned long flags;
302 char *x = NULL;
303
304 /* Take the first mount from our list of mounts to still process */
305 flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
306 if (!x)
307 break;
308
309 r = set_ensure_consume(&done, &path_hash_ops_free, x);
310 if (IN_SET(r, 0, -EEXIST))
311 continue; /* Already done */
312 if (r < 0)
313 return r;
314
315 /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
316 * the default anyway, thus redundant, and in userns we'll get an error if we try to
317 * explicitly enable it) */
318 r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
319 if (r < 0) {
320 int q;
321
322 /* OK, so the remount of this entry failed. We'll ultimately ignore this in
323 * almost all cases (there are simply so many reasons why this can fail,
324 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
325 * the very least. */
326
327 q = path_is_mount_point(x, NULL, 0);
328 if (IN_SET(q, 0, -ENOENT)) {
329 /* Hmm, whaaaa? The mount point is not actually a mount point? Then
330 * it is either obstructed by a later mount or somebody has been
331 * racing against us and removed it. Either way the mount point
332 * doesn't matter to us, let's ignore it hence. */
333 log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
334 continue;
335 }
336 if (q < 0) /* Any other error on this? Just log and continue */
337 log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
338
339 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
340 log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
341 continue;
342 }
343
344 /* Make this fatal if this is the top-level mount */
345 if (path_equal(x, prefix))
346 return r;
347
348 /* If this is not the top-level mount, then handle this gracefully: log but
349 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
350 * this might fail without a chance for us to do anything about it, let's
351 * hence be strict on the top-level mount and lenient on the inner ones. */
352 log_debug_errno(r, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x);
353 continue;
354 }
355
356 log_debug("Remounted %s.", x);
357 }
358 }
359 }
360
361 int bind_remount_one_with_mountinfo(
362 const char *path,
363 unsigned long new_flags,
364 unsigned long flags_mask,
365 FILE *proc_self_mountinfo) {
366
367 _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
368 unsigned long flags = 0;
369 struct libmnt_fs *fs;
370 const char *opts;
371 int r;
372
373 assert(path);
374 assert(proc_self_mountinfo);
375
376 if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && !skip_mount_set_attr) {
377 /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
378
379 if (mount_setattr(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW,
380 &(struct mount_attr) {
381 .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
382 .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
383 }, MOUNT_ATTR_SIZE_VER0) < 0) {
384
385 log_debug_errno(errno, "mount_setattr() didn't work, falling back to classic remounting: %m");
386
387 if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
388 skip_mount_set_attr = true;
389 } else
390 return 0; /* Nice, this worked! */
391 }
392
393 rewind(proc_self_mountinfo);
394
395 table = mnt_new_table();
396 if (!table)
397 return -ENOMEM;
398
399 r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
400 if (r < 0)
401 return r;
402
403 fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
404 if (!fs) {
405 if (laccess(path, F_OK) < 0) /* Hmm, it's not in the mount table, but does it exist at all? */
406 return -errno;
407
408 return -EINVAL; /* Not a mount point we recognize */
409 }
410
411 opts = mnt_fs_get_vfs_options(fs);
412 if (opts) {
413 r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
414 if (r < 0)
415 log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
416 }
417
418 r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
419 if (r < 0) {
420 if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
421 * since kernel adds it in
422 * everywhere, because it's the
423 * default. */
424 return r;
425
426 /* Let's handle redundant remounts gracefully */
427 log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
428 }
429
430 return 0;
431 }
432
433 static int mount_switch_root_pivot(const char *path, int fd_newroot) {
434 _cleanup_close_ int fd_oldroot = -EBADF;
435
436 fd_oldroot = open("/", O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
437 if (fd_oldroot < 0)
438 return log_debug_errno(errno, "Failed to open old rootfs");
439
440 /* Let the kernel tuck the new root under the old one. */
441 if (pivot_root(".", ".") < 0)
442 return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
443
444 /* At this point the new root is tucked under the old root. If we want
445 * to unmount it we cannot be fchdir()ed into it. So escape back to the
446 * old root. */
447 if (fchdir(fd_oldroot) < 0)
448 return log_debug_errno(errno, "Failed to change back to old rootfs: %m");
449
450 /* Note, usually we should set mount propagation up here but we'll
451 * assume that the caller has already done that. */
452
453 /* Get rid of the old root and reveal our brand new root. */
454 if (umount2(".", MNT_DETACH) < 0)
455 return log_debug_errno(errno, "Failed to unmount old rootfs: %m");
456
457 if (fchdir(fd_newroot) < 0)
458 return log_debug_errno(errno, "Failed to switch to new rootfs '%s': %m", path);
459
460 return 0;
461 }
462
463 static int mount_switch_root_move(const char *path) {
464 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
465 return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
466
467 if (chroot(".") < 0)
468 return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
469
470 if (chdir("/"))
471 return log_debug_errno(errno, "Failed to chdir to new rootfs '%s': %m", path);
472
473 return 0;
474 }
475
476 int mount_switch_root(const char *path, unsigned long mount_propagation_flag) {
477 _cleanup_close_ int fd_newroot = -EBADF;
478 int r;
479
480 assert(path);
481 assert(mount_propagation_flag_is_valid(mount_propagation_flag));
482
483 fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
484 if (fd_newroot < 0)
485 return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
486
487 /* Change into the new rootfs. */
488 if (fchdir(fd_newroot) < 0)
489 return log_debug_errno(errno, "Failed to change into new rootfs '%s': %m", path);
490
491 r = mount_switch_root_pivot(path, fd_newroot);
492 if (r < 0) {
493 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the
494 * rootfs is an initramfs in which case pivot_root() isn't supported. */
495 log_debug_errno(r, "Failed to pivot into new rootfs '%s': %m", path);
496 r = mount_switch_root_move(path);
497 }
498 if (r < 0)
499 return log_debug_errno(r, "Failed to switch to new rootfs '%s': %m", path);
500
501 /* Finally, let's establish the requested propagation flags. */
502 if (mount_propagation_flag == 0)
503 return 0;
504
505 if (mount(NULL, ".", NULL, mount_propagation_flag | MS_REC, 0) < 0)
506 return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
507 mount_propagation_flag_to_string(mount_propagation_flag), path);
508
509 return 0;
510 }
511
512 int repeat_unmount(const char *path, int flags) {
513 bool done = false;
514
515 assert(path);
516
517 /* If there are multiple mounts on a mount point, this
518 * removes them all */
519
520 for (;;) {
521 if (umount2(path, flags) < 0) {
522
523 if (errno == EINVAL)
524 return done;
525
526 return -errno;
527 }
528
529 done = true;
530 }
531 }
532
533 int mode_to_inaccessible_node(
534 const char *runtime_dir,
535 mode_t mode,
536 char **ret) {
537
538 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
539 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
540 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
541 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
542 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
543 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
544 * file nodes, and that's the most important thing that matters.
545 *
546 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
547 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
548
549 _cleanup_free_ char *d = NULL;
550 const char *node = NULL;
551
552 assert(ret);
553
554 if (!runtime_dir)
555 runtime_dir = "/run";
556
557 switch (mode & S_IFMT) {
558 case S_IFREG:
559 node = "/systemd/inaccessible/reg";
560 break;
561
562 case S_IFDIR:
563 node = "/systemd/inaccessible/dir";
564 break;
565
566 case S_IFCHR:
567 node = "/systemd/inaccessible/chr";
568 break;
569
570 case S_IFBLK:
571 node = "/systemd/inaccessible/blk";
572 break;
573
574 case S_IFIFO:
575 node = "/systemd/inaccessible/fifo";
576 break;
577
578 case S_IFSOCK:
579 node = "/systemd/inaccessible/sock";
580 break;
581 }
582 if (!node)
583 return -EINVAL;
584
585 d = path_join(runtime_dir, node);
586 if (!d)
587 return -ENOMEM;
588
589 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
590 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
591 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
592 * inaccessible block device node let's see if the block device node actually exists, and if not,
593 * fall back to the character device node. From there fall back to the socket device node. This means
594 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
595 * device node at all. */
596
597 if (S_ISBLK(mode) &&
598 access(d, F_OK) < 0 && errno == ENOENT) {
599 free(d);
600 d = path_join(runtime_dir, "/systemd/inaccessible/chr");
601 if (!d)
602 return -ENOMEM;
603 }
604
605 if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
606 access(d, F_OK) < 0 && errno == ENOENT) {
607 free(d);
608 d = path_join(runtime_dir, "/systemd/inaccessible/sock");
609 if (!d)
610 return -ENOMEM;
611 }
612
613 *ret = TAKE_PTR(d);
614 return 0;
615 }
616
617 int mount_flags_to_string(unsigned long flags, char **ret) {
618 static const struct {
619 unsigned long flag;
620 const char *name;
621 } map[] = {
622 { .flag = MS_RDONLY, .name = "MS_RDONLY", },
623 { .flag = MS_NOSUID, .name = "MS_NOSUID", },
624 { .flag = MS_NODEV, .name = "MS_NODEV", },
625 { .flag = MS_NOEXEC, .name = "MS_NOEXEC", },
626 { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
627 { .flag = MS_REMOUNT, .name = "MS_REMOUNT", },
628 { .flag = MS_MANDLOCK, .name = "MS_MANDLOCK", },
629 { .flag = MS_DIRSYNC, .name = "MS_DIRSYNC", },
630 { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
631 { .flag = MS_NOATIME, .name = "MS_NOATIME", },
632 { .flag = MS_NODIRATIME, .name = "MS_NODIRATIME", },
633 { .flag = MS_BIND, .name = "MS_BIND", },
634 { .flag = MS_MOVE, .name = "MS_MOVE", },
635 { .flag = MS_REC, .name = "MS_REC", },
636 { .flag = MS_SILENT, .name = "MS_SILENT", },
637 { .flag = MS_POSIXACL, .name = "MS_POSIXACL", },
638 { .flag = MS_UNBINDABLE, .name = "MS_UNBINDABLE", },
639 { .flag = MS_PRIVATE, .name = "MS_PRIVATE", },
640 { .flag = MS_SLAVE, .name = "MS_SLAVE", },
641 { .flag = MS_SHARED, .name = "MS_SHARED", },
642 { .flag = MS_RELATIME, .name = "MS_RELATIME", },
643 { .flag = MS_KERNMOUNT, .name = "MS_KERNMOUNT", },
644 { .flag = MS_I_VERSION, .name = "MS_I_VERSION", },
645 { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
646 { .flag = MS_LAZYTIME, .name = "MS_LAZYTIME", },
647 };
648 _cleanup_free_ char *str = NULL;
649
650 assert(ret);
651
652 for (size_t i = 0; i < ELEMENTSOF(map); i++)
653 if (flags & map[i].flag) {
654 if (!strextend_with_separator(&str, "|", map[i].name))
655 return -ENOMEM;
656 flags &= ~map[i].flag;
657 }
658
659 if (!str || flags != 0)
660 if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
661 return -ENOMEM;
662
663 *ret = TAKE_PTR(str);
664 return 0;
665 }
666
667 int mount_verbose_full(
668 int error_log_level,
669 const char *what,
670 const char *where,
671 const char *type,
672 unsigned long flags,
673 const char *options,
674 bool follow_symlink) {
675
676 _cleanup_free_ char *fl = NULL, *o = NULL;
677 unsigned long f;
678 int r;
679
680 r = mount_option_mangle(options, flags, &f, &o);
681 if (r < 0)
682 return log_full_errno(error_log_level, r,
683 "Failed to mangle mount options %s: %m",
684 strempty(options));
685
686 (void) mount_flags_to_string(f, &fl);
687
688 if ((f & MS_REMOUNT) && !what && !type)
689 log_debug("Remounting %s (%s \"%s\")...",
690 where, strnull(fl), strempty(o));
691 else if (!what && !type)
692 log_debug("Mounting %s (%s \"%s\")...",
693 where, strnull(fl), strempty(o));
694 else if ((f & MS_BIND) && !type)
695 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
696 what, where, strnull(fl), strempty(o));
697 else if (f & MS_MOVE)
698 log_debug("Moving mount %s %s %s (%s \"%s\")...",
699 what, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
700 else
701 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
702 strna(what), strna(type), where, strnull(fl), strempty(o));
703
704 if (follow_symlink)
705 r = RET_NERRNO(mount(what, where, type, f, o));
706 else
707 r = mount_nofollow(what, where, type, f, o);
708 if (r < 0)
709 return log_full_errno(error_log_level, r,
710 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
711 strna(what), strna(type), where, strnull(fl), strempty(o));
712 return 0;
713 }
714
715 int umount_verbose(
716 int error_log_level,
717 const char *what,
718 int flags) {
719
720 assert(what);
721
722 log_debug("Umounting %s...", what);
723
724 if (umount2(what, flags) < 0)
725 return log_full_errno(error_log_level, errno,
726 "Failed to unmount %s: %m", what);
727
728 return 0;
729 }
730
731 int mount_option_mangle(
732 const char *options,
733 unsigned long mount_flags,
734 unsigned long *ret_mount_flags,
735 char **ret_remaining_options) {
736
737 const struct libmnt_optmap *map;
738 _cleanup_free_ char *ret = NULL;
739 int r;
740
741 /* This extracts mount flags from the mount options, and stores
742 * non-mount-flag options to '*ret_remaining_options'.
743 * E.g.,
744 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
745 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
746 * "size=1630748k,mode=0700,uid=1000,gid=1000".
747 * See more examples in test-mount-util.c.
748 *
749 * If 'options' does not contain any non-mount-flag options,
750 * then '*ret_remaining_options' is set to NULL instead of empty string.
751 * The validity of options stored in '*ret_remaining_options' is not checked.
752 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
753
754 assert(ret_mount_flags);
755 assert(ret_remaining_options);
756
757 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
758 if (!map)
759 return -EINVAL;
760
761 for (const char *p = options;;) {
762 _cleanup_free_ char *word = NULL;
763 const struct libmnt_optmap *ent;
764
765 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
766 if (r < 0)
767 return r;
768 if (r == 0)
769 break;
770
771 for (ent = map; ent->name; ent++) {
772 /* All entries in MNT_LINUX_MAP do not take any argument.
773 * Thus, ent->name does not contain "=" or "[=]". */
774 if (!streq(word, ent->name))
775 continue;
776
777 if (!(ent->mask & MNT_INVERT))
778 mount_flags |= ent->id;
779 else if (mount_flags & ent->id)
780 mount_flags ^= ent->id;
781
782 break;
783 }
784
785 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
786 if (!ent->name &&
787 !startswith_no_case(word, "x-") &&
788 !strextend_with_separator(&ret, ",", word))
789 return -ENOMEM;
790 }
791
792 *ret_mount_flags = mount_flags;
793 *ret_remaining_options = TAKE_PTR(ret);
794
795 return 0;
796 }
797
798 static int mount_in_namespace(
799 pid_t target,
800 const char *propagate_path,
801 const char *incoming_path,
802 const char *src,
803 const char *dest,
804 bool read_only,
805 bool make_file_or_directory,
806 const MountOptions *options,
807 bool is_image) {
808
809 _cleanup_close_pair_ int errno_pipe_fd[2] = PIPE_EBADF;
810 _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF;
811 char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
812 bool mount_slave_created = false, mount_slave_mounted = false,
813 mount_tmp_created = false, mount_tmp_mounted = false,
814 mount_outside_created = false, mount_outside_mounted = false;
815 _cleanup_free_ char *chased_src_path = NULL;
816 struct stat st;
817 pid_t child;
818 int r;
819
820 assert(target > 0);
821 assert(propagate_path);
822 assert(incoming_path);
823 assert(src);
824 assert(dest);
825 assert(!options || is_image);
826
827 r = namespace_open(target, &pidns_fd, &mntns_fd, NULL, NULL, &root_fd);
828 if (r < 0)
829 return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
830
831 r = in_same_namespace(target, 0, NAMESPACE_MOUNT);
832 if (r < 0)
833 return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
834 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
835 if (r > 0)
836 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace");
837
838 /* One day, when bind mounting /proc/self/fd/n works across namespace boundaries we should rework
839 * this logic to make use of it... */
840
841 p = strjoina(propagate_path, "/");
842 r = laccess(p, F_OK);
843 if (r < 0)
844 return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
845
846 r = chase_symlinks(src, NULL, 0, &chased_src_path, &chased_src_fd);
847 if (r < 0)
848 return log_debug_errno(r, "Failed to resolve source path of %s: %m", src);
849 log_debug("Chased source path of %s to %s", src, chased_src_path);
850
851 if (fstat(chased_src_fd, &st) < 0)
852 return log_debug_errno(errno, "Failed to stat() resolved source path %s: %m", src);
853 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… */
854 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Source directory %s can't be a symbolic link", src);
855
856 /* Our goal is to install a new bind mount into the container,
857 possibly read-only. This is irritatingly complex
858 unfortunately, currently.
859
860 First, we start by creating a private playground in /tmp,
861 that we can mount MS_SLAVE. (Which is necessary, since
862 MS_MOVE cannot be applied to mounts with MS_SHARED parent
863 mounts.) */
864
865 if (!mkdtemp(mount_slave))
866 return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
867
868 mount_slave_created = true;
869
870 r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
871 if (r < 0)
872 goto finish;
873
874 mount_slave_mounted = true;
875
876 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
877 if (r < 0)
878 goto finish;
879
880 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
881 mount_tmp = strjoina(mount_slave, "/mount");
882 if (is_image)
883 r = mkdir_p(mount_tmp, 0700);
884 else
885 r = make_mount_point_inode_from_stat(&st, mount_tmp, 0700);
886 if (r < 0) {
887 log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
888 goto finish;
889 }
890
891 mount_tmp_created = true;
892
893 if (is_image)
894 r = verity_dissect_and_mount(chased_src_fd, chased_src_path, mount_tmp, options, NULL, NULL, NULL, NULL);
895 else
896 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
897 if (r < 0)
898 goto finish;
899
900 mount_tmp_mounted = true;
901
902 /* Third, we remount the new bind mount read-only if requested. */
903 if (read_only) {
904 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
905 if (r < 0)
906 goto finish;
907 }
908
909 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
910 * right-away. */
911
912 mount_outside = strjoina(propagate_path, "/XXXXXX");
913 if (is_image || S_ISDIR(st.st_mode))
914 r = mkdtemp(mount_outside) ? 0 : -errno;
915 else {
916 r = mkostemp_safe(mount_outside);
917 safe_close(r);
918 }
919 if (r < 0) {
920 log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
921 goto finish;
922 }
923
924 mount_outside_created = true;
925
926 r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
927 if (r < 0)
928 goto finish;
929
930 mount_outside_mounted = true;
931 mount_tmp_mounted = false;
932
933 if (is_image || S_ISDIR(st.st_mode))
934 (void) rmdir(mount_tmp);
935 else
936 (void) unlink(mount_tmp);
937 mount_tmp_created = false;
938
939 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
940 mount_slave_mounted = false;
941
942 (void) rmdir(mount_slave);
943 mount_slave_created = false;
944
945 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
946 log_debug_errno(errno, "Failed to create pipe: %m");
947 goto finish;
948 }
949
950 r = namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
951 pidns_fd, mntns_fd, -1, -1, root_fd, &child);
952 if (r < 0)
953 goto finish;
954 if (r == 0) {
955 const char *mount_inside;
956
957 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
958
959 if (make_file_or_directory) {
960 if (!is_image) {
961 (void) mkdir_parents(dest, 0755);
962 (void) make_mount_point_inode_from_stat(&st, dest, 0700);
963 } else
964 (void) mkdir_p(dest, 0755);
965 }
966
967 /* Fifth, move the mount to the right place inside */
968 mount_inside = strjoina(incoming_path, basename(mount_outside));
969 r = mount_nofollow_verbose(LOG_ERR, mount_inside, dest, NULL, MS_MOVE, NULL);
970 if (r < 0)
971 goto child_fail;
972
973 _exit(EXIT_SUCCESS);
974
975 child_fail:
976 (void) write(errno_pipe_fd[1], &r, sizeof(r));
977 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
978
979 _exit(EXIT_FAILURE);
980 }
981
982 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
983
984 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
985 if (r < 0) {
986 log_debug_errno(r, "Failed to wait for child: %m");
987 goto finish;
988 }
989 if (r != EXIT_SUCCESS) {
990 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
991 log_debug_errno(r, "Failed to mount: %m");
992 else
993 log_debug("Child failed.");
994 goto finish;
995 }
996
997 finish:
998 if (mount_outside_mounted)
999 (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
1000 if (mount_outside_created) {
1001 if (is_image || S_ISDIR(st.st_mode))
1002 (void) rmdir(mount_outside);
1003 else
1004 (void) unlink(mount_outside);
1005 }
1006
1007 if (mount_tmp_mounted)
1008 (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
1009 if (mount_tmp_created) {
1010 if (is_image || S_ISDIR(st.st_mode))
1011 (void) rmdir(mount_tmp);
1012 else
1013 (void) unlink(mount_tmp);
1014 }
1015
1016 if (mount_slave_mounted)
1017 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
1018 if (mount_slave_created)
1019 (void) rmdir(mount_slave);
1020
1021 return r;
1022 }
1023
1024 int bind_mount_in_namespace(
1025 pid_t target,
1026 const char *propagate_path,
1027 const char *incoming_path,
1028 const char *src,
1029 const char *dest,
1030 bool read_only,
1031 bool make_file_or_directory) {
1032
1033 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, NULL, false);
1034 }
1035
1036 int mount_image_in_namespace(
1037 pid_t target,
1038 const char *propagate_path,
1039 const char *incoming_path,
1040 const char *src,
1041 const char *dest,
1042 bool read_only,
1043 bool make_file_or_directory,
1044 const MountOptions *options) {
1045
1046 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, options, true);
1047 }
1048
1049 int make_mount_point(const char *path) {
1050 int r;
1051
1052 assert(path);
1053
1054 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1055
1056 r = path_is_mount_point(path, NULL, 0);
1057 if (r < 0)
1058 return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
1059 if (r > 0)
1060 return 0;
1061
1062 r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
1063 if (r < 0)
1064 return r;
1065
1066 return 1;
1067 }
1068
1069 static int make_userns(uid_t uid_shift, uid_t uid_range, uid_t owner, RemountIdmapping idmapping) {
1070 _cleanup_close_ int userns_fd = -EBADF;
1071 _cleanup_free_ char *line = NULL;
1072
1073 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1074 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1075
1076 if (IN_SET(idmapping, REMOUNT_IDMAPPING_NONE, REMOUNT_IDMAPPING_HOST_ROOT)) {
1077 if (asprintf(&line, UID_FMT " " UID_FMT " " UID_FMT "\n", 0u, uid_shift, uid_range) < 0)
1078 return log_oom_debug();
1079
1080 /* If requested we'll include an entry in the mapping so that the host root user can make
1081 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1082 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1083 * to create various missing inodes in the OS tree before booting into it, and this becomes
1084 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1085 * that in that case the container's runtime uidmap (i.e. the one the container payload
1086 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1087 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1088 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1089 * to the container's own UID range, but it's good to have a safety net, in case we
1090 * forget it.) */
1091 if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
1092 if (strextendf(&line,
1093 UID_FMT " " UID_FMT " " UID_FMT "\n",
1094 UID_MAPPED_ROOT, 0u, 1u) < 0)
1095 return log_oom_debug();
1096 }
1097
1098 if (idmapping == REMOUNT_IDMAPPING_HOST_OWNER) {
1099 /* Remap the owner of the bind mounted directory to the root user within the container. This
1100 * way every file written by root within the container to the bind-mounted directory will
1101 * be owned by the original user. All other user will remain unmapped. */
1102 if (asprintf(&line, UID_FMT " " UID_FMT " " UID_FMT "\n", owner, uid_shift, 1u) < 0)
1103 return log_oom_debug();
1104 }
1105
1106 /* We always assign the same UID and GID ranges */
1107 userns_fd = userns_acquire(line, line);
1108 if (userns_fd < 0)
1109 return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
1110
1111 return TAKE_FD(userns_fd);
1112 }
1113
1114 int remount_idmap(
1115 const char *p,
1116 uid_t uid_shift,
1117 uid_t uid_range,
1118 uid_t owner,
1119 RemountIdmapping idmapping) {
1120
1121 _cleanup_close_ int mount_fd = -EBADF, userns_fd = -EBADF;
1122 int r;
1123
1124 assert(p);
1125
1126 if (!userns_shift_range_valid(uid_shift, uid_range))
1127 return -EINVAL;
1128
1129 /* Clone the mount point */
1130 mount_fd = open_tree(-1, p, OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
1131 if (mount_fd < 0)
1132 return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", p);
1133
1134 /* Create a user namespace mapping */
1135 userns_fd = make_userns(uid_shift, uid_range, owner, idmapping);
1136 if (userns_fd < 0)
1137 return userns_fd;
1138
1139 /* Set the user namespace mapping attribute on the cloned mount point */
1140 if (mount_setattr(mount_fd, "", AT_EMPTY_PATH | AT_RECURSIVE,
1141 &(struct mount_attr) {
1142 .attr_set = MOUNT_ATTR_IDMAP,
1143 .userns_fd = userns_fd,
1144 }, sizeof(struct mount_attr)) < 0)
1145 return log_debug_errno(errno, "Failed to change bind mount attributes for '%s': %m", p);
1146
1147 /* Remove the old mount point */
1148 r = umount_verbose(LOG_DEBUG, p, UMOUNT_NOFOLLOW);
1149 if (r < 0)
1150 return r;
1151
1152 /* And place the cloned version in its place */
1153 if (move_mount(mount_fd, "", -1, p, MOVE_MOUNT_F_EMPTY_PATH) < 0)
1154 return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", p);
1155
1156 return 0;
1157 }
1158
1159 int make_mount_point_inode_from_stat(const struct stat *st, const char *dest, mode_t mode) {
1160 assert(st);
1161 assert(dest);
1162
1163 if (S_ISDIR(st->st_mode))
1164 return mkdir_label(dest, mode);
1165 else
1166 return RET_NERRNO(mknod(dest, S_IFREG|(mode & ~0111), 0));
1167 }
1168
1169 int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t mode) {
1170 struct stat st;
1171
1172 assert(source);
1173 assert(dest);
1174
1175 if (stat(source, &st) < 0)
1176 return -errno;
1177
1178 return make_mount_point_inode_from_stat(&st, dest, mode);
1179 }