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

systemd / systemd / 18795135167

24 Oct 2025 08:21PM UTC coverage: 72.26% (-0.02%) from 72.284%
18795135167

push

github

poettering
rules: apply loopback block device rule only onto loopback block devices

Fixes: #39426
Follow-up for: 9422ce83c

304809 of 421823 relevant lines covered (72.26%)

1112914.25 hits per line

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

0.0
/src/mountfsd/mountwork.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <linux/loop.h>
4
#include <poll.h>
5
#include <stdlib.h>
6
#include <sys/mount.h>
7
#include <unistd.h>
8

9
#include "sd-daemon.h"
10
#include "sd-event.h"
11
#include "sd-varlink.h"
12

13
#include "argv-util.h"
14
#include "bus-polkit.h"
15
#include "chase.h"
16
#include "discover-image.h"
17
#include "dissect-image.h"
18
#include "env-util.h"
19
#include "errno-util.h"
20
#include "fd-util.h"
21
#include "fs-util.h"
22
#include "format-util.h"
23
#include "hashmap.h"
24
#include "image-policy.h"
25
#include "io-util.h"
26
#include "iovec-util.h"
27
#include "json-util.h"
28
#include "loop-util.h"
29
#include "main-func.h"
30
#include "memory-util.h"
31
#include "mount-util.h"
32
#include "namespace-util.h"
33
#include "nsresource.h"
34
#include "nulstr-util.h"
35
#include "os-util.h"
36
#include "path-util.h"
37
#include "pidref.h"
38
#include "stat-util.h"
39
#include "string-table.h"
40
#include "string-util.h"
41
#include "strv.h"
42
#include "tmpfile-util.h"
43
#include "time-util.h"
44
#include "uid-classification.h"
45
#include "uid-range.h"
46
#include "user-util.h"
47
#include "varlink-io.systemd.MountFileSystem.h"
48
#include "varlink-util.h"
49

50
#define ITERATIONS_MAX 64U
51
#define RUNTIME_MAX_USEC (5 * USEC_PER_MINUTE)
52
#define PRESSURE_SLEEP_TIME_USEC (50 * USEC_PER_MSEC)
53
#define LISTEN_IDLE_USEC (90 * USEC_PER_SEC)
54

55
static const ImagePolicy image_policy_untrusted = {
56
        .n_policies = 2,
57
        .policies = {
58
                { PARTITION_ROOT,     PARTITION_POLICY_SIGNED|PARTITION_POLICY_ABSENT },
59
                { PARTITION_USR,      PARTITION_POLICY_SIGNED|PARTITION_POLICY_ABSENT },
60
        },
61
        .default_flags = PARTITION_POLICY_IGNORE,
62
};
63

64
static int json_dispatch_image_policy(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
×
65
        _cleanup_(image_policy_freep) ImagePolicy *q = NULL;
×
66
        ImagePolicy **p = ASSERT_PTR(userdata);
×
67
        int r;
×
68

69
        assert(p);
×
70

71
        if (sd_json_variant_is_null(variant)) {
×
72
                *p = image_policy_free(*p);
×
73
                return 0;
×
74
        }
75

76
        if (!sd_json_variant_is_string(variant))
×
77
                return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not a string.", strna(name));
×
78

79
        r = image_policy_from_string(sd_json_variant_string(variant), &q);
×
80
        if (r < 0)
×
81
                return json_log(variant, flags, r, "JSON field '%s' is not a valid image policy.", strna(name));
×
82

83
        image_policy_free(*p);
×
84
        *p = TAKE_PTR(q);
×
85
        return 0;
×
86
}
87

88
typedef struct MountImageParameters {
89
        unsigned image_fd_idx;
90
        unsigned userns_fd_idx;
91
        int read_only;
92
        int growfs;
93
        char *password;
94
        ImagePolicy *image_policy;
95
        bool verity_sharing;
96
        struct iovec verity_root_hash;
97
        struct iovec verity_root_hash_sig;
98
        unsigned verity_data_fd_idx;
99
} MountImageParameters;
100

101
static void mount_image_parameters_done(MountImageParameters *p) {
×
102
        assert(p);
×
103

104
        p->password = erase_and_free(p->password);
×
105
        p->image_policy = image_policy_free(p->image_policy);
×
106
        iovec_done(&p->verity_root_hash);
×
107
        iovec_done(&p->verity_root_hash_sig);
×
108
}
×
109

110
static int validate_image_fd(int fd, MountImageParameters *p) {
×
111
        int r, fl;
×
112

113
        assert(fd >= 0);
×
114
        assert(p);
×
115

116
        struct stat st;
×
117
        if (fstat(fd, &st) < 0)
×
118
                return -errno;
×
119
        /* Only support regular files and block devices. Let's use stat_verify_regular() here for the nice
120
         * error numbers it generates. */
121
        if (!S_ISBLK(st.st_mode)) {
×
122
                r = stat_verify_regular(&st);
×
123
                if (r < 0)
×
124
                        return r;
125
        }
126

127
        fl = fd_verify_safe_flags(fd);
×
128
        if (fl < 0)
×
129
                return log_debug_errno(fl, "Image file descriptor has unsafe flags set: %m");
×
130

131
        switch (fl & O_ACCMODE_STRICT) {
×
132

133
        case O_RDONLY:
×
134
                p->read_only = true;
×
135
                break;
×
136

137
        case O_RDWR:
138
                break;
139

140
        default:
141
                return -EBADF;
142
        }
143

144
        return 0;
145
}
146

147
static int verify_trusted_image_fd_by_path(int fd) {
×
148
        int r;
×
149

150
        assert(fd >= 0);
×
151

152
        r = secure_getenv_bool("SYSTEMD_MOUNTFSD_TRUSTED_DIRECTORIES");
×
153
        if (r == -ENXIO)  {
×
154
                if (!DEFAULT_MOUNTFSD_TRUSTED_DIRECTORIES) {
×
155
                        log_debug("Trusted directory mechanism disabled at compile time.");
×
156
                        return false;
×
157
                }
158
        } else if (r < 0) {
×
159
                log_debug_errno(r, "Failed to parse $SYSTEMD_MOUNTFSD_TRUSTED_DIRECTORIES environment variable, not trusting any image.");
×
160
                return false;
×
161
        } else if (!r) {
×
162
                log_debug("Trusted directory mechanism disabled via $SYSTEMD_MOUNTFSD_TRUSTED_DIRECTORIES environment variable.");
×
163
                return false;
×
164
        }
165

166
        _cleanup_free_ char *p = NULL;
×
167
        r = fd_get_path(fd, &p);
×
168
        if (r < 0)
×
169
                return log_debug_errno(r, "Failed to get path of passed image file descriptor: %m");
×
170

171
        struct stat sta;
×
172
        if (fstat(fd, &sta) < 0)
×
173
                return log_debug_errno(errno, "Failed to stat() passed image file descriptor: %m");
×
174
        if (!S_ISREG(sta.st_mode)) {
×
175
                log_debug("Image '%s' is not a regular file, hence skipping trusted directory check.", p);
×
176
                return false;
×
177
        }
178

179
        log_debug("Checking if image '%s' is in trusted directories.", p);
×
180

181
        for (ImageClass c = 0; c < _IMAGE_CLASS_MAX; c++)
×
182
                NULSTR_FOREACH(s, image_search_path[c]) {
×
183
                        _cleanup_close_ int dir_fd = -EBADF, inode_fd = -EBADF;
×
184
                        _cleanup_free_ char *q = NULL;
×
185
                        struct stat stb;
×
186
                        const char *e;
×
187

188
                        r = chase(s, NULL, CHASE_SAFE|CHASE_TRIGGER_AUTOFS, &q, &dir_fd);
×
189
                        if (r == -ENOENT)
×
190
                                continue;
×
191
                        if (r < 0) {
×
192
                                log_warning_errno(r, "Failed to resolve search path '%s', ignoring: %m", s);
×
193
                                continue;
×
194
                        }
195

196
                        /* Check that the inode refers to a file immediately inside the image directory,
197
                         * i.e. not the image directory itself, and nothing further down the tree */
198
                        e = path_startswith(p, q);
×
199
                        if (isempty(e))
×
200
                                continue;
×
201

202
                        e += strspn(e, "/");
×
203
                        if (!filename_is_valid(e))
×
204
                                continue;
×
205

206
                        r = chaseat(dir_fd, e, CHASE_SAFE|CHASE_TRIGGER_AUTOFS, NULL, &inode_fd);
×
207
                        if (r < 0)
×
208
                                return log_error_errno(r, "Couldn't verify that specified image '%s' is in search path '%s': %m", p, s);
×
209

210
                        if (fstat(inode_fd, &stb) < 0)
×
211
                                return log_error_errno(errno, "Failed to stat image file '%s/%s': %m", q, e);
×
212

213
                        if (stat_inode_same(&sta, &stb)) {
×
214
                                log_debug("Image '%s' is *in* trusted directories.", p);
×
215
                                return true; /* Yay */
×
216
                        }
217
                }
218

219
        log_debug("Image '%s' is *not* in trusted directories.", p);
×
220
        return false;
221
}
222

