• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 16082515961

04 Jul 2025 08:23PM UTC coverage: 72.095% (-0.1%) from 72.193%
16082515961

push

github

poettering
seccomp-util: allowlist open_tree() as part of @file-system

Now that we make use of open_tree() in places we previously used
openat() with O_PATH, it makes sense to move it from @mount to
@file-system. Without the OPEN_TREE_CLONE flag open_tree() is after all
unprivileged.

Note that open_tree_attr() I left in @mount, since it's purpose is
really to set mount options when cloning, and that's clearly a mount
related thing, not so much something you could use unpriv.

Follow-up for: c5de7b14a

This addresses an issue tracked down by Antonio Feijoo: since the commit
that started to use open_tree() various apps started to crash because
they used seccomp filters and sd-device started to use open_tree()
internally.

300842 of 417287 relevant lines covered (72.09%)

715300.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.02
/src/shared/mount-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdlib.h>
4
#include <sys/mount.h>
5
#include <sys/stat.h>
6
#include <unistd.h>
7

8
#include "alloc-util.h"
9
#include "chase.h"
10
#include "dissect-image.h"
11
#include "errno-util.h"
12
#include "extract-word.h"
13
#include "fd-util.h"
14
#include "fileio.h"
15
#include "format-util.h"
16
#include "fs-util.h"
17
#include "fstab-util.h"
18
#include "glyph-util.h"
19
#include "hashmap.h"
20
#include "libmount-util.h"
21
#include "log.h"
22
#include "missing_syscall.h"
23
#include "mkdir-label.h"
24
#include "mount-util.h"
25
#include "mountpoint-util.h"
26
#include "namespace-util.h"
27
#include "os-util.h"
28
#include "path-util.h"
29
#include "pidref.h"
30
#include "process-util.h"
31
#include "set.h"
32
#include "sort-util.h"
33
#include "stat-util.h"
34
#include "string-util.h"
35
#include "strv.h"
36
#include "tmpfile-util.h"
37
#include "user-util.h"
38

39
int umount_recursive_full(const char *prefix, int flags, char **keep) {
8,701✔
40
        _cleanup_fclose_ FILE *f = NULL;
8,701✔
41
        int n = 0, r;
8,701✔
42

43
        /* Try to umount everything recursively below a directory. Also, take care of stacked mounts, and
44
         * keep unmounting them until they are gone. */
45

46
        f = fopen("/proc/self/mountinfo", "re"); /* Pin the file, in case we unmount /proc/ as part of the logic here */
8,701✔
47
        if (!f)
8,701✔
48
                return log_debug_errno(errno, "Failed to open %s: %m", "/proc/self/mountinfo");
×
49

50
        for (;;) {
44,853✔
51
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
18,076✔
52
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
26,777✔
53
                bool again = false;
26,777✔
54

55
                r = libmount_parse_mountinfo(f, &table, &iter);
26,777✔
56
                if (r < 0)
26,777✔
57
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
58

59
                for (;;) {
2,866,897✔
60
                        bool shall_keep = false;
1,446,837✔
61
                        struct libmnt_fs *fs;
1,446,837✔
62
                        const char *path;
1,446,837✔
63

64
                        r = mnt_table_next_fs(table, iter, &fs);
1,446,837✔
65
                        if (r == 1)
1,446,837✔
66
                                break;
67
                        if (r < 0)
1,438,136✔
68
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
69

70
                        path = mnt_fs_get_target(fs);
1,438,136✔
71
                        if (!path)
1,438,136✔
72
                                continue;
1,420,060✔
73

74
                        if (prefix && !path_startswith(path, prefix)) {
2,875,941✔
75
                                // FIXME: This is extremely noisy, we're probably doing something very wrong
76
                                // to trigger this so often, needs more investigation.
77
                                // log_trace("Not unmounting %s, outside of prefix: %s", path, prefix);
78
                                continue;
1,410,906✔
79
                        }
80

81
                        STRV_FOREACH(k, keep)
27,300✔
82
                                /* Match against anything in the path to the dirs to keep, or below the dirs to keep */
83
                                if (path_startswith(path, *k) || path_startswith(*k, path)) {
346✔
84
                                        shall_keep = true;
276✔
85
                                        break;
276✔
86
                                }
87
                        if (shall_keep) {
27,506✔
88
                                log_debug("Not unmounting %s, referenced by keep list.", path);
276✔
89
                                continue;
276✔
90
                        }
91

92
                        if (umount2(path, flags | UMOUNT_NOFOLLOW) < 0) {
26,954✔
93
                                log_debug_errno(errno, "Failed to umount %s, ignoring: %m", path);
8,878✔
94
                                continue;
8,878✔
95
                        }
96

97
                        log_trace("Successfully unmounted %s", path);
18,076✔
98

99
                        again = true;
18,076✔
100
                        n++;
18,076✔
101

102
                        break;
18,076✔
103
                }
104

105
                if (!again)
8,701✔
106
                        break;
107

108
                rewind(f);
18,076✔
109
        }
110

111
        return n;
8,701✔
112
}
113

114
#define MS_CONVERTIBLE_FLAGS (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_NOSYMFOLLOW)
115

116
static uint64_t ms_flags_to_mount_attr(unsigned long a) {
38,486✔
117
        uint64_t f = 0;
38,486✔
118

119
        if (FLAGS_SET(a, MS_RDONLY))
38,486✔
120
                f |= MOUNT_ATTR_RDONLY;
1,428✔
121

122
        if (FLAGS_SET(a, MS_NOSUID))
38,486✔
123
                f |= MOUNT_ATTR_NOSUID;
17,817✔
124

125
        if (FLAGS_SET(a, MS_NODEV))
38,486✔
126
                f |= MOUNT_ATTR_NODEV;
2✔
127

128
        if (FLAGS_SET(a, MS_NOEXEC))
38,486✔
129
                f |= MOUNT_ATTR_NOEXEC;
2✔
130

131
        if (FLAGS_SET(a, MS_NOSYMFOLLOW))
38,486✔
132
                f |= MOUNT_ATTR_NOSYMFOLLOW;
×
133

134
        return f;
38,486✔
135
}
136

137
static bool skip_mount_set_attr = false;
138

139
/* Use this function only if you do not have direct access to /proc/self/mountinfo but the caller can open it
140
 * for you. This is the case when /proc is masked or not mounted. Otherwise, use bind_remount_recursive. */
141
int bind_remount_recursive_with_mountinfo(
37,003✔
142
                const char *prefix,
143
                unsigned long new_flags,
144
                unsigned long flags_mask,
145
                char **deny_list,
146
                FILE *proc_self_mountinfo) {
147

148
        _cleanup_fclose_ FILE *proc_self_mountinfo_opened = NULL;
37,003✔
149
        _cleanup_set_free_ Set *done = NULL;
37,003✔
150
        unsigned n_tries = 0;
37,003✔
151
        int r;
37,003✔
152

153
        assert(prefix);
37,003✔
154

155
        if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && strv_isempty(deny_list) && !skip_mount_set_attr) {
54,039✔
156
                /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
157

158
                if (mount_setattr(AT_FDCWD, prefix, AT_SYMLINK_NOFOLLOW|AT_RECURSIVE,
17,036✔
159
                                  &(struct mount_attr) {
17,036✔
160
                                          .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
17,036✔
161
                                          .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
17,036✔
162
                                  }, MOUNT_ATTR_SIZE_VER0) < 0) {
163

164
                        log_debug_errno(errno, "mount_setattr() failed, falling back to classic remounting: %m");
2✔
165

166
                        /* We fall through to classic behaviour if not supported (i.e. kernel < 5.12). We
167
                         * also do this for all other kinds of errors since they are so many different, and
168
                         * mount_setattr() has no graceful mode where it continues despite seeing errors one
169
                         * some mounts, but we want that. Moreover mount_setattr() only works on the mount
170
                         * point inode itself, not a non-mount point inode, and we want to support arbitrary
171
                         * prefixes here. */
172

173
                        if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
2✔
174
                                skip_mount_set_attr = true;
×
175
                } else
176
                        return 0; /* Nice, this worked! */
17,034✔
177
        }
178

179
        if (!proc_self_mountinfo) {
19,969✔
180
                r = fopen_unlocked("/proc/self/mountinfo", "re", &proc_self_mountinfo_opened);
3✔
181
                if (r < 0)
3✔
182
                        return r;
183

184
                proc_self_mountinfo = proc_self_mountinfo_opened;
3✔
185
        }
186

187
        /* Recursively remount a directory (and all its submounts) with desired flags (MS_READONLY,
188
         * MS_NOSUID, MS_NOEXEC). If the directory is already mounted, we reuse the mount and simply mark it
189
         * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write operation), ditto for other flags. If it
190
         * isn't we first make it one. Afterwards we apply (or remove) the flags to all submounts we can
191
         * access, too. When mounts are stacked on the same mount point we only care for each individual
192
         * "top-level" mount on each point, as we cannot influence/access the underlying mounts anyway. We do
193
         * not have any effect on future submounts that might get propagated, they might be writable
194
         * etc. This includes future submounts that have been triggered via autofs. Also note that we can't
195
         * operate atomically here. Mounts established while we process the tree might or might not get
196
         * noticed and thus might or might not be covered.
197
         *
198
         * If the "deny_list" parameter is specified it may contain a list of subtrees to exclude from the
199
         * remount operation. Note that we'll ignore the deny list for the top-level path. */
200

