]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/mount-util.c
tree-wide: use mode=0nnn for mount option
[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 const char *const mount_attr_propagation_type_table[_MOUNT_ATTR_PROPAGATION_TYPE_MAX] = {
434 [MOUNT_ATTR_PROPAGATION_INHERIT] = "inherited",
435 [MOUNT_ATTR_PROPAGATION_PRIVATE] = "private",
436 [MOUNT_ATTR_PROPAGATION_DEPENDENT] = "dependent",
437 [MOUNT_ATTR_PROPAGATION_SHARED] = "shared",
438 };
439
440 DEFINE_STRING_TABLE_LOOKUP(mount_attr_propagation_type, MountAttrPropagationType);
441
442 unsigned int mount_attr_propagation_type_to_flag(MountAttrPropagationType t) {
443 switch (t) {
444 case MOUNT_ATTR_PROPAGATION_INHERIT:
445 return 0;
446 case MOUNT_ATTR_PROPAGATION_PRIVATE:
447 return MS_PRIVATE;
448 case MOUNT_ATTR_PROPAGATION_DEPENDENT:
449 return MS_SLAVE;
450 case MOUNT_ATTR_PROPAGATION_SHARED:
451 return MS_SHARED;
452 default:
453 assert_not_reached();
454 }
455 }
456
457 static inline int mount_switch_root_pivot(const char *path, int fd_newroot) {
458 _cleanup_close_ int fd_oldroot = -EBADF;
459
460 fd_oldroot = open("/", O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
461 if (fd_oldroot < 0)
462 return log_debug_errno(errno, "Failed to open old rootfs");
463
464 /* Let the kernel tuck the new root under the old one. */
465 if (pivot_root(".", ".") < 0)
466 return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
467
468 /* At this point the new root is tucked under the old root. If we want
469 * to unmount it we cannot be fchdir()ed into it. So escape back to the
470 * old root. */
471 if (fchdir(fd_oldroot) < 0)
472 return log_debug_errno(errno, "Failed to change back to old rootfs: %m");
473
474 /* Note, usually we should set mount propagation up here but we'll
475 * assume that the caller has already done that. */
476
477 /* Get rid of the old root and reveal our brand new root. */
478 if (umount2(".", MNT_DETACH) < 0)
479 return log_debug_errno(errno, "Failed to unmount old rootfs: %m");
480
481 if (fchdir(fd_newroot) < 0)
482 return log_debug_errno(errno, "Failed to switch to new rootfs '%s': %m", path);
483
484 return 0;
485 }
486
487 static inline int mount_switch_root_move(const char *path) {
488 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
489 return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
490
491 if (chroot(".") < 0)
492 return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
493
494 if (chdir("/"))
495 return log_debug_errno(errno, "Failed to chdir to new rootfs '%s': %m", path);
496
497 return 0;
498 }
499
500 int mount_switch_root(const char *path, MountAttrPropagationType type) {
501 int r;
502 _cleanup_close_ int fd_newroot = -EBADF;
503 unsigned int flags;
504
505 assert(path);
506
507 fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
508 if (fd_newroot < 0)
509 return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
510
511 /* Change into the new rootfs. */
512 if (fchdir(fd_newroot) < 0)
513 return log_debug_errno(errno, "Failed to change into new rootfs '%s': %m", path);
514
515 r = mount_switch_root_pivot(path, fd_newroot);
516 if (r < 0) {
517 /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the
518 * rootfs is an initramfs in which case pivot_root() isn't supported. */
519 log_debug_errno(r, "Failed to pivot into new rootfs '%s': %m", path);
520 r = mount_switch_root_move(path);
521 }
522 if (r < 0)
523 return log_debug_errno(r, "Failed to switch to new rootfs '%s': %m", path);
524
525 /* Finally, let's establish the requested propagation type. */
526 flags = mount_attr_propagation_type_to_flag(type);
527 if ((flags != 0) && mount(NULL, ".", NULL, flags|MS_REC, 0) < 0)
528 return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
529 mount_attr_propagation_type_to_string(type), path);
530
531 return 0;
532 }
533
534 int repeat_unmount(const char *path, int flags) {
535 bool done = false;
536
537 assert(path);
538
539 /* If there are multiple mounts on a mount point, this
540 * removes them all */
541
542 for (;;) {
543 if (umount2(path, flags) < 0) {
544
545 if (errno == EINVAL)
546 return done;
547
548 return -errno;
549 }
550
551 done = true;
552 }
553 }
554
555 int mode_to_inaccessible_node(
556 const char *runtime_dir,
557 mode_t mode,
558 char **ret) {
559
560 /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
561 * during early boot by PID 1. In some cases we lacked the privs to create the character and block
562 * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
563 * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
564 * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
565 * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
566 * file nodes, and that's the most important thing that matters.
567 *
568 * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
569 * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
570
571 _cleanup_free_ char *d = NULL;
572 const char *node = NULL;
573
574 assert(ret);
575
576 if (!runtime_dir)
577 runtime_dir = "/run";
578
579 switch (mode & S_IFMT) {
580 case S_IFREG:
581 node = "/systemd/inaccessible/reg";
582 break;
583
584 case S_IFDIR:
585 node = "/systemd/inaccessible/dir";
586 break;
587
588 case S_IFCHR:
589 node = "/systemd/inaccessible/chr";
590 break;
591
592 case S_IFBLK:
593 node = "/systemd/inaccessible/blk";
594 break;
595
596 case S_IFIFO:
597 node = "/systemd/inaccessible/fifo";
598 break;
599
600 case S_IFSOCK:
601 node = "/systemd/inaccessible/sock";
602 break;
603 }
604 if (!node)
605 return -EINVAL;
606
607 d = path_join(runtime_dir, node);
608 if (!d)
609 return -ENOMEM;
610
611 /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
612 * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
613 * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
614 * inaccessible block device node let's see if the block device node actually exists, and if not,
615 * fall back to the character device node. From there fall back to the socket device node. This means
616 * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
617 * device node at all. */
618
619 if (S_ISBLK(mode) &&
620 access(d, F_OK) < 0 && errno == ENOENT) {
621 free(d);
622 d = path_join(runtime_dir, "/systemd/inaccessible/chr");
623 if (!d)
624 return -ENOMEM;
625 }
626
627 if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
628 access(d, F_OK) < 0 && errno == ENOENT) {
629 free(d);
630 d = path_join(runtime_dir, "/systemd/inaccessible/sock");
631 if (!d)
632 return -ENOMEM;
633 }
634
635 *ret = TAKE_PTR(d);
636 return 0;
637 }
638
639 int mount_flags_to_string(unsigned long flags, char **ret) {
640 static const struct {
641 unsigned long flag;
642 const char *name;
643 } map[] = {
644 { .flag = MS_RDONLY, .name = "MS_RDONLY", },
645 { .flag = MS_NOSUID, .name = "MS_NOSUID", },
646 { .flag = MS_NODEV, .name = "MS_NODEV", },
647 { .flag = MS_NOEXEC, .name = "MS_NOEXEC", },
648 { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
649 { .flag = MS_REMOUNT, .name = "MS_REMOUNT", },
650 { .flag = MS_MANDLOCK, .name = "MS_MANDLOCK", },
651 { .flag = MS_DIRSYNC, .name = "MS_DIRSYNC", },
652 { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
653 { .flag = MS_NOATIME, .name = "MS_NOATIME", },
654 { .flag = MS_NODIRATIME, .name = "MS_NODIRATIME", },
655 { .flag = MS_BIND, .name = "MS_BIND", },
656 { .flag = MS_MOVE, .name = "MS_MOVE", },
657 { .flag = MS_REC, .name = "MS_REC", },
658 { .flag = MS_SILENT, .name = "MS_SILENT", },
659 { .flag = MS_POSIXACL, .name = "MS_POSIXACL", },
660 { .flag = MS_UNBINDABLE, .name = "MS_UNBINDABLE", },
661 { .flag = MS_PRIVATE, .name = "MS_PRIVATE", },
662 { .flag = MS_SLAVE, .name = "MS_SLAVE", },
663 { .flag = MS_SHARED, .name = "MS_SHARED", },
664 { .flag = MS_RELATIME, .name = "MS_RELATIME", },
665 { .flag = MS_KERNMOUNT, .name = "MS_KERNMOUNT", },
666 { .flag = MS_I_VERSION, .name = "MS_I_VERSION", },
667 { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
668 { .flag = MS_LAZYTIME, .name = "MS_LAZYTIME", },
669 };
670 _cleanup_free_ char *str = NULL;
671
672 assert(ret);
673
674 for (size_t i = 0; i < ELEMENTSOF(map); i++)
675 if (flags & map[i].flag) {
676 if (!strextend_with_separator(&str, "|", map[i].name))
677 return -ENOMEM;
678 flags &= ~map[i].flag;
679 }
680
681 if (!str || flags != 0)
682 if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
683 return -ENOMEM;
684
685 *ret = TAKE_PTR(str);
686 return 0;
687 }
688
689 int mount_verbose_full(
690 int error_log_level,
691 const char *what,
692 const char *where,
693 const char *type,
694 unsigned long flags,
695 const char *options,
696 bool follow_symlink) {
697
698 _cleanup_free_ char *fl = NULL, *o = NULL;
699 unsigned long f;
700 int r;
701
702 r = mount_option_mangle(options, flags, &f, &o);
703 if (r < 0)
704 return log_full_errno(error_log_level, r,
705 "Failed to mangle mount options %s: %m",
706 strempty(options));
707
708 (void) mount_flags_to_string(f, &fl);
709
710 if ((f & MS_REMOUNT) && !what && !type)
711 log_debug("Remounting %s (%s \"%s\")...",
712 where, strnull(fl), strempty(o));
713 else if (!what && !type)
714 log_debug("Mounting %s (%s \"%s\")...",
715 where, strnull(fl), strempty(o));
716 else if ((f & MS_BIND) && !type)
717 log_debug("Bind-mounting %s on %s (%s \"%s\")...",
718 what, where, strnull(fl), strempty(o));
719 else if (f & MS_MOVE)
720 log_debug("Moving mount %s %s %s (%s \"%s\")...",
721 what, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
722 else
723 log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
724 strna(what), strna(type), where, strnull(fl), strempty(o));
725
726 if (follow_symlink)
727 r = RET_NERRNO(mount(what, where, type, f, o));
728 else
729 r = mount_nofollow(what, where, type, f, o);
730 if (r < 0)
731 return log_full_errno(error_log_level, r,
732 "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
733 strna(what), strna(type), where, strnull(fl), strempty(o));
734 return 0;
735 }
736
737 int umount_verbose(
738 int error_log_level,
739 const char *what,
740 int flags) {
741
742 assert(what);
743
744 log_debug("Umounting %s...", what);
745
746 if (umount2(what, flags) < 0)
747 return log_full_errno(error_log_level, errno,
748 "Failed to unmount %s: %m", what);
749
750 return 0;
751 }
752
753 int mount_option_mangle(
754 const char *options,
755 unsigned long mount_flags,
756 unsigned long *ret_mount_flags,
757 char **ret_remaining_options) {
758
759 const struct libmnt_optmap *map;
760 _cleanup_free_ char *ret = NULL;
761 int r;
762
763 /* This extracts mount flags from the mount options, and stores
764 * non-mount-flag options to '*ret_remaining_options'.
765 * E.g.,
766 * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
767 * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
768 * "size=1630748k,mode=0700,uid=1000,gid=1000".
769 * See more examples in test-mount-util.c.
770 *
771 * If 'options' does not contain any non-mount-flag options,
772 * then '*ret_remaining_options' is set to NULL instead of empty string.
773 * The validity of options stored in '*ret_remaining_options' is not checked.
774 * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
775
776 assert(ret_mount_flags);
777 assert(ret_remaining_options);
778
779 map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
780 if (!map)
781 return -EINVAL;
782
783 for (const char *p = options;;) {
784 _cleanup_free_ char *word = NULL;
785 const struct libmnt_optmap *ent;
786
787 r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
788 if (r < 0)
789 return r;
790 if (r == 0)
791 break;
792
793 for (ent = map; ent->name; ent++) {
794 /* All entries in MNT_LINUX_MAP do not take any argument.
795 * Thus, ent->name does not contain "=" or "[=]". */
796 if (!streq(word, ent->name))
797 continue;
798
799 if (!(ent->mask & MNT_INVERT))
800 mount_flags |= ent->id;
801 else if (mount_flags & ent->id)
802 mount_flags ^= ent->id;
803
804 break;
805 }
806
807 /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
808 if (!ent->name &&
809 !startswith_no_case(word, "x-") &&
810 !strextend_with_separator(&ret, ",", word))
811 return -ENOMEM;
812 }
813
814 *ret_mount_flags = mount_flags;
815 *ret_remaining_options = TAKE_PTR(ret);
816
817 return 0;
818 }
819
820 static int mount_in_namespace(
821 pid_t target,
822 const char *propagate_path,
823 const char *incoming_path,
824 const char *src,
825 const char *dest,
826 bool read_only,
827 bool make_file_or_directory,
828 const MountOptions *options,
829 bool is_image) {
830
831 _cleanup_close_pair_ int errno_pipe_fd[2] = { -1, -1 };
832 _cleanup_close_ int mntns_fd = -1, root_fd = -1, pidns_fd = -1, chased_src_fd = -1;
833 char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
834 bool mount_slave_created = false, mount_slave_mounted = false,
835 mount_tmp_created = false, mount_tmp_mounted = false,
836 mount_outside_created = false, mount_outside_mounted = false;
837 _cleanup_free_ char *chased_src_path = NULL;
838 struct stat st;
839 pid_t child;
840 int r;
841
842 assert(target > 0);
843 assert(propagate_path);
844 assert(incoming_path);
845 assert(src);
846 assert(dest);
847 assert(!options || is_image);
848
849 r = namespace_open(target, &pidns_fd, &mntns_fd, NULL, NULL, &root_fd);
850 if (r < 0)
851 return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
852
853 r = in_same_namespace(target, 0, NAMESPACE_MOUNT);
854 if (r < 0)
855 return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
856 /* We can't add new mounts at runtime if the process wasn't started in a namespace */
857 if (r > 0)
858 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace");
859
860 /* One day, when bind mounting /proc/self/fd/n works across namespace boundaries we should rework
861 * this logic to make use of it... */
862
863 p = strjoina(propagate_path, "/");
864 r = laccess(p, F_OK);
865 if (r < 0)
866 return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
867
868 r = chase_symlinks(src, NULL, 0, &chased_src_path, &chased_src_fd);
869 if (r < 0)
870 return log_debug_errno(r, "Failed to resolve source path of %s: %m", src);
871 log_debug("Chased source path of %s to %s", src, chased_src_path);
872
873 if (fstat(chased_src_fd, &st) < 0)
874 return log_debug_errno(errno, "Failed to stat() resolved source path %s: %m", src);
875 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… */
876 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Source directory %s can't be a symbolic link", src);
877
878 /* Our goal is to install a new bind mount into the container,
879 possibly read-only. This is irritatingly complex
880 unfortunately, currently.
881
882 First, we start by creating a private playground in /tmp,
883 that we can mount MS_SLAVE. (Which is necessary, since
884 MS_MOVE cannot be applied to mounts with MS_SHARED parent
885 mounts.) */
886
887 if (!mkdtemp(mount_slave))
888 return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
889
890 mount_slave_created = true;
891
892 r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
893 if (r < 0)
894 goto finish;
895
896 mount_slave_mounted = true;
897
898 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
899 if (r < 0)
900 goto finish;
901
902 /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
903 mount_tmp = strjoina(mount_slave, "/mount");
904 if (is_image)
905 r = mkdir_p(mount_tmp, 0700);
906 else
907 r = make_mount_point_inode_from_stat(&st, mount_tmp, 0700);
908 if (r < 0) {
909 log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
910 goto finish;
911 }
912
913 mount_tmp_created = true;
914
915 if (is_image)
916 r = verity_dissect_and_mount(chased_src_fd, chased_src_path, mount_tmp, options, NULL, NULL, NULL, NULL);
917 else
918 r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
919 if (r < 0)
920 goto finish;
921
922 mount_tmp_mounted = true;
923
924 /* Third, we remount the new bind mount read-only if requested. */
925 if (read_only) {
926 r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
927 if (r < 0)
928 goto finish;
929 }
930
931 /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
932 * right-away. */
933
934 mount_outside = strjoina(propagate_path, "/XXXXXX");
935 if (is_image || S_ISDIR(st.st_mode))
936 r = mkdtemp(mount_outside) ? 0 : -errno;
937 else {
938 r = mkostemp_safe(mount_outside);
939 safe_close(r);
940 }
941 if (r < 0) {
942 log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
943 goto finish;
944 }
945
946 mount_outside_created = true;
947
948 r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
949 if (r < 0)
950 goto finish;
951
952 mount_outside_mounted = true;
953 mount_tmp_mounted = false;
954
955 if (is_image || S_ISDIR(st.st_mode))
956 (void) rmdir(mount_tmp);
957 else
958 (void) unlink(mount_tmp);
959 mount_tmp_created = false;
960
961 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
962 mount_slave_mounted = false;
963
964 (void) rmdir(mount_slave);
965 mount_slave_created = false;
966
967 if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
968 log_debug_errno(errno, "Failed to create pipe: %m");
969 goto finish;
970 }
971
972 r = namespace_fork("(sd-bindmnt)", "(sd-bindmnt-inner)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
973 pidns_fd, mntns_fd, -1, -1, root_fd, &child);
974 if (r < 0)
975 goto finish;
976 if (r == 0) {
977 const char *mount_inside;
978
979 errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
980
981 if (make_file_or_directory) {
982 if (!is_image) {
983 (void) mkdir_parents(dest, 0755);
984 (void) make_mount_point_inode_from_stat(&st, dest, 0700);
985 } else
986 (void) mkdir_p(dest, 0755);
987 }
988
989 /* Fifth, move the mount to the right place inside */
990 mount_inside = strjoina(incoming_path, basename(mount_outside));
991 r = mount_nofollow_verbose(LOG_ERR, mount_inside, dest, NULL, MS_MOVE, NULL);
992 if (r < 0)
993 goto child_fail;
994
995 _exit(EXIT_SUCCESS);
996
997 child_fail:
998 (void) write(errno_pipe_fd[1], &r, sizeof(r));
999 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1000
1001 _exit(EXIT_FAILURE);
1002 }
1003
1004 errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
1005
1006 r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
1007 if (r < 0) {
1008 log_debug_errno(r, "Failed to wait for child: %m");
1009 goto finish;
1010 }
1011 if (r != EXIT_SUCCESS) {
1012 if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
1013 log_debug_errno(r, "Failed to mount: %m");
1014 else
1015 log_debug("Child failed.");
1016 goto finish;
1017 }
1018
1019 finish:
1020 if (mount_outside_mounted)
1021 (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
1022 if (mount_outside_created) {
1023 if (is_image || S_ISDIR(st.st_mode))
1024 (void) rmdir(mount_outside);
1025 else
1026 (void) unlink(mount_outside);
1027 }
1028
1029 if (mount_tmp_mounted)
1030 (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
1031 if (mount_tmp_created) {
1032 if (is_image || S_ISDIR(st.st_mode))
1033 (void) rmdir(mount_tmp);
1034 else
1035 (void) unlink(mount_tmp);
1036 }
1037
1038 if (mount_slave_mounted)
1039 (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
1040 if (mount_slave_created)
1041 (void) rmdir(mount_slave);
1042
1043 return r;
1044 }
1045
1046 int bind_mount_in_namespace(
1047 pid_t target,
1048 const char *propagate_path,
1049 const char *incoming_path,
1050 const char *src,
1051 const char *dest,
1052 bool read_only,
1053 bool make_file_or_directory) {
1054
1055 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, NULL, false);
1056 }
1057
1058 int mount_image_in_namespace(
1059 pid_t target,
1060 const char *propagate_path,
1061 const char *incoming_path,
1062 const char *src,
1063 const char *dest,
1064 bool read_only,
1065 bool make_file_or_directory,
1066 const MountOptions *options) {
1067
1068 return mount_in_namespace(target, propagate_path, incoming_path, src, dest, read_only, make_file_or_directory, options, true);
1069 }
1070
1071 int make_mount_point(const char *path) {
1072 int r;
1073
1074 assert(path);
1075
1076 /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1077
1078 r = path_is_mount_point(path, NULL, 0);
1079 if (r < 0)
1080 return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
1081 if (r > 0)
1082 return 0;
1083
1084 r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
1085 if (r < 0)
1086 return r;
1087
1088 return 1;
1089 }
1090
1091 static int make_userns(uid_t uid_shift, uid_t uid_range, uid_t owner, RemountIdmapping idmapping) {
1092 _cleanup_close_ int userns_fd = -1;
1093 _cleanup_free_ char *line = NULL;
1094
1095 /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1096 * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1097
1098 if (IN_SET(idmapping, REMOUNT_IDMAPPING_NONE, REMOUNT_IDMAPPING_HOST_ROOT)) {
1099 if (asprintf(&line, UID_FMT " " UID_FMT " " UID_FMT "\n", 0u, uid_shift, uid_range) < 0)
1100 return log_oom_debug();
1101
1102 /* If requested we'll include an entry in the mapping so that the host root user can make
1103 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1104 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1105 * to create various missing inodes in the OS tree before booting into it, and this becomes
1106 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1107 * that in that case the container's runtime uidmap (i.e. the one the container payload
1108 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1109 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1110 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1111 * to the container's own UID range, but it's good to have a safety net, in case we
1112 * forget it.) */
1113 if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
1114 if (strextendf(&line,
1115 UID_FMT " " UID_FMT " " UID_FMT "\n",
1116 UID_MAPPED_ROOT, 0u, 1u) < 0)
1117 return log_oom_debug();
1118 }
1119
1120 if (idmapping == REMOUNT_IDMAPPING_HOST_OWNER) {
1121 /* Remap the owner of the bind mounted directory to the root user within the container. This
1122 * way every file written by root within the container to the bind-mounted directory will
1123 * be owned by the original user. All other user will remain unmapped. */
1124 if (asprintf(&line, UID_FMT " " UID_FMT " " UID_FMT "\n", owner, uid_shift, 1u) < 0)
1125 return log_oom_debug();
1126 }
1127
1128 /* We always assign the same UID and GID ranges */
1129 userns_fd = userns_acquire(line, line);
1130 if (userns_fd < 0)
1131 return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
1132
1133 return TAKE_FD(userns_fd);
1134 }
1135
1136 int remount_idmap(
1137 const char *p,
1138 uid_t uid_shift,
1139 uid_t uid_range,
1140 uid_t owner,
1141 RemountIdmapping idmapping) {
1142
1143 _cleanup_close_ int mount_fd = -1, userns_fd = -1;
1144 int r;
1145
1146 assert(p);
1147
1148 if (!userns_shift_range_valid(uid_shift, uid_range))
1149 return -EINVAL;
1150
1151 /* Clone the mount point */
1152 mount_fd = open_tree(-1, p, OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
1153 if (mount_fd < 0)
1154 return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", p);
1155
1156 /* Create a user namespace mapping */
1157 userns_fd = make_userns(uid_shift, uid_range, owner, idmapping);
1158 if (userns_fd < 0)
1159 return userns_fd;
1160
1161 /* Set the user namespace mapping attribute on the cloned mount point */
1162 if (mount_setattr(mount_fd, "", AT_EMPTY_PATH | AT_RECURSIVE,
1163 &(struct mount_attr) {
1164 .attr_set = MOUNT_ATTR_IDMAP,
1165 .userns_fd = userns_fd,
1166 }, sizeof(struct mount_attr)) < 0)
1167 return log_debug_errno(errno, "Failed to change bind mount attributes for '%s': %m", p);
1168
1169 /* Remove the old mount point */
1170 r = umount_verbose(LOG_DEBUG, p, UMOUNT_NOFOLLOW);
1171 if (r < 0)
1172 return r;
1173
1174 /* And place the cloned version in its place */
1175 if (move_mount(mount_fd, "", -1, p, MOVE_MOUNT_F_EMPTY_PATH) < 0)
1176 return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", p);
1177
1178 return 0;
1179 }
1180
1181 int make_mount_point_inode_from_stat(const struct stat *st, const char *dest, mode_t mode) {
1182 assert(st);
1183 assert(dest);
1184
1185 if (S_ISDIR(st->st_mode))
1186 return mkdir_label(dest, mode);
1187 else
1188 return RET_NERRNO(mknod(dest, S_IFREG|(mode & ~0111), 0));
1189 }
1190
1191 int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t mode) {
1192 struct stat st;
1193
1194 assert(source);
1195 assert(dest);
1196
1197 if (stat(source, &st) < 0)
1198 return -errno;
1199
1200 return make_mount_point_inode_from_stat(&st, dest, mode);
1201 }