223
static int determine_image_policy(
×
224
                int image_fd,
225
                bool trusted,
226
                ImagePolicy *client_policy,
227
                ImagePolicy **ret) {
228

229
        _cleanup_(image_policy_freep) ImagePolicy *envvar_policy = NULL;
×
230
        const ImagePolicy *default_policy;
×
231
        const char *envvar, *e;
×
232
        int r;
×
233

234
        assert(image_fd >= 0);
×
235
        assert(ret);
×
236

237
        if (trusted) {
×
238
                envvar = "SYSTEMD_MOUNTFSD_IMAGE_POLICY_TRUSTED";
239
                default_policy = &image_policy_allow;
240
        } else {
241
                envvar = "SYSTEMD_MOUNTFSD_IMAGE_POLICY_UNTRUSTED";
×
242
                default_policy = &image_policy_untrusted;
×
243
        }
244

245
        e = secure_getenv(envvar);
×
246
        if (e) {
×
247
                r = image_policy_from_string(e, &envvar_policy);
×
248
                if (r < 0)
×
249
                        return log_error_errno(r, "Failed to parse image policy supplied via $%s: %m", envvar);
×
250

251
                default_policy = envvar_policy;
×
252
        }
253

254
        return image_policy_intersect(default_policy, client_policy, ret);
×
255
}
256

257
static int validate_userns(sd_varlink *link, int *userns_fd) {
×
258
        int r;
×
259

260
        assert(link);
×
261
        assert(userns_fd);
×
262

263
        if (*userns_fd < 0)
×
264
                return 0;
265

266
        r = fd_verify_safe_flags(*userns_fd);
×
267
        if (r < 0)
×
268
                return log_debug_errno(r, "User namespace file descriptor has unsafe flags set: %m");
×
269

270
        r = fd_is_namespace(*userns_fd, NAMESPACE_USER);
×
271
        if (r < 0)
×
272
                return r;
273
        if (r == 0)
×
274
                return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
×
275

276
        /* Our own host user namespace? Then close the fd, and handle it as if none was specified. */
277
        r = is_our_namespace(*userns_fd, NAMESPACE_USER);
×
278
        if (r < 0)
×
279
                return log_debug_errno(r, "Failed to determine if user namespace provided by client is our own.");
×
280
        if (r > 0) {
×
281
                log_debug("User namespace provided by client is our own.");
×
282
                *userns_fd = safe_close(*userns_fd);
×
283
        }
284

285
        return 0;
286
}
287