201
        for (;;) {
39,941✔
202
                _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
39,941✔
203
                _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
39,941✔
204
                _cleanup_hashmap_free_ Hashmap *todo = NULL;
39,939✔
205
                bool top_autofs = false;
39,941✔
206

207
                if (n_tries++ >= 32) /* Let's not retry this loop forever */
39,941✔
208
                        return -EBUSY;
209

210
                rewind(proc_self_mountinfo);
39,941✔
211

212
                r = libmount_parse_mountinfo(proc_self_mountinfo, &table, &iter);
39,941✔
213
                if (r < 0)
39,941✔
214
                        return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
215

216
                for (;;) {
2,790,167✔
217
                        _cleanup_free_ char *d = NULL;
2,750,226✔
218
                        const char *path, *type, *opts;
2,790,167✔
219
                        unsigned long flags = 0;
2,790,167✔
220
                        struct libmnt_fs *fs;
2,790,167✔
221

222
                        r = mnt_table_next_fs(table, iter, &fs);
2,790,167✔
223
                        if (r == 1) /* EOF */
2,790,167✔
224
                                break;
225
                        if (r < 0)
2,750,226✔
226
                                return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
227

228
                        path = mnt_fs_get_target(fs);
2,750,226✔
229
                        if (!path)
2,750,226✔
230
                                continue;
×
231

232
                        if (!path_startswith(path, prefix))
2,750,226✔
233
                                continue;
2,681,640✔
234

235
                        type = mnt_fs_get_fstype(fs);
68,586✔
236
                        if (!type)
68,586✔
237
                                continue;
×
238

239
                        /* Let's ignore autofs mounts. If they aren't triggered yet, we want to avoid
240
                         * triggering them, as we don't make any guarantees for future submounts anyway. If
241
                         * they are already triggered, then we will find another entry for this. */
242
                        if (streq(type, "autofs")) {
68,586✔
243
                                top_autofs = top_autofs || path_equal(path, prefix);
6,184✔
244
                                continue;
3,092✔
245
                        }
246

247
                        if (set_contains(done, path))
65,494✔
248
                                continue;
23,697✔
249

250
                        /* Ignore this mount if it is deny-listed, but only if it isn't the top-level mount
251
                         * we shall operate on. */
252
                        if (!path_equal(path, prefix)) {
41,797✔
253
                                bool deny_listed = false;
286,333✔
254

255
                                STRV_FOREACH(i, deny_list) {
286,333✔
256
                                        if (path_equal(*i, prefix))
282,607✔
257
                                                continue;
21,815✔
258

259
                                        if (!path_startswith(*i, prefix))
260,792✔
260
                                                continue;
141,808✔
261

262
                                        if (path_startswith(path, *i)) {
118,984✔
263
                                                deny_listed = true;
264
                                                log_trace("Not remounting %s deny-listed by %s, called for %s", path, *i, prefix);
265
                                                break;
266
                                        }
267
                                }
268

269
                                if (deny_listed)
21,826✔
270
                                        continue;
18,100✔
271
                        }
272

273
                        opts = mnt_fs_get_vfs_options(fs);
23,697✔
274
                        if (opts) {
23,697✔
275
                                r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
23,697✔
276
                                if (r < 0)
23,697✔
277
                                        log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
×
278
                        }
279

280
                        d = strdup(path);
23,697✔
281
                        if (!d)
23,697✔
282
                                return -ENOMEM;
283

284
                        r = hashmap_ensure_put(&todo, &path_hash_ops_free, d, ULONG_TO_PTR(flags));
23,697✔
285
                        if (r == -EEXIST)
23,697✔
286
                                /* If the same path was recorded, but with different mount flags, update it:
287
                                 * it means a mount point is overmounted, and libmount returns the "bottom" (or
288
                                 * older one) first, but we want to reapply the flags from the "top" (or newer
289
                                 * one). See: https://github.com/systemd/systemd/issues/20032
290
                                 * Note that this shouldn't really fail, as we were just told that the key
291
                                 * exists, and it's an update so we want 'd' to be freed immediately. */
292
                                r = hashmap_update(todo, d, ULONG_TO_PTR(flags));
8✔
293
                        if (r < 0)
23,697✔
294
                                return r;
295
                        if (r > 0)
23,697✔
296
                                TAKE_PTR(d);
23,656✔
297
                }
298

299
                /* Check if the top-level directory was among what we have seen so far. For that check both
300
                 * 'done' and 'todo'. Also check 'top_autofs' because if the top-level dir is an autofs we'll
301
                 * not include it in either set but will set this bool. */
302
                if (!set_contains(done, prefix) &&
39,941✔
303
                    !(top_autofs || hashmap_contains(todo, prefix))) {
19,971✔
304

305
                        /* The prefix directory itself is not yet a mount, make it one. */
306
                        r = mount_nofollow(prefix, prefix, NULL, MS_BIND|MS_REC, NULL);
2✔
307
                        if (r < 0)
2✔
308
                                return r;
309

310
                        /* Immediately rescan, so that we pick up the new mount's flags */
311
                        continue;
2✔
312
                }
313

314
                /* If we have no submounts to process anymore, we are done */
315
                if (hashmap_isempty(todo))
39,939✔
316
                        return 0;
317

318
                for (;;) {
43,625✔
319
                        unsigned long flags;
43,625✔
320
                        char *x = NULL;
43,625✔
321

322
                        /* Take the first mount from our list of mounts to still process */
323
                        flags = PTR_TO_ULONG(hashmap_steal_first_key_and_value(todo, (void**) &x));
43,625✔
324
                        if (!x)
43,625✔
325
                                break;
326

327
                        r = set_ensure_consume(&done, &path_hash_ops_free, x);
23,655✔
328
                        if (IN_SET(r, 0, -EEXIST))
23,655✔
329
                                continue; /* Already done */
211✔
330
                        if (r < 0)
23,655✔
331
                                return r;
×
332

333
                        /* Now, remount this with the new flags set, but exclude MS_RELATIME from it. (It's
334
                         * the default anyway, thus redundant, and in userns we'll get an error if we try to
335
                         * explicitly enable it) */
336
                        r = mount_nofollow(NULL, x, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
23,655✔
337
                        if (r < 0) {
23,655✔
338
                                int q;
211✔
339

340
                                /* OK, so the remount of this entry failed. We'll ultimately ignore this in
341
                                 * almost all cases (there are simply so many reasons why this can fail,
342
                                 * think autofs, NFS, FUSE, …), but let's generate useful debug messages at
343
                                 * the very least. */
344

345
                                q = path_is_mount_point(x);
211✔
346
                                if (IN_SET(q, 0, -ENOENT)) {
211✔
347
                                        /* Hmm, whaaaa? The mount point is not actually a mount point? Then
348
                                         * it is either obstructed by a later mount or somebody has been
349
                                         * racing against us and removed it. Either way the mount point
350
                                         * doesn't matter to us, let's ignore it hence. */
351
                                        log_debug_errno(r, "Mount point '%s' to remount is not a mount point anymore, ignoring remount failure: %m", x);
208✔
352
                                        continue;
208✔
353
                                }
354
                                if (q < 0) /* Any other error on this? Just log and continue */
3✔
355
                                        log_debug_errno(q, "Failed to determine whether '%s' is a mount point or not, ignoring: %m", x);
×
356

357
                                if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) == 0) { /* ignore MS_RELATIME while comparing */
3✔
358
                                        log_debug_errno(r, "Couldn't remount '%s', but the flags already match what we want, hence ignoring: %m", x);
×
359
                                        continue;
×
360
                                }
361

362
                                /* Make this fatal if this is the top-level mount */
363
                                if (path_equal(x, prefix))
3✔
364
                                        return r;
365

366
                                /* If this is not the top-level mount, then handle this gracefully: log but
367
                                 * otherwise ignore. With NFS, FUSE, autofs there are just too many reasons
368
                                 * this might fail without a chance for us to do anything about it, let's
369
                                 * hence be strict on the top-level mount and lenient on the inner ones. */
370
                                log_debug_errno(r, "Couldn't remount submount '%s' for unexpected reason, ignoring: %m", x);
3✔
371
                                continue;
3✔
372
                        }
373

374
                        log_trace("Remounted %s.", x);
23,444✔
375
                }
376
        }
377
}
378

379
int bind_remount_one_with_mountinfo(
2,206✔
380
                const char *path,
381
                unsigned long new_flags,
382
                unsigned long flags_mask,
383
                FILE *proc_self_mountinfo) {
384

385
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
2,206✔
386
        unsigned long flags = 0;
2,206✔
387
        struct libmnt_fs *fs;
2,206✔
388
        const char *opts;
2,206✔
389
        int r;
2,206✔
390

391
        assert(path);
2,206✔
392
        assert(proc_self_mountinfo);
2,206✔
393

394
        if ((flags_mask & ~MS_CONVERTIBLE_FLAGS) == 0 && !skip_mount_set_attr) {
2,206✔
395
                /* Let's take a shortcut for all the flags we know how to convert into mount_setattr() flags */
396

397
                if (mount_setattr(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW,
2,206✔
398
                                  &(struct mount_attr) {
2,206✔
399
                                          .attr_set = ms_flags_to_mount_attr(new_flags & flags_mask),
2,206✔
400
                                          .attr_clr = ms_flags_to_mount_attr(~new_flags & flags_mask),
2,206✔
401
                                  }, MOUNT_ATTR_SIZE_VER0) < 0) {
402

403
                        log_debug_errno(errno, "mount_setattr() didn't work, falling back to classic remounting: %m");
4✔
404

405
                        if (ERRNO_IS_NOT_SUPPORTED(errno)) /* if not supported, then don't bother at all anymore */
4✔
406
                                skip_mount_set_attr = true;
×
407
                } else
408
                        return 0; /* Nice, this worked! */
2,202✔
409
        }
410

411
        rewind(proc_self_mountinfo);
4✔
412

413
        table = mnt_new_table();
4✔
414
        if (!table)
4✔
415
                return -ENOMEM;
416

417
        r = mnt_table_parse_stream(table, proc_self_mountinfo, "/proc/self/mountinfo");
4✔
418
        if (r < 0)
4✔
419
                return r;
420

421
        fs = mnt_table_find_target(table, path, MNT_ITER_FORWARD);
4✔
422
        if (!fs) {
4✔
423
                r = access_nofollow(path, F_OK); /* Hmm, it's not in the mount table, but does it exist at all? */
4✔
424
                if (r < 0)
4✔
425
                        return r;
426

427
                return -EINVAL; /* Not a mount point we recognize */
2✔
428
        }
429

430
        opts = mnt_fs_get_vfs_options(fs);
×
431
        if (opts) {
×
432
                r = mnt_optstr_get_flags(opts, &flags, mnt_get_builtin_optmap(MNT_LINUX_MAP));
×
433
                if (r < 0)
×
434
                        log_debug_errno(r, "Could not get flags for '%s', ignoring: %m", path);
×
435
        }
436

437
        r = mount_nofollow(NULL, path, NULL, ((flags & ~flags_mask)|MS_BIND|MS_REMOUNT|new_flags) & ~MS_RELATIME, NULL);
×
438
        if (r < 0) {
×
439
                if (((flags ^ new_flags) & flags_mask & ~MS_RELATIME) != 0) /* Ignore MS_RELATIME again,
×
440
                                                                             * since kernel adds it in
441
                                                                             * everywhere, because it's the
442
                                                                             * default. */
443
                        return r;
444

445
                /* Let's handle redundant remounts gracefully */
446
                log_debug_errno(r, "Failed to remount '%s' but flags already match what we want, ignoring: %m", path);
4✔
447
        }
448

449
        return 0;
450
}
451

452
int bind_remount_one(const char *path, unsigned long new_flags, unsigned long flags_mask) {
53✔
453
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
53✔
454

455
        proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
53✔
456
        if (!proc_self_mountinfo)
53✔
457
                return log_debug_errno(errno, "Failed to open %s: %m", "/proc/self/mountinfo");
×
458

459
        return bind_remount_one_with_mountinfo(path, new_flags, flags_mask, proc_self_mountinfo);
53✔
460
}
461

462
static int mount_switch_root_pivot(int fd_newroot, const char *path) {
2,231✔
463
        assert(fd_newroot >= 0);
2,231✔
464
        assert(path);
2,231✔
465

466
        /* Let the kernel tuck the new root under the old one. */
467
        if (pivot_root(".", ".") < 0)
2,231✔
468
                return log_debug_errno(errno, "Failed to pivot root to new rootfs '%s': %m", path);
×
469

470
        /* Get rid of the old root and reveal our brand new root. (This will always operate on the top-most
471
         * mount on our cwd, regardless what our current directory actually points to.) */
472
        if (umount2(".", MNT_DETACH) < 0)
2,231✔
473
                return log_debug_errno(errno, "Failed to unmount old rootfs: %m");
×
474

475
        return 0;
476
}
477

478
static int mount_switch_root_move(int fd_newroot, const char *path) {
×
479
        assert(fd_newroot >= 0);
×
480
        assert(path);
×
481

482
        /* Move the new root fs */
483
        if (mount(".", "/", NULL, MS_MOVE, NULL) < 0)
×
484
                return log_debug_errno(errno, "Failed to move new rootfs '%s': %m", path);
×
485

486
        /* Also change root dir */
487
        if (chroot(".") < 0)
×
488
                return log_debug_errno(errno, "Failed to chroot to new rootfs '%s': %m", path);
×
489

490
        return 0;
491
}
492

