Debian Codegraph @

src/shared/dissect-image.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fnmatch.h>
4 #include <linux/loop.h>
5 #include <sys/file.h>
6 #include <sys/mount.h>
7 #include <unistd.h>
8
9 #include "sd-device.h"
10 #include "sd-id128.h"
11 #include "sd-json.h"
12 #include "sd-varlink.h"
13
14 #include "architecture.h"
15 #include "ask-password-api.h"
16 #include "blkid-util.h"
17 #include "blockdev-util.h"
18 #include "btrfs-util.h"
19 #include "chase.h"
20 #include "conf-files.h"
21 #include "constants.h"
22 #include "copy.h"
23 #include "crypto-util.h"
24 #include "cryptsetup-util.h"
25 #include "device-private.h"
26 #include "devnum-util.h"
27 #include "dissect-image.h"
28 #include "dm-util.h"
29 #include "env-file.h"
30 #include "env-util.h"
31 #include "errno-util.h"
32 #include "extension-util.h"
33 #include "extract-word.h"
34 #include "fd-util.h"
35 #include "fileio.h"
36 #include "format-util.h"
37 #include "fsck-util.h"
38 #include "fstab-util.h"
39 #include "gpt.h"
40 #include "hash-funcs.h"
41 #include "hexdecoct.h"
42 #include "hostname-setup.h"
43 #include "image-policy.h"
44 #include "import-util.h"
45 #include "io-util.h"
46 #include "iovec-util.h"
47 #include "json-util.h"
48 #include "libmount-util.h"
49 #include "loop-util.h"
50 #include "mkdir.h"
51 #include "mount-util.h"
52 #include "mountpoint-util.h"
53 #include "namespace-util.h"
54 #include "nulstr-util.h"
55 #include "os-util.h"
56 #include "path-util.h"
57 #include "pcrextend-util.h"
58 #include "pidref.h"
59 #include "proc-cmdline.h"
60 #include "process-util.h"
61 #include "resize-fs.h"
62 #include "rm-rf.h"
63 #include "runtime-scope.h"
64 #include "siphash24.h"
65 #include "stat-util.h"
66 #include "stdio-util.h"
67 #include "string-util.h"
68 #include "strv.h"
69 #include "time-util.h"
70 #include "udev-util.h"
71 #include "user-util.h"
72 #include "varlink-util.h"
73 #include "xattr-util.h"
74
75 /* how many times to wait for the device nodes to appear */
76 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
77
78 static int allowed_fstypes(char ***ret_strv) {
79 _cleanup_strv_free_ char **l = NULL;
80 const char *e;
81
82 assert(ret_strv);
83
84 e = secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
85 if (e)
86 l = strv_split(e, ":");
87 else
88 l = strv_new("btrfs",
89 "erofs",
90 "ext4",
91 "f2fs",
92 "squashfs",
93 "vfat",
94 "xfs");
95 if (!l)
96 return -ENOMEM;
97
98 *ret_strv = TAKE_PTR(l);
99 return 0;
100 }
101
102 int dissect_fstype_ok(const char *fstype) {
103 _cleanup_strv_free_ char **l = NULL;
104 int r;
105
106 /* When we automatically mount file systems, be a bit conservative by default what we are willing to
107 * mount, just as an extra safety net to not mount with badly maintained legacy file system
108 * drivers. */
109
110 r = allowed_fstypes(&l);
111 if (r < 0)
112 return r;
113
114 if (strv_contains(l, fstype))
115 return true;
116
117 log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype);
118 return false;
119 }
120
121 #if HAVE_BLKID
122 static const char *getenv_fstype(PartitionDesignator d) {
123
124 if (d < 0 ||
125 partition_designator_is_verity(d) ||
126 d == PARTITION_SWAP)
127 return NULL;
128
129 char *v = strjoina("SYSTEMD_DISSECT_FSTYPE_", partition_designator_to_string(d));
130 return secure_getenv(ascii_strupper(v));
131 }
132 #endif
133
134 int probe_sector_size(int fd, uint32_t *ret) {
135
136 assert(fd >= 0);
137 assert(ret);
138
139 ssize_t ssz = gpt_probe(fd, /* ret_header= */ NULL, /* ret_entries= */ NULL, /* ret_n_entries= */ NULL, /* ret_entry_size= */ NULL);
140 if (ssz == -ENOTUNIQ)
141 return log_debug_errno(ssz,
142 "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
143 if (ssz < 0)
144 return ssz;
145 if (ssz == 0) {
146 log_debug("Couldn't find any partition table to derive sector size of.");
147 *ret = 512; /* pick the traditional default */
148 return 0; /* indicate we didn't find it */
149 }
150
151 log_debug("Determined sector size %" PRIu32 " based on discovered partition table.", (uint32_t) ssz);
152 *ret = ssz;
153 return 1; /* indicate we *did* find it */
154 }
155
156 int probe_sector_size_prefer_ioctl(int fd, uint32_t *ret) {
157 struct stat st;
158
159 assert(fd >= 0);
160 assert(ret);
161
162 /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
163 * configured sector size rather than probing by contents */
164
165 if (fstat(fd, &st) < 0)
166 return -errno;
167
168 if (S_ISBLK(st.st_mode)) {
169 int r;
170
171 r = blockdev_get_sector_size(fd, ret);
172 if (r < 0)
173 return r;
174
175 return 1; /* indicate we *did* find it, like probe_sector_size() does */
176 }
177
178 return probe_sector_size(fd, ret);
179 }
180
181 #if HAVE_BLKID
182 static int probe_blkid_filter(blkid_probe p) {
183 _cleanup_strv_free_ char **fstypes = NULL;
184 int r;
185
186 assert(p);
187
188 r = allowed_fstypes(&fstypes);
189 if (r < 0)
190 return r;
191
192 /* allowed_fstypes() returns the list of filesystem types that we are willing to mount. For the
193 * blkid probe filter we additionally need to be able to detect crypto_LUKS (so that we can set up
194 * LUKS decryption for encrypted partitions) and swap (so that we can identify swap partitions). */
195 r = strv_extend_many(&fstypes, "crypto_LUKS", "swap");
196 if (r < 0)
197 return r;
198
199 errno = 0;
200 r = sym_blkid_probe_filter_superblocks_type(p, BLKID_FLTR_ONLYIN, fstypes);
201 if (r != 0)
202 return errno_or_else(EINVAL);
203
204 /* Note: don't call blkid_probe_filter_superblocks_usage() here. Both filter functions share the
205 * same bitmap internally, and each call resets it before applying its own filter — so a subsequent
206 * usage filter would wipe the type filter we just set. The ONLYIN type filter above already
207 * excludes everything not in the allowed list, including RAID superblocks, so a separate usage
208 * filter is redundant anyway. */
209
210 return 0;
211 }
212 #endif
213
214 int probe_filesystem_full(
215 int fd,
216 const char *path,
217 uint64_t offset,
218 uint64_t size,
219 bool restrict_fstypes,
220 char **ret_fstype) {
221
222 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
223 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
224 * different error otherwise. */
225
226 #if HAVE_BLKID
227 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
228 _cleanup_free_ char *path_by_fd = NULL;
229 _cleanup_close_ int fd_close = -EBADF;
230 const char *fstype;
231 int r;
232
233 assert(fd >= 0 || path);
234 assert(ret_fstype);
235
236 r = dlopen_libblkid(LOG_DEBUG);
237 if (r < 0)
238 return r;
239
240 if (fd < 0) {
241 fd_close = open(path, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
242 if (fd_close < 0)
243 return -errno;
244
245 fd = fd_close;
246 }
247
248 if (!path) {
249 r = fd_get_path(fd, &path_by_fd);
250 if (r < 0)
251 return r;
252
253 path = path_by_fd;
254 }
255
256 if (size == 0) /* empty size? nothing found! */
257 goto not_found;
258
259 b = sym_blkid_new_probe();
260 if (!b)
261 return -ENOMEM;
262
263 if (restrict_fstypes) {
264 r = probe_blkid_filter(b);
265 if (r < 0)
266 return r;
267 }
268
269 /* The Linux kernel maintains separate block device caches for main ("whole") and partition block
270 * devices, which means making a change to one might not be reflected immediately when reading via
271 * the other. That's massively confusing when mixing accesses to such devices. Let's address this in
272 * a limited way: when probing a file system that is not at the beginning of the block device we
273 * apparently probe a partition via the main block device, and in that case let's first flush the
274 * main block device cache, so that we get the data that the per-partition block device last
275 * sync'ed on.
276 *
277 * This only works under the assumption that any tools that write to the partition block devices
278 * issue an syncfs()/fsync() on the device after making changes. Typically file system formatting
279 * tools that write a superblock onto a partition block device do that, however. */
280 if (offset != 0)
281 if (ioctl(fd, BLKFLSBUF, 0) < 0)
282 log_debug_errno(errno, "Failed to flush block device cache, ignoring: %m");
283
284 errno = 0;
285 r = sym_blkid_probe_set_device(
286 b,
287 fd,
288 offset,
289 size == UINT64_MAX ? 0 : size); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
290 if (r != 0)
291 return errno_or_else(ENOMEM);
292
293 sym_blkid_probe_enable_superblocks(b, 1);
294 sym_blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
295
296 errno = 0;
297 r = sym_blkid_do_safeprobe(b);
298 if (r == _BLKID_SAFEPROBE_NOT_FOUND)
299 goto not_found;
300 if (r == _BLKID_SAFEPROBE_AMBIGUOUS)
301 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
302 "Results ambiguous for partition %s", path);
303 if (r == _BLKID_SAFEPROBE_ERROR)
304 return log_debug_errno(errno_or_else(EIO), "Failed to probe partition %s: %m", path);
305
306 assert(r == _BLKID_SAFEPROBE_FOUND);
307
308 (void) sym_blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
309 if (fstype) {
310 log_debug("Probed fstype '%s' on partition %s.", fstype, path);
311 return strdup_to_full(ret_fstype, fstype);
312 }
313
314 not_found:
315 log_debug("No type detected on partition %s", path);
316 *ret_fstype = NULL;
317 return 0;
318 #else
319 return -EOPNOTSUPP;
320 #endif
321 }
322
323 #if HAVE_BLKID
324 static int image_policy_may_use(
325 const ImagePolicy *policy,
326 PartitionDesignator designator) {
327
328 PartitionPolicyFlags f;
329
330 /* For each partition we find in the partition table do a first check if it may exist at all given
331 * the policy, or if it shall be ignored. */
332
333 f = image_policy_get_exhaustively(policy, designator);
334 if (f < 0)
335 return f;
336
337 if ((f & _PARTITION_POLICY_USE_MASK) == PARTITION_POLICY_ABSENT)
338 /* only flag set in policy is "absent"? then this partition may not exist at all */
339 return log_debug_errno(
340 SYNTHETIC_ERRNO(ERFKILL),
341 "Partition of designator '%s' exists, but not allowed by policy, refusing.",
342 partition_designator_to_string(designator));
343 if ((f & _PARTITION_POLICY_USE_MASK & ~PARTITION_POLICY_ABSENT) == PARTITION_POLICY_UNUSED) {
344 /* only "unused" or "unused" + "absent" are set? then don't use it */
345 log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
346 partition_designator_to_string(designator));
347 return false; /* ignore! */
348 }
349
350 return true; /* use! */
351 }
352
353 static int image_policy_check_protection(
354 const ImagePolicy *policy,
355 PartitionDesignator designator,
356 PartitionPolicyFlags found_flags) {
357
358 PartitionPolicyFlags policy_flags;
359
360 /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
361
362 if (found_flags < 0)
363 return found_flags;
364
365 policy_flags = image_policy_get_exhaustively(policy, designator);
366 if (policy_flags < 0)
367 return policy_flags;
368
369 if ((found_flags & policy_flags) == 0) {
370 _cleanup_free_ char *found_flags_string = NULL, *policy_flags_string = NULL;
371
372 (void) partition_policy_flags_to_string(found_flags, /* simplify= */ true, &found_flags_string);
373 (void) partition_policy_flags_to_string(policy_flags, /* simplify= */ true, &policy_flags_string);
374
375 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
376 partition_designator_to_string(designator),
377 strnull(found_flags_string), strnull(policy_flags_string));
378 }
379
380 return 0;
381 }
382
383 /* internal LUKS2 header defines */
384 #define LUKS2_FIXED_HDR_SIZE UINT64_C(0x1000)
385 #define LUKS2_MAGIC "LUKS\xba\xbe"
386
387 /* Matches the beginning of 'struct luks2_hdr_disk' from cryptsetup */
388 struct luks_header_incomplete {
389 char luks_magic[sizeof(LUKS2_MAGIC) - 1];
390 be16_t version;
391 be64_t hdr_len;
392 };
393
394 /* 'integrity' information from LUKS JSON header. Currently, only 'type' is extracted/checked. */
395 struct luks_integrity_data {
396 char *type;
397 };
398
399 static int integrity_information(const char *name, sd_json_variant *v, sd_json_dispatch_flags_t flags, void *userdata) {
400 static const sd_json_dispatch_field table[] = {
401 { "type", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(struct luks_integrity_data, type), SD_JSON_MANDATORY },
402 {}
403 };
404
405 return sd_json_dispatch(v, table, flags, userdata);
406 }
407
408 /* cryptsetup needs a loop device to work with a partition which has offset/size but
409 * dissect may be running unprivileged. Implement a minimal custom LUKS header parser
410 * checking integrity protection information. */
411 static int partition_is_luks2_integrity(int part_fd, uint64_t offset, uint64_t size) {
412 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
413 _cleanup_free_ char *json = NULL;
414 sd_json_variant *w;
415 const char *key;
416 struct luks_header_incomplete header;
417 ssize_t sz, json_len;
418 int r;
419
420 assert(part_fd >= 0);
421
422 if (size < LUKS2_FIXED_HDR_SIZE) {
423 log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Partition is too small to contain a LUKS header.");
424 return 0;
425 }
426
427 sz = pread(part_fd, &header, sizeof(header), offset);
428 if (sz < 0)
429 return log_error_errno(errno, "Failed to read LUKS header.");
430 if (sz != sizeof(header))
431 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read LUKS header.");
432
433 if (memcmp(header.luks_magic, LUKS2_MAGIC, sizeof(header.luks_magic)) != 0) {
434 log_debug("Partition does not have a LUKS magic header, assuming no integrity.");
435 return 0;
436 }
437
438 if (be16toh(header.version) != 2) {
439 log_debug("Partition is LUKS v%" PRIu16 ", not LUKS2, assuming no integrity.", be16toh(header.version));
440 return 0;
441 }
442
443 if (be64toh(header.hdr_len) > size)
444 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS header length exceeds partition size.");
445
446 if (be64toh(header.hdr_len) <= LUKS2_FIXED_HDR_SIZE || offset > UINT64_MAX - be64toh(header.hdr_len))
447 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid LUKS header length: %" PRIu64 ".", be64toh(header.hdr_len));
448
449 if (be64toh(header.hdr_len) - LUKS2_FIXED_HDR_SIZE > 16U * 1024U * 1024U)
450 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS header JSON area too large: %" PRIu64 ".", be64toh(header.hdr_len));
451
452 json_len = be64toh(header.hdr_len) - LUKS2_FIXED_HDR_SIZE;
453 json = malloc(json_len + 1);
454 if (!json)
455 return -ENOMEM;
456
457 sz = pread(part_fd, json, json_len, offset + LUKS2_FIXED_HDR_SIZE);
458 if (sz < 0)
459 return log_error_errno(errno, "Failed to read LUKS JSON header.");
460 if (sz != json_len)
461 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read LUKS JSON header.");
462 json[sz] = '\0';
463
464 r = sd_json_parse(json, /* flags= */ 0, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
465 if (r < 0)
466 return log_error_errno(r, "Failed to parse LUKS JSON header.");
467
468 v = sd_json_variant_by_key(v, "segments");
469 if (!v || !sd_json_variant_is_object(v)) {
470 log_debug("LUKS JSON header lacks 'segments' information, assuming no integrity.");
471 return 0;
472 }
473
474 /* Verify that all segments have integrity protection */
475 JSON_VARIANT_OBJECT_FOREACH(key, w, v) {
476 struct luks_integrity_data data = {};
477
478 static const sd_json_dispatch_field dispatch_segment[] = {
479 { "integrity", SD_JSON_VARIANT_OBJECT, integrity_information, 0, SD_JSON_MANDATORY },
480 {}
481 };
482
483 r = sd_json_dispatch(w, dispatch_segment, SD_JSON_ALLOW_EXTENSIONS, &data);
484 if (r < 0) {
485 log_debug("Failed to get integrity information from LUKS JSON for segment %s, assuming no integrity.", key);
486 return 0;
487 }
488
489 /* We don't require a particular integrity algorithm, everything but 'none' (which shouldn't
490 * be there in the first place but is theoretically possible) works. */
491 if (streq(data.type, "none"))
492 return 0;
493 }
494
495 return 1;
496 }
497
498 static int image_policy_check_partition_flags(
499 const ImagePolicy *policy,
500 PartitionDesignator designator,
501 uint64_t gpt_flags) {
502
503 PartitionPolicyFlags policy_flags;
504 bool b;
505
506 /* Checks if the partition flags in the policy match reality */
507
508 policy_flags = image_policy_get_exhaustively(policy, designator);
509 if (policy_flags < 0)
510 return policy_flags;
511
512 b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_READ_ONLY);
513 if ((policy_flags & _PARTITION_POLICY_READ_ONLY_MASK) == (b ? PARTITION_POLICY_READ_ONLY_OFF : PARTITION_POLICY_READ_ONLY_ON))
514 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
515 partition_designator_to_string(designator),
516 one_zero(!b), one_zero(b));
517
518 b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_GROWFS);
519 if ((policy_flags & _PARTITION_POLICY_GROWFS_MASK) == (b ? PARTITION_POLICY_GROWFS_OFF : PARTITION_POLICY_GROWFS_ON))
520 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
521 partition_designator_to_string(designator),
522 one_zero(!b), one_zero(b));
523
524 return 0;
525 }
526
527 static int dissected_image_probe_filesystems(
528 DissectedImage *m,
529 int fd,
530 const ImagePolicy *policy) {
531
532 int r;
533
534 assert(m);
535
536 /* Fill in file system types if we don't know them yet. */
537
538 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
539 DissectedPartition *p = m->partitions + i;
540 PartitionPolicyFlags found_flags;
541
542 if (!p->found)
543 continue;
544
545 if (!p->fstype) {
546 /* If we have an fd referring to the partition block device, use that. Otherwise go
547 * via the whole block device or backing regular file, and read via offset. */
548 if (p->mount_node_fd >= 0)
549 r = probe_filesystem_full(p->mount_node_fd, p->node, 0, UINT64_MAX, /* bool restrict_fstypes= */ true, &p->fstype);
550 else
551 r = probe_filesystem_full(fd, p->node, p->offset, p->size, /* bool restrict_fstypes= */ true, &p->fstype);
552 if (r < 0)
553 return r;
554 }
555
556 if (streq_ptr(p->fstype, "crypto_LUKS")) {
557 m->encrypted = true;
558
559 if (p->mount_node_fd >= 0)
560 r = partition_is_luks2_integrity(p->mount_node_fd, /* offset= */ 0, /* size= */ UINT64_MAX);
561 else
562 r = partition_is_luks2_integrity(fd, p->offset, p->size);
563 if (r < 0)
564 return r;
565
566 /* found this one, it's definitely encrypted + with or without integrity checking */
567 found_flags = PARTITION_POLICY_UNUSED|(r > 0 ? PARTITION_POLICY_ENCRYPTEDWITHINTEGRITY : PARTITION_POLICY_ENCRYPTED);
568 } else
569 /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
570 * set all other ways that indicate "present". */
571 found_flags = PARTITION_POLICY_UNUSED|PARTITION_POLICY_UNPROTECTED|PARTITION_POLICY_VERITY|PARTITION_POLICY_SIGNED;
572
573 if (p->fstype && fstype_is_ro(p->fstype))
574 p->rw = false;
575
576 if (!p->rw)
577 p->growfs = false;
578
579 /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
580 * hence we need to validate this against policy again, to see if the policy still matches
581 * with this new information. Note that image_policy_check_protection() will check for
582 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
583 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
584 * OR verity OR signed), but that's fine since the earlier policy check already checked more
585 * specific which of those three cases where OK. Keep in mind that this function here only
586 * looks at specific partitions (and thus can only deduce encryption or not) but not the
587 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
588 * checks already did the relevant checks that look at the whole partition table, and
589 * enforced policy there as needed. */
590 r = image_policy_check_protection(policy, i, found_flags);
591 if (r < 0)
592 return r;
593 }
594
595 return 0;
596 }
597
598 static void check_partition_flags(
599 const char *node,
600 unsigned long long pflags,
601 unsigned long long supported) {
602
603 assert(node);
604
605 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
606 pflags &= ~(supported |
607 SD_GPT_FLAG_REQUIRED_PARTITION |
608 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL |
609 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE);
610
611 if (pflags == 0)
612 return;
613
614 /* If there are other bits set, then log about it, to make things discoverable */
615 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
616 unsigned long long bit = 1ULL << i;
617 if (!FLAGS_SET(pflags, bit))
618 continue;
619
620 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
621 }
622 }
623 #endif
624
625 int dissected_image_name_from_path(const char *path, char **ret) {
626 int r;
627
628 assert(path);
629 assert(ret);
630
631 _cleanup_free_ char *filename = NULL;
632 r = path_extract_filename(path, &filename);
633 if (r < 0)
634 return r;
635
636 _cleanup_free_ char *name = NULL;
637 r = raw_strip_suffixes(filename, &name);
638 if (r < 0)
639 return r;
640
641 if (!image_name_is_valid(name)) {
642 log_debug("Image name %s is not valid, ignoring.", strna(name));
643 *ret = NULL;
644 return 0;
645 }
646
647 *ret = TAKE_PTR(name);
648 return 1;
649 }
650
651 #if HAVE_BLKID
652 static int dissected_image_new(const char *path, DissectedImage **ret) {
653 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
654 _cleanup_free_ char *name = NULL;
655 int r;
656
657 assert(ret);
658
659 if (path) {
660 r = dissected_image_name_from_path(path, &name);
661 if (r < 0)
662 return r;
663 }
664
665 m = new(DissectedImage, 1);
666 if (!m)
667 return -ENOMEM;
668
669 *m = (DissectedImage) {
670 .has_init_system = -1,
671 .image_name = TAKE_PTR(name),
672 };
673
674 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
675 m->partitions[i] = DISSECTED_PARTITION_NULL;
676
677 *ret = TAKE_PTR(m);
678 return 0;
679 }
680 #endif
681
682 static void dissected_partition_done(DissectedPartition *p) {
683 assert(p);
684
685 free(p->fstype);
686 free(p->node);
687 free(p->label);
688 free(p->decrypted_fstype);
689 free(p->decrypted_node);
690 free(p->mount_options);
691 safe_close(p->mount_node_fd);
692 safe_close(p->fsmount_fd);
693
694 *p = DISSECTED_PARTITION_NULL;
695 }
696
697 static int acquire_sig_for_roothash(
698 int fd,
699 uint64_t partition_offset,
700 uint64_t partition_size,
701 struct iovec *ret_root_hash,
702 struct iovec *ret_root_hash_sig) {
703
704 int r;
705
706 assert(fd >= 0);
707
708 if (partition_offset == UINT64_MAX || partition_size == UINT64_MAX)
709 return -EINVAL;
710
711 if (partition_size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
712 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG), "Verity signature partition is larger than 4M, refusing.");
713
714 _cleanup_free_ char *buf = new(char, partition_size+1);
715 if (!buf)
716 return -ENOMEM;
717
718 ssize_t n = pread(fd, buf, partition_size, partition_offset);
719 if (n < 0)
720 return -errno;
721 if ((uint64_t) n != partition_size)
722 return -EIO;
723
724 const char *e = memchr(buf, 0, partition_size);
725 if (e) {
726 /* If we found a NUL byte then the rest of the data must be NUL too */
727 if (!memeqzero(e, partition_size - (e - buf)))
728 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
729 } else
730 buf[partition_size] = 0;
731
732 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
733 r = sd_json_parse(buf, 0, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
734 if (r < 0)
735 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
736
737 sd_json_variant *rh = sd_json_variant_by_key(v, "rootHash");
738 if (!rh)
739 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
740
741 _cleanup_(iovec_done) struct iovec root_hash = {};
742 r = sd_json_variant_unhex(rh, &root_hash.iov_base, &root_hash.iov_len);
743 if (r < 0)
744 return log_debug_errno(r, "Failed to parse root hash field: %m");
745
746 sd_json_variant *sig = sd_json_variant_by_key(v, "signature");
747 if (!sig)
748 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
749
750 _cleanup_(iovec_done) struct iovec root_hash_sig = {};
751 r = sd_json_variant_unbase64(sig, &root_hash_sig.iov_base, &root_hash_sig.iov_len);
752 if (r < 0)
753 return log_debug_errno(r, "Failed to parse signature field: %m");
754
755 if (ret_root_hash)
756 *ret_root_hash = TAKE_STRUCT(root_hash);
757
758 if (ret_root_hash_sig)
759 *ret_root_hash_sig = TAKE_STRUCT(root_hash_sig);
760
761 return 0;
762 }
763
764 #if HAVE_BLKID
765 static int diskseq_should_be_used(
766 const char *whole_devname,
767 uint64_t diskseq,
768 DissectImageFlags flags) {
769
770 int r;
771
772 assert(whole_devname);
773
774 /* No diskseq. We cannot use by-diskseq symlink. */
775 if (diskseq == 0)
776 return false;
777
778 /* Do not use by-diskseq link unless DISSECT_IMAGE_DISKSEQ_DEVNODE flag is explicitly set. */
779 if (!FLAGS_SET(flags, DISSECT_IMAGE_DISKSEQ_DEVNODE))
780 return false;
781
782 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
783 r = sd_device_new_from_devname(&dev, whole_devname);
784 if (r < 0)
785 return r;
786
787 /* When ID_IGNORE_DISKSEQ udev property is set, the by-diskseq symlink will not be created. */
788 r = device_get_property_bool(dev, "ID_IGNORE_DISKSEQ");
789 if (r >= 0)
790 return !r; /* If explicitly specified, use it. */
791 if (r != -ENOENT)
792 return r;
793
794 return true;
795 }
796
797 static int make_partition_devname(
798 const char *whole_devname,
799 uint64_t diskseq,
800 int nr,
801 DissectImageFlags flags,
802 char **ret) {
803
804 _cleanup_free_ char *s = NULL;
805 int r;
806
807 assert(whole_devname);
808 assert(nr != 0); /* zero is not a valid partition nr */
809 assert(ret);
810
811 r = diskseq_should_be_used(whole_devname, diskseq, flags);
812 if (r < 0)
813 log_debug_errno(r, "Failed to determine if diskseq should be used for %s, assuming no, ignoring: %m", whole_devname);
814 if (r <= 0) {
815 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
816 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
817 * block device node name ends in a digit, then suffix a 'p', followed by the partition
818 * number. Otherwise, just suffix the partition number without any 'p'. */
819
820 if (nr < 0) { /* whole disk? */
821 s = strdup(whole_devname);
822 if (!s)
823 return -ENOMEM;
824 } else {
825 r = partition_node_of(whole_devname, nr, &s);
826 if (r < 0)
827 return r;
828 }
829 } else {
830 if (nr < 0) /* whole disk? */
831 r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64, diskseq);
832 else
833 r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64 "-part%i", diskseq, nr);
834 if (r < 0)
835 return -ENOMEM;
836 }
837
838 *ret = TAKE_PTR(s);
839 return 0;
840 }
841
842 static int open_partition(
843 const char *node,
844 bool is_partition,
845 const LoopDevice *loop) {
846
847 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
848 _cleanup_close_ int fd = -EBADF;
849 dev_t devnum;
850 int r;
851
852 assert(node);
853 assert(loop || !is_partition);
854
855 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
856 if (fd < 0)
857 return -errno;
858
859 if (!loop)
860 return TAKE_FD(fd);
861
862 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
863 r = block_device_new_from_fd(fd, is_partition ? BLOCK_DEVICE_LOOKUP_WHOLE_DISK : 0, &dev);
864 if (r < 0)
865 return r;
866
867 r = sd_device_get_devnum(dev, &devnum);
868 if (r < 0)
869 return r;
870
871 if (loop->devno != devnum)
872 return -ENXIO;
873
874 /* Also check diskseq. */
875 if (loop->diskseq != 0) {
876 uint64_t diskseq;
877
878 r = fd_get_diskseq(fd, &diskseq);
879 if (r < 0)
880 return r;
881
882 if (loop->diskseq != diskseq)
883 return -ENXIO;
884 }
885
886 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR ", diskseq=%" PRIu64 ").",
887 node, fd, DEVNUM_FORMAT_VAL(loop->devno), loop->diskseq);
888 return TAKE_FD(fd);
889 }
890
891 static int compare_arch(Architecture a, Architecture b) {
892 if (a == b)
893 return 0;
894
895 if (a == native_architecture())
896 return 1;
897
898 if (b == native_architecture())
899 return -1;
900
901 #ifdef ARCHITECTURE_SECONDARY
902 if (a == ARCHITECTURE_SECONDARY)
903 return 1;
904
905 if (b == ARCHITECTURE_SECONDARY)
906 return -1;
907 #endif
908
909 return 0;
910 }
911
912 static bool image_filter_test(const ImageFilter *filter, PartitionDesignator d, const char *label) {
913 assert(d < _PARTITION_DESIGNATOR_MAX);
914
915 if (d < 0) /* For unspecified designators we have no filter expression */
916 return true;
917
918 if (!filter || !filter->pattern[d])
919 return true;
920
921 return fnmatch(filter->pattern[d], strempty(label), FNM_NOESCAPE) == 0;
922 }
923
924 static int dissect_image_from_unpartitioned(
925 const char *devname,
926 uint64_t diskseq,
927 const sd_id128_t *uuid,
928 bool encrypted,
929 const VeritySettings *verity,
930 const MountOptions *mount_options,
931 const ImagePolicy *policy,
932 const ImageFilter *filter,
933 int *mount_node_fd, /* taken over on success */
934 char **fstype, /* taken over on success */
935 DissectedImage *m,
936 DissectImageFlags flags,
937 PartitionPolicyFlags found_flags) {
938
939 _cleanup_free_ char *n = NULL, *o = NULL;
940 const char *options = NULL;
941 int r;
942
943 assert(devname);
944 assert(m);
945 assert(fstype);
946 POINTER_MAY_BE_NULL(mount_node_fd);
947
948 if (!image_filter_test(filter, PARTITION_ROOT, /* label= */ NULL)) /* do a filter check with an empty partition label */
949 return -ECOMM;
950
951 r = image_policy_may_use(policy, PARTITION_ROOT);
952 if (r < 0)
953 return r;
954 if (r == 0) /* policy says ignore this, so we ignore it */
955 return -ENOPKG;
956
957 r = image_policy_check_protection(policy, PARTITION_ROOT, found_flags);
958 if (r < 0)
959 return r;
960
961 r = image_policy_check_partition_flags(policy, PARTITION_ROOT, 0); /* we have no gpt partition flags, hence check against all bits off */
962 if (r < 0)
963 return r;
964
965 r = make_partition_devname(devname, diskseq, /* nr= */ -1, flags, &n);
966 if (r < 0)
967 return r;
968
969 m->single_file_system = true;
970 m->encrypted = encrypted;
971
972 m->has_verity = verity && verity->data_path;
973 m->verity_ready = verity_settings_data_covers(verity, PARTITION_ROOT);
974
975 m->has_verity_sig = false; /* signature not embedded, must be specified */
976 m->verity_sig_ready = m->verity_ready && iovec_is_set(&verity->root_hash);
977
978 if (uuid)
979 m->image_uuid = *uuid;
980
981 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
982 if (options) {
983 o = strdup(options);
984 if (!o)
985 return -ENOMEM;
986 }
987
988 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
989 .found = true,
990 .rw = !m->verity_ready && !fstype_is_ro(*fstype),
991 .partno = -1,
992 .architecture = _ARCHITECTURE_INVALID,
993 .fstype = TAKE_PTR(*fstype),
994 .node = TAKE_PTR(n),
995 .mount_options = TAKE_PTR(o),
996 .mount_node_fd = mount_node_fd ? TAKE_FD(*mount_node_fd) : -EBADF,
997 .size = UINT64_MAX,
998 .fsmount_fd = -EBADF,
999 };
1000
1001 return 0;
1002 }
1003
1004 static int dissect_image(
1005 DissectedImage *m,
1006 int fd,
1007 const char *devname,
1008 const VeritySettings *verity,
1009 const MountOptions *mount_options,
1010 const ImagePolicy *policy,
1011 const ImageFilter *filter,
1012 DissectImageFlags flags) {
1013
1014 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
1015 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
1016 bool is_gpt, is_mbr, multiple_generic = false,
1017 generic_rw = false, /* initialize to appease gcc */
1018 generic_growfs = false;
1019 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
1020 _cleanup_free_ char *generic_node = NULL;
1021 sd_id128_t generic_uuid = SD_ID128_NULL;
1022 const char *pttype = NULL;
1023 blkid_partlist pl;
1024 int r, generic_nr = -1, n_partitions;
1025
1026 assert(m);
1027 assert(fd >= 0);
1028 assert(devname);
1029 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
1030 assert(!verity || iovec_is_valid(&verity->root_hash));
1031 assert(!verity || iovec_is_valid(&verity->root_hash_sig));
1032 assert(!verity || iovec_is_set(&verity->root_hash) || !iovec_is_set(&verity->root_hash_sig));
1033 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
1034 assert(m->sector_size > 0);
1035
1036 /* Probes a disk image, and returns information about what it found in *ret.
1037 *
1038 * Returns -ENOPKG if no suitable partition table or file system could be found.
1039 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
1040 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
1041 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that
1042 * Returns -ERFKILL if image doesn't match image policy
1043 * Returns -EBADR if verity data was provided externally for an image that has a GPT partition table (i.e. is not just a naked fs)
1044 * Returns -EPROTONOSUPPORT if DISSECT_IMAGE_ADD_PARTITION_DEVICES is set but the block device does not have partition logic enabled
1045 * Returns -ENOMSG if we didn't find a single usable partition (and DISSECT_IMAGE_REFUSE_EMPTY is set)
1046 * Returns -EUCLEAN if some file system had an ambiguous file system superblock signature
1047 */
1048
1049 uint64_t diskseq = m->loop ? m->loop->diskseq : 0;
1050
1051 if (verity && iovec_is_set(&verity->root_hash)) {
1052 sd_id128_t fsuuid, vuuid;
1053
1054 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
1055 * first 128-bit of the root hash. And we use the verity partition that has a UUID that match
1056 * the final 128-bit. */
1057
1058 if (verity->root_hash.iov_len < sizeof(sd_id128_t))
1059 return -EINVAL;
1060
1061 memcpy(&fsuuid, verity->root_hash.iov_base, sizeof(sd_id128_t));
1062 memcpy(&vuuid, (const uint8_t*) verity->root_hash.iov_base + verity->root_hash.iov_len - sizeof(sd_id128_t), sizeof(sd_id128_t));
1063
1064 if (sd_id128_is_null(fsuuid))
1065 return -EINVAL;
1066 if (sd_id128_is_null(vuuid))
1067 return -EINVAL;
1068
1069 /* If the verity data declares it's for the /usr partition, then search for that, in all
1070 * other cases assume it's for the root partition. */
1071 if (verity->designator == PARTITION_USR) {
1072 usr_uuid = fsuuid;
1073 usr_verity_uuid = vuuid;
1074 } else {
1075 root_uuid = fsuuid;
1076 root_verity_uuid = vuuid;
1077 }
1078 }
1079
1080 r = dlopen_libblkid(LOG_DEBUG);
1081 if (r < 0)
1082 return r;
1083
1084 b = sym_blkid_new_probe();
1085 if (!b)
1086 return -ENOMEM;
1087
1088 r = probe_blkid_filter(b);
1089 if (r < 0)
1090 return r;
1091
1092 errno = 0;
1093 r = sym_blkid_probe_set_device(b, fd, 0, 0);
1094 if (r != 0)
1095 return errno_or_else(ENOMEM);
1096
1097 errno = 0;
1098 r = sym_blkid_probe_set_sectorsize(b, m->sector_size);
1099 if (r != 0)
1100 return errno_or_else(EIO);
1101
1102 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
1103 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
1104 sym_blkid_probe_enable_superblocks(b, 1);
1105 sym_blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE|BLKID_SUBLKS_UUID);
1106 }
1107
1108 sym_blkid_probe_enable_partitions(b, 1);
1109 sym_blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
1110
1111 errno = 0;
1112 r = sym_blkid_do_safeprobe(b);
1113 if (r == _BLKID_SAFEPROBE_ERROR)
1114 return errno_or_else(EIO);
1115 if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
1116 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
1117
1118 assert(r == _BLKID_SAFEPROBE_FOUND);
1119
1120 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
1121 (flags & DISSECT_IMAGE_GENERIC_ROOT)) ||
1122 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
1123 _cleanup_free_ char *root_fstype_string = NULL;
1124 const char *usage = NULL;
1125 bool encrypted;
1126
1127 r = partition_policy_determine_fstype(policy, PARTITION_ROOT, &encrypted, &root_fstype_string);
1128 if (r < 0)
1129 return r;
1130
1131 /* If flags permit this, also allow using non-partitioned single-filesystem images */
1132
1133 (void) sym_blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
1134 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
1135 _cleanup_free_ char *t = NULL;
1136 const char *fstype = NULL;
1137 _cleanup_close_ int mount_node_fd = -EBADF;
1138 sd_id128_t uuid = SD_ID128_NULL;
1139 PartitionPolicyFlags found_flags;
1140
1141 /* OK, we have found a file system, that's our root partition then. */
1142
1143 if (!root_fstype_string) {
1144 (void) sym_blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
1145
1146 /* blkid will return FAT's serial number as UUID, hence it is quite possible that
1147 * parsing this will fail. We'll ignore the ID, since it's just too short to be
1148 * useful as true identifier. */
1149 (void) blkid_probe_lookup_value_id128(b, "UUID", &uuid);
1150 } else
1151 /* The policy fstype flags translate to the literal fstype name of each filesystem. */
1152 fstype = root_fstype_string;
1153
1154 encrypted = encrypted || streq_ptr(fstype, "crypto_LUKS");
1155
1156 if (verity_settings_data_covers(verity, PARTITION_ROOT))
1157 found_flags = iovec_is_set(&verity->root_hash_sig) ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY;
1158 else if (encrypted) {
1159 r = partition_is_luks2_integrity(fd, /* offset= */ 0, /* size= */ UINT64_MAX);
1160 if (r < 0)
1161 return r;
1162
1163 found_flags = r > 0 ? PARTITION_POLICY_ENCRYPTEDWITHINTEGRITY : PARTITION_POLICY_ENCRYPTED;
1164 } else
1165 found_flags = PARTITION_POLICY_UNPROTECTED;
1166
1167 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1168 mount_node_fd = open_partition(devname, /* is_partition= */ false, m->loop);
1169 if (mount_node_fd < 0)
1170 return mount_node_fd;
1171 }
1172
1173 if (fstype) {
1174 t = strdup(fstype);
1175 if (!t)
1176 return -ENOMEM;
1177 }
1178
1179 return dissect_image_from_unpartitioned(
1180 devname,
1181 diskseq,
1182 &uuid,
1183 encrypted,
1184 verity,
1185 mount_options,
1186 policy,
1187 filter,
1188 &mount_node_fd,
1189 &t,
1190 m,
1191 flags,
1192 found_flags);
1193 }
1194 }
1195
1196 (void) sym_blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
1197 if (!pttype)
1198 return -ENOPKG;
1199
1200 is_gpt = streq_ptr(pttype, "gpt");
1201 is_mbr = streq_ptr(pttype, "dos");
1202
1203 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
1204 return -ENOPKG;
1205
1206 /* We support external verity data partitions only if the image has no partition table */
1207 if (verity && verity->data_path)
1208 return -EBADR;
1209
1210 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
1211 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
1212 * do partition scanning. */
1213 r = blockdev_partscan_enabled_fd(fd);
1214 if (r < 0)
1215 return r;
1216 if (r == 0)
1217 return -EPROTONOSUPPORT;
1218 }
1219
1220 (void) blkid_probe_lookup_value_id128(b, "PTUUID", &m->image_uuid);
1221
1222 errno = 0;
1223 pl = sym_blkid_probe_get_partitions(b);
1224 if (!pl)
1225 return errno_or_else(ENOMEM);
1226
1227 errno = 0;
1228 n_partitions = sym_blkid_partlist_numof_partitions(pl);
1229 if (n_partitions < 0)
1230 return errno_or_else(EIO);
1231
1232 for (int i = 0; i < n_partitions; i++) {
1233 _cleanup_free_ char *node = NULL;
1234 unsigned long long pflags;
1235 blkid_loff_t start, size;
1236 blkid_partition pp;
1237 int nr;
1238
1239 errno = 0;
1240 pp = sym_blkid_partlist_get_partition(pl, i);
1241 if (!pp)
1242 return errno_or_else(EIO);
1243
1244 pflags = sym_blkid_partition_get_flags(pp);
1245
1246 errno = 0;
1247 nr = sym_blkid_partition_get_partno(pp);
1248 if (nr < 0)
1249 return errno_or_else(EIO);
1250
1251 errno = 0;
1252 start = sym_blkid_partition_get_start(pp);
1253 if (start < 0)
1254 return errno_or_else(EIO);
1255
1256 assert((uint64_t) start < UINT64_MAX/512);
1257
1258 errno = 0;
1259 size = sym_blkid_partition_get_size(pp);
1260 if (size < 0)
1261 return errno_or_else(EIO);
1262
1263 assert((uint64_t) size < UINT64_MAX/512);
1264
1265 /* While probing we need the non-diskseq device node name to access the thing, hence mask off
1266 * DISSECT_IMAGE_DISKSEQ_DEVNODE. */
1267 r = make_partition_devname(devname, diskseq, nr, flags & ~DISSECT_IMAGE_DISKSEQ_DEVNODE, &node);
1268 if (r < 0)
1269 return r;
1270
1271 /* So here's the thing: after the main ("whole") block device popped up it might take a while
1272 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
1273 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
1274 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
1275 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
1276 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
1277 * also good as the outcome is the same: the partition block device exists, and we can use
1278 * it.
1279 *
1280 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
1281 * partition already existent. */
1282
1283 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
1284 r = block_device_add_partition(fd, nr, (uint64_t) start * 512, (uint64_t) size * 512);
1285 if (r < 0) {
1286 if (r != -EBUSY)
1287 return log_debug_errno(r, "BLKPG_ADD_PARTITION failed: %m");
1288
1289 log_debug_errno(r, "Kernel was quicker than us in adding partition %i.", nr);
1290 } else
1291 log_debug("We were quicker than kernel in adding partition %i.", nr);
1292 }
1293
1294 if (is_gpt) {
1295 const char *label;
1296 sd_id128_t type_id, id;
1297 GptPartitionType type;
1298 bool rw = true, growfs = false;
1299
1300 r = blkid_partition_get_uuid_id128(pp, &id);
1301 if (r < 0) {
1302 log_debug_errno(r, "Failed to read partition UUID, ignoring: %m");
1303 continue;
1304 }
1305
1306 r = blkid_partition_get_type_id128(pp, &type_id);
1307 if (r < 0) {
1308 log_debug_errno(r, "Failed to read partition type UUID, ignoring: %m");
1309 continue;
1310 }
1311
1312 type = gpt_partition_type_from_uuid(type_id);
1313
1314 label = sym_blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
1315
1316 /* systemd-sysupdate expects empty partitions to be marked with an "_empty" label, hence ignore them here. */
1317 if (streq_ptr(label, "_empty"))
1318 continue;
1319
1320 if (!image_filter_test(filter, type.designator, label))
1321 continue;
1322
1323 log_debug("Dissecting %s partition with label %s and UUID %s.",
1324 strna(partition_designator_to_string(type.designator)), strna(label), SD_ID128_TO_UUID_STRING(id));
1325
1326 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
1327 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
1328 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
1329 * Partitions"). */
1330 if (FLAGS_SET(pflags, SD_GPT_FLAG_NO_AUTO) && type.designator != PARTITION_ESP) {
1331 log_debug("Partition has 'no auto' flag set, ignoring.");
1332 continue;
1333 }
1334
1335 if (!verity && partition_designator_is_verity(type.designator)) {
1336 log_debug("Partition is a verity hash or verity signature partition but no verity was requested, ignoring.");
1337 continue;
1338 }
1339
1340 PartitionDesignator vd = partition_verity_to_data(type.designator);
1341 if (verity && verity->designator >= 0 && vd >= 0 && vd != verity->designator) {
1342 log_debug("Partition is a %s partition but verity was only requested for the %s partition, ignoring.",
1343 partition_designator_to_string(type.designator),
1344 partition_designator_to_string(verity->designator));
1345 continue;
1346 }
1347
1348 const char *fstype = getenv_fstype(type.designator);
1349
1350 if (IN_SET(type.designator,
1351 PARTITION_HOME,
1352 PARTITION_SRV,
1353 PARTITION_XBOOTLDR,
1354 PARTITION_TMP)) {
1355
1356 check_partition_flags(node, pflags,
1357 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1358
1359 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1360 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1361
1362 /* XBOOTLDR cannot be integrity protected (since firmware needs to access
1363 * it), hence be restrictive with the fs choice when dissecting. */
1364 if (type.designator == PARTITION_XBOOTLDR && !fstype)
1365 fstype = "vfat";
1366
1367 } else if (type.designator == PARTITION_ESP) {
1368
1369 if (FLAGS_SET(pflags, SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL)) {
1370 log_debug("ESP Partition has 'no block io' flag set, ignoring.");
1371 continue;
1372 }
1373
1374 /* Effectively the ESP has to be VFAT, let's enforce this */
1375 if (!fstype)
1376 fstype = "vfat";
1377
1378 } else if (IN_SET(type.designator, PARTITION_ROOT, PARTITION_USR)) {
1379 sd_id128_t expected_uuid = type.designator == PARTITION_ROOT ? root_uuid : usr_uuid;
1380
1381 check_partition_flags(node, pflags,
1382 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1383
1384 if (!sd_id128_is_null(expected_uuid) && !sd_id128_equal(expected_uuid, id)) {
1385 log_debug("Partition UUID '%s' does not match expected UUID '%s' derived from %s verity hash, ignoring.",
1386 SD_ID128_TO_UUID_STRING(id),
1387 SD_ID128_TO_UUID_STRING(expected_uuid),
1388 partition_designator_to_string(type.designator));
1389 continue;
1390 }
1391
1392 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1393 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1394
1395 } else if (IN_SET(type.designator, PARTITION_ROOT_VERITY, PARTITION_USR_VERITY)) {
1396 sd_id128_t expected_uuid = type.designator == PARTITION_ROOT_VERITY ? root_verity_uuid : usr_verity_uuid;
1397
1398 check_partition_flags(node, pflags,
1399 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1400
1401 m->has_verity = true;
1402
1403 if (!sd_id128_is_null(expected_uuid) && !sd_id128_equal(expected_uuid, id)) {
1404 log_debug("Partition UUID '%s' does not match expected UUID '%s' derived from %s verity hash, ignoring.",
1405 SD_ID128_TO_UUID_STRING(id),
1406 SD_ID128_TO_UUID_STRING(expected_uuid),
1407 partition_designator_to_string(partition_verity_to_data(type.designator)));
1408 continue;
1409 }
1410
1411 fstype = "DM_verity_hash";
1412 rw = false;
1413
1414 } else if (IN_SET(type.designator, PARTITION_ROOT_VERITY_SIG, PARTITION_USR_VERITY_SIG)) {
1415 if (verity && iovec_is_set(&verity->root_hash)) {
1416 _cleanup_(iovec_done) struct iovec root_hash = {};
1417
1418 r = acquire_sig_for_roothash(
1419 fd,
1420 (uint64_t) start * 512,
1421 (uint64_t) size * 512,
1422 &root_hash,
1423 /* ret_root_hash_sig= */ NULL);
1424 if (r < 0)
1425 return r;
1426 if (!iovec_equal(&verity->root_hash, &root_hash)) {
1427 if (DEBUG_LOGGING) {
1428 _cleanup_free_ char *found = NULL, *expected = NULL;
1429
1430 found = hexmem(root_hash.iov_base, root_hash.iov_len);
1431 expected = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
1432
1433 log_debug("Verity root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(found), strna(expected));
1434 }
1435 continue;
1436 }
1437 }
1438
1439 check_partition_flags(node, pflags,
1440 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1441
1442 m->has_verity_sig = true;
1443 fstype = "verity_hash_signature";
1444 rw = false;
1445
1446 } else if (type.designator == PARTITION_SWAP) {
1447
1448 check_partition_flags(node, pflags, SD_GPT_FLAG_NO_AUTO);
1449
1450 /* Note: we don't set fstype = "swap" here, because we still need to probe if
1451 * it might be encrypted (i.e. fstype "crypt_LUKS") or unencrypted
1452 * (i.e. fstype "swap"), and the only way to figure that out is via fstype
1453 * probing. */
1454
1455 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
1456 } else if (sd_id128_equal(type.uuid, SD_GPT_LINUX_GENERIC)) {
1457
1458 if (!image_filter_test(filter, PARTITION_ROOT, label))
1459 continue;
1460
1461 check_partition_flags(node, pflags,
1462 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1463
1464 if (generic_node)
1465 multiple_generic = true;
1466 else {
1467 generic_nr = nr;
1468 generic_rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1469 generic_growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1470 generic_uuid = id;
1471 generic_node = TAKE_PTR(node);
1472 }
1473
1474 } else if (type.designator == PARTITION_VAR) {
1475
1476 check_partition_flags(node, pflags,
1477 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1478
1479 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
1480 sd_id128_t var_uuid;
1481
1482 /* For /var we insist that the uuid of the partition matches the
1483 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1484 * ID. Why? Unlike the other partitions /var is inherently
1485 * installation specific, hence we need to be careful not to mount it
1486 * in the wrong installation. By hashing the partition UUID from
1487 * /etc/machine-id we can securely bind the partition to the
1488 * installation. */
1489
1490 r = sd_id128_get_machine_app_specific(SD_GPT_VAR, &var_uuid);
1491 if (r < 0)
1492 return r;
1493
1494 if (!sd_id128_equal(var_uuid, id)) {
1495 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
1496 "(found: " SD_ID128_UUID_FORMAT_STR ", expected: " SD_ID128_UUID_FORMAT_STR "), ignoring.",
1497 SD_ID128_FORMAT_VAL(id), SD_ID128_FORMAT_VAL(var_uuid));
1498 continue;
1499 }
1500 }
1501
1502 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1503 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1504 }
1505
1506 if (type.designator != _PARTITION_DESIGNATOR_INVALID) {
1507 _cleanup_free_ char *t = NULL, *o = NULL, *l = NULL, *n = NULL;
1508 _cleanup_close_ int mount_node_fd = -EBADF;
1509 const char *options = NULL;
1510
1511 r = image_policy_may_use(policy, type.designator);
1512 if (r < 0)
1513 return r;
1514 if (r == 0) {
1515 /* Policy says: ignore; Remember this fact, so that we later can distinguish between "found but ignored" and "not found at all" */
1516
1517 if (!m->partitions[type.designator].found)
1518 m->partitions[type.designator].ignored = true;
1519
1520 continue;
1521 }
1522
1523 if (m->partitions[type.designator].found) {
1524 int c;
1525
1526 /* For most partition types the first one we see wins. Except for the
1527 * rootfs and /usr, where we do a version compare of the label, and
1528 * let the newest version win. This permits a simple A/B versioning
1529 * scheme in OS images. */
1530
1531 c = compare_arch(type.arch, m->partitions[type.designator].architecture);
1532 if (c < 0) /* the arch we already found is better than the one we found now */
1533 continue;
1534 if (c == 0 && /* same arch? then go by version in label */
1535 (!partition_designator_is_versioned(type.designator) ||
1536 strverscmp_improved(label, m->partitions[type.designator].label) <= 0))
1537 continue;
1538
1539 dissected_partition_done(m->partitions + type.designator);
1540 }
1541
1542 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES) &&
1543 type.designator != PARTITION_SWAP) {
1544 mount_node_fd = open_partition(node, /* is_partition= */ true, m->loop);
1545 if (mount_node_fd < 0)
1546 return mount_node_fd;
1547 }
1548
1549 r = make_partition_devname(devname, diskseq, nr, flags, &n);
1550 if (r < 0)
1551 return r;
1552
1553 /* Local override via env var or designator type wins */
1554 if (fstype) {
1555 t = strdup(fstype);
1556 if (!t)
1557 return -ENOMEM;
1558 } else {
1559 r = partition_policy_determine_fstype(policy, type.designator, /* ret_encrypted= */ NULL, &t);
1560 if (r < 0)
1561 return r;
1562 }
1563
1564 if (label) {
1565 l = strdup(label);
1566 if (!l)
1567 return -ENOMEM;
1568 }
1569
1570 options = mount_options_from_designator(mount_options, type.designator);
1571 if (options) {
1572 o = strdup(options);
1573 if (!o)
1574 return -ENOMEM;
1575 }
1576
1577 m->partitions[type.designator] = (DissectedPartition) {
1578 .found = true,
1579 .partno = nr,
1580 .rw = rw,
1581 .growfs = growfs,
1582 .architecture = type.arch,
1583 .node = TAKE_PTR(n),
1584 .fstype = TAKE_PTR(t),
1585 .label = TAKE_PTR(l),
1586 .uuid = id,
1587 .mount_options = TAKE_PTR(o),
1588 .mount_node_fd = TAKE_FD(mount_node_fd),
1589 .offset = (uint64_t) start * 512,
1590 .size = (uint64_t) size * 512,
1591 .gpt_flags = pflags,
1592 .fsmount_fd = -EBADF,
1593 };
1594 }
1595
1596 } else if (is_mbr) {
1597
1598 switch (sym_blkid_partition_get_type(pp)) {
1599
1600 case 0x83: /* Linux partition */
1601
1602 if (pflags != 0x80) /* Bootable flag */
1603 continue;
1604
1605 if (!image_filter_test(filter, PARTITION_ROOT, /* label= */ NULL))
1606 continue;
1607
1608 if (generic_node)
1609 multiple_generic = true;
1610 else {
1611 generic_nr = nr;
1612 generic_rw = true;
1613 generic_growfs = false;
1614 generic_node = TAKE_PTR(node);
1615 }
1616
1617 break;
1618
1619 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1620 _cleanup_close_ int mount_node_fd = -EBADF;
1621 _cleanup_free_ char *o = NULL, *n = NULL;
1622 sd_id128_t id = SD_ID128_NULL;
1623 const char *options = NULL;
1624
1625 if (!image_filter_test(filter, PARTITION_XBOOTLDR, /* label= */ NULL))
1626 continue;
1627
1628 r = image_policy_may_use(policy, PARTITION_XBOOTLDR);
1629 if (r < 0)
1630 return r;
1631 if (r == 0) { /* policy says: ignore */
1632 if (!m->partitions[PARTITION_XBOOTLDR].found)
1633 m->partitions[PARTITION_XBOOTLDR].ignored = true;
1634
1635 continue;
1636 }
1637
1638 /* First one wins */
1639 if (m->partitions[PARTITION_XBOOTLDR].found)
1640 continue;
1641
1642 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1643 mount_node_fd = open_partition(node, /* is_partition= */ true, m->loop);
1644 if (mount_node_fd < 0)
1645 return mount_node_fd;
1646 }
1647
1648 (void) blkid_partition_get_uuid_id128(pp, &id);
1649
1650 r = make_partition_devname(devname, diskseq, nr, flags, &n);
1651 if (r < 0)
1652 return r;
1653
1654 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
1655 if (options) {
1656 o = strdup(options);
1657 if (!o)
1658 return -ENOMEM;
1659 }
1660
1661 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1662 .found = true,
1663 .partno = nr,
1664 .rw = true,
1665 .growfs = false,
1666 .architecture = _ARCHITECTURE_INVALID,
1667 .node = TAKE_PTR(n),
1668 .uuid = id,
1669 .mount_options = TAKE_PTR(o),
1670 .mount_node_fd = TAKE_FD(mount_node_fd),
1671 .offset = (uint64_t) start * 512,
1672 .size = (uint64_t) size * 512,
1673 .fsmount_fd = -EBADF,
1674 };
1675
1676 break;
1677 }}
1678 }
1679 }
1680
1681 /* Verity found but no matching data partition? Something is off, refuse. */
1682 FOREACH_ELEMENT(dd, ((const PartitionDesignator[]) { PARTITION_ROOT, PARTITION_USR })) {
1683 PartitionDesignator dv = partition_verity_hash_of(*dd);
1684 PartitionDesignator ds = partition_verity_sig_of(*dd);
1685
1686 /* Hint to help static analyzers */
1687 assert(dv >= 0);
1688 assert(ds >= 0);
1689
1690 if (!m->partitions[*dd].found && (m->partitions[dv].found || m->partitions[ds].found))
1691 return log_debug_errno(
1692 SYNTHETIC_ERRNO(EADDRNOTAVAIL),
1693 "Found %s verity hash partition without matching %s data partition.",
1694 partition_designator_to_string(*dd),
1695 partition_designator_to_string(*dd));
1696
1697 if (m->partitions[ds].found && !m->partitions[dv].found)
1698 return log_debug_errno(
1699 SYNTHETIC_ERRNO(EADDRNOTAVAIL),
1700 "Found %s verity signature partition without matching %s verity hash partition.",
1701 partition_designator_to_string(*dd),
1702 partition_designator_to_string(*dd));
1703 }
1704
1705 /* If root and /usr are combined then insist that the architecture matches */
1706 if (m->partitions[PARTITION_ROOT].found &&
1707 m->partitions[PARTITION_USR].found &&
1708 (m->partitions[PARTITION_ROOT].architecture >= 0 &&
1709 m->partitions[PARTITION_USR].architecture >= 0 &&
1710 m->partitions[PARTITION_ROOT].architecture != m->partitions[PARTITION_USR].architecture))
1711 return log_debug_errno(SYNTHETIC_ERRNO(EREMOTE),
1712 "Found root and usr partitions with different architectures (%s vs %s).",
1713 architecture_to_string(m->partitions[PARTITION_ROOT].architecture),
1714 architecture_to_string(m->partitions[PARTITION_USR].architecture));
1715
1716 if (!m->partitions[PARTITION_ROOT].found &&
1717 !m->partitions[PARTITION_USR].found &&
1718 (flags & DISSECT_IMAGE_GENERIC_ROOT) &&
1719 (!verity || !iovec_is_set(&verity->root_hash) || verity->designator != PARTITION_USR)) {
1720
1721 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1722 * that. If the root hash was set however, then we won't fall back to a generic node, because
1723 * the root hash decides. */
1724
1725 /* If we didn't find a properly marked root partition, but we did find a single suitable
1726 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1727 if (multiple_generic)
1728 return -ENOTUNIQ;
1729
1730 /* If we didn't find a generic node, then we can't fix this up either */
1731 if (generic_node) {
1732 r = image_policy_may_use(policy, PARTITION_ROOT);
1733 if (r < 0)
1734 return r;
1735 if (r == 0)
1736 /* Policy says: ignore; remember that we did */
1737 m->partitions[PARTITION_ROOT].ignored = true;
1738 else {
1739 _cleanup_close_ int mount_node_fd = -EBADF;
1740 _cleanup_free_ char *o = NULL, *n = NULL;
1741 const char *options;
1742
1743 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1744 mount_node_fd = open_partition(generic_node, /* is_partition= */ true, m->loop);
1745 if (mount_node_fd < 0)
1746 return mount_node_fd;
1747 }
1748
1749 r = make_partition_devname(devname, diskseq, generic_nr, flags, &n);
1750 if (r < 0)
1751 return r;
1752
1753 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
1754 if (options) {
1755 o = strdup(options);
1756 if (!o)
1757 return -ENOMEM;
1758 }
1759
1760 assert(generic_nr >= 0);
1761 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1762 .found = true,
1763 .rw = generic_rw,
1764 .growfs = generic_growfs,
1765 .partno = generic_nr,
1766 .architecture = _ARCHITECTURE_INVALID,
1767 .node = TAKE_PTR(n),
1768 .uuid = generic_uuid,
1769 .mount_options = TAKE_PTR(o),
1770 .mount_node_fd = TAKE_FD(mount_node_fd),
1771 .offset = UINT64_MAX,
1772 .size = UINT64_MAX,
1773 .fsmount_fd = -EBADF,
1774 };
1775 }
1776 }
1777 }
1778
1779 /* Check if we have a root fs if we are told to do check. /usr alone is fine too, but only if appropriate flag for that is set too */
1780 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1781 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1782 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO), "Root or usr partition requested but found neither.");
1783
1784 if (m->partitions[PARTITION_ROOT_VERITY].found) {
1785 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1786 if (m->partitions[PARTITION_USR_VERITY].found)
1787 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ), "Found both root and usr verity enabled partitions which is not supported.");
1788
1789 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1790 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1791 if (m->partitions[PARTITION_USR].found)
1792 return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL), "Found verity enabled root partition with split usr partition which is not supported.");
1793 }
1794
1795 if (verity) {
1796 /* If a verity designator is specified, then insist that the matching partition exists */
1797 if (verity->designator >= 0 && !m->partitions[verity->designator].found)
1798 return log_debug_errno(
1799 SYNTHETIC_ERRNO(EADDRNOTAVAIL),
1800 "Explicit %s verity designator was specified but did not find %s partition.",
1801 partition_designator_to_string(verity->designator),
1802 partition_designator_to_string(verity->designator));
1803
1804 if (iovec_is_set(&verity->root_hash)) {
1805 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1806 * Verity, set things up for it */
1807
1808 PartitionDesignator d = verity->designator < 0 || verity->designator == PARTITION_ROOT
1809 ? PARTITION_ROOT : PARTITION_USR;
1810 PartitionDesignator dv = partition_verity_hash_of(d);
1811 assert(dv >= 0);
1812
1813 if (!m->partitions[d].found)
1814 return log_debug_errno(
1815 SYNTHETIC_ERRNO(EADDRNOTAVAIL),
1816 "Verity enabled %s partition was requested but did not find a %s data partition.",
1817 partition_designator_to_string(d),
1818 partition_designator_to_string(d));
1819
1820 if (!m->partitions[dv].found)
1821 return log_debug_errno(
1822 SYNTHETIC_ERRNO(EADDRNOTAVAIL),
1823 "Verity enabled %s partition was requested but did not find a %s verity hash partition.",
1824 partition_designator_to_string(d),
1825 partition_designator_to_string(d));
1826
1827 /* If we found a verity setup, then the data partition is necessarily read-only. */
1828 m->partitions[d].rw = false;
1829
1830 m->verity_ready = true;
1831
1832 if (iovec_is_set(&verity->root_hash_sig))
1833 m->verity_sig_ready = true;
1834 }
1835 }
1836
1837 bool any = false;
1838
1839 /* After we discovered all partitions let's see if the verity requirements match the policy. (Note:
1840 * we don't check encryption requirements here, because we haven't probed the file system yet, hence
1841 * don't know if this is encrypted or not) */
1842 for (PartitionDesignator di = 0; di < _PARTITION_DESIGNATOR_MAX; di++) {
1843 any = any || m->partitions[di].found;
1844
1845 /* Determine the verity protection level for this partition. */
1846 PartitionPolicyFlags found_flags;
1847 if (m->partitions[di].found) {
1848 found_flags = PARTITION_POLICY_ENCRYPTED|PARTITION_POLICY_ENCRYPTEDWITHINTEGRITY|PARTITION_POLICY_UNPROTECTED|PARTITION_POLICY_UNUSED;
1849
1850 PartitionDesignator vi = partition_verity_hash_of(di);
1851 if (vi >= 0 && m->partitions[vi].found) {
1852 found_flags |= PARTITION_POLICY_VERITY;
1853
1854 PartitionDesignator si = partition_verity_sig_of(di);
1855 if (si >= 0 && m->partitions[si].found)
1856 found_flags |= PARTITION_POLICY_SIGNED;
1857 }
1858 } else
1859 found_flags = m->partitions[di].ignored ? PARTITION_POLICY_UNUSED : PARTITION_POLICY_ABSENT;
1860
1861 if (DEBUG_LOGGING) {
1862 _cleanup_free_ char *s = NULL;
1863 (void) partition_policy_flags_to_string(found_flags, /* simplify= */ false, &s);
1864 log_debug("Found for designator %s: %s.", partition_designator_to_string(di), strna(s));
1865 }
1866
1867 r = image_policy_check_protection(policy, di, found_flags);
1868 if (r < 0)
1869 return r;
1870
1871 if (m->partitions[di].found) {
1872 r = image_policy_check_partition_flags(policy, di, m->partitions[di].gpt_flags);
1873 if (r < 0)
1874 return r;
1875 }
1876 }
1877
1878 if (!any && !FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_EMPTY))
1879 return -ENOMSG;
1880
1881 r = dissected_image_probe_filesystems(m, fd, policy);
1882 if (r < 0)
1883 return r;
1884
1885 return 0;
1886 }
1887 #endif
1888
1889 int dissected_image_new_from_existing_verity(
1890 const char *src,
1891 const VeritySettings *verity,
1892 const MountOptions *options,
1893 const ImagePolicy *image_policy,
1894 const ImageFilter *image_filter,
1895 RuntimeScope runtime_scope,
1896 DissectImageFlags dissect_image_flags,
1897 DissectedImage **ret) {
1898
1899 /* Look for an already set up dm-verity device with a single filesystem, according to our naming
1900 * scheme and image policy, and if it is pinned by filesystem type set up the image directly. */
1901
1902 #if HAVE_BLKID
1903 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
1904 _cleanup_free_ char *node = NULL, *root_hash_encoded = NULL, *root_fstype_string = NULL;
1905 _cleanup_close_ int mount_node_fd = -EBADF;
1906 PartitionPolicyFlags found_flags;
1907 bool encrypted = false;
1908 int r;
1909
1910 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
1911 assert(!verity || iovec_is_valid(&verity->root_hash));
1912 assert(!verity || iovec_is_valid(&verity->root_hash_sig));
1913 assert(!verity || iovec_is_set(&verity->root_hash) || !iovec_is_set(&verity->root_hash_sig));
1914 assert(ret);
1915
1916 /* Shortcut: this deals only with verity images and requires a policy, and only for system services */
1917 if (runtime_scope != RUNTIME_SCOPE_SYSTEM ||
1918 !FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_VERITY_SHARE) ||
1919 !image_policy ||
1920 !verity ||
1921 !verity->data_path ||
1922 (verity->designator >= 0 && verity->designator != PARTITION_ROOT) ||
1923 !iovec_is_set(&verity->root_hash))
1924 return -ENOPKG;
1925
1926 /* The policy fstype flags translate to the literal fstype name of each filesystem.
1927 * Input must be a single filesystem image, if the policy specifies more than one, we need to dissect */
1928 r = partition_policy_determine_fstype(image_policy, PARTITION_ROOT, &encrypted, &root_fstype_string);
1929 if (r < 0)
1930 return r;
1931 if (!root_fstype_string)
1932 return -ENOPKG;
1933
1934 if (verity_settings_data_covers(verity, PARTITION_ROOT))
1935 found_flags = iovec_is_set(&verity->root_hash_sig) ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY;
1936 else
1937 found_flags = encrypted ? PARTITION_POLICY_ENCRYPTED : PARTITION_POLICY_UNPROTECTED;
1938
1939 root_hash_encoded = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
1940 if (!root_hash_encoded)
1941 return -ENOMEM;
1942
1943 node = strjoin("/dev/mapper/", root_hash_encoded, "-verity");
1944 if (!node)
1945 return -ENOMEM;
1946
1947 r = dissected_image_new(src, &dissected_image);
1948 if (r < 0)
1949 return r;
1950
1951 mount_node_fd = open_partition(node, /* is_partition= */ false, /* loop= */ NULL);
1952 if (mount_node_fd < 0)
1953 return mount_node_fd;
1954
1955 r = dissect_image_from_unpartitioned(
1956 node,
1957 /* diskseq= */ 0,
1958 /* uuid= */ NULL,
1959 encrypted,
1960 verity,
1961 options,
1962 image_policy,
1963 image_filter,
1964 &mount_node_fd,
1965 &root_fstype_string,
1966 dissected_image,
1967 dissect_image_flags,
1968 found_flags);
1969 if (r < 0)
1970 return r;
1971
1972 *ret = TAKE_PTR(dissected_image);
1973
1974 return 0;
1975 #else
1976 return -EOPNOTSUPP;
1977 #endif
1978 }
1979
1980 int dissect_image_file(
1981 const char *path,
1982 const VeritySettings *verity,
1983 const MountOptions *mount_options,
1984 const ImagePolicy *image_policy,
1985 const ImageFilter *image_filter,
1986 DissectImageFlags flags,
1987 DissectedImage **ret) {
1988
1989 #if HAVE_BLKID
1990 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1991 _cleanup_close_ int fd = -EBADF;
1992 struct stat st;
1993 int r;
1994
1995 assert(path);
1996
1997 fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1998 if (fd < 0)
1999 return -errno;
2000
2001 if (fstat(fd, &st) < 0)
2002 return -errno;
2003
2004 r = stat_verify_regular(&st);
2005 if (r < 0)
2006 return r;
2007
2008 r = dissected_image_new(path, &m);
2009 if (r < 0)
2010 return r;
2011
2012 m->image_size = st.st_size;
2013
2014 r = probe_sector_size(fd, &m->sector_size);
2015 if (r < 0)
2016 return r;
2017
2018 r = dissect_image(m, fd, path, verity, mount_options, image_policy, image_filter, flags);
2019 if (r < 0)
2020 return r;
2021
2022 if (ret)
2023 *ret = TAKE_PTR(m);
2024 return 0;
2025 #else
2026 return -EOPNOTSUPP;
2027 #endif
2028 }
2029
2030 int dissect_log_error(int log_level, int r, const char *name, const VeritySettings *verity) {
2031 assert(log_level >= 0 && log_level <= LOG_DEBUG);
2032 assert(name);
2033
2034 switch (r) {
2035
2036 case 0 ... INT_MAX: /* success! */
2037 return r;
2038
2039 case -EOPNOTSUPP:
2040 return log_full_errno(log_level, r, "Dissecting images is not supported, compiled without blkid support.");
2041
2042 case -ENOPKG:
2043 return log_full_errno(log_level, r, "%s: Couldn't identify a suitable partition table or file system.", name);
2044
2045 case -ENOMEDIUM:
2046 return log_full_errno(log_level, r, "%s: The image does not pass os-release/extension-release validation.", name);
2047
2048 case -EADDRNOTAVAIL:
2049 return log_full_errno(log_level, r, "%s: No root/usr partition for specified root/usr hash found.", name);
2050
2051 case -EREMOTE:
2052 return log_full_errno(log_level, r, "%s: Found root and usr partitions with different architectures", name);
2053
2054 case -ENOTUNIQ:
2055 return log_full_errno(log_level, r, "%s: Multiple suitable root partitions found in image.", name);
2056
2057 case -ENXIO:
2058 return log_full_errno(log_level, r, "%s: No suitable root partition found in image.", name);
2059
2060 case -EPROTONOSUPPORT:
2061 return log_full_errno(log_level, r, "Device '%s' is a loopback block device with partition scanning turned off, please turn it on.", name);
2062
2063 case -ENOTBLK:
2064 return log_full_errno(log_level, r, "%s: Image is not a block device.", name);
2065
2066 case -EBADR:
2067 return log_full_errno(log_level, r,
2068 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
2069 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
2070 name, strna(verity ? verity->data_path : NULL));
2071
2072 case -ERFKILL:
2073 return log_full_errno(log_level, r, "%s: Image does not match image policy.", name);
2074
2075 case -ENOMSG:
2076 return log_full_errno(log_level, r, "%s: No suitable partitions found.", name);
2077
2078 case -EUCLEAN:
2079 return log_full_errno(log_level, r, "%s: Partition with ambiguous file system superblock signature found.", name);
2080
2081 default:
2082 return log_full_errno(log_level, r, "%s: Cannot dissect image: %m", name);
2083 }
2084 }
2085
2086 int dissect_image_file_and_warn(
2087 const char *path,
2088 const VeritySettings *verity,
2089 const MountOptions *mount_options,
2090 const ImagePolicy *image_policy,
2091 const ImageFilter *image_filter,
2092 DissectImageFlags flags,
2093 DissectedImage **ret) {
2094
2095 return dissect_log_error(
2096 LOG_ERR,
2097 dissect_image_file(path, verity, mount_options, image_policy, image_filter, flags, ret),
2098 path,
2099 verity);
2100 }
2101
2102 void dissected_image_close(DissectedImage *m) {
2103 if (!m)
2104 return;
2105
2106 /* Closes all fds we keep open associated with this, but nothing else */
2107
2108 FOREACH_ARRAY(p, m->partitions, _PARTITION_DESIGNATOR_MAX) {
2109 p->mount_node_fd = safe_close(p->mount_node_fd);
2110 p->fsmount_fd = safe_close(p->fsmount_fd);
2111 }
2112
2113 m->loop = loop_device_unref(m->loop);
2114 }
2115
2116 DissectedImage* dissected_image_unref(DissectedImage *m) {
2117 if (!m)
2118 return NULL;
2119
2120 /* First, clear dissected partitions. */
2121 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
2122 dissected_partition_done(m->partitions + i);
2123
2124 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
2125 * DecryptedImage may try to deactivate partitions. */
2126 decrypted_image_unref(m->decrypted_image);
2127
2128 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
2129 * remove existing partitions on the loopback block device. */
2130 loop_device_unref(m->loop);
2131
2132 free(m->image_name);
2133 free(m->hostname);
2134 strv_free(m->machine_info);
2135 strv_free(m->os_release);
2136 strv_free(m->initrd_release);
2137 strv_free(m->confext_release);
2138 strv_free(m->sysext_release);
2139
2140 return mfree(m);
2141 }
2142
2143 static int is_loop_device(const char *path) {
2144 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
2145 struct stat st;
2146 int r;
2147
2148 assert(path);
2149
2150 if (stat(path, &st) < 0)
2151 return -errno;
2152
2153 r = stat_verify_block(&st);
2154 if (r < 0)
2155 return r;
2156
2157 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
2158 if (access(s, F_OK) < 0) {
2159 if (errno != ENOENT)
2160 return -errno;
2161
2162 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
2163 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
2164 if (access(s, F_OK) < 0)
2165 return errno == ENOENT ? false : -errno;
2166 }
2167
2168 return true;
2169 }
2170
2171 static int run_fsck(int node_fd, const char *fstype) {
2172 int r, exit_status;
2173
2174 assert(node_fd >= 0);
2175 assert(fstype);
2176
2177 r = fsck_exists_for_fstype(fstype);
2178 if (r < 0) {
2179 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
2180 return 0;
2181 }
2182 if (r == 0) {
2183 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd), fstype);
2184 return 0;
2185 }
2186
2187 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
2188 r = pidref_safe_fork_full(
2189 "(fsck)",
2190 NULL,
2191 &node_fd, 1, /* Leave the node fd open */
2192 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_REARRANGE_STDIO|FORK_CLOEXEC_OFF,
2193 &pidref);
2194 if (r < 0)
2195 return log_debug_errno(r, "Failed to fork off fsck: %m");
2196 if (r == 0) {
2197 /* Child */
2198 execlp("fsck", "fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd), NULL);
2199 log_open();
2200 log_debug_errno(errno, "Failed to execl() fsck: %m");
2201 _exit(FSCK_OPERATIONAL_ERROR);
2202 }
2203
2204 exit_status = pidref_wait_for_terminate_and_check("fsck", &pidref, 0);
2205 if (exit_status < 0)
2206 return log_debug_errno(exit_status, "Failed to fork off fsck: %m");
2207
2208 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
2209 log_debug("fsck failed with exit status %i.", exit_status);
2210
2211 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
2212 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
2213
2214 log_debug("Ignoring fsck error.");
2215 }
2216
2217 return 0;
2218 }
2219
2220 static int fs_grow(const char *node_path, int mount_fd, const char *mount_path) {
2221 _cleanup_close_ int _mount_fd = -EBADF, node_fd = -EBADF;
2222 uint64_t size, newsize;
2223 const char *id;
2224 int r;
2225
2226 assert(node_path);
2227 assert(mount_fd >= 0 || mount_path);
2228
2229 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2230 if (node_fd < 0)
2231 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
2232
2233 r = blockdev_get_device_size(node_fd, &size);
2234 if (r < 0)
2235 return log_debug_errno(r, "Failed to get block device size of %s: %m", node_path);
2236
2237 if (mount_fd < 0) {
2238 assert(mount_path);
2239
2240 _mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
2241 if (_mount_fd < 0)
2242 return log_debug_errno(errno, "Failed to open mounted file system %s: %m", mount_path);
2243
2244 mount_fd = _mount_fd;
2245 } else {
2246 mount_fd = fd_reopen_condition(mount_fd, O_RDONLY|O_DIRECTORY|O_CLOEXEC, O_RDONLY|O_DIRECTORY|O_CLOEXEC, &_mount_fd);
2247 if (mount_fd < 0)
2248 return log_debug_errno(errno, "Failed to reopen mount node: %m");
2249 }
2250
2251 id = mount_path ?: node_path;
2252
2253 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", id, size);
2254 r = resize_fs(mount_fd, size, &newsize);
2255 if (r < 0)
2256 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", id, size);
2257
2258 if (newsize == size)
2259 log_debug("Successfully resized \"%s\" to %s bytes.",
2260 id, FORMAT_BYTES(newsize));
2261 else {
2262 assert(newsize < size);
2263 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
2264 id, FORMAT_BYTES(newsize), size - newsize);
2265 }
2266
2267 return 0;
2268 }
2269
2270 int partition_pick_mount_options(
2271 PartitionDesignator d,
2272 const char *fstype,
2273 bool rw,
2274 bool discard,
2275 char **ret_options,
2276 unsigned long *ret_ms_flags) {
2277
2278 _cleanup_free_ char *options = NULL;
2279
2280 assert(ret_options);
2281
2282 /* Selects a baseline of bind mount flags, that should always apply.
2283 *
2284 * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
2285 *
2286 * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
2287 *
2288 * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
2289 * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
2290 * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
2291 * there anyway. */
2292
2293 unsigned long flags = MS_NODEV;
2294
2295 if (!rw)
2296 flags |= MS_RDONLY;
2297
2298 switch (d) {
2299
2300 case PARTITION_ESP:
2301 case PARTITION_XBOOTLDR:
2302 flags |= MS_NOSUID|MS_NOEXEC|MS_NOSYMFOLLOW;
2303
2304 /* The ESP might contain a pre-boot random seed. Let's make this inaccessible to regular
2305 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
2306 if (!fstype || fstype_can_fmask_dmask(fstype))
2307 if (!strextend_with_separator(&options, ",", "fmask=0177,dmask=0077"))
2308 return -ENOMEM;
2309 break;
2310
2311 case PARTITION_TMP:
2312 flags |= MS_NOSUID;
2313 break;
2314
2315 default:
2316 ;
2317 }
2318
2319 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
2320 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
2321 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
2322 * from the upper file system still get propagated through to the underlying file system,
2323 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
2324 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
2325 * carry a per file system table here.
2326 *
2327 * Note that this means that we might not be able to mount corrupted file systems as read-only
2328 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
2329 * read-only and "norecovery" is specified). But I think for the case of automatically determined
2330 * mount options for loopback devices this is the right choice, since otherwise using the same
2331 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The use case of
2332 * making reuse of the immutable images "just work" is more relevant to us than having read-only
2333 * access that actually modifies stuff work on such image files. Or to say this differently: if
2334 * people want their file systems to be fixed up they should just open them in writable mode, where
2335 * all these problems don't exist. */
2336 if (!rw && fstype) {
2337 const char *option = fstype_norecovery_option(fstype);
2338
2339 if (option && !strextend_with_separator(&options, ",", option))
2340 return -ENOMEM;
2341 }
2342
2343 if (discard && fstype && fstype_can_discard(fstype))
2344 if (!strextend_with_separator(&options, ",", "discard"))
2345 return -ENOMEM;
2346
2347 if (!ret_ms_flags) /* Fold flags into option string if ret_flags specified as NULL */
2348 if (!strextend_with_separator(&options, ",",
2349 FLAGS_SET(flags, MS_RDONLY) ? "ro" : "rw",
2350 FLAGS_SET(flags, MS_NODEV) ? "nodev" : "dev",
2351 FLAGS_SET(flags, MS_NOSUID) ? "nosuid" : "suid",
2352 FLAGS_SET(flags, MS_NOEXEC) ? "noexec" : "exec",
2353 FLAGS_SET(flags, MS_NOSYMFOLLOW) ? "nosymfollow" : NULL))
2354 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
2355 return -ENOMEM;
2356
2357 if (ret_ms_flags)
2358 *ret_ms_flags = flags;
2359
2360 *ret_options = TAKE_PTR(options);
2361 return 0;
2362 }
2363
2364 static bool need_user_mapping(uid_t uid_shift, uid_t uid_range) {
2365
2366 if (!uid_is_valid(uid_shift))
2367 return false;
2368
2369 return uid_shift != 0 || uid_range != UINT32_MAX;
2370 }
2371
2372 static int mount_partition(
2373 PartitionDesignator d,
2374 DissectedPartition *m,
2375 const char *where,
2376 const char *directory,
2377 uid_t uid_shift,
2378 uid_t uid_range,
2379 int userns_fd,
2380 DissectImageFlags flags) {
2381
2382 _cleanup_free_ char *chased = NULL, *options = NULL;
2383 const char *p = NULL, *node, *fstype = NULL;
2384 bool rw, discard, grow;
2385 unsigned long ms_flags;
2386 int r;
2387
2388 assert(m);
2389
2390 if (!m->found)
2391 return 0;
2392
2393 /* Check the various combinations when we can't do anything anymore */
2394 if (m->fsmount_fd < 0 && m->mount_node_fd < 0)
2395 return 0;
2396 if (m->fsmount_fd >= 0 && !where)
2397 return 0;
2398 if (!where && m->mount_node_fd < 0)
2399 return 0;
2400
2401 if (m->fsmount_fd < 0) {
2402 fstype = dissected_partition_fstype(m);
2403 if (!fstype)
2404 return -EAFNOSUPPORT;
2405
2406 /* We are looking at an encrypted partition? This either means stacked encryption, or the
2407 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
2408 * for this case. */
2409 if (streq(fstype, "crypto_LUKS"))
2410 return -EUNATCH;
2411
2412 r = dissect_fstype_ok(fstype);
2413 if (r < 0)
2414 return r;
2415 if (!r)
2416 return -EIDRM; /* Recognizable error */
2417 }
2418
2419 node = m->mount_node_fd < 0 ? NULL : FORMAT_PROC_FD_PATH(m->mount_node_fd);
2420 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
2421
2422 discard = ((flags & DISSECT_IMAGE_DISCARD) ||
2423 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && (m->node && is_loop_device(m->node) > 0)));
2424
2425 grow = rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS);
2426
2427 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw && m->mount_node_fd >= 0 && m->fsmount_fd < 0) {
2428 r = run_fsck(m->mount_node_fd, fstype);
2429 if (r < 0)
2430 return r;
2431 }
2432
2433 if (where) {
2434 if (directory) {
2435 /* Automatically create missing mount points inside the image, if necessary. */
2436 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
2437 if (r < 0 && r != -EROFS)
2438 return r;
2439
2440 r = chase(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
2441 if (r < 0)
2442 return r;
2443
2444 p = chased;
2445 } else {
2446 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
2447 * image (as the branch above does) but the host hierarchy, and the created directory might
2448 * survive our mount in the host hierarchy hence. */
2449 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
2450 r = mkdir_p(where, 0755);
2451 if (r < 0)
2452 return r;
2453 }
2454
2455 p = where;
2456 }
2457 }
2458
2459 if (m->fsmount_fd < 0) {
2460 r = partition_pick_mount_options(d, fstype, rw, discard, &options, &ms_flags);
2461 if (r < 0)
2462 return r;
2463
2464 if (need_user_mapping(uid_shift, uid_range) && fstype_can_uid_gid(fstype)) {
2465 _cleanup_free_ char *uid_option = NULL;
2466
2467 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
2468 return -ENOMEM;
2469
2470 if (!strextend_with_separator(&options, ",", uid_option))
2471 return -ENOMEM;
2472
2473 userns_fd = -EBADF; /* Not needed */
2474 }
2475
2476 if (!isempty(m->mount_options))
2477 if (!strextend_with_separator(&options, ",", m->mount_options))
2478 return -ENOMEM;
2479 }
2480
2481 if (p) {
2482 if (m->fsmount_fd >= 0) {
2483 /* Case #1: Attach existing fsmount fd to the file system */
2484
2485 r = mount_exchange_graceful(
2486 m->fsmount_fd,
2487 p,
2488 FLAGS_SET(flags, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE));
2489 if (r < 0)
2490 return log_debug_errno(r, "Failed to mount image on '%s': %m", p);
2491
2492 } else {
2493 assert(node);
2494
2495 /* Case #2: Mount directly into place */
2496 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, ms_flags, options);
2497 if (r < 0)
2498 return r;
2499
2500 if (grow)
2501 (void) fs_grow(node, -EBADF, p);
2502
2503 if (userns_fd >= 0) {
2504 r = remount_idmap_fd(STRV_MAKE(p), userns_fd, /* extra_mount_attr_set= */ 0);
2505 if (r < 0)
2506 return r;
2507 }
2508 }
2509 } else {
2510 assert(node);
2511
2512 /* Case #3: Create fsmount fd */
2513
2514 m->fsmount_fd = make_fsmount(LOG_DEBUG, node, fstype, ms_flags, options, userns_fd);
2515 if (m->fsmount_fd < 0)
2516 return m->fsmount_fd;
2517
2518 if (grow)
2519 (void) fs_grow(node, m->fsmount_fd, NULL);
2520 }
2521
2522 return 1;
2523 }
2524
2525 static int mount_root_tmpfs(const char *where, uid_t uid_shift, uid_t uid_range, DissectImageFlags flags) {
2526 _cleanup_free_ char *options = NULL;
2527 int r;
2528
2529 assert(where);
2530
2531 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
2532
2533 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
2534 r = mkdir_p(where, 0755);
2535 if (r < 0)
2536 return r;
2537 }
2538
2539 if (need_user_mapping(uid_shift, uid_range)) {
2540 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
2541 return -ENOMEM;
2542 }
2543
2544 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
2545 if (r < 0)
2546 return r;
2547
2548 return 1;
2549 }
2550
2551 static int mount_point_is_available(const char *where, const char *path, bool missing_ok) {
2552 _cleanup_free_ char *p = NULL;
2553 int r;
2554
2555 /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
2556 * or does not exist at all (when missing_ok). */
2557
2558 r = chase(path, where, CHASE_PREFIX_ROOT, &p, NULL);
2559 if (r == -ENOENT)
2560 return missing_ok;
2561 if (r < 0)
2562 return log_debug_errno(r, "Failed to chase \"%s\": %m", path);
2563
2564 r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
2565 if (r == -ENOTDIR)
2566 return false;
2567 if (r < 0)
2568 return log_debug_errno(r, "Failed to check directory \"%s\": %m", p);
2569 return r > 0;
2570 }
2571
2572 int dissected_image_mount(
2573 DissectedImage *m,
2574 const char *where,
2575 uid_t uid_shift,
2576 uid_t uid_range,
2577 int userns_fd,
2578 DissectImageFlags flags) {
2579
2580 _cleanup_close_ int my_userns_fd = -EBADF;
2581 int r;
2582
2583 assert(m);
2584
2585 if (FLAGS_SET(flags, DISSECT_IMAGE_FOREIGN_UID)) /* For image based mounts we currently require an identity mapping */
2586 return -EOPNOTSUPP;
2587
2588 /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
2589 * store them in DissectedPartition.fsmount_fd.
2590 *
2591 * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
2592 * or use DissectedPartition.fsmount_fd and bind it to the right places.
2593 *
2594 * This allows splitting the setting up the superblocks and the binding to file systems paths into
2595 * two distinct and differently privileged components: one that gets the fsmount fds, and the other
2596 * that then applies them.
2597 *
2598 * Returns:
2599 *
2600 * -ENXIO → No root partition found
2601 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
2602 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
2603 * -EUCLEAN → fsck for file system failed
2604 * -EBUSY → File system already mounted/used elsewhere (kernel)
2605 * -EAFNOSUPPORT → File system type not supported or not known
2606 * -EIDRM → File system is not among allowlisted "common" file systems
2607 */
2608
2609 if (!where && (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0)
2610 return -EOPNOTSUPP; /* for now, not supported */
2611
2612 if (!(m->partitions[PARTITION_ROOT].found ||
2613 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
2614 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
2615
2616 if (userns_fd < 0 && need_user_mapping(uid_shift, uid_range) && FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED)) {
2617
2618 my_userns_fd = make_userns(uid_shift, uid_range, UID_INVALID, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
2619 if (my_userns_fd < 0)
2620 return my_userns_fd;
2621
2622 userns_fd = my_userns_fd;
2623 }
2624
2625 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
2626
2627 /* First mount the root fs. If there's none we use a tmpfs. */
2628 if (m->partitions[PARTITION_ROOT].found) {
2629 r = mount_partition(PARTITION_ROOT, m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, userns_fd, flags);
2630 if (r < 0)
2631 return r;
2632
2633 } else if (where) {
2634 r = mount_root_tmpfs(where, uid_shift, uid_range, flags);
2635 if (r < 0)
2636 return r;
2637 }
2638
2639 /* For us mounting root always means mounting /usr as well */
2640 r = mount_partition(PARTITION_USR, m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, userns_fd, flags);
2641 if (r < 0)
2642 return r;
2643 }
2644
2645 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0 &&
2646 (flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
2647 /* If either one of the validation flags are set, ensure that the image qualifies as
2648 * one or the other (or both). */
2649 bool ok = false;
2650
2651 assert(where);
2652
2653 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
2654 log_debug("Checking if '%s' is an OS tree", where);
2655
2656 r = path_is_os_tree(where);
2657 if (r < 0)
2658 return log_debug_errno(r, "Failed to check is '%s' is an OS tree: %m", where);
2659 if (r > 0) {
2660 log_debug("Successfully identified '%s' as an OS tree", where);
2661 ok = true;
2662 }
2663 }
2664 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT) && m->image_name) {
2665 log_debug("Checking if '%s' is an extension tree", where);
2666
2667 r = extension_has_forbidden_content(where);
2668 if (r < 0)
2669 return log_debug_errno(r, "Failed to check if '%s' contains content forbidden for an extension image: %m", where);
2670 if (r == 0) {
2671 ImageClass class = IMAGE_SYSEXT;
2672 r = path_is_extension_tree(class, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
2673 if (r == 0) {
2674 class = IMAGE_CONFEXT;
2675 r = path_is_extension_tree(class, where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_EXTENSION_CHECK));
2676 }
2677 if (r < 0)
2678 return log_debug_errno(r, "Failed to check if '%s' is an extension tree: %m", where);
2679 if (r > 0) {
2680 log_debug("Successfully identified '%s' as a %s extension tree", where, image_class_to_string(class));
2681 ok = true;
2682 }
2683 }
2684 }
2685
2686 if (!ok)
2687 return -ENOMEDIUM;
2688 }
2689
2690 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2691 return 0;
2692
2693 r = mount_partition(PARTITION_HOME, m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, userns_fd, flags);
2694 if (r < 0)
2695 return r;
2696
2697 r = mount_partition(PARTITION_SRV, m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, userns_fd, flags);
2698 if (r < 0)
2699 return r;
2700
2701 r = mount_partition(PARTITION_VAR, m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, userns_fd, flags);
2702 if (r < 0)
2703 return r;
2704
2705 r = mount_partition(PARTITION_TMP, m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, userns_fd, flags);
2706 if (r < 0)
2707 return r;
2708
2709 int slash_boot_is_available = 0;
2710 if (where) {
2711 r = slash_boot_is_available = mount_point_is_available(where, "/boot", /* missing_ok= */ true);
2712 if (r < 0)
2713 return r;
2714 }
2715 if (!where || slash_boot_is_available) {
2716 r = mount_partition(PARTITION_XBOOTLDR, m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, userns_fd, flags);
2717 if (r < 0)
2718 return r;
2719 slash_boot_is_available = !r;
2720 }
2721
2722 if (m->partitions[PARTITION_ESP].found) {
2723 const char *esp_path = NULL;
2724
2725 if (where) {
2726 /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
2727 * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
2728 * and is empty. */
2729
2730 if (slash_boot_is_available) {
2731 r = mount_point_is_available(where, "/boot", /* missing_ok= */ false);
2732 if (r < 0)
2733 return r;
2734 if (r > 0)
2735 esp_path = "/boot";
2736 }
2737
2738 if (!esp_path) {
2739 r = mount_point_is_available(where, "/efi", /* missing_ok= */ true);
2740 if (r < 0)
2741 return r;
2742 if (r > 0)
2743 esp_path = "/efi";
2744 }
2745 }
2746
2747 /* OK, let's mount the ESP now (possibly creating the dir if missing) */
2748 r = mount_partition(PARTITION_ESP, m->partitions + PARTITION_ESP, where, esp_path, uid_shift, uid_range, userns_fd, flags);
2749 if (r < 0)
2750 return r;
2751 }
2752
2753 return 0;
2754 }
2755
2756 int dissected_image_mount_and_warn(
2757 DissectedImage *m,
2758 const char *where,
2759 uid_t uid_shift,
2760 uid_t uid_range,
2761 int userns_fd,
2762 DissectImageFlags flags) {
2763
2764 int r;
2765
2766 assert(m);
2767
2768 r = dissected_image_mount(m, where, uid_shift, uid_range, userns_fd, flags);
2769 if (r == -ENXIO)
2770 return log_error_errno(r, "Failed to mount image: No root file system found in image.");
2771 if (r == -EMEDIUMTYPE)
2772 return log_error_errno(r, "Failed to mount image: No suitable os-release/extension-release file in image found.");
2773 if (r == -EUNATCH)
2774 return log_error_errno(r, "Failed to mount image: Encrypted file system discovered, but decryption not requested.");
2775 if (r == -EUCLEAN)
2776 return log_error_errno(r, "Failed to mount image: File system check on image failed.");
2777 if (r == -EBUSY)
2778 return log_error_errno(r, "Failed to mount image: File system already mounted elsewhere.");
2779 if (r == -EAFNOSUPPORT)
2780 return log_error_errno(r, "Failed to mount image: File system type not supported or not known.");
2781 if (r == -EIDRM)
2782 return log_error_errno(r, "Failed to mount image: File system is too uncommon, refused.");
2783 if (r < 0)
2784 return log_error_errno(r, "Failed to mount image: %m");
2785
2786 return r;
2787 }
2788
2789 #if HAVE_LIBCRYPTSETUP
2790 struct DecryptedPartition {
2791 struct crypt_device *device;
2792 char *name;
2793 bool relinquished;
2794 };
2795 #endif
2796
2797 typedef struct DecryptedPartition DecryptedPartition;
2798
2799 struct DecryptedImage {
2800 unsigned n_ref;
2801 DecryptedPartition *decrypted;
2802 size_t n_decrypted;
2803 };
2804
2805 static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
2806 #if HAVE_LIBCRYPTSETUP
2807 int r;
2808
2809 if (!d)
2810 return NULL;
2811
2812 for (size_t i = 0; i < d->n_decrypted; i++) {
2813 DecryptedPartition *p = d->decrypted + i;
2814
2815 if (p->device && p->name && !p->relinquished) {
2816 _cleanup_free_ char *node = NULL;
2817
2818 node = path_join("/dev/mapper", p->name);
2819 if (node) {
2820 r = btrfs_forget_device(node);
2821 if (r < 0 && r != -ENOENT)
2822 log_debug_errno(r, "Failed to forget btrfs device %s, ignoring: %m", node);
2823 } else
2824 log_oom_debug();
2825
2826 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2827 r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
2828 if (r < 0)
2829 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
2830 }
2831
2832 if (p->device)
2833 sym_crypt_free(p->device);
2834 free(p->name);
2835 }
2836
2837 free(d->decrypted);
2838 free(d);
2839 #endif
2840 return NULL;
2841 }
2842
2843 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
2844
2845 #if HAVE_LIBCRYPTSETUP
2846 static int decrypted_image_new(DecryptedImage **ret) {
2847 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2848
2849 assert(ret);
2850
2851 d = new(DecryptedImage, 1);
2852 if (!d)
2853 return -ENOMEM;
2854
2855 *d = (DecryptedImage) {
2856 .n_ref = 1,
2857 };
2858
2859 *ret = TAKE_PTR(d);
2860 return 0;
2861 }
2862
2863 static uint64_t dissected_image_diskseq(const DissectedImage *di) {
2864 assert(di);
2865
2866 return di->loop ? di->loop->diskseq : 0;
2867 }
2868
2869 static int make_dm_name_and_node(
2870 const char *base,
2871 uint64_t diskseq,
2872 const char *suffix,
2873 char **ret_name,
2874 char **ret_node) {
2875
2876 assert(base);
2877 assert(suffix);
2878 assert(ret_name);
2879 assert(ret_node);
2880
2881 _cleanup_free_ char *name = NULL;
2882 if (diskseq != 0)
2883 name = asprintf_safe("%s-%" PRIu64 "%s", base, diskseq, suffix);
2884 else
2885 name = strjoin(base, suffix);
2886 if (!name)
2887 return -ENOMEM;
2888 if (!filename_is_valid(name))
2889 return -EINVAL;
2890
2891 _cleanup_free_ char *node = path_join(sym_crypt_get_dir(), name);
2892 if (!node)
2893 return -ENOMEM;
2894
2895 *ret_name = TAKE_PTR(name);
2896 *ret_node = TAKE_PTR(node);
2897
2898 return 0;
2899 }
2900
2901 static int make_dm_name_and_node_from_node(
2902 const char *original_node,
2903 uint64_t diskseq,
2904 const char *suffix,
2905 char **ret_name,
2906 char **ret_node) {
2907
2908 int r;
2909
2910 assert(original_node);
2911
2912 _cleanup_free_ char *base = NULL;
2913 r = path_extract_filename(original_node, &base);
2914 if (r < 0)
2915 return r;
2916
2917 return make_dm_name_and_node(base, diskseq, suffix, ret_name, ret_node);
2918 }
2919
2920 static int decrypt_partition(
2921 DissectedImage *di,
2922 DissectedPartition *m,
2923 const char *passphrase,
2924 DissectImageFlags flags,
2925 PartitionPolicyFlags policy_flags,
2926 DecryptedImage *d) {
2927
2928 _cleanup_free_ char *node = NULL, *name = NULL;
2929 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
2930 _cleanup_close_ int fd = -EBADF;
2931 int r;
2932
2933 assert(di);
2934 assert(m);
2935 assert(d);
2936
2937 if (!m->found || !m->node || !m->fstype)
2938 return 0;
2939
2940 if (!streq(m->fstype, "crypto_LUKS"))
2941 return 0;
2942
2943 if (!passphrase)
2944 return -ENOKEY;
2945
2946 if (!FLAGS_SET(policy_flags, PARTITION_POLICY_ENCRYPTED))
2947 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Attempted to unlock partition via LUKS, but it's prohibited.");
2948
2949 r = dlopen_cryptsetup(LOG_DEBUG);
2950 if (r < 0)
2951 return r;
2952
2953 r = make_dm_name_and_node_from_node(m->node, dissected_image_diskseq(di), "-decrypted", &name, &node);
2954 if (r < 0)
2955 return r;
2956
2957 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2958 return -ENOMEM;
2959
2960 r = sym_crypt_init(&cd, m->node);
2961 if (r < 0)
2962 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
2963
2964 cryptsetup_enable_logging(cd);
2965
2966 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
2967 if (r < 0)
2968 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
2969
2970 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
2971 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
2972 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
2973 if (r < 0) {
2974 log_debug_errno(r, "Failed to activate LUKS device: %m");
2975 return r == -EPERM ? -EKEYREJECTED : r;
2976 }
2977
2978 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2979 if (fd < 0)
2980 return log_debug_errno(errno, "Failed to open %s: %m", node);
2981
2982 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2983 .name = TAKE_PTR(name),
2984 .device = TAKE_PTR(cd),
2985 };
2986
2987 m->decrypted_node = TAKE_PTR(node);
2988 close_and_replace(m->mount_node_fd, fd);
2989
2990 return 0;
2991 }
2992
2993 static int verity_can_reuse(
2994 const VeritySettings *verity,
2995 const char *name,
2996 struct crypt_device **ret_cd) {
2997
2998 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2999 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
3000 struct crypt_params_verity crypt_params = {};
3001 int r;
3002
3003 assert(verity);
3004 assert(name);
3005 assert(ret_cd);
3006
3007 r = sym_crypt_init_by_name(&cd, name);
3008 if (r < 0)
3009 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
3010
3011 cryptsetup_enable_logging(cd);
3012
3013 r = sym_crypt_get_verity_info(cd, &crypt_params);
3014 if (r < 0)
3015 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
3016
3017 _cleanup_(iovec_done) struct iovec root_hash_existing = {
3018 .iov_base = malloc0(verity->root_hash.iov_len),
3019 .iov_len = verity->root_hash.iov_len,
3020 };
3021 if (!root_hash_existing.iov_base)
3022 return -ENOMEM;
3023
3024 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing.iov_base, &root_hash_existing.iov_len, NULL, 0);
3025 if (r < 0)
3026 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
3027 if (!iovec_equal(&verity->root_hash, &root_hash_existing))
3028 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
3029
3030 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
3031 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
3032 * signing for the new one, and vice versa. */
3033 if (iovec_is_set(&verity->root_hash_sig) != FLAGS_SET(crypt_params.flags, CRYPT_VERITY_ROOT_HASH_SIGNATURE))
3034 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
3035
3036 *ret_cd = TAKE_PTR(cd);
3037 return 0;
3038 }
3039
3040 static char* dm_deferred_remove_clean(char *name) {
3041 if (!name)
3042 return NULL;
3043
3044 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
3045 return mfree(name);
3046 }
3047 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
3048
3049 static int validate_signature_userspace(const VeritySettings *verity, const char *root, DissectImageFlags flags) {
3050 int r;
3051
3052 /* Returns > 0 if signature checks out, == 0 if not, < 0 on unexpected errors */
3053
3054 if (!FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY)) {
3055 log_debug("Userspace dm-verity signature authentication disabled via flag.");
3056 return 0;
3057 }
3058
3059 r = secure_getenv_bool("SYSTEMD_ALLOW_USERSPACE_VERITY");
3060 if (r < 0 && r != -ENXIO) {
3061 log_debug_errno(r, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
3062 return 0;
3063 }
3064 if (!r) {
3065 log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
3066 return 0;
3067 }
3068
3069 bool b;
3070 r = proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING, &b);
3071 if (r < 0) {
3072 log_debug_errno(r, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
3073 return 0;
3074 }
3075 if (!b) {
3076 log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line option.");
3077 return 0;
3078 }
3079
3080 #if HAVE_OPENSSL
3081 _cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
3082 _cleanup_strv_free_ char **certs = NULL;
3083 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
3084 _cleanup_free_ char *s = NULL;
3085 _cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
3086 * of declaration in place, please */
3087 assert(verity);
3088 assert(iovec_is_set(&verity->root_hash));
3089 assert(iovec_is_set(&verity->root_hash_sig));
3090
3091 r = dlopen_libcrypto(LOG_DEBUG);
3092 if (r < 0)
3093 return r;
3094
3095 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
3096 * userspace validation. */
3097
3098 r = conf_files_list_nulstr(&certs, ".crt", root, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
3099 if (r < 0)
3100 return log_debug_errno(r, "Failed to enumerate certificates: %m");
3101 if (strv_isempty(certs)) {
3102 log_debug("No userspace dm-verity certificates found.");
3103 return 0;
3104 }
3105
3106 const unsigned char *d = verity->root_hash_sig.iov_base;
3107 p7 = sym_d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig.iov_len);
3108 if (!p7)
3109 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
3110
3111 s = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
3112 if (!s)
3113 return log_oom_debug();
3114
3115 bio = sym_BIO_new_mem_buf(s, strlen(s));
3116 if (!bio)
3117 return log_oom_debug();
3118
3119 sk = sym_sk_X509_new_null();
3120 if (!sk)
3121 return log_oom_debug();
3122
3123 STRV_FOREACH(i, certs) {
3124 _cleanup_(X509_freep) X509 *c = NULL;
3125 _cleanup_fclose_ FILE *f = NULL;
3126
3127 f = fopen(*i, "re");
3128 if (!f) {
3129 log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
3130 continue;
3131 }
3132
3133 c = sym_PEM_read_X509(f, NULL, NULL, NULL);
3134 if (!c) {
3135 log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
3136 continue;
3137 }
3138
3139 if (sym_sk_X509_push(sk, c) == 0)
3140 return log_oom_debug();
3141
3142 TAKE_PTR(c);
3143 }
3144
3145 r = sym_PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
3146 if (r)
3147 log_debug("Userspace PKCS#7 validation succeeded.");
3148 else
3149 log_debug("Userspace PKCS#7 validation failed: %s", sym_ERR_error_string(sym_ERR_get_error(), NULL));
3150
3151 return r;
3152 #else
3153 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
3154 return 0;
3155 #endif
3156 }
3157
3158 static int do_crypt_activate_verity(
3159 struct crypt_device *cd,
3160 const char *root,
3161 const char *name,
3162 const VeritySettings *verity,
3163 DissectImageFlags flags,
3164 PartitionPolicyFlags policy_flags) {
3165
3166 int r;
3167
3168 assert(cd);
3169 assert(name);
3170 assert(verity);
3171
3172 bool check_signature;
3173 if (iovec_is_set(&verity->root_hash_sig) && FLAGS_SET(policy_flags, PARTITION_POLICY_SIGNED)) {
3174 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
3175 if (r < 0 && r != -ENXIO)
3176 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
3177
3178 check_signature = r != 0;
3179 } else
3180 check_signature = false;
3181
3182 bool measure_signature;
3183 if (check_signature) {
3184 int k;
3185
3186 /* First, if we have support for signed keys in the kernel, then try that first. */
3187 r = sym_crypt_activate_by_signed_key(
3188 cd,
3189 name,
3190 verity->root_hash.iov_base,
3191 verity->root_hash.iov_len,
3192 verity->root_hash_sig.iov_base,
3193 verity->root_hash_sig.iov_len,
3194 CRYPT_ACTIVATE_READONLY);
3195 if (r >= 0) {
3196 log_debug("Verity activation via kernel signature logic worked.");
3197 measure_signature = true;
3198 goto done;
3199 }
3200
3201 log_debug_errno(r, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
3202
3203 /* Let's mangle ENOKEY → EDESTADDRREQ, so that we return a clear, recognizable error if
3204 * there's a signature we don't recognize, that is distinct from the LUKS/encryption
3205 * -ENOKEY, which means "password required, but I have none". */
3206 if (r == -ENOKEY)
3207 r = -EDESTADDRREQ;
3208
3209 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
3210 * works we'll try to activate without telling the kernel the signature. */
3211
3212 /* Preferably propagate the original kernel error, so that the fallback logic can work,
3213 * as the device-mapper is finicky around concurrent activations of the same volume */
3214 k = validate_signature_userspace(verity, root, flags);
3215 if (k < 0)
3216 return k;
3217 if (k == 0) {
3218 log_debug("Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
3219
3220 /* So if we had a signature and we're supposed to exclusively allow
3221 * signature-based activation, then return the error now */
3222 if (!FLAGS_SET(policy_flags, PARTITION_POLICY_VERITY))
3223 return r < 0 ? r : -EDESTADDRREQ;
3224
3225 log_debug("Activation of signed Verity volume without validating signature is permitted by policy. Continuing.");
3226 } else
3227 log_debug("Verity activation via userspace signature logic worked, activating by root hash.");
3228
3229 /* Otherwise let's see what signature-less activation results in. */
3230
3231 measure_signature = true;
3232
3233 } else if (!FLAGS_SET(policy_flags, PARTITION_POLICY_VERITY))
3234 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL),
3235 "No-signature activation of Verity volume not allowed by policy, refusing.");
3236 else
3237 measure_signature = false;
3238
3239 r = sym_crypt_activate_by_volume_key(
3240 cd,
3241 name,
3242 verity->root_hash.iov_base,
3243 verity->root_hash.iov_len,
3244 CRYPT_ACTIVATE_READONLY);
3245 if (r < 0)
3246 return log_debug_errno(r, "Activation of Verity via root hash failed: %m");
3247
3248 log_debug("Activation of Verity via root hash succeeded.");
3249
3250 done:
3251 (void) pcrextend_verity_now(
3252 name,
3253 &verity->root_hash,
3254 measure_signature ? &verity->root_hash_sig : NULL);
3255 return 0;
3256 }
3257
3258 static usec_t verity_timeout(void) {
3259 usec_t t = 100 * USEC_PER_MSEC;
3260 const char *e;
3261 int r;
3262
3263 /* On slower machines, like non-KVM vm, setting up device may take a long time.
3264 * Let's make the timeout configurable. */
3265
3266 e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
3267 if (!e)
3268 return t;
3269
3270 r = parse_sec(e, &t);
3271 if (r < 0)
3272 log_debug_errno(r,
3273 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
3274 "using the default timeout (%s).",
3275 FORMAT_TIMESPAN(t, USEC_PER_MSEC));
3276
3277 return t;
3278 }
3279
3280 static int verity_partition(
3281 DissectedImage *di,
3282 PartitionDesignator designator,
3283 DissectedPartition *m, /* data partition */
3284 DissectedPartition *v, /* verity partition */
3285 const char *root, /* The root to get user verity certs from (for a sysext) */
3286 const VeritySettings *verity,
3287 DissectImageFlags flags,
3288 PartitionPolicyFlags policy_flags,
3289 DecryptedImage *d) {
3290
3291 _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
3292 _cleanup_free_ char *node = NULL, *name = NULL;
3293 _cleanup_close_ int mount_node_fd = -EBADF;
3294 int r;
3295
3296 assert(di);
3297 assert(m);
3298 assert(v || (verity && verity->data_path));
3299
3300 if (!verity || !iovec_is_set(&verity->root_hash))
3301 return 0;
3302 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
3303 (verity->designator == designator)))
3304 return 0;
3305
3306 if (!m->found || !m->node || !m->fstype)
3307 return 0;
3308 if (!verity->data_path) {
3309 if (!v->found || !v->node || !v->fstype)
3310 return 0;
3311
3312 if (!streq(v->fstype, "DM_verity_hash"))
3313 return 0;
3314 }
3315
3316 if (!(policy_flags & (PARTITION_POLICY_VERITY|PARTITION_POLICY_SIGNED))) {
3317 log_debug("Attempted to unlock partition via Verity, but it's prohibited, skipping.");
3318 return 0;
3319 }
3320
3321 r = dlopen_cryptsetup(LOG_DEBUG);
3322 if (r < 0)
3323 return r;
3324
3325 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
3326 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
3327 _cleanup_free_ char *root_hash_encoded = NULL;
3328
3329 root_hash_encoded = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
3330 if (!root_hash_encoded)
3331 return -ENOMEM;
3332
3333 r = make_dm_name_and_node(root_hash_encoded, /* diskseq= */ 0, "-verity", &name, &node);
3334 } else
3335 r = make_dm_name_and_node_from_node(m->node, dissected_image_diskseq(di), "-verity", &name, &node);
3336 if (r < 0)
3337 return r;
3338
3339 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
3340 if (r < 0)
3341 return r;
3342
3343 cryptsetup_enable_logging(cd);
3344
3345 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
3346 if (r < 0)
3347 return r;
3348
3349 r = sym_crypt_set_data_device(cd, m->node);
3350 if (r < 0)
3351 return r;
3352
3353 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
3354 return -ENOMEM;
3355
3356 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
3357 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
3358 * retry a few times before giving up. */
3359 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
3360 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
3361 _cleanup_(crypt_freep) struct crypt_device *existing_cd = NULL;
3362 _cleanup_close_ int fd = -EBADF;
3363
3364 /* First, check if the device already exists. */
3365 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
3366 if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
3367 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
3368 if (fd >= 0)
3369 goto check; /* The device already exists. Let's check it. */
3370
3371 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
3372 r = do_crypt_activate_verity(cd, root, name, verity, flags, policy_flags);
3373 if (r >= 0)
3374 goto try_open; /* The device is activated. Let's open it. */
3375 /* libdevmapper can return EINVAL when the device is already in the activation stage.
3376 * There's no way to distinguish this situation from a genuine error due to invalid
3377 * parameters, so immediately fall back to activating the device with a unique name.
3378 * Improvements in libcrypsetup can ensure this never happens:
3379 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
3380 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
3381 break;
3382 /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
3383 * sharing is enabled. */
3384 if (r == -ENODEV && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
3385 goto try_again;
3386 if (!IN_SET(r,
3387 -EEXIST, /* Volume has already been opened and ready to be used. */
3388 -EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
3389 return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
3390
3391 check:
3392 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
3393 r = dm_deferred_remove_cancel(name);
3394 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
3395 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
3396 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
3397 if (IN_SET(r, -EBUSY, -ENXIO))
3398 goto try_again;
3399 if (r < 0)
3400 return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
3401
3402 restore_deferred_remove = strdup(name);
3403 if (!restore_deferred_remove)
3404 return log_oom_debug();
3405
3406 r = verity_can_reuse(verity, name, &existing_cd);
3407 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
3408 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
3409 break;
3410 if (IN_SET(r,
3411 -ENOENT, /* Removed?? */
3412 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
3413 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
3414 goto try_again;
3415 if (r < 0)
3416 return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
3417
3418 if (fd < 0) {
3419 /* devmapper might say that the device exists, but the devlink might not yet have been
3420 * created. Check and wait for the udev event in that case. */
3421 r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
3422 /* Fallback to activation with a unique device if it's taking too long */
3423 if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
3424 break;
3425 if (r < 0)
3426 return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
3427 }
3428
3429 try_open:
3430 if (fd < 0) {
3431 /* Now, the device is activated and devlink is created. Let's open it. */
3432 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
3433 if (fd < 0) {
3434 if (!ERRNO_IS_DEVICE_ABSENT(errno))
3435 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
3436
3437 /* The device has already been removed?? */
3438 goto try_again;
3439 }
3440 }
3441
3442 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
3443 restore_deferred_remove = mfree(restore_deferred_remove);
3444
3445 mount_node_fd = TAKE_FD(fd);
3446 if (existing_cd)
3447 crypt_free_and_replace(cd, existing_cd);
3448
3449 goto success;
3450
3451 try_again:
3452 /* Device is being removed by another process. Let's wait for a while. */
3453 (void) usleep_safe(2 * USEC_PER_MSEC);
3454 }
3455
3456 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
3457 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
3458 /* Before trying to activate with unique name, we need to free crypt_device object.
3459 * Otherwise, we get error from libcryptsetup like the following:
3460 * ------
3461 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
3462 * ------
3463 */
3464 sym_crypt_free(cd);
3465 cd = NULL;
3466 return verity_partition(
3467 di,
3468 designator,
3469 m,
3470 v,
3471 root,
3472 verity,
3473 flags & ~DISSECT_IMAGE_VERITY_SHARE,
3474 policy_flags,
3475 d);
3476 }
3477
3478 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
3479
3480 success:
3481 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
3482 .name = TAKE_PTR(name),
3483 .device = TAKE_PTR(cd),
3484 };
3485
3486 m->decrypted_node = TAKE_PTR(node);
3487 close_and_replace(m->mount_node_fd, mount_node_fd);
3488
3489 return 0;
3490 }
3491 #endif
3492
3493 int dissected_image_decrypt(
3494 DissectedImage *m,
3495 const char *root, /* The root to get user verity certs from (for a sysext) */
3496 const char *passphrase,
3497 const VeritySettings *verity,
3498 const ImagePolicy *policy,
3499 DissectImageFlags flags) {
3500
3501 #if HAVE_LIBCRYPTSETUP
3502 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
3503 #endif
3504 int r;
3505
3506 assert(m);
3507 assert(!verity || iovec_is_valid(&verity->root_hash));
3508 assert(!verity || iovec_is_valid(&verity->root_hash_sig));
3509
3510 /* Returns:
3511 *
3512 * = 0 → There was nothing to decrypt/setup
3513 * > 0 → Decrypted/setup successfully
3514 * -ENOKEY → dm-crypt: there's something to decrypt but no decryption key was supplied
3515 * -EKEYREJECTED → dm-crypt: Passed key was not correct
3516 * -EDESTADDRREQ → dm-verity: there's something to setup but no signature was supplied
3517 * -EBUSY → dm-verity: Generic Verity error (kernel is not very explanatory)
3518 * -ERFKILL → image policy not compatible with request
3519 * -EEXIST → DM device already exists under the specified name
3520 */
3521
3522 if (verity && iovec_is_set(&verity->root_hash) && verity->root_hash.iov_len < sizeof(sd_id128_t))
3523 return -EINVAL;
3524
3525 if (!m->encrypted && !m->verity_ready)
3526 return 0;
3527
3528 r = secure_getenv_bool("SYSTEMD_VERITY_SHARING");
3529 if (r >= 0)
3530 SET_FLAG(flags, DISSECT_IMAGE_VERITY_SHARE, r);
3531
3532 #if HAVE_LIBCRYPTSETUP
3533 r = decrypted_image_new(&d);
3534 if (r < 0)
3535 return r;
3536
3537 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
3538 DissectedPartition *p = m->partitions + i;
3539 PartitionDesignator k;
3540
3541 if (!p->found)
3542 continue;
3543
3544 PartitionPolicyFlags fl = image_policy_get_exhaustively(policy, i);
3545
3546 r = decrypt_partition(m, p, passphrase, flags, fl, d);
3547 if (r < 0)
3548 return r;
3549
3550 k = partition_verity_hash_of(i);
3551 if (k >= 0) {
3552 r = verity_partition(m, i, p, m->partitions + k, root, verity, flags, fl, d);
3553 if (r < 0)
3554 return r;
3555 }
3556
3557 if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
3558 r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, 0, UINT64_MAX, /* bool restrict_fstypes= */ true, &p->decrypted_fstype);
3559 if (r < 0 && r != -EUCLEAN)
3560 return r;
3561 }
3562 }
3563
3564 m->decrypted_image = TAKE_PTR(d);
3565 return 1;
3566 #else
3567 return -EOPNOTSUPP;
3568 #endif
3569 }
3570
3571 int dissected_image_decrypt_interactively(
3572 DissectedImage *m,
3573 const char *passphrase,
3574 const VeritySettings *verity,
3575 const ImagePolicy *image_policy,
3576 DissectImageFlags flags) {
3577
3578 _cleanup_strv_free_erase_ char **z = NULL;
3579 int n = 3, r;
3580
3581 if (passphrase)
3582 n--;
3583
3584 for (;;) {
3585 r = dissected_image_decrypt(m, /* root= */ NULL, passphrase, verity, image_policy, flags);
3586 if (r >= 0)
3587 return r;
3588 if (r == -EKEYREJECTED)
3589 log_error_errno(r, "Incorrect passphrase, try again!");
3590 else if (r == -EDESTADDRREQ)
3591 return log_error_errno(r, "Image lacks recognized signature.");
3592 else if (r == -ERFKILL)
3593 return log_error_errno(r, "Unlocking of Verity/LUKS volumes not permitted by policy.");
3594 else if (r != -ENOKEY)
3595 return log_error_errno(r, "Failed to decrypt/set up image: %m");
3596
3597 if (--n < 0)
3598 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
3599 "Too many retries.");
3600
3601 z = strv_free_erase(z);
3602
3603 static const AskPasswordRequest req = {
3604 .tty_fd = -EBADF,
3605 .message = "Please enter image passphrase:",
3606 .id = "dissect",
3607 .keyring = "dissect",
3608 .credential = "dissect.passphrase",
3609 .until = USEC_INFINITY,
3610 .hup_fd = -EBADF,
3611 };
3612
3613 r = ask_password_auto(&req, /* flags= */ 0, &z);
3614 if (r < 0)
3615 return log_error_errno(r, "Failed to query for passphrase: %m");
3616
3617 assert(!strv_isempty(z));
3618 passphrase = z[0];
3619 }
3620 }
3621
3622 static int decrypted_image_relinquish(DecryptedImage *d) {
3623 assert(d);
3624
3625 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
3626 * boolean so that we don't clean it up ourselves either anymore */
3627
3628 #if HAVE_LIBCRYPTSETUP
3629 int r;
3630
3631 for (size_t i = 0; i < d->n_decrypted; i++) {
3632 DecryptedPartition *p = d->decrypted + i;
3633
3634 if (p->relinquished)
3635 continue;
3636
3637 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
3638 if (r < 0)
3639 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
3640
3641 p->relinquished = true;
3642 }
3643 #endif
3644
3645 return 0;
3646 }
3647
3648 int dissected_image_relinquish(DissectedImage *m) {
3649 int r;
3650
3651 assert(m);
3652
3653 if (m->decrypted_image) {
3654 r = decrypted_image_relinquish(m->decrypted_image);
3655 if (r < 0)
3656 return r;
3657 }
3658
3659 if (m->loop)
3660 loop_device_relinquish(m->loop);
3661
3662 return 0;
3663 }
3664
3665 void image_filter_done(ImageFilter *f) {
3666 assert(f);
3667
3668 FOREACH_ELEMENT(p, f->pattern)
3669 *p = mfree(*p);
3670 }
3671
3672 ImageFilter *image_filter_free(ImageFilter *f) {
3673 if (!f)
3674 return NULL;
3675
3676 image_filter_done(f);
3677 return mfree(f);
3678 }
3679
3680 int image_filter_parse(const char *s, ImageFilter **ret) {
3681 _cleanup_(image_filter_freep) ImageFilter *f = NULL;
3682 int r;
3683
3684 if (isempty(s)) {
3685 if (ret)
3686 *ret = NULL;
3687 return 0;
3688 }
3689
3690 for (;;) {
3691 _cleanup_free_ char *word = NULL;
3692
3693 r = extract_first_word(&s, &word, ":", EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS);
3694 if (r < 0)
3695 return log_debug_errno(r, "Failed to extract word: %m");
3696 if (r == 0)
3697 break;
3698
3699 _cleanup_free_ char *designator = NULL, *pattern = NULL;
3700 const char *x = word;
3701 r = extract_many_words(&x, "=", EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS, &designator, &pattern);
3702 if (r < 0)
3703 return log_debug_errno(r, "Failed to extract designator: %m");
3704 if (r != 2 || !isempty(x))
3705 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to split: %s", word);
3706
3707 PartitionDesignator d = partition_designator_from_string(designator);
3708 if (d < 0)
3709 return log_debug_errno(d, "Failed to parse partition designator: %s", designator);
3710
3711 if (!f) {
3712 f = new0(ImageFilter, 1);
3713 if (!f)
3714 return log_oom_debug();
3715 } else if (f->pattern[d])
3716 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Duplicate pattern for '%s', refusing.", partition_designator_to_string(d));
3717
3718 f->pattern[d] = TAKE_PTR(pattern);
3719 }
3720
3721 if (ret)
3722 *ret = TAKE_PTR(f);
3723
3724 return 0;
3725 }
3726
3727 static char *build_auxiliary_path(const char *image, const char *suffix) {
3728 const char *e;
3729 char *n;
3730
3731 assert(image);
3732 assert(suffix);
3733
3734 e = endswith(image, ".raw");
3735 if (!e)
3736 return strjoin(image, suffix);
3737
3738 n = new(char, e - image + strlen(suffix) + 1);
3739 if (!n)
3740 return NULL;
3741
3742 strcpy(mempcpy(n, image, e - image), suffix);
3743 return n;
3744 }
3745
3746 void verity_settings_done(VeritySettings *v) {
3747 assert(v);
3748
3749 iovec_done(&v->root_hash);
3750 iovec_done(&v->root_hash_sig);
3751 v->data_path = mfree(v->data_path);
3752 }
3753
3754 VeritySettings* verity_settings_free(VeritySettings *v) {
3755 if (!v)
3756 return NULL;
3757
3758 verity_settings_done(v);
3759 return mfree(v);
3760 }
3761
3762 void verity_settings_hash_func(const VeritySettings *s, struct siphash *state) {
3763 assert(s);
3764
3765 siphash24_compress_typesafe(s->root_hash.iov_len, state);
3766 siphash24_compress(s->root_hash.iov_base, s->root_hash.iov_len, state);
3767 }
3768
3769 int verity_settings_compare_func(const VeritySettings *x, const VeritySettings *y) {
3770 assert(x);
3771 assert(y);
3772
3773 return iovec_memcmp(&x->root_hash, &y->root_hash);
3774 }
3775
3776 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(verity_settings_hash_ops, VeritySettings, verity_settings_hash_func, verity_settings_compare_func, VeritySettings, verity_settings_free);
3777
3778 int verity_settings_load(
3779 VeritySettings *verity,
3780 const char *image,
3781 const char *root_hash_path,
3782 const char *root_hash_sig_path) {
3783
3784 PartitionDesignator designator;
3785 int r;
3786
3787 assert(verity);
3788 assert(image);
3789 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
3790
3791 /* If we are asked to load the root hash for a device node, exit early */
3792 if (is_device_path(image))
3793 return 0;
3794
3795 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
3796 if (r < 0 && r != -ENXIO)
3797 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
3798 if (r == 0)
3799 return 0;
3800
3801 designator = verity->designator;
3802
3803 /* We only fill in what isn't already filled in */
3804
3805 _cleanup_(iovec_done) struct iovec root_hash = {};
3806 if (!iovec_is_set(&verity->root_hash)) {
3807 _cleanup_free_ char *text = NULL;
3808
3809 if (root_hash_path) {
3810 /* If explicitly specified it takes precedence */
3811 r = read_one_line_file(root_hash_path, &text);
3812 if (r < 0)
3813 return r;
3814
3815 if (designator < 0)
3816 designator = PARTITION_ROOT;
3817 } else {
3818 /* Otherwise look for xattr and separate file, and first for the data for root and if
3819 * that doesn't exist for /usr */
3820
3821 if (designator < 0 || designator == PARTITION_ROOT) {
3822 r = getxattr_malloc(image, "user.verity.roothash", &text, /* ret_size= */ NULL);
3823 if (r < 0) {
3824 _cleanup_free_ char *p = NULL;
3825
3826 if (!ERRNO_IS_XATTR_ABSENT(r))
3827 return r;
3828
3829 p = build_auxiliary_path(image, ".roothash");
3830 if (!p)
3831 return -ENOMEM;
3832
3833 r = read_one_line_file(p, &text);
3834 if (r < 0 && r != -ENOENT)
3835 return r;
3836 }
3837
3838 if (text)
3839 designator = PARTITION_ROOT;
3840 }
3841
3842 if (!text && (designator < 0 || designator == PARTITION_USR)) {
3843 /* So in the "roothash" xattr/file name above the "root" of course primarily
3844 * refers to the root of the Verity Merkle tree. But coincidentally it also
3845 * is the hash for the *root* file system, i.e. the "root" neatly refers to
3846 * two distinct concepts called "root". Taking benefit of this happy
3847 * coincidence we call the file with the root hash for the /usr/ file system
3848 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
3849 * confusing. We thus drop the reference to the root of the Merkle tree, and
3850 * just indicate which file system it's about. */
3851 r = getxattr_malloc(image, "user.verity.usrhash", &text, /* ret_size= */ NULL);
3852 if (r < 0) {
3853 _cleanup_free_ char *p = NULL;
3854
3855 if (!ERRNO_IS_XATTR_ABSENT(r))
3856 return r;
3857
3858 p = build_auxiliary_path(image, ".usrhash");
3859 if (!p)
3860 return -ENOMEM;
3861
3862 r = read_one_line_file(p, &text);
3863 if (r < 0 && r != -ENOENT)
3864 return r;
3865 }
3866
3867 if (text)
3868 designator = PARTITION_USR;
3869 }
3870 }
3871
3872 if (text) {
3873 r = unhexmem(text, &root_hash.iov_base, &root_hash.iov_len);
3874 if (r < 0)
3875 return r;
3876 if (root_hash.iov_len < sizeof(sd_id128_t))
3877 return -EINVAL;
3878 }
3879 }
3880
3881 _cleanup_(iovec_done) struct iovec root_hash_sig = {};
3882 if ((iovec_is_set(&root_hash) || iovec_is_set(&verity->root_hash)) && !iovec_is_set(&verity->root_hash_sig)) {
3883 if (root_hash_sig_path) {
3884 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig.iov_base, &root_hash_sig.iov_len);
3885 if (r < 0 && r != -ENOENT)
3886 return r;
3887
3888 if (r >= 0 && root_hash_sig.iov_len == 0) /* refuse empty size signatures */
3889 return -EINVAL;
3890
3891 if (designator < 0)
3892 designator = PARTITION_ROOT;
3893 } else {
3894 if (designator < 0 || designator == PARTITION_ROOT) {
3895 _cleanup_free_ char *p = NULL;
3896
3897 /* Follow naming convention recommended by the relevant RFC:
3898 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
3899 p = build_auxiliary_path(image, ".roothash.p7s");
3900 if (!p)
3901 return -ENOMEM;
3902
3903 r = read_full_file(p, (char**) &root_hash_sig.iov_base, &root_hash_sig.iov_len);
3904 if (r < 0 && r != -ENOENT)
3905 return r;
3906 if (r >= 0) {
3907 designator = PARTITION_ROOT;
3908 if (root_hash_sig.iov_len == 0) /* refuse empty size signatures */
3909 return -EINVAL;
3910 }
3911 }
3912
3913 if (!iovec_is_set(&root_hash_sig) && (designator < 0 || designator == PARTITION_USR)) {
3914 _cleanup_free_ char *p = NULL;
3915
3916 p = build_auxiliary_path(image, ".usrhash.p7s");
3917 if (!p)
3918 return -ENOMEM;
3919
3920 r = read_full_file(p, (char**) &root_hash_sig.iov_base, &root_hash_sig.iov_len);
3921 if (r < 0 && r != -ENOENT)
3922 return r;
3923 if (r >= 0) {
3924 designator = PARTITION_USR;
3925 if (root_hash_sig.iov_len == 0) /* refuse empty size signatures */
3926 return -EINVAL;
3927 }
3928 }
3929 }
3930 }
3931
3932 _cleanup_free_ char *verity_data_path = NULL;
3933 if (!verity->data_path) {
3934 _cleanup_free_ char *p = NULL;
3935
3936 p = build_auxiliary_path(image, ".verity");
3937 if (!p)
3938 return -ENOMEM;
3939
3940 if (access(p, F_OK) < 0) {
3941 if (errno != ENOENT)
3942 return -errno;
3943 } else
3944 verity_data_path = TAKE_PTR(p);
3945 }
3946
3947 if (iovec_is_set(&root_hash))
3948 verity->root_hash = TAKE_STRUCT(root_hash);
3949
3950 if (iovec_is_set(&root_hash_sig))
3951 verity->root_hash_sig = TAKE_STRUCT(root_hash_sig);
3952
3953 if (verity_data_path)
3954 verity->data_path = TAKE_PTR(verity_data_path);
3955
3956 if (verity->designator < 0)
3957 verity->designator = designator;
3958
3959 return 1;
3960 }
3961
3962 int verity_settings_copy(VeritySettings *dest, const VeritySettings *source) {
3963 assert(dest);
3964
3965 if (!source) {
3966 *dest = VERITY_SETTINGS_DEFAULT;
3967 return 0;
3968 }
3969
3970 _cleanup_(iovec_done) struct iovec rh = {};
3971 if (iovec_is_set(&source->root_hash)) {
3972 if (!iovec_memdup(&source->root_hash, &rh))
3973 return log_oom_debug();
3974 }
3975
3976 _cleanup_(iovec_done) struct iovec sig = {};
3977 if (iovec_is_set(&source->root_hash_sig)) {
3978 if (!iovec_memdup(&source->root_hash_sig, &sig))
3979 return log_oom_debug();
3980 }
3981
3982 _cleanup_free_ char *p = NULL;
3983 if (source->data_path) {
3984 p = strdup(source->data_path);
3985 if (!p)
3986 return log_oom_debug();
3987 }
3988
3989 *dest = (VeritySettings) {
3990 .root_hash = TAKE_STRUCT(rh),
3991 .root_hash_sig = TAKE_STRUCT(sig),
3992 .data_path = TAKE_PTR(p),
3993 .designator = source->designator,
3994 };
3995
3996 return 1;
3997 }
3998
3999 int dissected_image_load_verity_sig_partition(
4000 DissectedImage *m,
4001 int fd,
4002 VeritySettings *verity) {
4003
4004 int r;
4005
4006 assert(m);
4007 assert(fd >= 0);
4008 assert(verity);
4009
4010 if (iovec_is_set(&verity->root_hash) && iovec_is_set(&verity->root_hash_sig)) /* Already loaded? */
4011 return 0;
4012
4013 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_EMBEDDED");
4014 if (r < 0 && r != -ENXIO)
4015 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
4016 if (r == 0)
4017 return 0;
4018
4019 PartitionDesignator dd = verity->designator;
4020 if (dd < 0) {
4021 if (m->partitions[PARTITION_ROOT_VERITY].found)
4022 dd = PARTITION_ROOT;
4023 else if (m->partitions[PARTITION_USR_VERITY].found)
4024 dd = PARTITION_USR;
4025 else
4026 return 0;
4027 }
4028
4029 if (!m->partitions[dd].found)
4030 return 0;
4031
4032 PartitionDesignator dv = partition_verity_hash_of(dd);
4033 assert(dv >= 0);
4034 if (!m->partitions[dv].found)
4035 return 0;
4036
4037 PartitionDesignator ds = partition_verity_sig_of(dd);
4038 assert(ds >= 0);
4039
4040 DissectedPartition *p = m->partitions + ds;
4041 if (!p->found)
4042 return 0;
4043
4044 _cleanup_(iovec_done) struct iovec root_hash = {}, root_hash_sig = {};
4045 r = acquire_sig_for_roothash(
4046 fd,
4047 p->offset,
4048 p->size,
4049 &root_hash,
4050 &root_hash_sig);
4051 if (r < 0)
4052 return r;
4053
4054 /* Check if specified root hash matches if it is specified */
4055 if (iovec_is_set(&verity->root_hash) &&
4056 !iovec_equal(&verity->root_hash, &root_hash)) {
4057 _cleanup_free_ char *a = NULL, *b = NULL;
4058
4059 a = hexmem(root_hash.iov_base, root_hash.iov_len);
4060 b = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
4061
4062 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
4063 }
4064
4065 iovec_done(&verity->root_hash);
4066 verity->root_hash = TAKE_STRUCT(root_hash);
4067
4068 iovec_done(&verity->root_hash_sig);
4069 verity->root_hash_sig = TAKE_STRUCT(root_hash_sig);
4070
4071 verity->designator = dd;
4072
4073 m->verity_ready = true;
4074 m->verity_sig_ready = true;
4075 m->partitions[dd].rw = false;
4076
4077 return 1;
4078 }
4079
4080 int dissected_image_guess_verity_roothash(
4081 DissectedImage *m,
4082 VeritySettings *verity) {
4083
4084 int r;
4085
4086 assert(m);
4087 assert(verity);
4088
4089 /* Guesses the Verity root hash from the partitions we found, taking into account that as per
4090 * https://uapi-group.org/specifications/specs/discoverable_partitions_specification/ the UUIDS of
4091 * the data and verity partitions are respectively the first and second halves of the dm-verity
4092 * roothash.
4093 *
4094 * Note of course that relying on this guesswork is mostly useful for later attestation, not so much
4095 * for a-priori security. */
4096
4097 if (iovec_is_set(&verity->root_hash)) /* Already loaded? */
4098 return 0;
4099
4100 r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_GUESS");
4101 if (r < 0 && r != -ENXIO)
4102 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_GUESS, ignoring: %m");
4103 if (r == 0)
4104 return 0;
4105
4106 PartitionDesignator dd = verity->designator;
4107 if (dd < 0) {
4108 if (m->partitions[PARTITION_ROOT_VERITY].found)
4109 dd = PARTITION_ROOT;
4110 else if (m->partitions[PARTITION_USR_VERITY].found)
4111 dd = PARTITION_USR;
4112 else
4113 return 0;
4114 }
4115
4116 DissectedPartition *d = m->partitions + dd;
4117 if (!d->found)
4118 return 0;
4119
4120 PartitionDesignator dv = partition_verity_hash_of(dd);
4121 assert(dv >= 0);
4122
4123 DissectedPartition *p = m->partitions + dv;
4124 if (!p->found)
4125 return 0;
4126
4127 _cleanup_free_ void *rh = malloc(sizeof(sd_id128_t) * 2);
4128 if (!rh)
4129 return log_oom_debug();
4130
4131 memcpy(mempcpy(rh, &d->uuid, sizeof(sd_id128_t)), &p->uuid, sizeof(sd_id128_t));
4132 verity->root_hash = IOVEC_MAKE(TAKE_PTR(rh), sizeof(sd_id128_t) * 2);
4133
4134 verity->designator = dd;
4135
4136 m->verity_ready = true;
4137 m->partitions[dd].rw = false;
4138
4139 return 0;
4140 }
4141
4142 int dissected_image_acquire_metadata(
4143 DissectedImage *m,
4144 int userns_fd,
4145 DissectImageFlags extra_flags) {
4146
4147 enum {
4148 META_HOSTNAME,
4149 META_MACHINE_ID,
4150 META_MACHINE_INFO,
4151 META_OS_RELEASE,
4152 META_INITRD_RELEASE,
4153 META_SYSEXT_RELEASE,
4154 META_CONFEXT_RELEASE,
4155 META_HAS_INIT_SYSTEM,
4156 _META_MAX,
4157 };
4158
4159 static const char *const paths[_META_MAX] = {
4160 [META_HOSTNAME] = "/etc/hostname\0",
4161 [META_MACHINE_ID] = "/etc/machine-id\0",
4162 [META_MACHINE_INFO] = "/etc/machine-info\0",
4163 [META_OS_RELEASE] = "/etc/os-release\0"
4164 "/usr/lib/os-release\0",
4165 [META_INITRD_RELEASE] = "/etc/initrd-release\0"
4166 "/usr/lib/initrd-release\0",
4167 [META_SYSEXT_RELEASE] = "sysext-release\0", /* String used only for logging. */
4168 [META_CONFEXT_RELEASE] = "confext-release\0", /* ditto */
4169 [META_HAS_INIT_SYSTEM] = "has-init-system\0", /* ditto */
4170 };
4171
4172 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **initrd_release = NULL, **sysext_release = NULL, **confext_release = NULL;
4173 _cleanup_free_ char *hostname = NULL, *t = NULL;
4174 _cleanup_close_pair_ int error_pipe[2] = EBADF_PAIR;
4175 _cleanup_(pidref_done_sigkill_wait) PidRef child = PIDREF_NULL;
4176 sd_id128_t machine_id = SD_ID128_NULL;
4177 unsigned n_meta_initialized = 0;
4178 int fds[2 * _META_MAX], r, v;
4179 int has_init_system = -1;
4180 ssize_t n;
4181
4182 assert(m);
4183
4184 r = dlopen_libmount(LOG_DEBUG);
4185 if (r < 0)
4186 return r;
4187
4188 for (; n_meta_initialized < _META_MAX; n_meta_initialized++) {
4189 assert(paths[n_meta_initialized]);
4190
4191 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
4192 r = -errno;
4193 goto finish;
4194 }
4195 }
4196
4197 r = get_common_dissect_directory(&t);
4198 if (r < 0)
4199 goto finish;
4200
4201 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
4202 r = -errno;
4203 goto finish;
4204 }
4205
4206 r = pidref_safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM, &child);
4207 if (r < 0)
4208 goto finish;
4209 if (r == 0) {
4210 /* Child */
4211 error_pipe[0] = safe_close(error_pipe[0]);
4212
4213 if (userns_fd < 0)
4214 r = detach_mount_namespace_harder(0, 0);
4215 else
4216 r = detach_mount_namespace_userns(userns_fd);
4217 if (r < 0) {
4218 log_debug_errno(r, "Failed to detach mount namespace: %m");
4219 report_errno_and_exit(error_pipe[1], r);
4220 }
4221
4222 r = dissected_image_mount(
4223 m,
4224 t,
4225 /* uid_shift= */ UID_INVALID,
4226 /* uid_range= */ UID_INVALID,
4227 /* userns_fd= */ -EBADF,
4228 extra_flags |
4229 DISSECT_IMAGE_READ_ONLY |
4230 DISSECT_IMAGE_MOUNT_ROOT_ONLY |
4231 DISSECT_IMAGE_USR_NO_ROOT);
4232 if (r < 0) {
4233 log_debug_errno(r, "Failed to mount dissected image: %m");
4234 report_errno_and_exit(error_pipe[1], r);
4235 }
4236
4237 for (unsigned k = 0; k < _META_MAX; k++) {
4238 _cleanup_close_ int fd = -ENOENT;
4239
4240 assert(paths[k]);
4241
4242 fds[2*k] = safe_close(fds[2*k]);
4243
4244 switch (k) {
4245
4246 case META_SYSEXT_RELEASE:
4247 if (!m->image_name)
4248 goto next;
4249
4250 /* As per the os-release spec, if the image is an extension it will have a
4251 * file named after the image name in extension-release.d/ - we use the image
4252 * name and try to resolve it with the extension-release helpers, as
4253 * sometimes the image names are mangled on deployment and do not match
4254 * anymore. Unlike other paths this is not fixed, and the image name can be
4255 * mangled on deployment, so by calling into the helper we allow a fallback
4256 * that matches on the first extension-release file found in the directory,
4257 * if one named after the image cannot be found first. */
4258 r = open_extension_release(
4259 t,
4260 IMAGE_SYSEXT,
4261 m->image_name,
4262 /* relax_extension_release_check= */ false,
4263 /* ret_path= */ NULL,
4264 &fd);
4265 if (r < 0)
4266 fd = r;
4267 break;
4268
4269 case META_CONFEXT_RELEASE:
4270 if (!m->image_name)
4271 goto next;
4272
4273 /* As above */
4274 r = open_extension_release(
4275 t,
4276 IMAGE_CONFEXT,
4277 m->image_name,
4278 /* relax_extension_release_check= */ false,
4279 /* ret_path= */ NULL,
4280 &fd);
4281 if (r < 0)
4282 fd = r;
4283
4284 break;
4285
4286 case META_HAS_INIT_SYSTEM: {
4287 bool found = false;
4288
4289 FOREACH_STRING(init,
4290 "/usr/lib/systemd/systemd", /* systemd on /usr/ merged system */
4291 "/lib/systemd/systemd", /* systemd on /usr/ non-merged systems */
4292 "/sbin/init") { /* traditional path the Linux kernel invokes */
4293
4294 r = chase(init, t, CHASE_PREFIX_ROOT, NULL, NULL);
4295 if (r < 0) {
4296 if (r != -ENOENT)
4297 log_debug_errno(r, "Failed to resolve %s, ignoring: %m", init);
4298 } else {
4299 found = true;
4300 break;
4301 }
4302 }
4303
4304 r = loop_write(fds[2*k+1], &found, sizeof(found));
4305 if (r < 0)
4306 report_errno_and_exit(error_pipe[1], r);
4307
4308 goto next;
4309 }
4310
4311 default:
4312 NULSTR_FOREACH(p, paths[k]) {
4313 fd = chase_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
4314 if (fd >= 0)
4315 break;
4316 }
4317 }
4318
4319 if (fd < 0) {
4320 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
4321 goto next;
4322 }
4323
4324 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
4325 if (r < 0)
4326 report_errno_and_exit(error_pipe[1], r);
4327
4328 next:
4329 fds[2*k+1] = safe_close(fds[2*k+1]);
4330 }
4331
4332 _exit(EXIT_SUCCESS);
4333 }
4334
4335 error_pipe[1] = safe_close(error_pipe[1]);
4336
4337 for (unsigned k = 0; k < _META_MAX; k++) {
4338 _cleanup_fclose_ FILE *f = NULL;
4339
4340 assert(paths[k]);
4341
4342 fds[2*k+1] = safe_close(fds[2*k+1]);
4343
4344 f = take_fdopen(&fds[2*k], "r");
4345 if (!f) {
4346 r = -errno;
4347 goto finish;
4348 }
4349
4350 switch (k) {
4351
4352 case META_HOSTNAME:
4353 r = read_etc_hostname_stream(f, /* substitute_wildcards= */ false, &hostname);
4354 if (r < 0)
4355 log_debug_errno(r, "Failed to read /etc/hostname of image: %m");
4356
4357 break;
4358
4359 case META_MACHINE_ID: {
4360 _cleanup_free_ char *line = NULL;
4361
4362 r = read_line(f, LONG_LINE_MAX, &line);
4363 if (r < 0)
4364 log_debug_errno(r, "Failed to read /etc/machine-id of image: %m");
4365 else if (r == 33) {
4366 r = sd_id128_from_string(line, &machine_id);
4367 if (r < 0)
4368 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
4369 } else if (r == 0)
4370 log_debug("/etc/machine-id file of image is empty.");
4371 else if (streq(line, "uninitialized"))
4372 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
4373 else
4374 log_debug("/etc/machine-id file of image has unexpected length %i.", r);
4375
4376 break;
4377 }
4378
4379 case META_MACHINE_INFO:
4380 r = load_env_file_pairs(f, "machine-info", &machine_info);
4381 if (r < 0)
4382 log_debug_errno(r, "Failed to read /etc/machine-info of image: %m");
4383
4384 break;
4385
4386 case META_OS_RELEASE:
4387 r = load_env_file_pairs(f, "os-release", &os_release);
4388 if (r < 0)
4389 log_debug_errno(r, "Failed to read OS release file of image: %m");
4390
4391 break;
4392
4393 case META_INITRD_RELEASE:
4394 r = load_env_file_pairs(f, "initrd-release", &initrd_release);
4395 if (r < 0)
4396 log_debug_errno(r, "Failed to read initrd release file of image: %m");
4397
4398 break;
4399
4400 case META_SYSEXT_RELEASE:
4401 r = load_env_file_pairs(f, "sysext-release", &sysext_release);
4402 if (r < 0)
4403 log_debug_errno(r, "Failed to read sysext release file of image: %m");
4404
4405 break;
4406
4407 case META_CONFEXT_RELEASE:
4408 r = load_env_file_pairs(f, "confext-release", &confext_release);
4409 if (r < 0)
4410 log_debug_errno(r, "Failed to read confext release file of image: %m");
4411
4412 break;
4413
4414 case META_HAS_INIT_SYSTEM: {
4415 bool b = false;
4416 size_t nr;
4417
4418 errno = 0;
4419 nr = fread(&b, 1, sizeof(b), f);
4420 if (nr != sizeof(b))
4421 log_debug_errno(errno_or_else(EIO), "Failed to read has-init-system boolean: %m");
4422 else
4423 has_init_system = b;
4424
4425 break;
4426 }}
4427 }
4428
4429 r = pidref_wait_for_terminate_and_check("(sd-dissect)", &child, 0);
4430 if (r < 0)
4431 goto finish;
4432
4433 pidref_done(&child);
4434
4435 n = read(error_pipe[0], &v, sizeof(v));
4436 if (n < 0) {
4437 r = -errno;
4438 goto finish;
4439 }
4440 if (n == sizeof(v)) {
4441 r = v; /* propagate error sent to us from child */
4442 goto finish;
4443 }
4444 if (n != 0) {
4445 r = -EIO;
4446 goto finish;
4447 }
4448 if (r != EXIT_SUCCESS) {
4449 r = -EPROTO;
4450 goto finish;
4451 }
4452
4453 free_and_replace(m->hostname, hostname);
4454 m->machine_id = machine_id;
4455 strv_free_and_replace(m->machine_info, machine_info);
4456 strv_free_and_replace(m->os_release, os_release);
4457 strv_free_and_replace(m->initrd_release, initrd_release);
4458 strv_free_and_replace(m->sysext_release, sysext_release);
4459 strv_free_and_replace(m->confext_release, confext_release);
4460 m->has_init_system = has_init_system;
4461
4462 finish:
4463 for (unsigned k = 0; k < n_meta_initialized; k++)
4464 safe_close_pair(fds + 2*k);
4465
4466 return r;
4467 }
4468
4469 Architecture dissected_image_architecture(DissectedImage *m) {
4470 assert(m);
4471
4472 if (m->partitions[PARTITION_ROOT].found &&
4473 m->partitions[PARTITION_ROOT].architecture >= 0)
4474 return m->partitions[PARTITION_ROOT].architecture;
4475
4476 if (m->partitions[PARTITION_USR].found &&
4477 m->partitions[PARTITION_USR].architecture >= 0)
4478 return m->partitions[PARTITION_USR].architecture;
4479
4480 return _ARCHITECTURE_INVALID;
4481 }
4482
4483 bool dissected_image_is_portable(DissectedImage *m) {
4484 return m && (strv_env_pairs_get(m->os_release, "PORTABLE_PREFIXES") || strv_env_pairs_get(m->os_release, "PORTABLE_SCOPE"));
4485 }
4486
4487 bool dissected_image_is_initrd(DissectedImage *m) {
4488 return m && !strv_isempty(m->initrd_release);
4489 }
4490
4491 int dissect_loop_device(
4492 LoopDevice *loop,
4493 const VeritySettings *verity,
4494 const MountOptions *mount_options,
4495 const ImagePolicy *image_policy,
4496 const ImageFilter *image_filter,
4497 DissectImageFlags flags,
4498 DissectedImage **ret) {
4499
4500 #if HAVE_BLKID
4501 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
4502 int r;
4503
4504 assert(loop);
4505
4506 r = dissected_image_new(loop->backing_file ?: loop->node, &m);
4507 if (r < 0)
4508 return r;
4509
4510 m->loop = loop_device_ref(loop);
4511 m->image_size = m->loop->device_size;
4512 m->sector_size = m->loop->sector_size;
4513
4514 r = dissect_image(
4515 m,
4516 loop->fd,
4517 loop->node,
4518 verity,
4519 mount_options,
4520 image_policy,
4521 image_filter,
4522 flags);
4523 if (r < 0)
4524 return r;
4525
4526 if (ret)
4527 *ret = TAKE_PTR(m);
4528
4529 return 0;
4530 #else
4531 return -EOPNOTSUPP;
4532 #endif
4533 }
4534
4535 int dissect_loop_device_and_warn(
4536 LoopDevice *loop,
4537 const VeritySettings *verity,
4538 const MountOptions *mount_options,
4539 const ImagePolicy *image_policy,
4540 const ImageFilter *image_filter,
4541 DissectImageFlags flags,
4542 DissectedImage **ret) {
4543
4544 assert(loop);
4545
4546 return dissect_log_error(
4547 LOG_ERR,
4548 dissect_loop_device(loop, verity, mount_options, image_policy, image_filter, flags, ret),
4549 loop->backing_file ?: loop->node,
4550 verity);
4551 }
4552
4553 bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
4554 assert(image);
4555
4556 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
4557 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
4558 * images we only check the partition type.
4559 *
4560 * This call is used to decide whether to suppress or show a verity column in tabular output of the
4561 * image. */
4562
4563 if (image->single_file_system)
4564 return partition_designator == PARTITION_ROOT && image->has_verity;
4565
4566 return partition_verity_hash_of(partition_designator) >= 0;
4567 }
4568
4569 bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
4570 PartitionDesignator k;
4571
4572 assert(image);
4573
4574 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
4575 * works for the root partition, for others only if the associated verity partition was found. */
4576
4577 if (!image->verity_ready)
4578 return false;
4579
4580 if (image->single_file_system)
4581 return partition_designator == PARTITION_ROOT;
4582
4583 k = partition_verity_hash_of(partition_designator);
4584 return k >= 0 && image->partitions[k].found;
4585 }
4586
4587 bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
4588 PartitionDesignator k;
4589
4590 assert(image);
4591
4592 /* Checks if this partition has verity signature data available that we can use. */
4593
4594 if (!image->verity_sig_ready)
4595 return false;
4596
4597 if (image->single_file_system)
4598 return partition_designator == PARTITION_ROOT;
4599
4600 k = partition_verity_sig_of(partition_designator);
4601 return k >= 0 && image->partitions[k].found;
4602 }
4603
4604 int mount_options_set_and_consume(MountOptions **options, PartitionDesignator d, char *s) {
4605 assert(options);
4606 assert(d >= 0);
4607
4608 if (!*options) {
4609 *options = new0(MountOptions, 1);
4610 if (!*options) {
4611 free(s);
4612 return log_oom();
4613 }
4614 }
4615
4616 return free_and_replace((*options)->options[d], s);
4617 }
4618
4619 int mount_options_dup(const MountOptions *source, MountOptions **ret) {
4620 _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
4621
4622 assert(source);
4623 assert(ret);
4624
4625 options = new0(MountOptions, 1);
4626 if (!options)
4627 return log_oom_debug();
4628
4629 for (PartitionDesignator d = 0; d < _PARTITION_DESIGNATOR_MAX; d++)
4630 if (source->options[d]) {
4631 options->options[d] = strdup(source->options[d]);
4632 if (!options->options[d])
4633 return log_oom_debug();
4634 }
4635
4636 *ret = TAKE_PTR(options);
4637 return 0;
4638 }
4639
4640 int mount_options_to_string(const MountOptions *mount_options, char **ret) {
4641 _cleanup_free_ char *s = NULL;
4642
4643 assert(mount_options);
4644 assert(ret);
4645
4646 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
4647 if (!isempty(mount_options->options[i]))
4648 if (!strextend_with_separator(&s, ":", "%s:%s",
4649 partition_designator_to_string(i),
4650 mount_options->options[i]))
4651 return log_oom_debug();
4652
4653 *ret = TAKE_PTR(s);
4654
4655 return 0;
4656 }
4657
4658 MountOptions* mount_options_free_all(MountOptions *options) {
4659 if (!options)
4660 return NULL;
4661
4662 free_many_charp(options->options, _PARTITION_DESIGNATOR_MAX);
4663
4664 return mfree(options);
4665 }
4666
4667 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
4668 assert(designator >= 0 && designator < _PARTITION_DESIGNATOR_MAX);
4669
4670 if (!options)
4671 return NULL;
4672
4673 return options->options[designator];
4674 }
4675
4676 int mount_image_privately_interactively(
4677 const char *image,
4678 const ImagePolicy *image_policy,
4679 DissectImageFlags flags,
4680 char **ret_directory,
4681 int *ret_dir_fd,
4682 LoopDevice **ret_loop_device) {
4683
4684 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
4685 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
4686 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
4687 _cleanup_free_ char *dir = NULL;
4688 int r;
4689
4690 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
4691 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
4692 * easily. */
4693
4694 assert(image);
4695 assert(ret_loop_device);
4696
4697 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
4698 flags |= DISSECT_IMAGE_ADD_PARTITION_DEVICES |
4699 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
4700
4701 r = verity_settings_load(&verity, image, NULL, NULL);
4702 if (r < 0)
4703 return log_error_errno(r, "Failed to load root hash data: %m");
4704
4705 r = loop_device_make_by_path(
4706 image,
4707 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : -1,
4708 /* sector_size= */ UINT32_MAX,
4709 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
4710 LOCK_SH,
4711 &d);
4712 if (r < 0)
4713 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
4714
4715 r = dissect_loop_device_and_warn(
4716 d,
4717 &verity,
4718 /* mount_options= */ NULL,
4719 image_policy,
4720 /* image_filter= */ NULL,
4721 flags,
4722 &dissected_image);
4723 if (r < 0)
4724 return r;
4725
4726 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
4727 if (r < 0)
4728 return r;
4729
4730 r = dissected_image_guess_verity_roothash(dissected_image, &verity);
4731 if (r < 0)
4732 return r;
4733
4734 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, image_policy, flags);
4735 if (r < 0)
4736 return r;
4737
4738 r = detach_mount_namespace();
4739 if (r < 0)
4740 return log_error_errno(r, "Failed to detach mount namespace: %m");
4741
4742 r = mkdir_p("/run/systemd/mount-rootfs", 0555);
4743 if (r < 0)
4744 return log_error_errno(r, "Failed to create mount point: %m");
4745
4746 r = dissected_image_mount_and_warn(
4747 dissected_image,
4748 "/run/systemd/mount-rootfs",
4749 /* uid_shift= */ UID_INVALID,
4750 /* uid_range= */ UID_INVALID,
4751 /* userns_fd= */ -EBADF,
4752 flags);
4753 if (r < 0)
4754 return r;
4755
4756 r = loop_device_flock(d, LOCK_UN);
4757 if (r < 0)
4758 return r;
4759
4760 r = dissected_image_relinquish(dissected_image);
4761 if (r < 0)
4762 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
4763
4764 if (ret_directory) {
4765 dir = strdup("/run/systemd/mount-rootfs");
4766 if (!dir)
4767 return log_oom();
4768 }
4769
4770 if (ret_dir_fd) {
4771 _cleanup_close_ int dir_fd = -EBADF;
4772
4773 dir_fd = open("/run/systemd/mount-rootfs", O_CLOEXEC|O_DIRECTORY);
4774 if (dir_fd < 0)
4775 return log_error_errno(errno, "Failed to open mount point directory: %m");
4776
4777 *ret_dir_fd = TAKE_FD(dir_fd);
4778 }
4779
4780 if (ret_directory)
4781 *ret_directory = TAKE_PTR(dir);
4782
4783 *ret_loop_device = TAKE_PTR(d);
4784 return 0;
4785 }
4786
4787 static bool mount_options_relax_extension_release_checks(const MountOptions *options) {
4788 if (!options)
4789 return false;
4790
4791 return string_contains_word(mount_options_from_designator(options, PARTITION_ROOT), ",", "x-systemd.relax-extension-release-check") ||
4792 string_contains_word(mount_options_from_designator(options, PARTITION_USR), ",", "x-systemd.relax-extension-release-check");
4793 }
4794
4795 int verity_dissect_and_mount(
4796 int src_fd,
4797 const char *src,
4798 const char *dest,
4799 const MountOptions *options,
4800 const ImagePolicy *image_policy,
4801 const ImageFilter *image_filter,
4802 const ExtensionReleaseData *extension_release_data,
4803 ImageClass required_class,
4804 VeritySettings *verity,
4805 RuntimeScope runtime_scope,
4806 DissectedImage **ret_image) {
4807
4808 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
4809 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
4810 _cleanup_(verity_settings_done) VeritySettings local_verity = VERITY_SETTINGS_DEFAULT;
4811 _cleanup_close_ int userns_fd = -EBADF;
4812 DissectImageFlags dissect_image_flags;
4813 bool relax_extension_release_check;
4814 int r;
4815
4816 assert(src);
4817 /* Verifying release metadata requires mounted image for now, so ensure the check is skipped when
4818 * opening an image without mounting it immediately (i.e.: 'dest' is NULL). */
4819 assert(!extension_release_data || dest);
4820
4821 relax_extension_release_check = mount_options_relax_extension_release_checks(options);
4822
4823 /* We might get an FD for the image, but we use the original path to look for the dm-verity files.
4824 * The caller might also give us a pre-loaded VeritySettings, in which case we just use it. It will
4825 * also be extended, as dissected_image_load_verity_sig_partition() is invoked. */
4826 if (!verity) {
4827 r = verity_settings_load(&local_verity, src, NULL, NULL);
4828 if (r < 0)
4829 return log_debug_errno(r, "Failed to load root hash: %m");
4830
4831 verity = &local_verity;
4832 }
4833
4834 dissect_image_flags =
4835 (verity->data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0) |
4836 (relax_extension_release_check ? DISSECT_IMAGE_RELAX_EXTENSION_CHECK : 0) |
4837 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
4838 DISSECT_IMAGE_PIN_PARTITION_DEVICES |
4839 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY |
4840 DISSECT_IMAGE_VERITY_SHARE;
4841
4842 /* First check if we have a verity device already open and with a fstype pinned by policy. If it
4843 * cannot be found, then fallback to the slow path (full dissect). */
4844 r = dissected_image_new_from_existing_verity(
4845 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4846 verity,
4847 options,
4848 image_policy,
4849 image_filter,
4850 runtime_scope,
4851 dissect_image_flags,
4852 &dissected_image);
4853 if (r < 0 && !ERRNO_IS_NEG_DEVICE_ABSENT(r) && r != -ENOPKG)
4854 return r;
4855 if (r >= 0)
4856 log_debug("Reusing pre-existing verity-protected image %s", src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src);
4857 else {
4858 if (runtime_scope == RUNTIME_SCOPE_SYSTEM) {
4859 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
4860 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4861 r = loop_device_make_by_path(
4862 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4863 /* open_flags= */ -1,
4864 /* sector_size= */ UINT32_MAX,
4865 verity->data_path ? 0 : LO_FLAGS_PARTSCAN,
4866 LOCK_SH,
4867 &loop_device);
4868 if (r < 0)
4869 return log_debug_errno(r, "Failed to create loop device for image: %m");
4870
4871 r = dissect_loop_device(
4872 loop_device,
4873 verity,
4874 options,
4875 image_policy,
4876 image_filter,
4877 dissect_image_flags,
4878 &dissected_image);
4879 /* No partition table? Might be a single-filesystem image, try again */
4880 if (!verity->data_path && r == -ENOPKG)
4881 r = dissect_loop_device(
4882 loop_device,
4883 verity,
4884 options,
4885 image_policy,
4886 image_filter,
4887 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
4888 &dissected_image);
4889 if (r < 0)
4890 return log_debug_errno(r, "Failed to dissect image: %m");
4891
4892 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, verity);
4893 if (r < 0)
4894 return r;
4895
4896 r = dissected_image_guess_verity_roothash(dissected_image, verity);
4897 if (r < 0)
4898 return r;
4899
4900 r = dissected_image_decrypt(
4901 dissected_image,
4902 /* root= */ NULL,
4903 /* passphrase= */ NULL,
4904 verity,
4905 image_policy,
4906 dissect_image_flags);
4907 if (r < 0)
4908 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
4909 } else {
4910 userns_fd = namespace_open_by_type(NAMESPACE_USER);
4911 if (userns_fd < 0)
4912 return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
4913
4914 r = mountfsd_mount_image(
4915 /* vl= */ NULL,
4916 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
4917 userns_fd,
4918 options,
4919 image_policy,
4920 verity,
4921 dissect_image_flags,
4922 &dissected_image);
4923 if (r < 0)
4924 return r;
4925 }
4926 }
4927
4928 if (dest) {
4929 r = mkdir_p_label(dest, 0755);
4930 if (r < 0)
4931 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
4932 r = umount_recursive(dest, 0);
4933 if (r < 0)
4934 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
4935 }
4936
4937 r = dissected_image_mount(
4938 dissected_image,
4939 dest,
4940 /* uid_shift= */ UID_INVALID,
4941 /* uid_range= */ UID_INVALID,
4942 userns_fd,
4943 dissect_image_flags);
4944 if (r < 0)
4945 return log_debug_errno(r, "Failed to mount image: %m");
4946
4947 if (loop_device) {
4948 r = loop_device_flock(loop_device, LOCK_UN);
4949 if (r < 0)
4950 return log_debug_errno(r, "Failed to unlock loopback device: %m");
4951 }
4952
4953 /* If we got os-release values from the caller, then we need to match them with the image's
4954 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
4955 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
4956 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
4957 * then a simple match on the ID will be performed. Also if an extension class was specified,
4958 * check that it matches or return ENOCSI (which looks like error-no-class if one squints enough). */
4959 if ((extension_release_data && extension_release_data->os_release_id) || required_class >= 0) {
4960 _cleanup_strv_free_ char **extension_release = NULL;
4961 ImageClass class = IMAGE_SYSEXT;
4962
4963 r = load_extension_release_pairs(dest, required_class >= 0 ? required_class : IMAGE_SYSEXT, dissected_image->image_name, relax_extension_release_check, &extension_release);
4964 if (r == -ENOENT) {
4965 if (required_class >= 0)
4966 return log_debug_errno(SYNTHETIC_ERRNO(ENOCSI), "Image %s extension-release metadata does not match the expected class", dissected_image->image_name);
4967
4968 r = load_extension_release_pairs(dest, IMAGE_CONFEXT, dissected_image->image_name, relax_extension_release_check, &extension_release);
4969 if (r >= 0)
4970 class = IMAGE_CONFEXT;
4971 }
4972 if (r < 0)
4973 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
4974
4975 if (extension_release_data && !isempty(extension_release_data->os_release_id)) {
4976 r = extension_release_validate(
4977 dissected_image->image_name,
4978 extension_release_data->os_release_id,
4979 extension_release_data->os_release_id_like,
4980 extension_release_data->os_release_version_id,
4981 class == IMAGE_SYSEXT ? extension_release_data->os_release_sysext_level : extension_release_data->os_release_confext_level,
4982 extension_release_data->os_release_extension_scope,
4983 extension_release,
4984 class);
4985 if (r == 0)
4986 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
4987 if (r < 0)
4988 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
4989 }
4990 }
4991
4992 r = dissected_image_relinquish(dissected_image);
4993 if (r < 0)
4994 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
4995
4996 if (ret_image)
4997 *ret_image = TAKE_PTR(dissected_image);
4998
4999 return 0;
5000 }
5001
5002 void extension_release_data_done(ExtensionReleaseData *data) {
5003 assert(data);
5004
5005 data->os_release_id = mfree(data->os_release_id);
5006 data->os_release_id_like = mfree(data->os_release_id_like);
5007 data->os_release_version_id = mfree(data->os_release_version_id);
5008 data->os_release_sysext_level = mfree(data->os_release_sysext_level);
5009 data->os_release_confext_level = mfree(data->os_release_confext_level);
5010 data->os_release_extension_scope = mfree(data->os_release_extension_scope);
5011 }
5012
5013 int get_common_dissect_directory(char **ret) {
5014 _cleanup_free_ char *t = NULL;
5015 int r;
5016
5017 /* A common location we mount dissected images to. The assumption is that everyone who uses this
5018 * function runs in their own private mount namespace (with mount propagation off on /run/systemd/,
5019 * and thus can mount something here without affecting anyone else). */
5020
5021 t = strdup("/run/systemd/dissect-root");
5022 if (!t)
5023 return log_oom_debug();
5024
5025 r = mkdir_parents(t, 0755);
5026 if (r < 0)
5027 return log_debug_errno(r, "Failed to create parent dirs of mount point '%s': %m", t);
5028
5029 r = RET_NERRNO(mkdir(t, 0000)); /* It's supposed to be overmounted, hence let's make this inaccessible */
5030 if (r < 0 && r != -EEXIST)
5031 return log_debug_errno(r, "Failed to create mount point '%s': %m", t);
5032
5033 if (ret)
5034 *ret = TAKE_PTR(t);
5035
5036 return 0;
5037 }
5038
5039 #if HAVE_BLKID
5040
5041 static JSON_DISPATCH_ENUM_DEFINE(dispatch_architecture, Architecture, architecture_from_string);
5042 static JSON_DISPATCH_ENUM_DEFINE(dispatch_partition_designator, PartitionDesignator, partition_designator_from_string);
5043
5044 typedef struct PartitionFields {
5045 PartitionDesignator designator;
5046 bool rw;
5047 bool growfs;
5048 unsigned partno;
5049 Architecture architecture;
5050 sd_id128_t uuid;
5051 char *fstype;
5052 char *label;
5053 uint64_t size;
5054 uint64_t offset;
5055 unsigned fsmount_fd_idx;
5056 } PartitionFields;
5057
5058 static void partition_fields_done(PartitionFields *f) {
5059 assert(f);
5060
5061 f->fstype = mfree(f->fstype);
5062 f->label = mfree(f->label);
5063 }
5064
5065 typedef struct MountImageReplyParameters {
5066 sd_json_variant *partitions;
5067 bool single_file_system;
5068 char *image_policy;
5069 uint64_t image_size;
5070 uint32_t sector_size;
5071 sd_id128_t image_uuid;
5072 } MountImageReplyParameters;
5073
5074 static void mount_image_reply_parameters_done(MountImageReplyParameters *p) {
5075 assert(p);
5076
5077 p->image_policy = mfree(p->image_policy);
5078 p->partitions = sd_json_variant_unref(p->partitions);
5079 }
5080
5081 #endif
5082
5083 int mountfsd_connect(sd_varlink **ret) {
5084 int r;
5085
5086 assert(ret);
5087
5088 _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
5089 r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.MountFileSystem");
5090 if (r < 0)
5091 return log_debug_errno(r, "Failed to connect to mountfsd: %m");
5092
5093 r = sd_varlink_set_allow_fd_passing_input(vl, true);
5094 if (r < 0)
5095 return log_debug_errno(r, "Failed to enable varlink fd passing for read: %m");
5096
5097 r = sd_varlink_set_allow_fd_passing_output(vl, true);
5098 if (r < 0)
5099 return log_debug_errno(r, "Failed to enable varlink fd passing for write: %m");
5100
5101 *ret = TAKE_PTR(vl);
5102 return 0;
5103 }
5104
5105 int mountfsd_mount_image_fd(
5106 sd_varlink *vl,
5107 int image_fd,
5108 int userns_fd,
5109 const MountOptions *options,
5110 const ImagePolicy *image_policy,
5111 const VeritySettings *verity,
5112 DissectImageFlags flags,
5113 DissectedImage **ret) {
5114
5115 #if HAVE_BLKID
5116 _cleanup_(mount_image_reply_parameters_done) MountImageReplyParameters p = {};
5117
5118 static const sd_json_dispatch_field dispatch_table[] = {
5119 { "partitions", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_variant, offsetof(struct MountImageReplyParameters, partitions), SD_JSON_MANDATORY },
5120 { "singleFileSystem", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(struct MountImageReplyParameters, single_file_system), 0 },
5121 { "imagePolicy", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(struct MountImageReplyParameters, image_policy), 0 },
5122 { "imageSize", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(struct MountImageReplyParameters, image_size), SD_JSON_MANDATORY },
5123 { "sectorSize", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(struct MountImageReplyParameters, sector_size), SD_JSON_MANDATORY },
5124 { "imageUuid", SD_JSON_VARIANT_STRING, sd_json_dispatch_id128, offsetof(struct MountImageReplyParameters, image_uuid), 0 },
5125 {}
5126 };
5127
5128 _cleanup_(dissected_image_unrefp) DissectedImage *di = NULL;
5129 _cleanup_close_ int verity_data_fd = -EBADF;
5130 _cleanup_free_ char *ps = NULL;
5131 const char *error_id;
5132 int r;
5133
5134 assert(image_fd >= 0);
5135 assert(ret);
5136
5137 _cleanup_(sd_varlink_unrefp) sd_varlink *_vl = NULL;
5138 if (!vl) {
5139 r = mountfsd_connect(&_vl);
5140 if (r < 0)
5141 return r;
5142
5143 vl = _vl;
5144 }
5145
5146 _cleanup_close_ int reopened_fd = -EBADF;
5147
5148 image_fd = fd_reopen_condition(image_fd, O_CLOEXEC|O_NOCTTY|O_NONBLOCK|(FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_READ_ONLY) ? O_RDONLY : O_RDWR), O_PATH, &reopened_fd);
5149 if (image_fd < 0)
5150 return log_debug_errno(image_fd, "Failed to reopen fd: %m");
5151
5152 r = sd_varlink_push_dup_fd(vl, image_fd);
5153 if (r < 0)
5154 return log_debug_errno(r, "Failed to push image fd into varlink connection: %m");
5155
5156 if (userns_fd >= 0) {
5157 r = sd_varlink_push_dup_fd(vl, userns_fd);
5158 if (r < 0)
5159 return log_debug_errno(r, "Failed to push image fd into varlink connection: %m");
5160 }
5161
5162 if (image_policy) {
5163 r = image_policy_to_string(image_policy, /* simplify= */ false, &ps);
5164 if (r < 0)
5165 return log_debug_errno(r, "Failed to format image policy to string: %m");
5166 }
5167
5168 if (verity && verity->data_path) {
5169 verity_data_fd = open(verity->data_path, O_RDONLY|O_CLOEXEC);
5170 if (verity_data_fd < 0)
5171 return log_debug_errno(errno, "Failed to open verity data file '%s': %m", verity->data_path);
5172
5173 r = sd_varlink_push_dup_fd(vl, verity_data_fd);
5174 if (r < 0)
5175 return log_debug_errno(r, "Failed to push verity data fd into varlink connection: %m");
5176 }
5177
5178 _cleanup_(sd_json_variant_unrefp) sd_json_variant *mount_options = NULL;
5179 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
5180 _cleanup_free_ char *filtered = NULL;
5181
5182 const char *o = mount_options_from_designator(options, i);
5183 if (!o)
5184 continue;
5185
5186 /* We communicate relaxExtensionReleaseCheck separately via the varlink API, so filter it out
5187 * from the mount options we pass to mountfsd. */
5188 if (IN_SET(i, PARTITION_ROOT, PARTITION_USR)) {
5189 r = fstab_filter_options(
5190 o,
5191 "x-systemd.relax-extension-release-check\0",
5192 /* ret_namefound= */ NULL,
5193 /* ret_value= */ NULL,
5194 /* ret_values= */ NULL,
5195 &filtered);
5196 if (r < 0)
5197 return log_debug_errno(r, "Failed to filter mount options: %m");
5198
5199 if (isempty(filtered))
5200 continue;
5201 }
5202
5203 r = sd_json_variant_merge_objectbo(
5204 &mount_options,
5205 SD_JSON_BUILD_PAIR_STRING(partition_designator_to_string(i), filtered ?: o));
5206 if (r < 0)
5207 return log_debug_errno(r, "Failed to build mount options array: %m");
5208 }
5209
5210 sd_json_variant *reply = NULL;
5211 r = varlink_callbo_and_log(
5212 vl,
5213 "io.systemd.MountFileSystem.MountImage",
5214 &reply,
5215 &error_id,
5216 SD_JSON_BUILD_PAIR_UNSIGNED("imageFileDescriptor", 0),
5217 SD_JSON_BUILD_PAIR_CONDITION(userns_fd >= 0, "userNamespaceFileDescriptor", SD_JSON_BUILD_UNSIGNED(1)),
5218 SD_JSON_BUILD_PAIR_BOOLEAN("readOnly", FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_READ_ONLY)),
5219 SD_JSON_BUILD_PAIR_BOOLEAN("growFileSystems", FLAGS_SET(flags, DISSECT_IMAGE_GROWFS)),
5220 SD_JSON_BUILD_PAIR_CONDITION(!!ps, "imagePolicy", SD_JSON_BUILD_STRING(ps)),
5221 JSON_BUILD_PAIR_VARIANT_NON_NULL("mountOptions", mount_options),
5222 SD_JSON_BUILD_PAIR_BOOLEAN("relaxExtensionReleaseChecks", mount_options_relax_extension_release_checks(options)),
5223 SD_JSON_BUILD_PAIR_BOOLEAN("veritySharing", FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)),
5224 SD_JSON_BUILD_PAIR_CONDITION(verity_data_fd >= 0, "verityDataFileDescriptor", SD_JSON_BUILD_UNSIGNED(userns_fd >= 0 ? 2 : 1)),
5225 SD_JSON_BUILD_PAIR_CONDITION(verity && iovec_is_set(&verity->root_hash), "verityRootHash", JSON_BUILD_IOVEC_HEX(&verity->root_hash)),
5226 SD_JSON_BUILD_PAIR_CONDITION(verity && iovec_is_set(&verity->root_hash_sig), "verityRootHashSignature", JSON_BUILD_IOVEC_BASE64(&verity->root_hash_sig)),
5227 SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH)));
5228 if (r < 0)
5229 return r;
5230
5231 r = sd_json_dispatch(reply, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
5232 if (r < 0)
5233 return log_debug_errno(r, "Failed to parse MountImage() reply: %m");
5234
5235 log_debug("Effective image policy: %s", p.image_policy);
5236
5237 sd_json_variant *i;
5238 JSON_VARIANT_ARRAY_FOREACH(i, p.partitions) {
5239 _cleanup_close_ int fsmount_fd = -EBADF;
5240
5241 _cleanup_(partition_fields_done) PartitionFields pp = {
5242 .designator = _PARTITION_DESIGNATOR_INVALID,
5243 .architecture = _ARCHITECTURE_INVALID,
5244 .size = UINT64_MAX,
5245 .offset = UINT64_MAX,
5246 .fsmount_fd_idx = UINT_MAX,
5247 };
5248
5249 static const sd_json_dispatch_field partition_dispatch_table[] = {
5250 { "designator", SD_JSON_VARIANT_STRING, dispatch_partition_designator, offsetof(struct PartitionFields, designator), SD_JSON_MANDATORY },
5251 { "writable", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(struct PartitionFields, rw), SD_JSON_MANDATORY },
5252 { "growFileSystem", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(struct PartitionFields, growfs), SD_JSON_MANDATORY },
5253 { "partitionNumber", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(struct PartitionFields, partno), 0 },
5254 { "architecture", SD_JSON_VARIANT_STRING, dispatch_architecture, offsetof(struct PartitionFields, architecture), 0 },
5255 { "partitionUuid", SD_JSON_VARIANT_STRING, sd_json_dispatch_id128, offsetof(struct PartitionFields, uuid), 0 },
5256 { "fileSystemType", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(struct PartitionFields, fstype), SD_JSON_MANDATORY },
5257 { "partitionLabel", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(struct PartitionFields, label), 0 },
5258 { "size", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(struct PartitionFields, size), SD_JSON_MANDATORY },
5259 { "offset", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64, offsetof(struct PartitionFields, offset), SD_JSON_MANDATORY },
5260 { "mountFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(struct PartitionFields, fsmount_fd_idx), SD_JSON_MANDATORY },
5261 {}
5262 };
5263
5264 r = sd_json_dispatch(i, partition_dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &pp);
5265 if (r < 0)
5266 return log_debug_errno(r, "Failed to parse partition data: %m");
5267
5268 if (pp.fsmount_fd_idx != UINT_MAX) {
5269 fsmount_fd = sd_varlink_take_fd(vl, pp.fsmount_fd_idx);
5270 if (fsmount_fd < 0)
5271 return fsmount_fd;
5272 }
5273
5274 assert(pp.designator >= 0);
5275
5276 if (!di) {
5277 r = dissected_image_new(/* path= */ NULL, &di);
5278 if (r < 0)
5279 return log_debug_errno(r, "Failed to allocated new dissected image structure: %m");
5280 }
5281
5282 if (di->partitions[pp.designator].found)
5283 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Duplicate partition data for '%s'.", partition_designator_to_string(pp.designator));
5284
5285 di->partitions[pp.designator] = (DissectedPartition) {
5286 .found = true,
5287 .rw = pp.rw,
5288 .growfs = pp.growfs,
5289 .partno = pp.partno,
5290 .architecture = pp.architecture,
5291 .uuid = pp.uuid,
5292 .fstype = TAKE_PTR(pp.fstype),
5293 .label = TAKE_PTR(pp.label),
5294 .mount_node_fd = -EBADF,
5295 .size = pp.size,
5296 .offset = pp.offset,
5297 .fsmount_fd = TAKE_FD(fsmount_fd),
5298 };
5299 }
5300
5301 if (!di)
5302 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Partition list is empty.");
5303
5304 di->single_file_system = p.single_file_system;
5305 di->image_size = p.image_size;
5306 di->sector_size = p.sector_size;
5307 di->image_uuid = p.image_uuid;
5308
5309 *ret = TAKE_PTR(di);
5310 return 0;
5311 #else
5312 return -EOPNOTSUPP;
5313 #endif
5314 }
5315
5316 int mountfsd_mount_image(
5317 sd_varlink *vl,
5318 const char *path,
5319 int userns_fd,
5320 const MountOptions *options,
5321 const ImagePolicy *image_policy,
5322 const VeritySettings *verity,
5323 DissectImageFlags flags,
5324 DissectedImage **ret) {
5325
5326 int r;
5327
5328 assert(path);
5329 assert(ret);
5330
5331 _cleanup_close_ int image_fd = open(path, O_RDONLY|O_CLOEXEC);
5332 if (image_fd < 0)
5333 return log_debug_errno(errno, "Failed to open '%s': %m", path);
5334
5335 _cleanup_(dissected_image_unrefp) DissectedImage *di = NULL;
5336 r = mountfsd_mount_image_fd(vl, image_fd, userns_fd, options, image_policy, verity, flags, &di);
5337 if (r < 0)
5338 return r;
5339
5340 if (!di->image_name) {
5341 r = dissected_image_name_from_path(path, &di->image_name);
5342 if (r < 0)
5343 return r;
5344 }
5345
5346 *ret = TAKE_PTR(di);
5347 return 0;
5348 }
5349
5350 int mountfsd_mount_directory_fd(
5351 sd_varlink *vl,
5352 int directory_fd,
5353 int userns_fd,
5354 DissectImageFlags flags,
5355 int *ret_mount_fd) {
5356
5357 int r;
5358
5359 assert(directory_fd >= 0);
5360 assert(ret_mount_fd);
5361
5362 /* Pick one identity, not both, that makes no sense. */
5363 assert(!FLAGS_SET(flags, DISSECT_IMAGE_FOREIGN_UID|DISSECT_IMAGE_IDENTITY_UID));
5364
5365 _cleanup_(sd_varlink_unrefp) sd_varlink *_vl = NULL;
5366 if (!vl) {
5367 r = mountfsd_connect(&_vl);
5368 if (r < 0)
5369 return r;
5370
5371 vl = _vl;
5372 }
5373
5374 r = sd_varlink_push_dup_fd(vl, directory_fd);
5375 if (r < 0)
5376 return log_debug_errno(r, "Failed to push directory fd into varlink connection: %m");
5377
5378 if (userns_fd >= 0) {
5379 r = sd_varlink_push_dup_fd(vl, userns_fd);
5380 if (r < 0)
5381 return log_debug_errno(r, "Failed to push user namespace fd into varlink connection: %m");
5382 }
5383
5384 sd_json_variant *reply = NULL;
5385 const char *error_id = NULL;
5386 r = varlink_callbo_and_log(
5387 vl,
5388 "io.systemd.MountFileSystem.MountDirectory",
5389 &reply,
5390 &error_id,
5391 SD_JSON_BUILD_PAIR_UNSIGNED("directoryFileDescriptor", 0),
5392 SD_JSON_BUILD_PAIR_CONDITION(userns_fd >= 0, "userNamespaceFileDescriptor", SD_JSON_BUILD_UNSIGNED(1)),
5393 SD_JSON_BUILD_PAIR_BOOLEAN("readOnly", FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_READ_ONLY)),
5394 SD_JSON_BUILD_PAIR_STRING("mode", FLAGS_SET(flags, DISSECT_IMAGE_FOREIGN_UID) ? "foreign" :
5395 FLAGS_SET(flags, DISSECT_IMAGE_IDENTITY_UID) ? "identity" : "auto"),
5396 SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH)));
5397 if (r < 0)
5398 return r;
5399
5400 static const sd_json_dispatch_field dispatch_table[] = {
5401 { "mountFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, 0, SD_JSON_MANDATORY },
5402 {}
5403 };
5404
5405 unsigned fsmount_fd_idx = UINT_MAX;
5406 r = sd_json_dispatch(reply, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &fsmount_fd_idx);
5407 if (r < 0)
5408 return log_debug_errno(r, "Failed to parse MountImage() reply: %m");
5409
5410 _cleanup_close_ int fsmount_fd = sd_varlink_take_fd(vl, fsmount_fd_idx);
5411 if (fsmount_fd < 0)
5412 return log_debug_errno(fsmount_fd, "Failed to take mount fd from Varlink connection: %m");
5413
5414 *ret_mount_fd = TAKE_FD(fsmount_fd);
5415 return 0;
5416 }
5417
5418 int mountfsd_mount_directory(
5419 sd_varlink *vl,
5420 const char *path,
5421 int userns_fd,
5422 DissectImageFlags flags,
5423 int *ret_mount_fd) {
5424
5425 assert(path);
5426 assert(ret_mount_fd);
5427
5428 _cleanup_close_ int directory_fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_PATH);
5429 if (directory_fd < 0)
5430 return log_debug_errno(errno, "Failed to open '%s': %m", path);
5431
5432 return mountfsd_mount_directory_fd(vl, directory_fd, userns_fd, flags, ret_mount_fd);
5433 }
5434
5435 int mountfsd_make_directory_fd(
5436 sd_varlink *vl,
5437 int parent_fd,
5438 const char *name,
5439 mode_t mode,
5440 DissectImageFlags flags,
5441 int *ret_directory_fd) {
5442
5443 int r;
5444
5445 assert(parent_fd >= 0);
5446 assert(name);
5447
5448 _cleanup_(sd_varlink_unrefp) sd_varlink *_vl = NULL;
5449 if (!vl) {
5450 r = mountfsd_connect(&_vl);
5451 if (r < 0)
5452 return r;
5453
5454 vl = _vl;
5455 }
5456
5457 r = sd_varlink_push_dup_fd(vl, parent_fd);
5458 if (r < 0)
5459 return log_debug_errno(r, "Failed to push parent fd into varlink connection: %m");
5460
5461 sd_json_variant *reply = NULL;
5462 const char *error_id = NULL;
5463 r = varlink_callbo_and_log(
5464 vl,
5465 "io.systemd.MountFileSystem.MakeDirectory",
5466 &reply,
5467 &error_id,
5468 SD_JSON_BUILD_PAIR_UNSIGNED("parentFileDescriptor", 0),
5469 SD_JSON_BUILD_PAIR_STRING("name", name),
5470 SD_JSON_BUILD_PAIR_CONDITION(!IN_SET(mode, MODE_INVALID, 0700), "mode", SD_JSON_BUILD_UNSIGNED(mode)), /* suppress this field if default/unset */
5471 SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH)));
5472 if (r < 0)
5473 return r;
5474
5475 static const sd_json_dispatch_field dispatch_table[] = {
5476 { "directoryFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, 0, SD_JSON_MANDATORY },
5477 {}
5478 };
5479
5480 unsigned directory_fd_idx = UINT_MAX;
5481 r = sd_json_dispatch(reply, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &directory_fd_idx);
5482 if (r < 0)
5483 return log_debug_errno(r, "Failed to parse MountImage() reply: %m");
5484
5485 _cleanup_close_ int directory_fd = sd_varlink_take_fd(vl, directory_fd_idx);
5486 if (directory_fd < 0)
5487 return log_debug_errno(directory_fd, "Failed to take directory fd from Varlink connection: %m");
5488
5489 if (ret_directory_fd)
5490 *ret_directory_fd = TAKE_FD(directory_fd);
5491 return 0;
5492 }
5493
5494 int mountfsd_make_directory(
5495 sd_varlink *vl,
5496 const char *path,
5497 mode_t mode,
5498 DissectImageFlags flags,
5499 int *ret_directory_fd) {
5500
5501 int r;
5502
5503 _cleanup_free_ char *parent = NULL;
5504 r = path_extract_directory(path, &parent);
5505 if (r < 0)
5506 return log_debug_errno(r, "Failed to extract parent directory from '%s': %m", path);
5507
5508 _cleanup_free_ char *dirname = NULL;
5509 r = path_extract_filename(path, &dirname);
5510 if (r < 0)
5511 return log_debug_errno(r, "Failed to extract directory name from '%s': %m", path);
5512
5513 _cleanup_close_ int fd = open(parent, O_DIRECTORY|O_CLOEXEC);
5514 if (fd < 0)
5515 return log_debug_errno(errno, "Failed to open '%s': %m", parent);
5516
5517 return mountfsd_make_directory_fd(vl, fd, dirname, mode, flags, ret_directory_fd);
5518 }
5519
5520 int copy_tree_at_foreign(int source_fd, int target_fd, int userns_fd) {
5521 int r;
5522
5523 assert(source_fd >= 0);
5524 assert(target_fd >= 0);
5525 assert(userns_fd >= 0);
5526
5527 /* Copies dir referenced by source_fd into dir referenced by source_fd, moves to the specified userns
5528 * for that, which should be foreign UID range */
5529
5530 r = pidref_safe_fork_full(
5531 "copy-tree",
5532 /* stdio_fds= */ NULL,
5533 (int[]) { userns_fd, source_fd, target_fd }, 3,
5534 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_WAIT|FORK_REOPEN_LOG,
5535 /* ret= */ NULL);
5536 if (r < 0)
5537 return r;
5538 if (r == 0) {
5539 r = namespace_enter(
5540 /* pidns_fd= */ -EBADF,
5541 /* mntns_fd= */ -EBADF,
5542 /* netns_fd= */ -EBADF,
5543 userns_fd,
5544 /* root_fd= */ -EBADF);
5545 if (r < 0) {
5546 log_debug_errno(r, "Failed to join user namespace: %m");
5547 _exit(EXIT_FAILURE);
5548 }
5549
5550 r = copy_tree_at(
5551 source_fd, /* from= */ NULL,
5552 target_fd, /* to= */ NULL,
5553 /* override_uid= */ UID_INVALID,
5554 /* override_gid= */ GID_INVALID,
5555 COPY_REFLINK|COPY_HARDLINKS|COPY_MERGE_EMPTY|COPY_MERGE_APPLY_STAT|COPY_SAME_MOUNT|COPY_ALL_XATTRS,
5556 /* denylist= */ NULL,
5557 /* subvolumes= */ NULL);
5558 if (r < 0) {
5559 log_debug_errno(r, "Failed to copy tree: %m");
5560 _exit(EXIT_FAILURE);
5561 }
5562
5563 _exit(EXIT_SUCCESS);
5564 }
5565
5566 return 0;
5567 }
5568
5569 int remove_tree_foreign(const char *path, int userns_fd) {
5570 int r;
5571
5572 assert(path);
5573 assert(userns_fd >= 0);
5574
5575 _cleanup_close_ int tree_fd = -EBADF;
5576 r = mountfsd_mount_directory(
5577 /* vl= */ NULL,
5578 path,
5579 userns_fd,
5580 DISSECT_IMAGE_FOREIGN_UID,
5581 &tree_fd);
5582 if (r < 0)
5583 return r;
5584
5585 r = pidref_safe_fork_full(
5586 "rm-tree",
5587 /* stdio_fds= */ NULL,
5588 (int[]) { userns_fd, tree_fd }, 2,
5589 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGTERM|FORK_WAIT|FORK_REOPEN_LOG,
5590 /* ret= */ NULL);
5591 if (r < 0)
5592 return r;
5593 if (r == 0) {
5594 /* child */
5595
5596 r = namespace_enter(
5597 /* pidns_fd= */ -EBADF,
5598 /* mntns_fd= */ -EBADF,
5599 /* netns_fd= */ -EBADF,
5600 userns_fd,
5601 /* root_fd= */ -EBADF);
5602 if (r < 0) {
5603 log_debug_errno(r, "Failed to join user namespace: %m");
5604 _exit(EXIT_FAILURE);
5605 }
5606
5607 _cleanup_close_ int dfd = fd_reopen(tree_fd, O_DIRECTORY|O_CLOEXEC);
5608 if (dfd < 0) {
5609 log_debug_errno(r, "Failed to reopen tree fd: %m");
5610 _exit(EXIT_FAILURE);
5611 }
5612
5613 r = rm_rf_children(dfd, REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_CHMOD, /* root_dev= */ NULL);
5614 if (r < 0)
5615 log_debug_errno(r, "Failed to empty '%s' directory in foreign UID mode, ignoring: %m", path);
5616
5617 _exit(EXIT_SUCCESS);
5618 }
5619
5620 return 0;
5621 }