288
static int vl_method_mount_image(
×
289
                sd_varlink *link,
290
                sd_json_variant *parameters,
291
                sd_varlink_method_flags_t flags,
292
                void *userdata) {
293

294
        static const sd_json_dispatch_field dispatch_table[] = {
×
295
                { "imageFileDescriptor",         SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,        offsetof(MountImageParameters, image_fd_idx),         SD_JSON_MANDATORY },
296
                { "userNamespaceFileDescriptor", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,        offsetof(MountImageParameters, userns_fd_idx),        0 },
297
                { "readOnly",                    SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_tristate,    offsetof(MountImageParameters, read_only),            0 },
298
                { "growFileSystems",             SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_tristate,    offsetof(MountImageParameters, growfs),               0 },
299
                { "password",                    SD_JSON_VARIANT_STRING,   sd_json_dispatch_string,      offsetof(MountImageParameters, password),             0 },
300
                { "imagePolicy",                 SD_JSON_VARIANT_STRING,   json_dispatch_image_policy,   offsetof(MountImageParameters, image_policy),         0 },
301
                { "veritySharing",               SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_stdbool,     offsetof(MountImageParameters, verity_sharing),       0 },
302
                { "verityDataFileDescriptor",    SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,        offsetof(MountImageParameters, verity_data_fd_idx),   0 },
303
                { "verityRootHash",              SD_JSON_VARIANT_STRING,   json_dispatch_unhex_iovec,    offsetof(MountImageParameters, verity_root_hash),     0 },
304
                { "verityRootHashSignature",     SD_JSON_VARIANT_STRING,   json_dispatch_unbase64_iovec, offsetof(MountImageParameters, verity_root_hash_sig), 0 },
305
                VARLINK_DISPATCH_POLKIT_FIELD,
306
                {}
307
        };
308

309
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
×
310
        _cleanup_(mount_image_parameters_done) MountImageParameters p = {
×
311
                .image_fd_idx = UINT_MAX,
312
                .userns_fd_idx = UINT_MAX,
313
                .verity_data_fd_idx = UINT_MAX,
314
                .read_only = -1,
315
                .growfs = -1,
316
        };
317
        _cleanup_(dissected_image_unrefp) DissectedImage *di = NULL;
×
318
        _cleanup_(loop_device_unrefp) LoopDevice *loop = NULL;
×
319
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *aj = NULL;
×
320
        _cleanup_close_ int image_fd = -EBADF, userns_fd = -EBADF, verity_data_fd = -EBADF;
×
321
        _cleanup_(image_policy_freep) ImagePolicy *use_policy = NULL;
×
322
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
×
323
        _cleanup_free_ char *ps = NULL;
×
324
        bool image_is_trusted = false;
×
325
        int r;
×
326

327
        assert(link);
×
328
        assert(parameters);
×
329

330
        sd_json_variant_sensitive(parameters); /* might contain passwords */
×
331

332
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
333
        if (r != 0)
×
334
                return r;
335

336
        /* Verity data and roothash have to be either both set, or both unset. The sig can be set only if
337
         * the roothash is set. */
338
        if ((p.verity_data_fd_idx != UINT_MAX) != (p.verity_root_hash.iov_len > 0))
×
339
                return sd_varlink_error_invalid_parameter_name(link, "verityDataFileDescriptor");
×
340
        if (p.verity_root_hash_sig.iov_len > 0 && p.verity_root_hash.iov_len == 0)
×
341
                return sd_varlink_error_invalid_parameter_name(link, "verityRootHashSignature");
×
342

343
        if (p.image_fd_idx != UINT_MAX) {
×
344
                image_fd = sd_varlink_peek_dup_fd(link, p.image_fd_idx);
×
345
                if (image_fd < 0)
×
346
                        return log_debug_errno(image_fd, "Failed to peek image fd from client: %m");
×
347
        }
348

349
        if (p.userns_fd_idx != UINT_MAX) {
×
350
                userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
×
351
                if (userns_fd < 0)
×
352
                        return log_debug_errno(userns_fd, "Failed to peek user namespace fd from client: %m");
×
353
        }
354

355
        r = validate_image_fd(image_fd, &p);
×
356
        if (r < 0)
×
357
                return r;
358

359
        r = validate_userns(link, &userns_fd);
×
360
        if (r != 0)
×
361
                return r;
362

363
        r = verify_trusted_image_fd_by_path(image_fd);
×
364
        if (r < 0)
×
365
                return r;
366
        image_is_trusted = r;
×
367

368
        if (p.verity_data_fd_idx != UINT_MAX) {
×
369
                verity_data_fd = sd_varlink_peek_dup_fd(link, p.verity_data_fd_idx);
×
370
                if (verity_data_fd < 0)
×
371
                        return log_debug_errno(verity_data_fd, "Failed to peek verity data fd from client: %m");
×
372

373
                r = fd_verify_safe_flags(verity_data_fd);
×
374
                if (r < 0)
×
375
                        return log_debug_errno(r, "Verity data file descriptor has unsafe flags set: %m");
×
376

377
                verity.data_path = strdup(FORMAT_PROC_FD_PATH(verity_data_fd));
×
378
                if (!verity.data_path)
×
379
                        return -ENOMEM;
380

381
                verity.designator = PARTITION_ROOT;
×
382

383
                verity.root_hash = TAKE_PTR(p.verity_root_hash.iov_base);
×
384
                verity.root_hash_size = p.verity_root_hash.iov_len;
×
385
                p.verity_root_hash.iov_len = 0;
×
386

387
                verity.root_hash_sig = TAKE_PTR(p.verity_root_hash_sig.iov_base);
×
388
                verity.root_hash_sig_size = p.verity_root_hash_sig.iov_len;
×
389
                p.verity_root_hash_sig.iov_len = 0;
×
390
        }
391

392
        const char *polkit_details[] = {
×
393
                "read_only", one_zero(p.read_only > 0),
×
394
                NULL,
395
        };
396

397
        const char *polkit_action, *polkit_untrusted_action;
×
398
        PolkitFlags polkit_flags;
×
399
        if (userns_fd < 0) {
×
400
                /* Mount into the host user namespace */
401
                polkit_action = "io.systemd.mount-file-system.mount-image";
402
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-image";
403
                polkit_flags = 0;
404
        } else {
405
                /* Mount into a private user namespace */
406
                polkit_action = "io.systemd.mount-file-system.mount-image-privately";
×
407
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-image-privately";
×
408

409
                /* If polkit is not around, let's allow mounting authenticated images by default */
410
                polkit_flags = POLKIT_DEFAULT_ALLOW;
×
411
        }
412

413
        /* Let's definitely acquire the regular action privilege, for mounting properly signed images */
414
        r = varlink_verify_polkit_async_full(
×
415
                        link,
416
                        /* bus= */ NULL,
417
                        polkit_action,
418
                        polkit_details,
419
                        /* good_user= */ UID_INVALID,
420
                        polkit_flags,
421
                        polkit_registry);
422
        if (r <= 0)
×
423
                return r;
424

425
        /* Generate the common dissection directory here. We are not going to use it, but the clients might,
426
         * and they likely are unprivileged, hence cannot create it themselves. Hence let's just create it
427
         * here, if it is missing. */
428
        r = get_common_dissect_directory(NULL);
×
429
        if (r < 0)
×
430
                return r;
431

432
        r = loop_device_make(
×
433
                        image_fd,
434
                        p.read_only == 0 ? O_RDONLY : O_RDWR,
×
435
                        0,
436
                        UINT64_MAX,
437
                        UINT32_MAX,
438
                        LO_FLAGS_PARTSCAN,
439
                        LOCK_EX,
440
                        &loop);
441
        if (r < 0)
×
442
                return r;
443

444
        DissectImageFlags dissect_flags =
×
445
                (p.read_only == 0 ? DISSECT_IMAGE_READ_ONLY : 0) |
×
446
                (p.growfs != 0 ? DISSECT_IMAGE_GROWFS : 0) |
×
447
                DISSECT_IMAGE_DISCARD_ANY |
448
                DISSECT_IMAGE_FSCK |
449
                DISSECT_IMAGE_ADD_PARTITION_DEVICES |
×
450
                DISSECT_IMAGE_PIN_PARTITION_DEVICES |
×
451
                (p.verity_sharing ? DISSECT_IMAGE_VERITY_SHARE : 0) |
×
452
                /* Maybe the image is a bare filesystem. Note that this requires privileges, as it is
453
                 * classified by the policy as an 'unprotected' image and will be refused otherwise. */
454
                DISSECT_IMAGE_NO_PARTITION_TABLE |
×
455
                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY;
456

457
        /* Let's see if we have acquired the privilege to mount untrusted images already */
458
        bool polkit_have_untrusted_action =
×
459
                varlink_has_polkit_action(link, polkit_untrusted_action, polkit_details, polkit_registry);
×
460

461
        for (;;) {
×
462
                use_policy = image_policy_free(use_policy);
×
463
                ps = mfree(ps);
×
464

465
                /* We use the image policy for trusted images if either the path is below a trusted
466
                 * directory, or if we have already acquired a PK authentication that tells us that untrusted
467
                 * images are OK */
468
                bool use_trusted_policy =
×
469
                        image_is_trusted ||
470
                        polkit_have_untrusted_action;
471

472
                r = determine_image_policy(
×
473
                                image_fd,
474
                                use_trusted_policy,
475
                                p.image_policy,
476
                                &use_policy);
477
                if (r < 0)
×
478
                        return r;
479

480
                r = image_policy_to_string(use_policy, /* simplify= */ true, &ps);
×
481
                if (r < 0)
×
482
                        return r;
483

484
                log_debug("Using image policy: %s", ps);
×
485

486
                r = dissect_loop_device(
×
487
                                loop,
488
                                &verity,
489
                                /* mount_options= */ NULL,
490
                                use_policy,
491
                                /* image_filter= */ NULL,
492
                                dissect_flags,
493
                                &di);
494
                if (r == -ENOPKG)
×
495
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.IncompatibleImage", NULL);
×
496
                if (r == -ENOTUNIQ)
×
497
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.MultipleRootPartitionsFound", NULL);
×
498
                if (r == -ENXIO)
×
499
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.RootPartitionNotFound", NULL);
×
500
                if (r == -ERFKILL) {
×
501
                        /* The image policy refused this, let's retry after trying to get PolicyKit */
502

503
                        if (!polkit_have_untrusted_action) {
×
504
                                log_debug("Denied by image policy. Trying a stronger polkit authentication before continuing.");
×
505
                                r = varlink_verify_polkit_async_full(
×
506
                                                link,
507
                                                /* bus= */ NULL,
508
                                                polkit_untrusted_action,
509
                                                polkit_details,
510
                                                /* good_user= */ UID_INVALID,
511
                                                /* flags= */ 0,                   /* NB: the image cannot be authenticated, hence unless PK is around to allow this anyway, fail! */
512
                                                polkit_registry);
513
                                if (r <= 0 && !ERRNO_IS_NEG_PRIVILEGE(r))
×
514
                                        return r;
515
                                if (r > 0) {
×
516
                                        /* Try again, now that we know the client has enough privileges. */
517
                                        log_debug("Denied by image policy, retrying after polkit authentication.");
×
518
                                        polkit_have_untrusted_action = true;
×
519
                                        continue;
×
520
                                }
521
                        }
522

523
                        return sd_varlink_error(link, "io.systemd.MountFileSystem.DeniedByImagePolicy", NULL);
×
524
                }
525
                if (r < 0)
×
526
                        return r;
527

528
                /* Success */
529
                break;
×
530
        }
531

532
        r = dissected_image_load_verity_sig_partition(
×
533
                        di,
534
                        loop->fd,
×
535
                        &verity);
536
        if (r < 0)
×
537
                return r;
538

539
        r = dissected_image_guess_verity_roothash(
×
540
                        di,
541
                        &verity);
542
        if (r < 0)
×
543
                return r;
544

545
        r = dissected_image_decrypt(
×
546
                        di,
547
                        p.password,
×
548
                        &verity,
549
                        use_policy,
550
                        dissect_flags);
551
        if (r == -ENOKEY) /* new dm-verity userspace returns ENOKEY if the dm-verity signature key is not in
×
552
                           * key chain. That's great. */
553
                return sd_varlink_error(link, "io.systemd.MountFileSystem.KeyNotFound", NULL);
×
554
        if (r == -EBUSY) /* DM kernel subsystem is shit with returning useful errors hence we keep retrying
×
555
                          * under the assumption that some errors are transitional. Which the errors might
556
                          * not actually be. After all retries failed we return EBUSY. Let's turn that into a
557
                          * generic Verity error. It's not very helpful, could mean anything, but at least it
558
                          * gives client a clear idea that this has to do with Verity. */
559
                return sd_varlink_error(link, "io.systemd.MountFileSystem.VerityFailure", NULL);
×
560
        if (r < 0)
×
561
                return r;
562

563
        r = dissected_image_mount(
×
564
                        di,
565
                        /* where= */ NULL,
566
                        /* uid_shift= */ UID_INVALID,
567
                        /* uid_range= */ UID_INVALID,
568
                        userns_fd,
569
                        dissect_flags);
570
        if (r < 0)
×
571
                return r;
572

573
        for (PartitionDesignator d = 0; d < _PARTITION_DESIGNATOR_MAX; d++) {
×
574
                DissectedPartition *pp = di->partitions + d;
×
575
                int fd_idx;
×
576

577
                if (!pp->found)
×
578
                        continue;
×
579

580
                if (pp->fsmount_fd < 0)
×
581
                        continue;
×
582

583
                if (userns_fd >= 0) {
×
584
                        r = nsresource_add_mount(userns_fd, pp->fsmount_fd);
×
585
                        if (r < 0)
×
586
                                return r;
×
587
                }
588

589
                fd_idx = sd_varlink_push_fd(link, pp->fsmount_fd);
×
590
                if (fd_idx < 0)
×
591
                        return fd_idx;
592

593
                TAKE_FD(pp->fsmount_fd);
×
594

595
                const char *m = partition_mountpoint_to_string(d);
×
596
                _cleanup_strv_free_ char **l = NULL;
×
597
                if (!isempty(m)) {
×
598
                        l = strv_split_nulstr(m);
×
599
                        if (!l)
×
600
                                return log_oom_debug();
×
601
                }
602

603
                r = sd_json_variant_append_arraybo(
×
604
                                &aj,
605
                                SD_JSON_BUILD_PAIR("designator", SD_JSON_BUILD_STRING(partition_designator_to_string(d))),
606
                                SD_JSON_BUILD_PAIR("writable", SD_JSON_BUILD_BOOLEAN(pp->rw)),
607
                                SD_JSON_BUILD_PAIR("growFileSystem", SD_JSON_BUILD_BOOLEAN(pp->growfs)),
608
                                SD_JSON_BUILD_PAIR_CONDITION(pp->partno > 0, "partitionNumber", SD_JSON_BUILD_INTEGER(pp->partno)),
609
                                SD_JSON_BUILD_PAIR_CONDITION(pp->architecture > 0, "architecture", SD_JSON_BUILD_STRING(architecture_to_string(pp->architecture))),
610
                                SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(pp->uuid), "partitionUuid", SD_JSON_BUILD_UUID(pp->uuid)),
611
                                SD_JSON_BUILD_PAIR("fileSystemType", SD_JSON_BUILD_STRING(dissected_partition_fstype(pp))),
612
                                SD_JSON_BUILD_PAIR_CONDITION(!!pp->label, "partitionLabel", SD_JSON_BUILD_STRING(pp->label)),
613
                                SD_JSON_BUILD_PAIR("size", SD_JSON_BUILD_UNSIGNED(pp->size)),
614
                                SD_JSON_BUILD_PAIR("offset", SD_JSON_BUILD_UNSIGNED(pp->offset)),
615
                                SD_JSON_BUILD_PAIR("mountFileDescriptor", SD_JSON_BUILD_INTEGER(fd_idx)),
616
                                JSON_BUILD_PAIR_STRV_NON_EMPTY("mountPoint", l));
617
                if (r < 0)
×
618
                        return r;
619
        }