493
int mount_switch_root_full(const char *path, unsigned long mount_propagation_flag, bool force_ms_move) {
2,233✔
494
        _cleanup_close_ int fd_newroot = -EBADF;
2,233✔
495
        int r, is_current_root;
2,233✔
496

497
        assert(path);
2,233✔
498
        assert(mount_propagation_flag_is_valid(mount_propagation_flag));
2,233✔
499

500
        fd_newroot = open(path, O_PATH|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
2,233✔
501
        if (fd_newroot < 0)
2,233✔
502
                return log_debug_errno(errno, "Failed to open new rootfs '%s': %m", path);
×
503

504
        is_current_root = path_is_root_at(fd_newroot, NULL);
2,233✔
505
        if (is_current_root < 0)
2,233✔
506
                return log_debug_errno(is_current_root, "Failed to determine if target dir is our root already: %m");
×
507

508
        /* Change into the new rootfs. */
509
        if (fchdir(fd_newroot) < 0)
2,233✔
510
                return log_debug_errno(errno, "Failed to chdir into new rootfs '%s': %m", path);
×
511

512
        /* Make this a NOP if we are supposed to switch to our current root fs. After all, both pivot_root()
513
         * and MS_MOVE don't like that. */
514
        if (!is_current_root) {
2,233✔
515
                if (!force_ms_move) {
2,231✔
516
                        r = mount_switch_root_pivot(fd_newroot, path);
2,231✔
517
                        if (r < 0) {
2,231✔
518
                                log_debug_errno(r, "Failed to pivot into new rootfs '%s', will try to use MS_MOVE instead: %m", path);
×
519
                                force_ms_move = true;
520
                        }
521
                }
522
                if (force_ms_move) {
523
                        /* Failed to pivot_root() fallback to MS_MOVE. For example, this may happen if the rootfs is
524
                         * an initramfs in which case pivot_root() isn't supported. */
525
                        r = mount_switch_root_move(fd_newroot, path);
×
526
                        if (r < 0)
×
527
                                return log_debug_errno(r, "Failed to switch to new rootfs '%s' with MS_MOVE: %m", path);
×
528
                }
529
        }
530

531
        log_debug("Successfully switched root to '%s'.", path);
2,233✔
532

533
        /* Finally, let's establish the requested propagation flags. */
534
        if (mount_propagation_flag == 0)
2,233✔
535
                return 0;
536

537
        if (mount(NULL, ".", NULL, mount_propagation_flag | MS_REC, NULL) < 0)
227✔
538
                return log_debug_errno(errno, "Failed to turn new rootfs '%s' into %s mount: %m",
×
539
                                       mount_propagation_flag_to_string(mount_propagation_flag), path);
540

541
        return 0;
542
}
543

544
int repeat_unmount(const char *path, int flags) {
15✔
545
        bool done = false;
15✔
546

547
        assert(path);
15✔
548

549
        /* If there are multiple mounts on a mount point, this
550
         * removes them all */
551

552
        for (;;) {
30✔
553
                if (umount2(path, flags) < 0) {
30✔
554

555
                        if (errno == EINVAL)
15✔
556
                                return done;
15✔
557

558
                        return -errno;
×
559
                }
560

561
                done = true;
562
        }
563
}
564

565
int mode_to_inaccessible_node(
4,890✔
566
                const char *runtime_dir,
567
                mode_t mode,
568
                char **ret) {
569

570
        /* This function maps a node type to a corresponding inaccessible file node. These nodes are created
571
         * during early boot by PID 1. In some cases we lacked the privs to create the character and block
572
         * devices (maybe because we run in an userns environment, or miss CAP_SYS_MKNOD, or run with a
573
         * devices policy that excludes device nodes with major and minor of 0), but that's fine, in that
574
         * case we use an AF_UNIX file node instead, which is not the same, but close enough for most
575
         * uses. And most importantly, the kernel allows bind mounts from socket nodes to any non-directory
576
         * file nodes, and that's the most important thing that matters.
577
         *
578
         * Note that the runtime directory argument shall be the top-level runtime directory, i.e. /run/ if
579
         * we operate in system context and $XDG_RUNTIME_DIR if we operate in user context. */
580

581
        _cleanup_free_ char *d = NULL;
4,890✔
582
        const char *node;
4,890✔
583

584
        assert(ret);
4,890✔
585

586
        if (!runtime_dir)
4,890✔
587
                runtime_dir = "/run";
4✔
588

589
        if (S_ISLNK(mode))
4,890✔
590
                return -EINVAL;
591

592
        node = inode_type_to_string(mode);
4,890✔
593
        if (!node)
4,890✔
594
                return -EINVAL;
595

596
        d = path_join(runtime_dir, "systemd/inaccessible", node);
4,890✔
597
        if (!d)
4,890✔
598
                return -ENOMEM;
599

600
        /* On new kernels unprivileged users are permitted to create 0:0 char device nodes (because they also
601
         * act as whiteout inode for overlayfs), but no other char or block device nodes. On old kernels no
602
         * device node whatsoever may be created by unprivileged processes. Hence, if the caller asks for the
603
         * inaccessible block device node let's see if the block device node actually exists, and if not,
604
         * fall back to the character device node. From there fall back to the socket device node. This means
605
         * in the best case we'll get the right device node type — but if not we'll hopefully at least get a
606
         * device node at all. */
607

608
        if (S_ISBLK(mode) &&
4,890✔
609
            access(d, F_OK) < 0 && errno == ENOENT) {
×
610
                free(d);
×
611
                d = path_join(runtime_dir, "/systemd/inaccessible/chr");
×
612
                if (!d)
×
613
                        return -ENOMEM;
614
        }
615

616
        if (IN_SET(mode & S_IFMT, S_IFBLK, S_IFCHR) &&
5,414✔
617
            access(d, F_OK) < 0 && errno == ENOENT) {
524✔
618
                free(d);
×
619
                d = path_join(runtime_dir, "/systemd/inaccessible/sock");
×
620
                if (!d)
×
621
                        return -ENOMEM;
622
        }
623

624
        *ret = TAKE_PTR(d);
4,890✔
625
        return 0;
4,890✔
626
}
627

628
int mount_flags_to_string(unsigned long flags, char **ret) {
48,724✔
629
        static const struct {
48,724✔
630
                unsigned long flag;
631
                const char *name;
632
        } map[] = {
633
                { .flag = MS_RDONLY,      .name = "MS_RDONLY",      },
634
                { .flag = MS_NOSUID,      .name = "MS_NOSUID",      },
635
                { .flag = MS_NODEV,       .name = "MS_NODEV",       },
636
                { .flag = MS_NOEXEC,      .name = "MS_NOEXEC",      },
637
                { .flag = MS_SYNCHRONOUS, .name = "MS_SYNCHRONOUS", },
638
                { .flag = MS_REMOUNT,     .name = "MS_REMOUNT",     },
639
                { .flag = MS_MANDLOCK,    .name = "MS_MANDLOCK",    },
640
                { .flag = MS_DIRSYNC,     .name = "MS_DIRSYNC",     },
641
                { .flag = MS_NOSYMFOLLOW, .name = "MS_NOSYMFOLLOW", },
642
                { .flag = MS_NOATIME,     .name = "MS_NOATIME",     },
643
                { .flag = MS_NODIRATIME,  .name = "MS_NODIRATIME",  },
644
                { .flag = MS_BIND,        .name = "MS_BIND",        },
645
                { .flag = MS_MOVE,        .name = "MS_MOVE",        },
646
                { .flag = MS_REC,         .name = "MS_REC",         },
647
                { .flag = MS_SILENT,      .name = "MS_SILENT",      },
648
                { .flag = MS_POSIXACL,    .name = "MS_POSIXACL",    },
649
                { .flag = MS_UNBINDABLE,  .name = "MS_UNBINDABLE",  },
650
                { .flag = MS_PRIVATE,     .name = "MS_PRIVATE",     },
651
                { .flag = MS_SLAVE,       .name = "MS_SLAVE",       },
652
                { .flag = MS_SHARED,      .name = "MS_SHARED",      },
653
                { .flag = MS_RELATIME,    .name = "MS_RELATIME",    },
654
                { .flag = MS_KERNMOUNT,   .name = "MS_KERNMOUNT",   },
655
                { .flag = MS_I_VERSION,   .name = "MS_I_VERSION",   },
656
                { .flag = MS_STRICTATIME, .name = "MS_STRICTATIME", },
657
                { .flag = MS_LAZYTIME,    .name = "MS_LAZYTIME",    },
658
        };
659
        _cleanup_free_ char *str = NULL;
48,724✔
660

661
        assert(ret);
48,724✔
662

663
        FOREACH_ELEMENT(entry, map)
1,266,824✔
664
                if (flags & entry->flag) {
1,218,100✔
665
                        if (!strextend_with_separator(&str, "|", entry->name))
115,834✔
666
                                return -ENOMEM;
667
                        flags &= ~entry->flag;
115,834✔
668
                }
669

670
        if (!str || flags != 0)
48,724✔
671
                if (strextendf_with_separator(&str, "|", "%lx", flags) < 0)
158✔
672
                        return -ENOMEM;
673

674
        *ret = TAKE_PTR(str);
48,724✔
675
        return 0;
48,724✔
676
}
677

678
int mount_verbose_full(
48,694✔
679
                int error_log_level,
680
                const char *what,
681
                const char *where,
682
                const char *type,
683
                unsigned long flags,
684
                const char *options,
685
                bool follow_symlink) {
686

687
        _cleanup_free_ char *fl = NULL, *o = NULL;
48,694✔
688
        unsigned long f;
48,694✔
689
        int r;
48,694✔
690

691
        r = mount_option_mangle(options, flags, &f, &o);
48,694✔
692
        if (r < 0)
48,694✔
693
                return log_full_errno(error_log_level, r,
×
694
                                      "Failed to mangle mount options %s: %m",
695
                                      strempty(options));
696

697
        (void) mount_flags_to_string(f, &fl);
48,694✔
698

699
        if (FLAGS_SET(f, MS_REMOUNT|MS_BIND))
48,694✔
700
                log_debug("Changing mount flags %s (%s \"%s\")...",
10,583✔
701
                          where, strnull(fl), strempty(o));
702
        else if (f & MS_REMOUNT)
43,402✔
703
                log_debug("Remounting superblock %s (%s \"%s\")...",
4✔
704
                          where, strnull(fl), strempty(o));
705
        else if (f & (MS_SHARED|MS_PRIVATE|MS_SLAVE|MS_UNBINDABLE))
43,398✔
706
                log_debug("Changing mount propagation %s (%s \"%s\")",
6,370✔
707
                          where, strnull(fl), strempty(o));
708
        else if (f & MS_BIND)
40,213✔
709
                log_debug("Bind-mounting %s on %s (%s \"%s\")...",
56,581✔
710
                          what, where, strnull(fl), strempty(o));
711
        else if (f & MS_MOVE)
11,849✔
712
                log_debug("Moving mount %s %s %s (%s \"%s\")...",
7,466✔
713
                          what, glyph(GLYPH_ARROW_RIGHT), where, strnull(fl), strempty(o));
714
        else
715
                log_debug("Mounting %s (%s) on %s (%s \"%s\")...",
9,435✔
716
                          strna(what), strna(type), where, strnull(fl), strempty(o));
717

718
        if (follow_symlink)
48,694✔
719
                r = RET_NERRNO(mount(what, where, type, f, o));
49,082✔
720
        else
721
                r = mount_nofollow(what, where, type, f, o);
43,584✔
722
        if (r < 0)
43,972✔
723
                return log_full_errno(error_log_level, r,
8,917✔
724
                                      "Failed to mount %s (type %s) on %s (%s \"%s\"): %m",
725
                                      strna(what), strna(type), where, strnull(fl), strempty(o));
726
        return 0;
727
}
728

729
int umount_verbose(
485✔
730
                int error_log_level,
731
                const char *where,
732
                int flags) {
733

734
        assert(where);
485✔
735

736
        log_debug("Unmounting '%s'...", where);
485✔
737

738
        if (umount2(where, flags) < 0)
485✔
739
                return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", where);
89✔
740

741
        return 0;
742
}
743

744
int umountat_detach_verbose(
224✔
745
                int error_log_level,
746
                int fd,
747
                const char *where) {
748

749
        /* Similar to umountat_verbose(), but goes by fd + path. This implies MNT_DETACH, since to do this we
750
         * must pin the inode in question via an fd. */
751

752
        assert(fd >= 0 || fd == AT_FDCWD);
224✔
753

754
        /* If neither fd nor path are specified take this as reference to the cwd */
755
        if (fd == AT_FDCWD && isempty(where))
224✔
756
                return umount_verbose(error_log_level, ".", MNT_DETACH|UMOUNT_NOFOLLOW);
224✔
757

758
        /* If we don't actually take the fd into consideration for this operation shortcut things, so that we
759
         * don't have to open the inode */
760
        if (fd == AT_FDCWD || path_is_absolute(where))
224✔
761
                return umount_verbose(error_log_level, where, MNT_DETACH|UMOUNT_NOFOLLOW);
×
762

763
        _cleanup_free_ char *prefix = NULL;
448✔
764
        const char *p;
224✔
765
        if (fd_get_path(fd, &prefix) < 0)
224✔
766
                p = "<fd>"; /* if we can't get the path, return something vaguely useful */
767
        else
768
                p = prefix;
224✔
769
        _cleanup_free_ char *joined = isempty(where) ? strdup(p) : path_join(p, where);
569✔
770

771
        log_debug("Unmounting '%s'...", strna(joined));
224✔
772

773
        _cleanup_close_ int inode_fd = -EBADF;
224✔
774
        int mnt_fd;
224✔
775
        if (isempty(where))
224✔
776
                mnt_fd = fd;
777
        else {
778
                inode_fd = openat(fd, where, O_PATH|O_CLOEXEC|O_NOFOLLOW);
121✔
779
                if (inode_fd < 0)
121✔
780
                        return log_full_errno(error_log_level, errno, "Failed to pin '%s': %m", strna(joined));
×
781

782
                mnt_fd = inode_fd;
783
        }
784

785
        if (umount2(FORMAT_PROC_FD_PATH(mnt_fd), MNT_DETACH) < 0)
224✔
786
                return log_full_errno(error_log_level, errno, "Failed to unmount '%s': %m", strna(joined));
9✔
787

788
        return 0;
215✔
789
}
790

791
int mount_exchange_graceful(int fsmount_fd, const char *dest, bool mount_beneath) {
25✔
792
        int r;
25✔
793

794
        assert(fsmount_fd >= 0);
25✔
795
        assert(dest);
25✔
796

797
        /* First, try to mount beneath an existing mount point, and if that works, umount the old mount,
798
         * which is now at the top. This will ensure we can atomically replace a mount. Note that this works
799
         * also in the case where there are submounts down the tree. Mount propagation is allowed but
800
         * restricted to layouts that don't end up propagation the new mount on top of the mount stack.  If
801
         * this is not supported (minimum kernel v6.5), or if there is no mount on the mountpoint, we get
802
         * -EINVAL and then we fallback to normal mounting. */
803

804
        r = RET_NERRNO(move_mount(fsmount_fd, /* from_path = */ "",
35✔
805
                                  /* to_fd = */ -EBADF, dest,
806
                                  MOVE_MOUNT_F_EMPTY_PATH | (mount_beneath ? MOVE_MOUNT_BENEATH : 0)));
807
        if (mount_beneath) {
25✔
808
                if (r >= 0) /* Mounting beneath worked! Now unmount the upper mount. */
15✔
809
                        return umount_verbose(LOG_DEBUG, dest, UMOUNT_NOFOLLOW|MNT_DETACH);
11✔
810

811
                if (r == -EINVAL) { /* Fallback if mount_beneath is not supported */
4✔
812
                        log_debug_errno(r,
4✔
813
                                        "Cannot mount beneath '%s', falling back to overmount: %m",
814
                                        dest);
815
                        return mount_exchange_graceful(fsmount_fd, dest, /* mount_beneath = */ false);
4✔
816
                }
817
        }
818

819
        return r;
820
}
821

822
int mount_option_mangle(
48,766✔
823
                const char *options,
824
                unsigned long mount_flags,
825
                unsigned long *ret_mount_flags,
826
                char **ret_remaining_options) {
827

828
        const struct libmnt_optmap *map;
48,766✔
829
        _cleanup_free_ char *ret = NULL;
48,766✔
830
        int r;
48,766✔
831

832
        /* This extracts mount flags from the mount options, and stores
833
         * non-mount-flag options to '*ret_remaining_options'.
834
         * E.g.,
835
         * "rw,nosuid,nodev,relatime,size=1630748k,mode=0700,uid=1000,gid=1000"
836
         * is split to MS_NOSUID|MS_NODEV|MS_RELATIME and
837
         * "size=1630748k,mode=0700,uid=1000,gid=1000".
838
         * See more examples in test-mount-util.c.
839
         *
840
         * If 'options' does not contain any non-mount-flag options,
841
         * then '*ret_remaining_options' is set to NULL instead of empty string.
842
         * The validity of options stored in '*ret_remaining_options' is not checked.
843
         * If 'options' is NULL, this just copies 'mount_flags' to *ret_mount_flags. */
844

845
        assert(ret_mount_flags);
48,766✔
846
        assert(ret_remaining_options);
48,766✔
847

848
        map = mnt_get_builtin_optmap(MNT_LINUX_MAP);
48,766✔
849
        if (!map)
48,766✔
850
                return -EINVAL;
851

852
        for (const char *p = options;;) {
48,766✔
853
                _cleanup_free_ char *word = NULL;
23,320✔
854
                const struct libmnt_optmap *ent;
72,085✔
855

856
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
72,085✔
857
                if (r < 0)
72,085✔
858
                        return r;
859
                if (r == 0)
72,084✔
860
                        break;
861

862
                for (ent = map; ent->name; ent++) {
976,815✔
863
                        /* All entries in MNT_LINUX_MAP do not take any argument.
864
                         * Thus, ent->name does not contain "=" or "[=]". */
865
                        if (!streq(word, ent->name))
953,587✔
866
                                continue;
953,496✔
867

868
                        if (!(ent->mask & MNT_INVERT))
91✔
869
                                mount_flags |= ent->id;
82✔
870
                        else
871
                                mount_flags &= ~ent->id;
9✔
872

873
                        break;
874
                }
875

876
                /* If 'word' is not a mount flag, then store it in '*ret_remaining_options'. */
877
                if (!ent->name &&
46,547✔
878
                    !startswith_no_case(word, "x-") &&
46,454✔
879
                    !strextend_with_separator(&ret, ",", word))
23,226✔
880
                        return -ENOMEM;
881
        }
882

883
        *ret_mount_flags = mount_flags;
48,765✔
884
        *ret_remaining_options = TAKE_PTR(ret);
48,765✔
885

886
        return 0;
48,765✔
887
}
888

889
static int mount_in_namespace_legacy(
×
890
                const char *chased_src_path,
891
                int chased_src_fd,
892
                struct stat *chased_src_st,
893
                const char *propagate_path,
894
                const char *incoming_path,
895
                const char *dest,
896
                int pidns_fd,
897
                int mntns_fd,
898
                int root_fd,
899
                MountInNamespaceFlags flags,
900
                const MountOptions *options,
901
                const ImagePolicy *image_policy) {
902

903
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
×
904
        char mount_slave[] = "/tmp/propagate.XXXXXX", *mount_tmp, *mount_outside, *p;
×
905
        bool mount_slave_created = false, mount_slave_mounted = false,
×
906
                mount_tmp_created = false, mount_tmp_mounted = false,
×
907
                mount_outside_created = false, mount_outside_mounted = false;
×
908
        pid_t child;
×
909
        int r;
×
910

911
        assert(chased_src_path);
×
912
        assert(chased_src_fd >= 0);
×
913
        assert(chased_src_st);
×
914
        assert(propagate_path);
×
915
        assert(incoming_path);
×
916
        assert(dest);
×
917
        assert(pidns_fd >= 0);
×
918
        assert(mntns_fd >= 0);
×
919
        assert(root_fd >= 0);
×
920
        assert(!options || (flags & MOUNT_IN_NAMESPACE_IS_IMAGE));
×
921

922
        p = strjoina(propagate_path, "/");
×
923
        r = access_nofollow(p, F_OK);
×
924
        if (r < 0)
×
925
                return log_debug_errno(r == -ENOENT ? SYNTHETIC_ERRNO(EOPNOTSUPP) : r, "Target does not allow propagation of mount points");
×
926

927
        /* Our goal is to install a new bind mount into the container,
928
           possibly read-only. This is irritatingly complex
929
           unfortunately, currently.
930

931
           First, we start by creating a private playground in /tmp,
932
           that we can mount MS_SLAVE. (Which is necessary, since
933
           MS_MOVE cannot be applied to mounts with MS_SHARED parent
934
           mounts.) */
935

936
        if (!mkdtemp(mount_slave))
×
937
                return log_debug_errno(errno, "Failed to create playground %s: %m", mount_slave);
×
938

939
        mount_slave_created = true;
×
940

941
        r = mount_nofollow_verbose(LOG_DEBUG, mount_slave, mount_slave, NULL, MS_BIND, NULL);
×
942
        if (r < 0)
×
943
                goto finish;
×
944

945
        mount_slave_mounted = true;
×
946

947
        r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_slave, NULL, MS_SLAVE, NULL);
×
948
        if (r < 0)
×
949
                goto finish;
×
950

951
        /* Second, we mount the source file or directory to a directory inside of our MS_SLAVE playground. */
952
        mount_tmp = strjoina(mount_slave, "/mount");
×
953
        r = make_mount_point_inode_from_mode(AT_FDCWD, mount_tmp, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
×
954
        if (r < 0) {
×
955
                log_debug_errno(r, "Failed to create temporary mount point %s: %m", mount_tmp);
×
956
                goto finish;
×
957
        }
958

959
        mount_tmp_created = true;
×
960

961
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
×
962
                r = verity_dissect_and_mount(
×
963
                                chased_src_fd,
964
                                chased_src_path,
965
                                mount_tmp,
966
                                options,
967
                                image_policy,
968
                                /* image_filter= */ NULL,
969
                                /* extension_release_data= */ NULL,
970
                                /* required_class= */ _IMAGE_CLASS_INVALID,
971
                                /* verity= */ NULL,
972
                                /* ret_image= */ NULL);
973
        else
974
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(chased_src_fd), mount_tmp, NULL, MS_BIND, NULL);
×
975
        if (r < 0)
×
976
                goto finish;
×
977

978
        mount_tmp_mounted = true;
×
979

980
        /* Third, we remount the new bind mount read-only if requested. */
981
        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY) {
×
982
                r = mount_nofollow_verbose(LOG_DEBUG, NULL, mount_tmp, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL);
×
983
                if (r < 0)
×
984
                        goto finish;
×
985
        }