620

621
        loop_device_relinquish(loop);
×
622

623
        return sd_varlink_replybo(
×
624
                        link,
625
                        SD_JSON_BUILD_PAIR("partitions", SD_JSON_BUILD_VARIANT(aj)),
626
                        SD_JSON_BUILD_PAIR("imagePolicy", SD_JSON_BUILD_STRING(ps)),
627
                        SD_JSON_BUILD_PAIR("imageSize", SD_JSON_BUILD_UNSIGNED(di->image_size)),
628
                        SD_JSON_BUILD_PAIR("sectorSize", SD_JSON_BUILD_UNSIGNED(di->sector_size)),
629
                        SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(di->image_uuid), "imageUuid", SD_JSON_BUILD_UUID(di->image_uuid)));
630
}
631

632
typedef enum MountMapMode {
633
        MOUNT_MAP_AUTO = 0,     /* determine automatically from image and caller */
634
        MOUNT_MAP_ROOT,         /* map caller's UID to root in namespace (map 1 UID only) */
635
        MOUNT_MAP_FOREIGN,      /* map foreign UID range to base in namespace (map 64K) */
636
        MOUNT_MAP_IDENTITY,     /* apply identity mapping (map 64K) */
637
        _MOUNT_MAP_MODE_MAX,
638
        _MOUNT_MAP_MODE_INVALID = -EINVAL,
639
} MountMapMode;
640

641
static const char *const mount_map_mode_table[_MOUNT_MAP_MODE_MAX] = {
642
        [MOUNT_MAP_AUTO]     = "auto",
643
        [MOUNT_MAP_ROOT]     = "root",
644
        [MOUNT_MAP_FOREIGN]  = "foreign",
645
        [MOUNT_MAP_IDENTITY] = "identity",
646
};
647

648
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(mount_map_mode, MountMapMode);
×
649

650
typedef struct MountDirectoryParameters {
651
        MountMapMode mode;
652
        unsigned directory_fd_idx;
653
        unsigned userns_fd_idx;
654
        int read_only;
655
} MountDirectoryParameters;
656

657
typedef enum DirectoryOwnership {
658
        DIRECTORY_IS_ROOT_PEER_OWNED,  /* This is returned if the directory is owned by the root user and the peer is root */
659
        DIRECTORY_IS_ROOT_OWNED,       /* This is returned if the directory is owned by the root user (and the peer user is not root) */
660
        DIRECTORY_IS_PEER_OWNED,       /* This is returned if the directory is owned by the peer user (who is not root) */
661
        DIRECTORY_IS_FOREIGN_OWNED,    /* This is returned if the directory is owned by the foreign UID range */
662
        DIRECTORY_IS_OTHERWISE_OWNED,  /* This is returned if the directory is owned by something else */
663
        _DIRECTORY_OWNERSHIP_MAX,
664
        _DIRECTORY_OWNERSHIP_ERRNO_MAX = -ERRNO_MAX, /* Guarantee the whole negative errno range fits */
665
} DirectoryOwnership;
666