986

987
        /* Fourth, we move the new bind mount into the propagation directory. This way it will appear there read-only
988
         * right-away. */
989

990
        mount_outside = strjoina(propagate_path, "/XXXXXX");
×
991
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
992
                r = mkdtemp(mount_outside) ? 0 : -errno;
×
993
        else {
994
                r = mkostemp_safe(mount_outside);
×
995
                safe_close(r);
×
996
        }
997
        if (r < 0) {
×
998
                log_debug_errno(r, "Cannot create propagation file or directory %s: %m", mount_outside);
×
999
                goto finish;
×
1000
        }
1001

1002
        mount_outside_created = true;
×
1003

1004
        r = mount_nofollow_verbose(LOG_DEBUG, mount_tmp, mount_outside, NULL, MS_MOVE, NULL);
×
1005
        if (r < 0)
×
1006
                goto finish;
×
1007

1008
        mount_outside_mounted = true;
×
1009
        mount_tmp_mounted = false;
×
1010

1011
        if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1012
                (void) rmdir(mount_tmp);
×
1013
        else
1014
                (void) unlink(mount_tmp);
×
1015
        mount_tmp_created = false;
×
1016

1017
        (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
×
1018
        mount_slave_mounted = false;
×
1019

1020
        (void) rmdir(mount_slave);
×
1021
        mount_slave_created = false;
×
1022

1023
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0) {
×
1024
                log_debug_errno(errno, "Failed to create pipe: %m");
×
1025
                goto finish;
×
1026
        }