667
static MountMapMode default_mount_map_mode(DirectoryOwnership ownership) {
×
668
        /* Derives a suitable mapping mode from the ownership of the base tree */
669

670
        switch (ownership) {
×
671
        case DIRECTORY_IS_PEER_OWNED:
672
                return MOUNT_MAP_ROOT;     /* Map the peer's UID to root in the container */
673

674
        case DIRECTORY_IS_FOREIGN_OWNED:
×
675
                return MOUNT_MAP_FOREIGN;  /* Map the foreign UID range to the container's UID range */
×
676

677
        case DIRECTORY_IS_ROOT_PEER_OWNED:
×
678
        case DIRECTORY_IS_ROOT_OWNED:
679
        case DIRECTORY_IS_OTHERWISE_OWNED:
680
                return MOUNT_MAP_IDENTITY; /* Don't map */
×
681

682
        default:
×
683
                return _MOUNT_MAP_MODE_INVALID;
×
684
        }
685
}
686

687
static JSON_DISPATCH_ENUM_DEFINE(dispatch_mount_directory_mode, MountMapMode, mount_map_mode_from_string);
×
688

689
static DirectoryOwnership validate_directory_fd(
×
690
                int fd,
691
                uid_t peer_uid,
692
                uid_t *ret_current_owner_uid) {
693

694
        int r, fl;
×
695

696
        assert(fd >= 0);
×
697
        assert(uid_is_valid(peer_uid));
×
698
        assert(ret_current_owner_uid);
×
699

700
        /* Checks if the specified directory fd looks sane. Returns a DirectoryOwnership that categorizes the
701
         * ownership situation in comparison to the peer's UID.
702
         *
703
         * Note one key difference to image validation (as implemented above): for regular files if the
704
         * client provided us with an open fd it implies the client has access, as well as what kind of
705
         * access (i.e. ro or rw). But for directories this doesn't work the same way, as directories are
706
         * always opened read-only only. Hence we use a different mechanism to validate access to them: we
707
         * check if the directory is owned by the peer UID or by the foreign UID range (in the latter case
708
         * one of the parent directories must be owned by the peer though). */
709

710
        struct stat st;
×
711
        if (fstat(fd, &st) < 0)
×
712
                return log_debug_errno(errno, "Failed to stat() directory fd: %m");
×
713

714
        r = stat_verify_directory(&st);
×
715
        if (r < 0)
×
716
                return r;
717

718
        fl = fd_verify_safe_flags_full(fd, O_DIRECTORY|O_PATH);
×
719
        if (fl < 0)
×
720
                return log_debug_errno(fl, "Directory file descriptor has unsafe flags set: %m");
×
721

722
        if (st.st_uid == 0) {
×
723
                *ret_current_owner_uid = st.st_uid;
×
724
                if (peer_uid == 0) {
×
725
                        log_debug("Directory file descriptor points to root owned directory, who is also the peer.");
×
726
                        return DIRECTORY_IS_ROOT_PEER_OWNED;
×
727
                }
728
                log_debug("Directory file descriptor points to root owned directory.");
×
729
                return DIRECTORY_IS_ROOT_OWNED;
×
730
        }
731
        if (st.st_uid == peer_uid) {
×
732
                log_debug("Directory file descriptor points to peer owned directory.");
×
733
                *ret_current_owner_uid = st.st_uid;
×
734
                return DIRECTORY_IS_PEER_OWNED;
×
735
        }
736

737
        /* For bind mounted directories we check if they are either owned by the client's UID, or by the
738
         * foreign UID set, but in that case the parent directory must be owned by the client's UID, or some
739
         * directory iteratively up the chain */
740

741
        _cleanup_close_ int parent_fd = -EBADF;
×
742
        unsigned n_level;
743
        for (n_level = 0; n_level < 16; n_level++) {
×
744
                /* Stop iteration if we find a directory up the tree that is neither owned by the user, nor is from the foreign UID range */
745
                if (!uid_is_foreign(st.st_uid) || !gid_is_foreign(st.st_gid)) {
×
746
                        log_debug("Directory file descriptor points to directory which itself or its parents is neither owned by foreign UID range nor by the user.");
×
747
                        *ret_current_owner_uid = st.st_uid;
×
748
                        return DIRECTORY_IS_OTHERWISE_OWNED;
×
749
                }
750

751
                /* If the peer is root, then it doesn't matter if we find a parent owned by root, let's shortcut things. */
752
                if (peer_uid == 0) {
×
753
                        log_debug("Directory file descriptor is owned by foreign UID range, and peer is root.");
×
754
                        *ret_current_owner_uid = st.st_uid;
×
755
                        return DIRECTORY_IS_FOREIGN_OWNED;
×
756
                }
757

758
                /* Go one level up */
759
                _cleanup_close_ int new_parent_fd = openat(fd, "..", O_DIRECTORY|O_PATH|O_CLOEXEC);
×
760
                if (new_parent_fd < 0)
×
761
                        return log_debug_errno(errno, "Failed to open parent directory of directory file descriptor: %m");
×
762

763
                struct stat new_st;
×
764
                if (fstat(new_parent_fd, &new_st) < 0)
×
765
                        return log_debug_errno(errno, "Failed to stat parent directory of directory file descriptor: %m");
×
766

767
                /* Safety check to see if we hit the root dir */
768
                if (stat_inode_same(&st, &new_st)) {
×
769
                        log_debug("Directory file descriptor is owned by foreign UID range, but didn't find parent directory that is owned by peer among ancestors.");
×
770
                        *ret_current_owner_uid = st.st_uid;
×
771
                        return DIRECTORY_IS_OTHERWISE_OWNED;
×
772
                }
773

774
                if (new_st.st_uid == peer_uid) { /* Parent inode is owned by the peer. That's good! Everything's fine. */
×
775
                        log_debug("Directory file descriptor is owned by foreign UID range, and ancestor is owned by peer.");
×
776
                        *ret_current_owner_uid = st.st_uid;
×
777
                        return DIRECTORY_IS_FOREIGN_OWNED;
×
778
                }
779

780
                close_and_replace(parent_fd, new_parent_fd);
×
781
                st = new_st;
×
782
        }
783

784
        log_debug("Failed to find peer owned parent directory after %u levels, refusing.", n_level);
×
785
        *ret_current_owner_uid = st.st_uid;
×
786
        return DIRECTORY_IS_OTHERWISE_OWNED;
×
787
}
788