1027

1028
        r = namespace_fork(
×
1029
                        "(sd-bindmnt)",
1030
                        "(sd-bindmnt-inner)",
1031
                        /* except_fds= */ NULL,
1032
                        /* n_except_fds= */ 0,
1033
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1034
                        pidns_fd,
1035
                        mntns_fd,
1036
                        /* netns_fd= */ -EBADF,
1037
                        /* userns_fd= */ -EBADF,
1038
                        root_fd,
1039
                        &child);
1040
        if (r < 0)
×
1041
                goto finish;
×
1042
        if (r == 0) {
×
1043
                _cleanup_free_ char *mount_outside_fn = NULL, *mount_inside = NULL;
×
1044

1045
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
×
1046

1047
                _cleanup_close_ int dest_fd = -EBADF;
×
1048
                _cleanup_free_ char *dest_fn = NULL;
×
1049
                r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
×
1050
                if (r < 0)
×
1051
                        log_debug_errno(r, "Failed to pin parent directory of mount '%s', ignoring: %m", dest);
×
1052
                else if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) {
×
1053
                        r = make_mount_point_inode_from_mode(dest_fd, dest_fn, (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) ? S_IFDIR : chased_src_st->st_mode, 0700);
×
1054
                        if (r < 0)
×
1055
                                log_debug_errno(r, "Failed to make mount point inode of mount '%s', ignoring: %m", dest);
×
1056
                }
1057

1058
                /* Fifth, move the mount to the right place inside */
1059
                r = path_extract_filename(mount_outside, &mount_outside_fn);
×
1060
                if (r < 0) {
×
1061
                        log_debug_errno(r, "Failed to extract filename from propagation file or directory '%s': %m", mount_outside);
×
1062
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1063
                }
1064

1065
                mount_inside = path_join(incoming_path, mount_outside_fn);
×
1066
                if (!mount_inside)
×
1067
                        report_errno_and_exit(errno_pipe_fd[1], log_oom_debug());
×
1068

1069
                r = mount_nofollow_verbose(LOG_DEBUG, mount_inside, dest_fd >= 0 ? FORMAT_PROC_FD_PATH(dest_fd) : dest, /* fstype= */ NULL, MS_MOVE, /* options= */ NULL);
×
1070
                if (r < 0)
×
1071
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1072

1073
                _exit(EXIT_SUCCESS);
×
1074
        }
1075

1076
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
×
1077

1078
        r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
×
1079
        if (r < 0) {
×
1080
                log_debug_errno(r, "Failed to wait for child: %m");
×
1081
                goto finish;
×
1082
        }
1083
        if (r != EXIT_SUCCESS) {
×
1084
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
×
1085
                        log_debug_errno(r, "Failed to mount: %m");
×
1086
                else
1087
                        log_debug("Child failed.");
×
1088
                goto finish;
×
1089
        }
1090

1091
finish:
×
1092
        if (mount_outside_mounted)
×
1093
                (void) umount_verbose(LOG_DEBUG, mount_outside, UMOUNT_NOFOLLOW);
×
1094
        if (mount_outside_created) {
×
1095
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1096
                        (void) rmdir(mount_outside);
×
1097
                else
1098
                        (void) unlink(mount_outside);
×
1099
        }
1100

1101
        if (mount_tmp_mounted)
×
1102
                (void) umount_verbose(LOG_DEBUG, mount_tmp, UMOUNT_NOFOLLOW);
×
1103
        if (mount_tmp_created) {
×
1104
                if ((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || S_ISDIR(chased_src_st->st_mode))
×
1105
                        (void) rmdir(mount_tmp);
×
1106
                else
1107
                        (void) unlink(mount_tmp);
×
1108
        }
1109

1110
        if (mount_slave_mounted)
×
1111
                (void) umount_verbose(LOG_DEBUG, mount_slave, UMOUNT_NOFOLLOW);
×
1112
        if (mount_slave_created)
×
1113
                (void) rmdir(mount_slave);
×
1114

1115
        return r;
×
1116
}
1117

1118
static int mount_in_namespace(
6✔
1119
                const PidRef *target,
1120
                const char *propagate_path,
1121
                const char *incoming_path,
1122
                const char *src,
1123
                const char *dest,
1124
                MountInNamespaceFlags flags,
1125
                const MountOptions *options,
1126
                const ImagePolicy *image_policy) {
1127

1128
        _cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF, chased_src_fd = -EBADF;
18✔
1129
        _cleanup_free_ char *chased_src_path = NULL;
6✔
1130
        struct stat st;
6✔
1131
        int r;
6✔
1132

1133
        assert(propagate_path);
6✔
1134
        assert(incoming_path);
6✔
1135
        assert(src);
6✔
1136
        assert(dest);
6✔
1137
        assert((flags & MOUNT_IN_NAMESPACE_IS_IMAGE) || (!options && !image_policy));
6✔
1138

1139
        if (!pidref_is_set(target))
12✔
1140
                return -ESRCH;
1141

1142
        r = pidref_namespace_open(target, &pidns_fd, &mntns_fd, /* ret_netns_fd = */ NULL, /* ret_userns_fd = */ NULL, &root_fd);
6✔
1143
        if (r < 0)
6✔
1144
                return log_debug_errno(r, "Failed to retrieve FDs of the target process' namespace: %m");
×
1145

1146
        r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
6✔
1147
        if (r < 0)
6✔
1148
                return log_debug_errno(r, "Failed to determine if mount namespaces are equal: %m");
×
1149
        /* We can't add new mounts at runtime if the process wasn't started in a namespace */
1150
        if (r > 0)
6✔
1151
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to activate bind mount in target, not running in a mount namespace.");
×
1152

1153
        r = chase(src, NULL, 0, &chased_src_path, &chased_src_fd);
6✔
1154
        if (r < 0)
6✔
1155
                return log_debug_errno(r, "Failed to resolve source path '%s': %m", src);
×
1156
        log_debug("Chased source path '%s': %s", src, chased_src_path);
6✔
1157

1158
        if (fstat(chased_src_fd, &st) < 0)
6✔
1159
                return log_debug_errno(errno, "Failed to stat() resolved source path '%s': %m", src);
×
1160
        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… */
6✔
1161
                return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Source path '%s' can't be a symbolic link.", src);
×
1162

1163
        if (!mount_new_api_supported()) /* Fallback if we can't use the new mount API */
6✔
1164
                return mount_in_namespace_legacy(
×
1165
                                chased_src_path,
1166
                                chased_src_fd,
1167
                                &st,
1168
                                propagate_path,
1169
                                incoming_path,
1170
                                dest,
1171
                                pidns_fd,
1172
                                mntns_fd,
1173
                                root_fd,
1174
                                flags,
1175
                                options,
1176
                                image_policy);
1177

1178
        _cleanup_(dissected_image_unrefp) DissectedImage *img = NULL;
×
1179
        _cleanup_close_ int new_mount_fd = -EBADF;
6✔
1180
        _cleanup_close_pair_ int errno_pipe_fd[2] = EBADF_PAIR;
6✔
1181
        pid_t child;
6✔
1182

1183
        if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE) {
6✔
1184
                r = verity_dissect_and_mount(
2✔
1185
                                chased_src_fd,
1186
                                chased_src_path,
1187
                                /* dest= */ NULL,
1188
                                options,
1189
                                image_policy,
1190
                                /* image_filter= */ NULL,
1191
                                /* extension_release_data= */ NULL,
1192
                                /* required_class= */ _IMAGE_CLASS_INVALID,
1193
                                /* verity= */ NULL,
1194
                                &img);
1195
                if (r < 0)
2✔
1196
                        return log_debug_errno(r,
×
1197
                                               "Failed to dissect and mount image '%s': %m",
1198
                                               chased_src_path);
1199
        } else {
1200
                new_mount_fd = open_tree(
4✔
1201
                                chased_src_fd,
1202
                                "",
1203
                                OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
1204
                if (new_mount_fd < 0)
4✔
1205
                        return log_debug_errno(
×
1206
                                        errno,
1207
                                        "Failed to open mount source '%s': %m",
1208
                                        chased_src_path);
1209

1210
                if ((flags & MOUNT_IN_NAMESPACE_READ_ONLY) && mount_setattr(new_mount_fd, "", AT_EMPTY_PATH,
4✔
1211
                                               &(struct mount_attr) {
×
1212
                                                       .attr_set = MOUNT_ATTR_RDONLY,
1213
                                               }, MOUNT_ATTR_SIZE_VER0) < 0)
1214
                        return log_debug_errno(errno,
×
1215
                                               "Failed to set mount for '%s' to read only: %m",
1216
                                               chased_src_path);
1217
        }
1218

1219
        if (pipe2(errno_pipe_fd, O_CLOEXEC|O_NONBLOCK) < 0)
6✔
1220
                return log_debug_errno(errno, "Failed to create pipe: %m");
×
1221

1222
        r = namespace_fork("(sd-bindmnt)",
6✔
1223
                           "(sd-bindmnt-inner)",
1224
                           /* except_fds= */ NULL,
1225
                           /* n_except_fds= */ 0,
1226
                           FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM,
1227
                           pidns_fd,
1228
                           mntns_fd,
1229
                           /* netns_fd= */ -EBADF,
1230
                           /* userns_fd= */ -EBADF,
1231
                           root_fd,
1232
                           &child);
1233
        if (r < 0)
12✔
1234
                return log_debug_errno(r, "Failed to fork off mount helper into namespace: %m");
×
1235
        if (r == 0) {
12✔
1236
                errno_pipe_fd[0] = safe_close(errno_pipe_fd[0]);
6✔
1237

1238
                _cleanup_close_ int dest_fd = -EBADF;
×
1239
                _cleanup_free_ char *dest_fn = NULL;
×
1240
                r = chase(dest, /* root= */ NULL, CHASE_PARENT|CHASE_EXTRACT_FILENAME|((flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY) ? CHASE_MKDIR_0755 : 0), &dest_fn, &dest_fd);
6✔
1241
                if (r < 0)
6✔
1242
                        report_errno_and_exit(errno_pipe_fd[1], r);
×
1243

1244
                if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
6✔
1245
                        (void) make_mount_point_inode_from_mode(dest_fd, dest_fn, img ? S_IFDIR : st.st_mode, 0700);
6✔
1246

1247
                if (img) {
6✔
1248
                        DissectImageFlags f =
2✔
1249
                                DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE |
1250
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
1251

1252
                        if (flags & MOUNT_IN_NAMESPACE_MAKE_FILE_OR_DIRECTORY)
2✔
1253
                                f |= DISSECT_IMAGE_MKDIR;
2✔
1254

1255
                        if (flags & MOUNT_IN_NAMESPACE_READ_ONLY)
2✔
1256
                                f |= DISSECT_IMAGE_READ_ONLY;
×
1257

1258
                        r = dissected_image_mount(
2✔
1259
                                        img,
1260
                                        dest,
1261
                                        /* uid_shift= */ UID_INVALID,
1262
                                        /* uid_range= */ UID_INVALID,
1263
                                        /* userns_fd= */ -EBADF,
1264
                                        f);
1265
                } else
1266
                        r = mount_exchange_graceful(new_mount_fd, dest, /* mount_beneath= */ true);
4✔
1267

1268
                report_errno_and_exit(errno_pipe_fd[1], r);
6✔
1269
        }
1270

1271
        errno_pipe_fd[1] = safe_close(errno_pipe_fd[1]);
6✔
1272

1273
        r = wait_for_terminate_and_check("(sd-bindmnt)", child, 0);
6✔
1274
        if (r < 0)
6✔
1275
                return log_debug_errno(r, "Failed to wait for child: %m");
×
1276
        if (r != EXIT_SUCCESS) {
6✔
1277
                if (read(errno_pipe_fd[0], &r, sizeof(r)) == sizeof(r))
×
1278
                        return log_debug_errno(r, "Failed to mount into namespace: %m");
×
1279

1280
                return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Child failed.");
×
1281
        }
1282

1283
        return 0;
1284
}
1285

1286
int bind_mount_in_namespace(
4✔
1287
                const PidRef *target,
1288
                const char *propagate_path,
1289
                const char *incoming_path,
1290
                const char *src,
1291
                const char *dest,
1292
                MountInNamespaceFlags flags) {
1293

1294
        return mount_in_namespace(target,
8✔
1295
                                  propagate_path,
1296
                                  incoming_path,
1297
                                  src,
1298
                                  dest,
1299
                                  flags & ~MOUNT_IN_NAMESPACE_IS_IMAGE,
4✔
1300
                                  /* options = */ NULL,
1301
                                  /* image_policy = */ NULL);
1302
}
1303

1304
int mount_image_in_namespace(
2✔
1305
                const PidRef *target,
1306
                const char *propagate_path,
1307
                const char *incoming_path,
1308
                const char *src,
1309
                const char *dest,
1310
                MountInNamespaceFlags flags,
1311
                const MountOptions *options,
1312
                const ImagePolicy *image_policy) {
1313

1314
        return mount_in_namespace(target,
4✔
1315
                                  propagate_path,
1316
                                  incoming_path,
1317
                                  src,
1318
                                  dest,
1319
                                  flags | MOUNT_IN_NAMESPACE_IS_IMAGE,
2✔
1320
                                  options,
1321
                                  image_policy);
1322
}
1323

1324
int make_mount_point(const char *path) {
23✔
1325
        int r;
23✔
1326

1327
        assert(path);
23✔
1328

1329
        /* If 'path' is already a mount point, does nothing and returns 0. If it is not it makes it one, and returns 1. */
1330

1331
        r = path_is_mount_point(path);
23✔
1332
        if (r < 0)
23✔
1333
                return log_debug_errno(r, "Failed to determine whether '%s' is a mount point: %m", path);
×
1334
        if (r > 0)
23✔
1335
                return 0;
1336

1337
        r = mount_nofollow_verbose(LOG_DEBUG, path, path, NULL, MS_BIND|MS_REC, NULL);
9✔
1338
        if (r < 0)
9✔
1339
                return r;
×
1340

1341
        return 1;
1342
}
1343

1344
int fd_make_mount_point(int fd) {
11✔
1345
        int r;
11✔
1346

1347
        assert(fd >= 0);
11✔
1348

1349
        r = is_mount_point_at(fd, NULL, 0);
11✔
1350
        if (r < 0)
11✔
1351
                return log_debug_errno(r, "Failed to determine whether file descriptor is a mount point: %m");
×
1352
        if (r > 0)
11✔
1353
                return 0;
1354

1355
        r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(fd), FORMAT_PROC_FD_PATH(fd), NULL, MS_BIND|MS_REC, NULL);
1✔
1356
        if (r < 0)
1✔
1357
                return r;
×
1358

1359
        return 1;
1360
}
1361

1362
int make_userns(uid_t uid_shift,
90✔
1363
                uid_t uid_range,
1364
                uid_t source_owner,
1365
                uid_t dest_owner,
1366
                RemountIdmapping idmapping) {
1367

1368
        _cleanup_close_ int userns_fd = -EBADF;
90✔
1369
        _cleanup_free_ char *line = NULL;
90✔
1370
        uid_t source_base = 0;
90✔
1371

1372
        /* Allocates a userns file descriptor with the mapping we need. For this we'll fork off a child
1373
         * process whose only purpose is to give us a new user namespace. It's killed when we got it. */
1374

1375
        if (!userns_shift_range_valid(uid_shift, uid_range))
90✔
1376
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UID range for user namespace.");
×
1377

1378
        switch (idmapping) {
90✔
1379

1380
        case REMOUNT_IDMAPPING_FOREIGN_WITH_HOST_ROOT:
2✔
1381
                source_base = FOREIGN_UID_BASE;
2✔
1382
                _fallthrough_;
88✔
1383

1384
        case REMOUNT_IDMAPPING_NONE:
88✔
1385
        case REMOUNT_IDMAPPING_HOST_ROOT:
1386

1387
                if (asprintf(&line,
88✔
1388
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1389
                             source_base, uid_shift, uid_range) < 0)
1390
                        return log_oom_debug();
×
1391

1392
                /* If requested we'll include an entry in the mapping so that the host root user can make
1393
                 * changes to the uidmapped mount like it normally would. Specifically, we'll map the user
1394
                 * with UID_MAPPED_ROOT on the backing fs to UID 0. This is useful, since nspawn code wants
1395
                 * to create various missing inodes in the OS tree before booting into it, and this becomes
1396
                 * very easy and straightforward to do if it can just do it under its own regular UID. Note
1397
                 * that in that case the container's runtime uidmap (i.e. the one the container payload
1398
                 * processes run in) will leave this UID unmapped, i.e. if we accidentally leave files owned
1399
                 * by host root in the already uidmapped tree around they'll show up as owned by 'nobody',
1400
                 * which is safe. (Of course, we shouldn't leave such inodes around, but always chown() them
1401
                 * to the container's own UID range, but it's good to have a safety net, in case we
1402
                 * forget it.) */
1403
                if (idmapping == REMOUNT_IDMAPPING_HOST_ROOT)
88✔
1404
                        if (strextendf(&line,
86✔
1405
                                       UID_FMT " " UID_FMT " " UID_FMT "\n",
1406
                                       UID_MAPPED_ROOT, (uid_t) 0u, (uid_t) 1u) < 0)
1407
                                return log_oom_debug();
×
1408

1409
                break;
1410

1411
        case REMOUNT_IDMAPPING_HOST_OWNER:
×
1412
                /* Remap the owner of the bind mounted directory to the root user within the container. This
1413
                 * way every file written by root within the container to the bind-mounted directory will
1414
                 * be owned by the original user from the host. All other users will remain unmapped. */
1415
                if (asprintf(&line,
×
1416
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1417
                             source_owner, uid_shift, (uid_t) 1u) < 0)
1418
                        return log_oom_debug();
×
1419
                break;
1420

1421
        case REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER:
2✔
1422
                /* Remap the owner of the bind mounted directory to the owner of the target directory
1423
                 * within the container. This way every file written by target directory owner within the
1424
                 * container to the bind-mounted directory will be owned by the original host user.
1425
                 * All other users will remain unmapped. */
1426
                if (asprintf(&line,
2✔
1427
                             UID_FMT " " UID_FMT " " UID_FMT "\n",
1428
                             source_owner, dest_owner, (uid_t) 1u) < 0)
1429
                        return log_oom_debug();
×
1430
                break;
1431

1432
        default:
×
1433
                assert_not_reached();
×
1434
        }
1435

1436
        /* We always assign the same UID and GID ranges */
1437
        userns_fd = userns_acquire(line, line, /* setgroups_deny= */ true);
90✔
1438
        if (userns_fd < 0)
90✔
1439
                return log_debug_errno(userns_fd, "Failed to acquire new userns: %m");
×
1440

1441
        return TAKE_FD(userns_fd);
1442
}
1443