789
static int vl_method_mount_directory(
×
790
                sd_varlink *link,
791
                sd_json_variant *parameters,
792
                sd_varlink_method_flags_t flags,
793
                void *userdata) {
794

795
        static const sd_json_dispatch_field dispatch_table[] = {
×
796
                { "mode",                        SD_JSON_VARIANT_STRING,   dispatch_mount_directory_mode, offsetof(MountDirectoryParameters, mode),             0                 },
797
                { "directoryFileDescriptor",     SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,         offsetof(MountDirectoryParameters, directory_fd_idx), SD_JSON_MANDATORY },
798
                { "userNamespaceFileDescriptor", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,         offsetof(MountDirectoryParameters, userns_fd_idx),    0                 },
799
                { "readOnly",                    SD_JSON_VARIANT_BOOLEAN,  sd_json_dispatch_tristate,     offsetof(MountDirectoryParameters, read_only),        0                 },
800
                VARLINK_DISPATCH_POLKIT_FIELD,
801
                {}
802
        };
803

804
        MountDirectoryParameters p = {
×
805
                .mode = MOUNT_MAP_AUTO,
806
                .directory_fd_idx = UINT_MAX,
807
                .userns_fd_idx = UINT_MAX,
808
                .read_only = -1,
809
        };
810
        _cleanup_close_ int directory_fd = -EBADF, userns_fd = -EBADF;
×
811
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
×
812
        int r;
×
813

814
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
815
        if (r != 0)
×
816
                return r;
817

818
        if (p.directory_fd_idx == UINT_MAX)
×
819
                return sd_varlink_error_invalid_parameter_name(link, "directoryFileDescriptor");
×
820

821
        directory_fd = sd_varlink_peek_dup_fd(link, p.directory_fd_idx);
×
822
        if (directory_fd < 0)
×
823
                return log_debug_errno(directory_fd, "Failed to peek directory fd from client: %m");
×
824

825
        if (p.userns_fd_idx != UINT_MAX) {
×
826
                userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
×
827
                if (userns_fd < 0)
×
828
                        return log_debug_errno(userns_fd, "Failed to peek user namespace fd from client: %m");
×
829
        }
830

831
        uid_t peer_uid;
×
832
        r = sd_varlink_get_peer_uid(link, &peer_uid);
×
833
        if (r < 0)
×
834
                return log_debug_errno(r, "Failed to get client UID: %m");
×
835

836
        uid_t current_owner_uid;
×
837
        DirectoryOwnership owned_by = validate_directory_fd(directory_fd, peer_uid, &current_owner_uid);
×
838
        if (owned_by == -EREMOTEIO)
×
839
                return sd_varlink_errorbo(link, "io.systemd.MountFileSystem.BadFileDescriptorFlags", SD_JSON_BUILD_PAIR_STRING("parameter", "directoryFileDescriptor"));
×
840
        if (owned_by < 0)
×
841
                return owned_by;
842

843
        r = validate_userns(link, &userns_fd);
×
844
        if (r != 0)
×
845
                return r;
846

847
        /* If no mode is specified, pick sensible default */
848
        if (p.mode <= 0) {
×
849
                p.mode = default_mount_map_mode(owned_by);
×
850
                assert(p.mode > 0);
×
851
        }
852

853
        _cleanup_free_ char *directory_path = NULL;
×
854
        (void) fd_get_path(directory_fd, &directory_path);
×
855

856
        log_debug("Mounting '%s' with mapping mode: %s", strna(directory_path), mount_map_mode_to_string(p.mode));
×
857

858
        const char *polkit_details[] = {
×
859
                "read_only", one_zero(p.read_only > 0),
×
860
                "directory", strna(directory_path),
×
861
                NULL,
862
        };
863

864
        const char *polkit_action, *polkit_untrusted_action;
×
865
        PolkitFlags polkit_flags;
×
866
        if (userns_fd < 0) {
×
867
                /* Mount into the host user namespace */
868
                polkit_action = "io.systemd.mount-file-system.mount-directory";
869
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-directory";
870
                polkit_flags = 0;
871
        } else {
872
                /* Mount into a private user namespace */
873
                polkit_action = "io.systemd.mount-file-system.mount-directory-privately";
×
874
                polkit_untrusted_action = "io.systemd.mount-file-system.mount-untrusted-directory-privately";
×
875

876
                /* If polkit is not around, let's allow mounting authenticated images by default */
877
                polkit_flags = POLKIT_DEFAULT_ALLOW;
×
878
        }
879

880
        /* We consider a directory "trusted" if it is owned by the peer or the foreign UID range */
881
        bool trusted_directory = IN_SET(owned_by, DIRECTORY_IS_ROOT_PEER_OWNED, DIRECTORY_IS_PEER_OWNED, DIRECTORY_IS_FOREIGN_OWNED);
×
882

883
        /* Let's definitely acquire the regular action privilege, for mounting properly signed images */
884
        r = varlink_verify_polkit_async_full(
×
885
                        link,
886
                        /* bus= */ NULL,
887
                        trusted_directory ? polkit_action : polkit_untrusted_action,
888
                        polkit_details,
889
                        /* good_user= */ UID_INVALID,
890
                        trusted_directory ? polkit_flags : 0,
891
                        polkit_registry);
892
        if (r <= 0)
×
893
                return r;
894

895
        /* Generate the common dissection directory here. We are not going to use it, but the clients might,
896
         * and they likely are unprivileged, hence cannot create it themselves. Hence let's just create it
897
         * here, if it is missing. */
898
        r = get_common_dissect_directory(NULL);
×
899
        if (r < 0)
×
900
                return r;
901

902
        _cleanup_close_ int mount_fd = open_tree_try_drop_idmap(
×
903
                        directory_fd,
904
                        "",
905
                        OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH);
906
        if (mount_fd < 0)
×
907
                return log_debug_errno(errno, "Failed to issue open_tree() of provided directory '%s': %m", strna(directory_path));
×
908

909
        /* MOUNT_ATTR_IDMAP has possibly been cleared. Let's verify that the underlying data matches our expectations. */
910
        struct stat unmapped_st;
×
911
        if (fstat(mount_fd, &unmapped_st) < 0)
×
912
                return log_debug_errno(errno, "Failed to stat unmapped inode: %m");
×
913

914
        r = stat_verify_directory(&unmapped_st);
×
915
        if (r < 0)
×
916
                return r;
917

918
        /* For now, let's simply refuse things if dropping the idmapping changed anything. For now that
919
         * should be good enough, because the primary usecase for this (homed) will mount the foreign UID
920
         * range 1:1. */
921
        if (unmapped_st.st_uid != current_owner_uid)
×
922
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Owner UID of mount after clearing ID mapping not the same anymore, refusing.");
×
923

924
        if (p.read_only > 0 && mount_setattr(
×
925
                            mount_fd, "", AT_EMPTY_PATH,
926
                            &(struct mount_attr) {
×
927
                                    .attr_set = MOUNT_ATTR_RDONLY,
928
                            }, MOUNT_ATTR_SIZE_VER0) < 0)
929
                return log_debug_errno(errno, "Failed to enable read-only mode: %m");
×
930

931
        if (p.mode != MOUNT_MAP_IDENTITY) {
×
932
                uid_t start;
×
933

934
                if (userns_fd >= 0) {
×
935
                        _cleanup_(uid_range_freep) UIDRange *uid_range_outside = NULL, *uid_range_inside = NULL, *gid_range_outside = NULL, *gid_range_inside = NULL;
×
936
                        r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &uid_range_outside);
×
937
                        if (r < 0)
×
938
                                return log_debug_errno(r, "Failed to load outside UID range of provided userns: %m");
×
939
                        r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_INSIDE, &uid_range_inside);
×
940
                        if (r < 0)
×
941
                                return log_debug_errno(r, "Failed to load inside UID range of provided userns: %m");
×
942
                        r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &gid_range_outside);
×
943
                        if (r < 0)
×
944
                                return log_debug_errno(r, "Failed to load outside GID range of provided userns: %m");
×
945
                        r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_INSIDE, &gid_range_inside);
×
946
                        if (r < 0)
×
947
                                return log_debug_errno(r, "Failed to load inside GID range of provided userns: %m");
×
948

949
                        /* Be very strict for now */
950
                        if (!uid_range_equal(uid_range_outside, gid_range_outside) ||
×
951
                            !uid_range_equal(uid_range_inside, gid_range_inside) ||
×
952
                            uid_range_outside->n_entries != 1 ||
×
953
                            uid_range_outside->entries[0].nr != 0x10000 ||
×
954
                            uid_range_inside->n_entries != 1 ||
×
955
                            uid_range_inside->entries[0].start != 0 ||
×
956
                            uid_range_inside->entries[0].nr != 0x10000)
×
957
                                return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
×
958

959
                        start = uid_range_outside->entries[0].start;
×
960
                } else
961
                        start = 0;
962

963
                _cleanup_free_ char *new_uid_map = NULL;
×
964
                switch (p.mode) {
×
965
                case MOUNT_MAP_ROOT:
×
966
                        r = strextendf(&new_uid_map, UID_FMT " " UID_FMT " " UID_FMT,
×
967
                                       peer_uid, start, (uid_t) 1);
968
                        break;
969
                case MOUNT_MAP_FOREIGN:
×
970
                        r = strextendf(&new_uid_map, UID_FMT " " UID_FMT " " UID_FMT,
×
971
                                       (uid_t) FOREIGN_UID_MIN, start, (uid_t) 0x10000);
972
                        break;
973
                default:
×
974
                        assert_not_reached();
×
975
                }
976
                if (r < 0)
×
977
                        return r;
978

979
                _cleanup_close_ int idmap_userns_fd = userns_acquire(new_uid_map, new_uid_map, /* setgroups_deny= */ true);
×
980
                if (idmap_userns_fd < 0)
×
981
                        return log_debug_errno(idmap_userns_fd, "Failed to acquire user namespace for id mapping: %m");
×
982

983
                if (mount_setattr(mount_fd, "", AT_EMPTY_PATH,
×
984
                                  &(struct mount_attr) {
×
985
                                          .attr_set = MOUNT_ATTR_IDMAP,
986
                                          .userns_fd = idmap_userns_fd,
987
                                          .propagation = MS_PRIVATE,
988
                                  }, MOUNT_ATTR_SIZE_VER0) < 0)
989
                        return log_debug_errno(errno, "Failed to enable id mapping: %m");
×
990
        }
991

992
        if (userns_fd >= 0) {
×
993
                r = nsresource_add_mount(userns_fd, mount_fd);
×
994
                if (r < 0)
×
995
                        return r;
996
        }
997

998
        int fd_idx = sd_varlink_push_fd(link, mount_fd);
×
999
        if (fd_idx < 0)
×
1000
                return fd_idx;
1001

1002
        TAKE_FD(mount_fd);
×
1003

1004
        return sd_varlink_replybo(
×
1005
                        link,
1006
                        SD_JSON_BUILD_PAIR("mountFileDescriptor", SD_JSON_BUILD_INTEGER(fd_idx)));
1007
}
1008

1009
typedef struct MakeDirectoryParameters {
1010
        unsigned parent_fd_idx;
1011
        const char *name;
1012
} MakeDirectoryParameters;
1013

1014
static int vl_method_make_directory(
×
1015
                sd_varlink *link,
1016
                sd_json_variant *parameters,
1017
                sd_varlink_method_flags_t flags,
1018
                void *userdata) {
1019

1020
        static const sd_json_dispatch_field dispatch_table[] = {
×
1021
                { "parentFileDescriptor", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint,        offsetof(MakeDirectoryParameters, parent_fd_idx), SD_JSON_MANDATORY },
1022
                { "name",                 SD_JSON_VARIANT_STRING,   json_dispatch_const_filename, offsetof(MakeDirectoryParameters, name),          SD_JSON_MANDATORY },
1023
                VARLINK_DISPATCH_POLKIT_FIELD,
1024
                {}
1025
        };
1026

1027
        MakeDirectoryParameters p = {
×
1028
                .parent_fd_idx = UINT_MAX,
1029
        };
1030
        Hashmap **polkit_registry = ASSERT_PTR(userdata);
×
1031
        int r;
×
1032

1033
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
×
1034
        if (r != 0)
×
1035
                return r;
×
1036

1037
        if (p.parent_fd_idx == UINT_MAX)
×
1038
                return sd_varlink_error_invalid_parameter_name(link, "parentFileDescriptor");
×
1039

1040
        _cleanup_close_ int parent_fd = sd_varlink_peek_dup_fd(link, p.parent_fd_idx);
×
1041
        if (parent_fd < 0)
×
1042
                return log_debug_errno(parent_fd, "Failed to peek parent directory fd from client: %m");
×
1043

1044
        uid_t peer_uid;
×
1045
        r = sd_varlink_get_peer_uid(link, &peer_uid);
×
1046
        if (r < 0)
×
1047
                return log_debug_errno(r, "Failed to get client UID: %m");
×
1048

1049
        struct stat parent_stat;
×
1050
        if (fstat(parent_fd, &parent_stat) < 0)
×
1051
                return r;
1052

1053
        r = stat_verify_directory(&parent_stat);
×
1054
        if (r < 0)
×
1055
                return r;
1056

1057
        int fl = fd_verify_safe_flags_full(parent_fd, O_DIRECTORY);
×
1058
        if (fl < 0)
×
1059
                return log_debug_errno(fl, "Directory file descriptor has unsafe flags set: %m");
×
1060

1061
        _cleanup_free_ char *parent_path = NULL;
×
1062
        (void) fd_get_path(parent_fd, &parent_path);
×
1063

1064
        _cleanup_free_ char *new_path = parent_path ? path_join(parent_path, p.name) : NULL;
×
1065
        log_debug("Asked to make directory: %s", strna(new_path));
×
1066

1067
        const char *polkit_details[] = {
×
1068
                "directory", strna(new_path),
×
1069
                NULL,
1070
        };
1071

1072
        const char *polkit_action;
×
1073
        PolkitFlags polkit_flags;
×
1074
        if (parent_stat.st_uid != peer_uid) {
×
1075
                polkit_action = "io.systemd.mount-file-system.make-directory-untrusted";
1076
                polkit_flags = 0;
1077
        } else {
1078
                polkit_action = "io.systemd.mount-file-system.make-directory";
×
1079
                polkit_flags = POLKIT_DEFAULT_ALLOW;
×
1080
        }
1081

1082
        r = varlink_verify_polkit_async_full(
×
1083
                        link,
1084
                        /* bus= */ NULL,
1085
                        polkit_action,
1086
                        polkit_details,
1087
                        /* good_user= */ UID_INVALID,
1088
                        polkit_flags,
1089
                        polkit_registry);
1090
        if (r <= 0)
×
1091
                return r;
1092

1093
        _cleanup_free_ char *t = NULL;
×
1094
        r = tempfn_random(p.name, "mountfsd", &t);
×
1095
        if (r < 0)
×
1096
                return r;
1097

1098
        _cleanup_close_ int fd = open_mkdir_at(parent_fd, t, O_CLOEXEC, 0700);
×
1099
        if (fd < 0)
×
1100
                return fd;
1101

1102
        r = RET_NERRNO(fchmod(fd, 0700)); /* Set mode explicitly, as paranoia regarding umask games */
×
1103
        if (r < 0)
×
1104
                goto fail;
×
1105

1106
        r = RET_NERRNO(fchown(fd, FOREIGN_UID_BASE, FOREIGN_UID_BASE));
×
1107
        if (r < 0)
×
1108
                goto fail;
×
1109

1110
        r = rename_noreplace(parent_fd, t, parent_fd, p.name);
×
1111
        if (r < 0)
×
1112
                goto fail;
×
1113

1114
        t = mfree(t); /* temporary filename no longer exists */
×
1115

1116
        int fd_idx = sd_varlink_push_fd(link, fd);
×
1117
        if (fd_idx < 0) {
×
1118
                r = fd_idx;
×
1119
                goto fail;
×
1120
        }
1121

1122
        TAKE_FD(fd);
×
1123

1124
        return sd_varlink_replybo(
×
1125
                        link,
1126
                        SD_JSON_BUILD_PAIR("directoryFileDescriptor", SD_JSON_BUILD_INTEGER(fd_idx)));
1127

1128
fail:
×
1129
        (void) unlinkat(parent_fd, t ?: p.name, AT_REMOVEDIR);
×
1130
        return r;
×
1131
}
1132

1133
static int process_connection(sd_varlink_server *server, int _fd) {
×
1134
        _cleanup_close_ int fd = TAKE_FD(_fd); /* always take possession */
×
1135
        _cleanup_(sd_varlink_close_unrefp) sd_varlink *vl = NULL;
×
1136
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
×
1137
        int r;
×
1138

1139
        r = sd_event_new(&event);
×
1140
        if (r < 0)
×
1141
                return r;
1142

1143
        r = sd_varlink_server_attach_event(server, event, 0);
×
1144
        if (r < 0)
×
1145
                return log_error_errno(r, "Failed to attach Varlink server to event loop: %m");
×
1146

1147
        r = sd_varlink_server_add_connection(server, fd, &vl);
×
1148
        if (r < 0)
×
1149
                return log_error_errno(r, "Failed to add connection: %m");
×
1150

1151
        TAKE_FD(fd);
×
1152
        vl = sd_varlink_ref(vl);
×
1153

1154
        r = sd_event_loop(event);
×
1155
        if (r < 0)
×
1156
                return log_error_errno(r, "Failed to run event loop: %m");
×
1157

1158
        r = sd_varlink_server_detach_event(server);
×
1159
        if (r < 0)
×
1160
                return log_error_errno(r, "Failed to detach Varlink server from event loop: %m");
×
1161

1162
        return 0;
1163
}
1164

1165
static int run(int argc, char *argv[]) {
×
1166
        usec_t start_time, listen_idle_usec, last_busy_usec = USEC_INFINITY;
×
1167
        _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *server = NULL;
×
1168
        _cleanup_hashmap_free_ Hashmap *polkit_registry = NULL;
×
1169
        _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
×
1170
        unsigned n_iterations = 0;
×
1171
        int m, listen_fd, r;
×
1172

1173
        log_setup();
×
1174

1175
        m = sd_listen_fds(false);
×
1176
        if (m < 0)
×
1177
                return log_error_errno(m, "Failed to determine number of listening fds: %m");
×
1178
        if (m == 0)
×
1179
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No socket to listen on received.");
×
1180
        if (m > 1)
×
1181
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Worker can only listen on a single socket at a time.");
×
1182

1183
        listen_fd = SD_LISTEN_FDS_START;
×
1184

1185
        r = fd_nonblock(listen_fd, false);
×
1186
        if (r < 0)
×
1187
                return log_error_errno(r, "Failed to turn off non-blocking mode for listening socket: %m");
×
1188

1189
        r = varlink_server_new(&server,
×
1190
                               SD_VARLINK_SERVER_INHERIT_USERDATA|
1191
                               SD_VARLINK_SERVER_ALLOW_FD_PASSING_INPUT|SD_VARLINK_SERVER_ALLOW_FD_PASSING_OUTPUT,
1192
                               &polkit_registry);
1193
        if (r < 0)
×
1194
                return log_error_errno(r, "Failed to allocate server: %m");
×
1195

1196
        r = sd_varlink_server_add_interface(server, &vl_interface_io_systemd_MountFileSystem);
×
1197
        if (r < 0)
×
1198
                return log_error_errno(r, "Failed to add MountFileSystem interface to varlink server: %m");
×
1199

1200
        r = sd_varlink_server_bind_method_many(
×
1201
                        server,
1202
                        "io.systemd.MountFileSystem.MountImage",     vl_method_mount_image,
1203
                        "io.systemd.MountFileSystem.MountDirectory", vl_method_mount_directory,
1204
                        "io.systemd.MountFileSystem.MakeDirectory",  vl_method_make_directory);
1205
        if (r < 0)
×
1206
                return log_error_errno(r, "Failed to bind methods: %m");
×
1207

1208
        r = sd_varlink_server_set_exit_on_idle(server, true);
×
1209
        if (r < 0)
×
1210
                return log_error_errno(r, "Failed to enable exit-on-idle mode: %m");
×
1211

1212
        r = getenv_bool("MOUNTFS_FIXED_WORKER");
×
1213
        if (r < 0)
×
1214
                return log_error_errno(r, "Failed to parse MOUNTFSD_FIXED_WORKER: %m");
×
1215
        listen_idle_usec = r ? USEC_INFINITY : LISTEN_IDLE_USEC;
×
1216

1217
        r = pidref_set_parent(&parent);
×
1218
        if (r < 0)
×
1219
                return log_error_errno(r, "Failed to acquire pidfd of parent process: %m");
×
1220

1221
        start_time = now(CLOCK_MONOTONIC);
×
1222

1223
        for (;;) {
×
1224
                _cleanup_close_ int fd = -EBADF;
×
1225
                usec_t n;
×
1226

1227
                /* Exit the worker in regular intervals, to flush out all memory use */
1228
                if (n_iterations++ > ITERATIONS_MAX) {
×
1229
                        log_debug("Exiting worker, processed %u iterations, that's enough.", n_iterations);
×
1230
                        break;
1231
                }
1232

1233
                n = now(CLOCK_MONOTONIC);
×
1234
                if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) {
×
1235
                        log_debug("Exiting worker, ran for %s, that's enough.",
×
1236
                                  FORMAT_TIMESPAN(usec_sub_unsigned(n, start_time), 0));
1237
                        break;
×
1238
                }
1239

1240
                if (last_busy_usec == USEC_INFINITY)
×
1241
                        last_busy_usec = n;
1242
                else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) {
×
1243
                        log_debug("Exiting worker, been idle for %s.",
×
1244
                                  FORMAT_TIMESPAN(usec_sub_unsigned(n, last_busy_usec), 0));
1245
                        break;
×
1246
                }
1247

1248
                (void) rename_process("systemd-mountwork: waiting...");
×
1249
                fd = RET_NERRNO(accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC));
×
1250
                (void) rename_process("systemd-mountwork: processing...");
×
1251

1252
                if (fd == -EAGAIN)
×
1253
                        continue; /* The listening socket has SO_RECVTIMEO set, hence a timeout is expected
×
1254
                                   * after a while, let's check if it's time to exit though. */
1255
                if (fd == -EINTR)
×
1256
                        continue; /* Might be that somebody attached via strace, let's just continue in that
×
1257
                                   * case */
1258
                if (fd < 0)
×
1259
                        return log_error_errno(fd, "Failed to accept() from listening socket: %m");
×
1260

1261
                if (now(CLOCK_MONOTONIC) <= usec_add(n, PRESSURE_SLEEP_TIME_USEC)) {
×
1262
                        /* We only slept a very short time? If so, let's see if there are more sockets
1263
                         * pending, and if so, let's ask our parent for more workers */
1264

1265
                        r = fd_wait_for_event(listen_fd, POLLIN, 0);
×
1266
                        if (r < 0)
×
1267
                                return log_error_errno(r, "Failed to test for POLLIN on listening socket: %m");
×
1268

1269
                        if (FLAGS_SET(r, POLLIN)) {
×
1270
                                r = pidref_kill(&parent, SIGUSR2);
×
1271
                                if (r == -ESRCH)
×
1272
                                        return log_error_errno(r, "Parent already died?");
×
1273
                                if (r < 0)
×
1274
                                        return log_error_errno(r, "Failed to send SIGUSR2 signal to parent: %m");
×
1275
                        }
1276
                }
1277

1278
                (void) process_connection(server, TAKE_FD(fd));
×
1279
                last_busy_usec = USEC_INFINITY;
×
1280
        }
1281

1282
        return 0;
1283
}
1284

1285
DEFINE_MAIN_FUNCTION(run);
×
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