1444
int remount_idmap_fd(
101✔
1445
                char **paths,
1446
                int userns_fd,
1447
                uint64_t extra_mount_attr_set) {
1448

1449
        int r;
101✔
1450

1451
        assert(userns_fd >= 0);
101✔
1452

1453
        /* This remounts all specified paths with the specified userns as idmap. It will do so in the
1454
         * order specified in the strv: the expectation is that the top-level directories are at the
1455
         * beginning, and nested directories in the right, so that the tree can be built correctly from left
1456
         * to right. */
1457

1458
        size_t n = strv_length(paths);
101✔
1459
        if (n == 0) /* Nothing to do? */
101✔
1460
                return 0;
101✔
1461

1462
        int *mount_fds = NULL;
101✔
1463
        size_t n_mounts_fds = 0;
101✔
1464

1465
        mount_fds = new(int, n);
101✔
1466
        if (!mount_fds)
101✔
1467
                return log_oom_debug();
×
1468

1469
        CLEANUP_ARRAY(mount_fds, n_mounts_fds, close_many_and_free);
101✔
1470

1471
        for (size_t i = 0; i < n; i++) {
200✔
1472
                int mntfd;
101✔
1473

1474
                /* Clone the mount point */
1475
                mntfd = mount_fds[n_mounts_fds] = open_tree(-EBADF, paths[i], OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
101✔
1476
                if (mount_fds[n_mounts_fds] < 0)
101✔
1477
                        return log_debug_errno(errno, "Failed to open tree of mounted filesystem '%s': %m", paths[i]);
×
1478

1479
                n_mounts_fds++;
101✔
1480

1481
                /* Set the user namespace mapping attribute on the cloned mount point */
1482
                if (mount_setattr(mntfd, "", AT_EMPTY_PATH,
101✔
1483
                                  &(struct mount_attr) {
101✔
1484
                                          .attr_set = MOUNT_ATTR_IDMAP | extra_mount_attr_set,
101✔
1485
                                          .userns_fd = userns_fd,
1486
                                  }, sizeof(struct mount_attr)) < 0)
1487
                        return log_debug_errno(errno, "Failed to change bind mount attributes for clone of '%s': %m", paths[i]);
2✔
1488
        }
1489

1490
        for (size_t i = n; i > 0; i--) { /* Unmount the paths right-to-left */
198✔
1491
                /* Remove the old mount points now that we have a idmapped mounts as replacement for all of them */
1492
                r = umount_verbose(LOG_DEBUG, paths[i-1], UMOUNT_NOFOLLOW);
99✔
1493
                if (r < 0)
99✔
1494
                        return r;
1495
        }
1496

1497
        for (size_t i = 0; i < n; i++) { /* Mount the replacement mounts left-to-right */
198✔
1498
                /* And place the cloned version in its place */
1499
                log_debug("Mounting idmapped fs to '%s'", paths[i]);
99✔
1500
                if (move_mount(mount_fds[i], "", -EBADF, paths[i], MOVE_MOUNT_F_EMPTY_PATH) < 0)
99✔
1501
                        return log_debug_errno(errno, "Failed to attach UID mapped mount to '%s': %m", paths[i]);
×
1502
        }
1503

1504
        return 0;
1505
}
1506

1507
int remount_idmap(
88✔
1508
                char **p,
1509
                uid_t uid_shift,
1510
                uid_t uid_range,
1511
                uid_t source_owner,
1512
                uid_t dest_owner,
1513
                RemountIdmapping idmapping) {
1514

1515
        _cleanup_close_ int userns_fd = -EBADF;
88✔
1516

1517
        userns_fd = make_userns(uid_shift, uid_range, source_owner, dest_owner, idmapping);
88✔
1518
        if (userns_fd < 0)
88✔
1519
                return userns_fd;
1520

1521
        return remount_idmap_fd(p, userns_fd, /* extra_mount_attr_set= */ 0);
88✔
1522
}
1523

1524
static void sub_mount_clear(SubMount *s) {
5,519✔
1525
        assert(s);
5,519✔
1526

1527
        s->path = mfree(s->path);
5,519✔
1528
        s->mount_fd = safe_close(s->mount_fd);
5,519✔
1529
}
5,519✔
1530

1531
void sub_mount_array_free(SubMount *s, size_t n) {
1,257✔
1532
        assert(s || n == 0);
1,257✔
1533

1534
        for (size_t i = 0; i < n; i++)
5,993✔
1535
                sub_mount_clear(s + i);
4,736✔
1536

1537
        free(s);
1,257✔
1538
}
1,257✔
1539

1540
static int sub_mount_compare(const SubMount *a, const SubMount *b) {
6,911✔
1541
        assert(a);
6,911✔
1542
        assert(b);
6,911✔
1543
        assert(a->path);
6,911✔
1544
        assert(b->path);
6,911✔
1545

1546
        return path_compare(a->path, b->path);
6,911✔
1547
}
1548

1549
static void sub_mount_drop(SubMount *s, size_t n) {
1,835✔
1550
        assert(s || n == 0);
1,835✔
1551

1552
        for (size_t m = 0, i = 1; i < n; i++) {
5,314✔
1553
                if (path_startswith(s[i].path, s[m].path))
3,479✔
1554
                        sub_mount_clear(s + i);
783✔
1555
                else
1556
                        m = i;
1557
        }
1558
}
1,835✔
1559

1560
int get_sub_mounts(const char *prefix, SubMount **ret_mounts, size_t *ret_n_mounts) {
1,835✔
1561

1562
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
1,835✔
1563
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
1,835✔
1564
        SubMount *mounts = NULL;
1,835✔
1565
        size_t n = 0;
1,835✔
1566
        int r;
1,835✔
1567

1568
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,835✔
1569

1570
        assert(prefix);
1,835✔
1571
        assert(ret_mounts);
1,835✔
1572
        assert(ret_n_mounts);
1,835✔
1573

1574
        r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
1,835✔
1575
        if (r < 0)
1,835✔
1576
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
1577

1578
        for (;;) {
93,840✔
1579
                _cleanup_close_ int mount_fd = -EBADF;
92,005✔
1580
                _cleanup_free_ char *p = NULL;
93,840✔
1581
                struct libmnt_fs *fs;
93,840✔
1582
                const char *path;
93,840✔
1583
                int id1, id2;
93,840✔
1584

1585
                r = mnt_table_next_fs(table, iter, &fs);
93,840✔
1586
                if (r == 1)
93,840✔
1587
                        break; /* EOF */
1588
                if (r < 0)
92,005✔
1589
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
×
1590

1591
                path = mnt_fs_get_target(fs);
92,005✔
1592
                if (!path)
92,005✔
1593
                        continue;
×
1594

1595
                if (isempty(path_startswith(path, prefix)))
92,005✔
1596
                        continue;
86,491✔
1597

1598
                id1 = mnt_fs_get_id(fs);
5,514✔
1599
                r = path_get_mnt_id(path, &id2);
5,514✔
1600
                if (r < 0) {
5,514✔
1601
                        log_debug_errno(r, "Failed to get mount ID of '%s', ignoring: %m", path);
×
1602
                        continue;
×
1603
                }
1604
                if (id1 != id2) {
5,514✔
1605
                        /* The path may be hidden by another over-mount or already remounted. */
1606
                        log_debug("The mount IDs of '%s' obtained by libmount and path_get_mnt_id() are different (%i vs %i), ignoring.",
778✔
1607
                                  path, id1, id2);
1608
                        continue;
778✔
1609
                }
1610

1611
                mount_fd = open(path, O_CLOEXEC|O_PATH);
4,736✔
1612
                if (mount_fd < 0) {
4,736✔
1613
                        if (errno == ENOENT) /* The path may be hidden by another over-mount or already unmounted. */
×
1614
                                continue;
×
1615

1616
                        return log_debug_errno(errno, "Failed to open subtree of mounted filesystem '%s': %m", path);
×
1617
                }
1618

1619
                p = strdup(path);
4,736✔
1620
                if (!p)
4,736✔
1621
                        return log_oom_debug();
×
1622

1623
                if (!GREEDY_REALLOC(mounts, n + 1))
4,736✔
1624
                        return log_oom_debug();
×
1625

1626
                mounts[n++] = (SubMount) {
4,736✔
1627
                        .path = TAKE_PTR(p),
4,736✔
1628
                        .mount_fd = TAKE_FD(mount_fd),
4,736✔
1629
                };
1630
        }
1631

1632
        typesafe_qsort(mounts, n, sub_mount_compare);
1,835✔
1633
        sub_mount_drop(mounts, n);
1,835✔
1634

1635
        *ret_mounts = TAKE_PTR(mounts);
1,835✔
1636
        *ret_n_mounts = n;
1,835✔
1637
        return 0;
1,835✔
1638
}
1639

1640
int bind_mount_submounts(
1,265✔
1641
                const char *source,
1642
                const char *target) {
1643

1644
        SubMount *mounts = NULL;
1,265✔
1645
        size_t n = 0;
1,265✔
1646
        int ret = 0, r;
1,265✔
1647

1648
        /* Bind mounts all child mounts of 'source' to 'target'. Useful when setting up a new procfs instance
1649
         * with new mount options to copy the original submounts over. */
1650

1651
        assert(source);
1,265✔
1652
        assert(target);
1,265✔
1653

1654
        CLEANUP_ARRAY(mounts, n, sub_mount_array_free);
1,265✔
1655

1656
        r = get_sub_mounts(source, &mounts, &n);
1,265✔
1657
        if (r < 0)
1,265✔
1658
                return r;
1659

1660
        FOREACH_ARRAY(m, mounts, n) {
5,997✔
1661
                _cleanup_free_ char *t = NULL;
4,732✔
1662
                const char *suffix;
4,732✔
1663

1664
                if (isempty(m->path))
4,732✔
1665
                        continue;
783✔
1666

1667
                assert_se(suffix = path_startswith(m->path, source));
3,949✔
1668

1669
                t = path_join(target, suffix);
3,949✔
1670
                if (!t)
3,949✔
1671
                        return -ENOMEM;
×
1672

1673
                r = path_is_mount_point(t);
3,949✔
1674
                if (r < 0) {
3,949✔
1675
                        log_debug_errno(r, "Failed to detect if '%s' already is a mount point, ignoring: %m", t);
9✔
1676
                        continue;
9✔
1677
                }
1678
                if (r > 0) {
3,940✔
1679
                        log_debug("Not bind mounting '%s' from '%s' to '%s', since there's already a mountpoint.", suffix, source, target);
×
1680
                        continue;
×
1681
                }
1682

1683
                r = mount_follow_verbose(LOG_DEBUG, FORMAT_PROC_FD_PATH(m->mount_fd), t, NULL, MS_BIND|MS_REC, NULL);
3,940✔
1684
                if (r < 0 && ret == 0)
3,940✔
1685
                        ret = r;
388✔
1686
        }
1687

1688
        return ret;
1689
}
1690

1691
int make_mount_point_inode_from_mode(int dir_fd, const char *dest, mode_t source_mode, mode_t target_mode) {
998✔
1692
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
998✔
1693
        assert(dest);
998✔
1694

1695
        if (S_ISDIR(source_mode))
998✔
1696
                return mkdirat_label(dir_fd, dest, target_mode & 07777);
981✔
1697
        else
1698
                return RET_NERRNO(mknodat(dir_fd, dest, S_IFREG|(target_mode & 07666), 0)); /* Mask off X bit */
18✔
1699
}
1700

1701
int make_mount_point_inode_from_path(const char *source, const char *dest, mode_t access_mode) {
852✔
1702
        struct stat st;
852✔
1703

1704
        assert(source);
852✔
1705
        assert(dest);
852✔
1706

1707
        if (stat(source, &st) < 0)
852✔
1708
                return -errno;
×
1709

1710
        return make_mount_point_inode_from_mode(AT_FDCWD, dest, st.st_mode, access_mode);
852✔
1711
}
1712

1713
int trigger_automount_at(int dir_fd, const char *path) {
384✔
1714
        _cleanup_free_ char *nested = NULL;
768✔
1715

1716
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
384✔
1717

1718
        nested = path_join(path, "a");
384✔
1719
        if (!nested)
384✔
1720
                return -ENOMEM;
1721

1722
        (void) faccessat(dir_fd, nested, F_OK, 0);
384✔
1723

1724
        return 0;
384✔
1725
}
1726

1727
unsigned long credentials_fs_mount_flags(bool ro) {
3,886✔
1728
        /* A tight set of mount flags for credentials mounts */
1729
        return MS_NODEV|MS_NOEXEC|MS_NOSUID|ms_nosymfollow_supported()|(ro ? MS_RDONLY : 0);
3,886✔
1730
}
1731

1732
int mount_credentials_fs(const char *path, size_t size, bool ro) {
1,943✔
1733
        _cleanup_free_ char *opts = NULL;
1,943✔
1734
        int r, noswap_supported;
1,943✔
1735

1736
        /* Mounts a file system we can place credentials in, i.e. with tight access modes right from the
1737
         * beginning, and ideally swapping turned off. In order of preference:
1738
         *
1739
         *      1. tmpfs if it supports "noswap"
1740
         *      2. ramfs
1741
         *      3. tmpfs if it doesn't support "noswap"
1742
         */
1743

1744
        noswap_supported = mount_option_supported("tmpfs", "noswap", NULL); /* Check explicitly to avoid kmsg noise */
1,943✔
1745
        if (noswap_supported > 0) {
1,943✔
1746
                _cleanup_free_ char *noswap_opts = NULL;
1,942✔
1747

1748
                if (asprintf(&noswap_opts, "mode=0700,nr_inodes=1024,size=%zu,noswap", size) < 0)
1,942✔
1749
                        return -ENOMEM;
1750

1751
                /* Best case: tmpfs with noswap (needs kernel >= 6.3) */
1752

1753
                r = mount_nofollow_verbose(
1,942✔
1754
                                LOG_DEBUG,
1755
                                "tmpfs",
1756
                                path,
1757
                                "tmpfs",
1758
                                credentials_fs_mount_flags(ro),
1759
                                noswap_opts);
1760
                if (r >= 0)
1,942✔
1761
                        return r;
1762
        }
1763

1764
        r = mount_nofollow_verbose(
1✔
1765
                        LOG_DEBUG,
1766
                        "ramfs",
1767
                        path,
1768
                        "ramfs",
1769
                        credentials_fs_mount_flags(ro),
1770
                        "mode=0700");
1771
        if (r >= 0)
1✔
1772
                return r;
1773

1774
        if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%zu", size) < 0)
1✔
1775
                return -ENOMEM;
1776

1777
        return mount_nofollow_verbose(
1,943✔
1778
                        LOG_DEBUG,
1779
                        "tmpfs",
1780
                        path,
1781
                        "tmpfs",
1782
                        credentials_fs_mount_flags(ro),
1783
                        opts);
1784
}
1785

1786
int make_fsmount(
2✔
1787
                int error_log_level,
1788
                const char *what,
1789
                const char *type,
1790
                unsigned long flags,
1791
                const char *options,
1792
                int userns_fd) {
1793

1794
        _cleanup_close_ int fs_fd = -EBADF, mnt_fd = -EBADF;
2✔
1795
        _cleanup_free_ char *o = NULL;
2✔
1796
        unsigned long f;
2✔
1797
        int r;
2✔
1798

1799
        assert(type);
2✔
1800
        assert(what);
2✔
1801

1802
        r = mount_option_mangle(options, flags, &f, &o);
2✔
1803
        if (r < 0)
2✔
1804
                return log_full_errno(
×
1805
                                error_log_level, r, "Failed to mangle mount options %s: %m",
1806
                                strempty(options));
1807

1808
        if (DEBUG_LOGGING) {
2✔
1809
                _cleanup_free_ char *fl = NULL;
2✔
1810
                (void) mount_flags_to_string(f, &fl);
2✔
1811

1812
                log_debug("Creating mount fd for %s (%s) (%s \"%s\")...",
4✔
1813
                        strna(what), strna(type), strnull(fl), strempty(o));
1814
        }
1815

1816
        fs_fd = fsopen(type, FSOPEN_CLOEXEC);
2✔
1817
        if (fs_fd < 0)
2✔
1818
                return log_full_errno(error_log_level, errno, "Failed to open superblock for \"%s\": %m", type);
×
1819

1820
        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "source", what, 0) < 0)
2✔
1821
                return log_full_errno(error_log_level, errno, "Failed to set mount source for \"%s\" to \"%s\": %m", type, what);
×
1822

1823
        if (FLAGS_SET(f, MS_RDONLY))
2✔
1824
                if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, "ro", NULL, 0) < 0)
2✔
1825
                        return log_full_errno(error_log_level, errno, "Failed to set read only mount flag for \"%s\": %m", type);
×
1826

1827
        for (const char *p = o;;) {
2✔
1828
                _cleanup_free_ char *word = NULL;
×
1829
                char *eq;
2✔
1830

1831
                r = extract_first_word(&p, &word, ",", EXTRACT_KEEP_QUOTE);
2✔
1832
                if (r < 0)
2✔
1833
                        return log_full_errno(error_log_level, r, "Failed to parse mount option string \"%s\": %m", o);
×
1834
                if (r == 0)
2✔
1835
                        break;
1836

1837
                eq = strchr(word, '=');
×
1838
                if (eq) {
×
1839
                        *eq = 0;
×
1840
                        eq++;
×
1841

1842
                        if (fsconfig(fs_fd, FSCONFIG_SET_STRING, word, eq, 0) < 0)
×
1843
                                return log_full_errno(error_log_level, errno, "Failed to set mount option \"%s=%s\" for \"%s\": %m", word, eq, type);
×
1844
                } else {
1845
                        if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, word, NULL, 0) < 0)
×
1846
                                return log_full_errno(error_log_level, errno, "Failed to set mount flag \"%s\" for \"%s\": %m", word, type);
×
1847
                }
1848
        }
1849

1850
        if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0)
2✔
1851
                return log_full_errno(error_log_level, errno, "Failed to realize fs fd for \"%s\" (\"%s\"): %m", what, type);
×
1852

1853
        mnt_fd = fsmount(fs_fd, FSMOUNT_CLOEXEC, 0);
2✔
1854
        if (mnt_fd < 0)
2✔
1855
                return log_full_errno(error_log_level, errno, "Failed to create mount fd for \"%s\" (\"%s\"): %m", what, type);
×
1856

1857
        struct mount_attr ma = {
4✔
1858
                .attr_set = ms_flags_to_mount_attr(f) | (userns_fd >= 0 ? MOUNT_ATTR_IDMAP : 0),
2✔
1859
                .userns_fd = userns_fd,
1860
        };
1861
        if (ma.attr_set != 0 && mount_setattr(mnt_fd, "", AT_EMPTY_PATH|AT_RECURSIVE, &ma, MOUNT_ATTR_SIZE_VER0) < 0)
2✔
1862
                return log_full_errno(error_log_level,
×
1863
                                      errno,
1864
                                      "Failed to set mount flags for \"%s\" (\"%s\"): %m",
1865
                                      what,
1866
                                      type);
1867

1868
        return TAKE_FD(mnt_fd);
1869
}
1870

1871
char* umount_and_rmdir_and_free(char *p) {
145✔
1872
        if (!p)
145✔
1873
                return NULL;
145✔
1874

1875
        PROTECT_ERRNO;
×
1876
        (void) umount_recursive(p, 0);
145✔
1877
        (void) rmdir(p);
145✔
1878
        return mfree(p);
145✔
1879
}
1880

1881
char* umount_and_free(char *p) {
39✔
1882
        if (!p)
39✔
1883
                return NULL;
39✔
1884

1885
        PROTECT_ERRNO;
×
1886
        (void) umount_recursive(p, 0);
39✔
1887
        return mfree(p);
39✔
1888
}
1889

1890
char* umount_and_unlink_and_free(char *p) {
1✔
1891
        if (!p)
1✔
1892
                return NULL;
1✔
1893

1894
        PROTECT_ERRNO;
2✔
1895
        (void) umount2(p, 0);
1✔
1896
        (void) unlink(p);
1✔
1897
        return mfree(p);
1✔
1898
}
1899

1900
int path_get_mount_info_at(
646✔
1901
                int dir_fd,
1902
                const char *path,
1903
                char **ret_fstype,
1904
                char **ret_options,
1905
                char **ret_source) {
1906

1907
        _cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
646✔
1908
        _cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
646✔
1909
        int r, mnt_id;
646✔
1910

1911
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
646✔
1912

1913
        r = path_get_mnt_id_at(dir_fd, path, &mnt_id);
646✔
1914
        if (r < 0)
646✔
1915
                return log_debug_errno(r, "Failed to get mount ID: %m");
×
1916

1917
        /* When getting options is requested, we also need to parse utab, otherwise userspace options like
1918
         * "_netdev" will be lost. */
1919
        if (ret_options)
646✔
1920
                r = libmount_parse_with_utab(&table, &iter);
636✔
1921
        else
1922
                r = libmount_parse_mountinfo(/* source = */ NULL, &table, &iter);
10✔
1923
        if (r < 0)
646✔
1924
                return log_debug_errno(r, "Failed to parse /proc/self/mountinfo: %m");
×
1925

1926
        for (;;) {
3,454✔
1927
                struct libmnt_fs *fs;
2,050✔
1928

1929
                r = mnt_table_next_fs(table, iter, &fs);
2,050✔
1930
                if (r == 1)
2,050✔
1931
                        break; /* EOF */
1932
                if (r < 0)
2,050✔
1933
                        return log_debug_errno(r, "Failed to get next entry from /proc/self/mountinfo: %m");
646✔
1934

1935
                if (mnt_fs_get_id(fs) != mnt_id)
2,050✔
1936
                        continue;
1,404✔
1937

1938
                _cleanup_free_ char *fstype = NULL, *options = NULL, *source = NULL;
646✔
1939

1940
                if (ret_fstype) {
646✔
1941
                        fstype = strdup(strempty(mnt_fs_get_fstype(fs)));
636✔
1942
                        if (!fstype)
636✔
1943
                                return log_oom_debug();
×
1944
                }
1945

1946
                if (ret_options) {
646✔
1947
                        options = strdup(strempty(mnt_fs_get_options(fs)));
636✔
1948
                        if (!options)
636✔
1949
                                return log_oom_debug();
×
1950
                }
1951

1952
                if (ret_source) {
646✔
1953
                        source = strdup(strempty(mnt_fs_get_source(fs)));
10✔
1954
                        if (!source)
10✔
1955
                                return log_oom_debug();
×
1956
                }
1957

1958
                if (ret_fstype)
646✔
1959
                        *ret_fstype = TAKE_PTR(fstype);
636✔
1960
                if (ret_options)
646✔
1961
                        *ret_options = TAKE_PTR(options);
636✔
1962
                if (ret_source)
646✔
1963
                        *ret_source = TAKE_PTR(source);
10✔
1964

1965
                return 0;
1966
        }
1967

1968
        return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Cannot find mount ID %i from /proc/self/mountinfo.", mnt_id);
×
1969
}
1970

1971
int path_is_network_fs_harder_at(int dir_fd, const char *path) {
654✔
1972
        _cleanup_close_ int fd = -EBADF;
654✔
1973
        int r;
654✔
1974

1975
        assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
654✔
1976

1977
        fd = xopenat(dir_fd, path, O_PATH | O_CLOEXEC | O_NOFOLLOW);
654✔
1978
        if (fd < 0)
654✔
1979
                return fd;
1980

1981
        r = fd_is_network_fs(fd);
636✔
1982
        if (r != 0)
636✔
1983
                return r;
1984

1985
        _cleanup_free_ char *fstype = NULL, *options = NULL;
636✔
1986
        r = path_get_mount_info_at(fd, /* path = */ NULL, &fstype, &options, /* ret_source = */ NULL);
636✔
1987
        if (r < 0)
636✔
1988
                return r;
1989

1990
        if (fstype_is_network(fstype))
636✔
1991
                return true;
1992

1993
        if (fstab_test_option(options, "_netdev\0"))
636✔
1994
                return true;
×
1995

1996
        return false;
1997
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc