]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/dissect-image.c
dissect: actually enforce policy
[thirdparty/systemd.git] / src / shared / dissect-image.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
5 #endif
6
7 #include <linux/dm-ioctl.h>
8 #include <linux/loop.h>
9 #include <sys/file.h>
10 #include <sys/mount.h>
11 #include <sys/prctl.h>
12 #include <sys/wait.h>
13 #include <sysexits.h>
14
15 #if HAVE_OPENSSL
16 #include <openssl/err.h>
17 #include <openssl/pem.h>
18 #include <openssl/x509.h>
19 #endif
20
21 #include "sd-device.h"
22 #include "sd-id128.h"
23
24 #include "architecture.h"
25 #include "ask-password-api.h"
26 #include "blkid-util.h"
27 #include "blockdev-util.h"
28 #include "btrfs-util.h"
29 #include "chase.h"
30 #include "conf-files.h"
31 #include "constants.h"
32 #include "copy.h"
33 #include "cryptsetup-util.h"
34 #include "device-nodes.h"
35 #include "device-util.h"
36 #include "devnum-util.h"
37 #include "discover-image.h"
38 #include "dissect-image.h"
39 #include "dm-util.h"
40 #include "env-file.h"
41 #include "env-util.h"
42 #include "extension-util.h"
43 #include "fd-util.h"
44 #include "fileio.h"
45 #include "fs-util.h"
46 #include "fsck-util.h"
47 #include "gpt.h"
48 #include "hexdecoct.h"
49 #include "hostname-setup.h"
50 #include "id128-util.h"
51 #include "import-util.h"
52 #include "io-util.h"
53 #include "missing_mount.h"
54 #include "mkdir-label.h"
55 #include "mount-util.h"
56 #include "mountpoint-util.h"
57 #include "namespace-util.h"
58 #include "nulstr-util.h"
59 #include "openssl-util.h"
60 #include "os-util.h"
61 #include "path-util.h"
62 #include "process-util.h"
63 #include "raw-clone.h"
64 #include "resize-fs.h"
65 #include "signal-util.h"
66 #include "sparse-endian.h"
67 #include "stat-util.h"
68 #include "stdio-util.h"
69 #include "string-table.h"
70 #include "string-util.h"
71 #include "strv.h"
72 #include "tmpfile-util.h"
73 #include "udev-util.h"
74 #include "user-util.h"
75 #include "xattr-util.h"
76
77 /* how many times to wait for the device nodes to appear */
78 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
79
80 int dissect_fstype_ok(const char *fstype) {
81 const char *e;
82 bool b;
83
84 /* When we automatically mount file systems, be a bit conservative by default what we are willing to
85 * mount, just as an extra safety net to not mount with badly maintained legacy file system
86 * drivers. */
87
88 e = secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
89 if (e) {
90 _cleanup_strv_free_ char **l = NULL;
91
92 l = strv_split(e, ":");
93 if (!l)
94 return -ENOMEM;
95
96 b = strv_contains(l, fstype);
97 } else
98 b = STR_IN_SET(fstype,
99 "btrfs",
100 "erofs",
101 "ext4",
102 "squashfs",
103 "vfat",
104 "xfs");
105 if (b)
106 return true;
107
108 log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype);
109 return false;
110 }
111
112 int probe_sector_size(int fd, uint32_t *ret) {
113
114 struct gpt_header {
115 char signature[8];
116 le32_t revision;
117 le32_t header_size;
118 le32_t crc32;
119 le32_t reserved;
120 le64_t my_lba;
121 le64_t alternate_lba;
122 le64_t first_usable_lba;
123 le64_t last_usable_lba;
124 sd_id128_t disk_guid;
125 le64_t partition_entry_lba;
126 le32_t number_of_partition_entries;
127 le32_t size_of_partition_entry;
128 le32_t partition_entry_array_crc32;
129 } _packed_;
130
131 /* Disk images might be for 512B or for 4096 sector sizes, let's try to auto-detect that by searching
132 * for the GPT headers at the relevant byte offsets */
133
134 assert_cc(sizeof(struct gpt_header) == 92);
135
136 /* We expect a sector size in the range 512…4096. The GPT header is located in the second
137 * sector. Hence it could be at byte 512 at the earliest, and at byte 4096 at the latest. And we must
138 * read with granularity of the largest sector size we care about. Which means 8K. */
139 uint8_t sectors[2 * 4096];
140 uint32_t found = 0;
141 ssize_t n;
142
143 assert(fd >= 0);
144 assert(ret);
145
146 n = pread(fd, sectors, sizeof(sectors), 0);
147 if (n < 0)
148 return -errno;
149 if (n != sizeof(sectors)) /* too short? */
150 goto not_found;
151
152 /* Let's see if we find the GPT partition header with various expected sector sizes */
153 for (uint32_t sz = 512; sz <= 4096; sz <<= 1) {
154 struct gpt_header *p;
155
156 assert(sizeof(sectors) >= sz * 2);
157 p = (struct gpt_header*) (sectors + sz);
158
159 if (memcmp(p->signature, (const char[8]) { 'E', 'F', 'I', ' ', 'P', 'A', 'R', 'T' }, 8) != 0)
160 continue;
161
162 if (le32toh(p->revision) != UINT32_C(0x00010000)) /* the only known revision of the spec: 1.0 */
163 continue;
164
165 if (le32toh(p->header_size) < sizeof(struct gpt_header))
166 continue;
167
168 if (le32toh(p->header_size) > 4096) /* larger than a sector? something is off… */
169 continue;
170
171 if (le64toh(p->my_lba) != 1) /* this sector must claim to be at sector offset 1 */
172 continue;
173
174 if (found != 0)
175 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
176 "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
177
178 found = sz;
179 }
180
181 if (found != 0) {
182 log_debug("Determined sector size %" PRIu32 " based on discovered partition table.", found);
183 *ret = found;
184 return 1; /* indicate we *did* find it */
185 }
186
187 not_found:
188 log_debug("Couldn't find any partition table to derive sector size of.");
189 *ret = 512; /* pick the traditional default */
190 return 0; /* indicate we didn't find it */
191 }
192
193 int probe_sector_size_prefer_ioctl(int fd, uint32_t *ret) {
194 struct stat st;
195
196 assert(fd >= 0);
197 assert(ret);
198
199 /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
200 * configured sector size rather than probing by contents */
201
202 if (fstat(fd, &st) < 0)
203 return -errno;
204
205 if (S_ISBLK(st.st_mode))
206 return blockdev_get_sector_size(fd, ret);
207
208 return probe_sector_size(fd, ret);
209 }
210
211 int probe_filesystem_full(
212 int fd,
213 const char *path,
214 uint64_t offset,
215 uint64_t size,
216 char **ret_fstype) {
217
218 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
219 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
220 * different error otherwise. */
221
222 #if HAVE_BLKID
223 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
224 _cleanup_free_ char *path_by_fd = NULL;
225 _cleanup_close_ int fd_close = -EBADF;
226 const char *fstype;
227 int r;
228
229 assert(fd >= 0 || path);
230 assert(ret_fstype);
231
232 if (fd < 0) {
233 fd_close = open(path, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
234 if (fd_close < 0)
235 return -errno;
236
237 fd = fd_close;
238 }
239
240 if (!path) {
241 r = fd_get_path(fd, &path_by_fd);
242 if (r < 0)
243 return r;
244
245 path = path_by_fd;
246 }
247
248 if (size == 0) /* empty size? nothing found! */
249 goto not_found;
250
251 b = blkid_new_probe();
252 if (!b)
253 return -ENOMEM;
254
255 errno = 0;
256 r = blkid_probe_set_device(
257 b,
258 fd,
259 offset,
260 size == UINT64_MAX ? 0 : size); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
261 if (r != 0)
262 return errno_or_else(ENOMEM);
263
264 blkid_probe_enable_superblocks(b, 1);
265 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
266
267 errno = 0;
268 r = blkid_do_safeprobe(b);
269 if (r == _BLKID_SAFEPROBE_NOT_FOUND)
270 goto not_found;
271 if (r == _BLKID_SAFEPROBE_AMBIGUOUS)
272 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
273 "Results ambiguous for partition %s", path);
274 if (r == _BLKID_SAFEPROBE_ERROR)
275 return log_debug_errno(errno_or_else(EIO), "Failed to probe partition %s: %m", path);
276
277 assert(r == _BLKID_SAFEPROBE_FOUND);
278
279 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
280
281 if (fstype) {
282 char *t;
283
284 log_debug("Probed fstype '%s' on partition %s.", fstype, path);
285
286 t = strdup(fstype);
287 if (!t)
288 return -ENOMEM;
289
290 *ret_fstype = t;
291 return 1;
292 }
293
294 not_found:
295 log_debug("No type detected on partition %s", path);
296 *ret_fstype = NULL;
297 return 0;
298 #else
299 return -EOPNOTSUPP;
300 #endif
301 }
302
303 #if HAVE_BLKID
304 static int image_policy_may_use(
305 const ImagePolicy *policy,
306 PartitionDesignator designator) {
307
308 PartitionPolicyFlags f;
309
310 /* For each partition we find in the partition table do a first check if it may exist at all given
311 * the policy, or if it shall be ignored. */
312
313 f = image_policy_get_exhaustively(policy, designator);
314 if (f < 0)
315 return f;
316
317 if ((f & _PARTITION_POLICY_USE_MASK) == PARTITION_POLICY_ABSENT)
318 /* only flag set in policy is "absent"? then this partition may not exist at all */
319 return log_debug_errno(
320 SYNTHETIC_ERRNO(ERFKILL),
321 "Partition of designator '%s' exists, but not allowed by policy, refusing.",
322 partition_designator_to_string(designator));
323 if ((f & _PARTITION_POLICY_USE_MASK & ~PARTITION_POLICY_ABSENT) == PARTITION_POLICY_UNUSED) {
324 /* only "unused" or "unused" + "absent" are set? then don't use it */
325 log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
326 partition_designator_to_string(designator));
327 return false; /* ignore! */
328 }
329
330 return true; /* use! */
331 }
332
333 static int image_policy_check_protection(
334 const ImagePolicy *policy,
335 PartitionDesignator designator,
336 PartitionPolicyFlags found_flags) {
337
338 PartitionPolicyFlags policy_flags;
339
340 /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
341
342 if (found_flags < 0)
343 return found_flags;
344
345 policy_flags = image_policy_get_exhaustively(policy, designator);
346 if (policy_flags < 0)
347 return policy_flags;
348
349 if ((found_flags & policy_flags) == 0) {
350 _cleanup_free_ char *found_flags_string = NULL, *policy_flags_string = NULL;
351
352 (void) partition_policy_flags_to_string(found_flags, /* simplify= */ true, &found_flags_string);
353 (void) partition_policy_flags_to_string(policy_flags, /* simplify= */ true, &policy_flags_string);
354
355 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
356 partition_designator_to_string(designator),
357 strnull(found_flags_string), strnull(policy_flags_string));
358 }
359
360 return 0;
361 }
362
363 static int image_policy_check_partition_flags(
364 const ImagePolicy *policy,
365 PartitionDesignator designator,
366 uint64_t gpt_flags) {
367
368 PartitionPolicyFlags policy_flags;
369 bool b;
370
371 /* Checks if the partition flags in the policy match reality */
372
373 policy_flags = image_policy_get_exhaustively(policy, designator);
374 if (policy_flags < 0)
375 return policy_flags;
376
377 b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_READ_ONLY);
378 if ((policy_flags & _PARTITION_POLICY_READ_ONLY_MASK) == (b ? PARTITION_POLICY_READ_ONLY_OFF : PARTITION_POLICY_READ_ONLY_ON))
379 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
380 partition_designator_to_string(designator),
381 one_zero(!b), one_zero(b));
382
383 b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_GROWFS);
384 if ((policy_flags & _PARTITION_POLICY_GROWFS_MASK) == (b ? PARTITION_POLICY_GROWFS_OFF : PARTITION_POLICY_GROWFS_ON))
385 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
386 partition_designator_to_string(designator),
387 one_zero(!b), one_zero(b));
388
389 return 0;
390 }
391
392 static int dissected_image_probe_filesystems(
393 DissectedImage *m,
394 int fd,
395 const ImagePolicy *policy) {
396
397 int r;
398
399 assert(m);
400
401 /* Fill in file system types if we don't know them yet. */
402
403 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
404 DissectedPartition *p = m->partitions + i;
405 PartitionPolicyFlags found_flags;
406
407 if (!p->found)
408 continue;
409
410 if (!p->fstype) {
411 /* If we have an fd referring to the partition block device, use that. Otherwise go
412 * via the whole block device or backing regular file, and read via offset. */
413 if (p->mount_node_fd >= 0)
414 r = probe_filesystem_full(p->mount_node_fd, p->node, 0, UINT64_MAX, &p->fstype);
415 else
416 r = probe_filesystem_full(fd, p->node, p->offset, p->size, &p->fstype);
417 if (r < 0)
418 return r;
419 }
420
421 if (streq_ptr(p->fstype, "crypto_LUKS")) {
422 m->encrypted = true;
423 found_flags = PARTITION_POLICY_ENCRYPTED; /* found this one, and its definitely encrypted */
424 } else
425 /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
426 * set all other ways that indicate "present". */
427 found_flags = PARTITION_POLICY_UNPROTECTED|PARTITION_POLICY_VERITY|PARTITION_POLICY_SIGNED;
428
429 if (p->fstype && fstype_is_ro(p->fstype))
430 p->rw = false;
431
432 if (!p->rw)
433 p->growfs = false;
434
435 /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
436 * hence we need to validate this against policy again, to see if the policy still matches
437 * with this new information. Note that image_policy_check_protection() will check for
438 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
439 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
440 * OR verity OR signed), but that's fine since the earlier policy check already checked more
441 * specific which of those three cases where OK. Keep in mind that this function here only
442 * looks at specific partitions (and thus can only deduce encryption or not) but not the
443 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
444 * checks already did the relevant checks that look at the whole partition table, and
445 * enforced policy there as needed. */
446 r = image_policy_check_protection(policy, i, found_flags);
447 if (r < 0)
448 return r;
449 }
450
451 return 0;
452 }
453
454 static void check_partition_flags(
455 const char *node,
456 unsigned long long pflags,
457 unsigned long long supported) {
458
459 assert(node);
460
461 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
462 pflags &= ~(supported |
463 SD_GPT_FLAG_REQUIRED_PARTITION |
464 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL |
465 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE);
466
467 if (pflags == 0)
468 return;
469
470 /* If there are other bits set, then log about it, to make things discoverable */
471 for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
472 unsigned long long bit = 1ULL << i;
473 if (!FLAGS_SET(pflags, bit))
474 continue;
475
476 log_debug("Unexpected partition flag %llu set on %s!", bit, node);
477 }
478 }
479
480 static int dissected_image_new(const char *path, DissectedImage **ret) {
481 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
482 _cleanup_free_ char *name = NULL;
483 int r;
484
485 assert(ret);
486
487 if (path) {
488 _cleanup_free_ char *filename = NULL;
489
490 r = path_extract_filename(path, &filename);
491 if (r < 0)
492 return r;
493
494 r = raw_strip_suffixes(filename, &name);
495 if (r < 0)
496 return r;
497
498 if (!image_name_is_valid(name)) {
499 log_debug("Image name %s is not valid, ignoring.", strna(name));
500 name = mfree(name);
501 }
502 }
503
504 m = new(DissectedImage, 1);
505 if (!m)
506 return -ENOMEM;
507
508 *m = (DissectedImage) {
509 .has_init_system = -1,
510 .image_name = TAKE_PTR(name),
511 };
512
513 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
514 m->partitions[i] = DISSECTED_PARTITION_NULL;
515
516 *ret = TAKE_PTR(m);
517 return 0;
518 }
519 #endif
520
521 static void dissected_partition_done(DissectedPartition *p) {
522 assert(p);
523
524 free(p->fstype);
525 free(p->node);
526 free(p->label);
527 free(p->decrypted_fstype);
528 free(p->decrypted_node);
529 free(p->mount_options);
530 safe_close(p->mount_node_fd);
531
532 *p = DISSECTED_PARTITION_NULL;
533 }
534
535 #if HAVE_BLKID
536 static int make_partition_devname(
537 const char *whole_devname,
538 uint64_t diskseq,
539 int nr,
540 DissectImageFlags flags,
541 char **ret) {
542
543 _cleanup_free_ char *s = NULL;
544 int r;
545
546 assert(whole_devname);
547 assert(nr != 0); /* zero is not a valid partition nr */
548 assert(ret);
549
550 if (!FLAGS_SET(flags, DISSECT_IMAGE_DISKSEQ_DEVNODE) || diskseq == 0) {
551
552 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
553 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
554 * block device node name ends in a digit, then suffix a 'p', followed by the partition
555 * number. Otherwise, just suffix the partition number without any 'p'. */
556
557 if (nr < 0) { /* whole disk? */
558 s = strdup(whole_devname);
559 if (!s)
560 return -ENOMEM;
561 } else {
562 size_t l = strlen(whole_devname);
563 if (l < 1) /* underflow check for the subtraction below */
564 return -EINVAL;
565
566 bool need_p = ascii_isdigit(whole_devname[l-1]); /* Last char a digit? */
567
568 if (asprintf(&s, "%s%s%i", whole_devname, need_p ? "p" : "", nr) < 0)
569 return -ENOMEM;
570 }
571 } else {
572 if (nr < 0) /* whole disk? */
573 r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64, diskseq);
574 else
575 r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64 "-part%i", diskseq, nr);
576 if (r < 0)
577 return -ENOMEM;
578 }
579
580 *ret = TAKE_PTR(s);
581 return 0;
582 }
583
584 static int open_partition(
585 const char *node,
586 bool is_partition,
587 const LoopDevice *loop) {
588
589 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
590 _cleanup_close_ int fd = -EBADF;
591 dev_t devnum;
592 int r;
593
594 assert(node);
595 assert(loop);
596
597 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
598 if (fd < 0)
599 return -errno;
600
601 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
602 r = block_device_new_from_fd(fd, is_partition ? BLOCK_DEVICE_LOOKUP_WHOLE_DISK : 0, &dev);
603 if (r < 0)
604 return r;
605
606 r = sd_device_get_devnum(dev, &devnum);
607 if (r < 0)
608 return r;
609
610 if (loop->devno != devnum)
611 return -ENXIO;
612
613 /* Also check diskseq. */
614 if (loop->diskseq != 0) {
615 uint64_t diskseq;
616
617 r = fd_get_diskseq(fd, &diskseq);
618 if (r < 0)
619 return r;
620
621 if (loop->diskseq != diskseq)
622 return -ENXIO;
623 }
624
625 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR ", diskseq=%" PRIu64 ").",
626 node, fd, DEVNUM_FORMAT_VAL(loop->devno), loop->diskseq);
627 return TAKE_FD(fd);
628 }
629
630 static int compare_arch(Architecture a, Architecture b) {
631 if (a == b)
632 return 0;
633
634 if (a == native_architecture())
635 return 1;
636
637 if (b == native_architecture())
638 return -1;
639
640 #ifdef ARCHITECTURE_SECONDARY
641 if (a == ARCHITECTURE_SECONDARY)
642 return 1;
643
644 if (b == ARCHITECTURE_SECONDARY)
645 return -1;
646 #endif
647
648 return 0;
649 }
650
651 static int dissect_image(
652 DissectedImage *m,
653 int fd,
654 const char *devname,
655 const VeritySettings *verity,
656 const MountOptions *mount_options,
657 const ImagePolicy *policy,
658 DissectImageFlags flags) {
659
660 sd_id128_t root_uuid = SD_ID128_NULL, root_verity_uuid = SD_ID128_NULL;
661 sd_id128_t usr_uuid = SD_ID128_NULL, usr_verity_uuid = SD_ID128_NULL;
662 bool is_gpt, is_mbr, multiple_generic = false,
663 generic_rw = false, /* initialize to appease gcc */
664 generic_growfs = false;
665 _cleanup_(blkid_free_probep) blkid_probe b = NULL;
666 _cleanup_free_ char *generic_node = NULL;
667 sd_id128_t generic_uuid = SD_ID128_NULL;
668 const char *pttype = NULL, *sptuuid = NULL;
669 blkid_partlist pl;
670 int r, generic_nr = -1, n_partitions;
671
672 assert(m);
673 assert(fd >= 0);
674 assert(devname);
675 assert(!verity || verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
676 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
677 assert(!verity || verity->root_hash_sig || verity->root_hash_sig_size == 0);
678 assert(!verity || (verity->root_hash || !verity->root_hash_sig));
679 assert(!((flags & DISSECT_IMAGE_GPT_ONLY) && (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)));
680 assert(m->sector_size > 0);
681
682 /* Probes a disk image, and returns information about what it found in *ret.
683 *
684 * Returns -ENOPKG if no suitable partition table or file system could be found.
685 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
686 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
687 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
688
689 uint64_t diskseq = m->loop ? m->loop->diskseq : 0;
690
691 if (verity && verity->root_hash) {
692 sd_id128_t fsuuid, vuuid;
693
694 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
695 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
696 * the final 128bit. */
697
698 if (verity->root_hash_size < sizeof(sd_id128_t))
699 return -EINVAL;
700
701 memcpy(&fsuuid, verity->root_hash, sizeof(sd_id128_t));
702 memcpy(&vuuid, (const uint8_t*) verity->root_hash + verity->root_hash_size - sizeof(sd_id128_t), sizeof(sd_id128_t));
703
704 if (sd_id128_is_null(fsuuid))
705 return -EINVAL;
706 if (sd_id128_is_null(vuuid))
707 return -EINVAL;
708
709 /* If the verity data declares it's for the /usr partition, then search for that, in all
710 * other cases assume it's for the root partition. */
711 if (verity->designator == PARTITION_USR) {
712 usr_uuid = fsuuid;
713 usr_verity_uuid = vuuid;
714 } else {
715 root_uuid = fsuuid;
716 root_verity_uuid = vuuid;
717 }
718 }
719
720 b = blkid_new_probe();
721 if (!b)
722 return -ENOMEM;
723
724 errno = 0;
725 r = blkid_probe_set_device(b, fd, 0, 0);
726 if (r != 0)
727 return errno_or_else(ENOMEM);
728
729 errno = 0;
730 r = blkid_probe_set_sectorsize(b, m->sector_size);
731 if (r != 0)
732 return errno_or_else(EIO);
733
734 if ((flags & DISSECT_IMAGE_GPT_ONLY) == 0) {
735 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
736 blkid_probe_enable_superblocks(b, 1);
737 blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_USAGE|BLKID_SUBLKS_UUID);
738 }
739
740 blkid_probe_enable_partitions(b, 1);
741 blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
742
743 errno = 0;
744 r = blkid_do_safeprobe(b);
745 if (r == _BLKID_SAFEPROBE_ERROR)
746 return errno_or_else(EIO);
747 if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
748 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG), "Failed to identify any partition table.");
749
750 assert(r == _BLKID_SAFEPROBE_FOUND);
751
752 if ((!(flags & DISSECT_IMAGE_GPT_ONLY) &&
753 (flags & DISSECT_IMAGE_GENERIC_ROOT)) ||
754 (flags & DISSECT_IMAGE_NO_PARTITION_TABLE)) {
755 const char *usage = NULL;
756
757 /* If flags permit this, also allow using non-partitioned single-filesystem images */
758
759 (void) blkid_probe_lookup_value(b, "USAGE", &usage, NULL);
760 if (STRPTR_IN_SET(usage, "filesystem", "crypto")) {
761 _cleanup_free_ char *t = NULL, *n = NULL, *o = NULL;
762 const char *fstype = NULL, *options = NULL, *suuid = NULL;
763 _cleanup_close_ int mount_node_fd = -EBADF;
764 sd_id128_t uuid = SD_ID128_NULL;
765 PartitionPolicyFlags found_flags;
766 bool encrypted;
767
768 /* OK, we have found a file system, that's our root partition then. */
769
770 r = image_policy_may_use(policy, PARTITION_ROOT);
771 if (r < 0)
772 return r;
773 if (r == 0) /* policy says ignore this, so we ignore it */
774 return -ENOPKG;
775
776 (void) blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
777 (void) blkid_probe_lookup_value(b, "UUID", &suuid, NULL);
778
779 encrypted = streq_ptr(fstype, "crypto_LUKS");
780
781 if (verity_settings_data_covers(verity, PARTITION_ROOT))
782 found_flags = verity->root_hash_sig ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY;
783 else
784 found_flags = encrypted ? PARTITION_POLICY_ENCRYPTED : PARTITION_POLICY_UNPROTECTED;
785
786 r = image_policy_check_protection(policy, PARTITION_ROOT, found_flags);
787 if (r < 0)
788 return r;
789
790 r = image_policy_check_partition_flags(policy, PARTITION_ROOT, 0); /* we have no gpt partition flags, hence check against all bits off */
791 if (r < 0)
792 return r;
793
794 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
795 mount_node_fd = open_partition(devname, /* is_partition = */ false, m->loop);
796 if (mount_node_fd < 0)
797 return mount_node_fd;
798 }
799
800 if (fstype) {
801 t = strdup(fstype);
802 if (!t)
803 return -ENOMEM;
804 }
805
806 if (suuid) {
807 /* blkid will return FAT's serial number as UUID, hence it is quite possible
808 * that parsing this will fail. We'll ignore the ID, since it's just too
809 * short to be useful as tru identifier. */
810 r = sd_id128_from_string(suuid, &uuid);
811 if (r < 0)
812 log_debug_errno(r, "Failed to parse file system UUID '%s', ignoring: %m", suuid);
813 }
814
815 r = make_partition_devname(devname, diskseq, -1, flags, &n);
816 if (r < 0)
817 return r;
818
819 m->single_file_system = true;
820 m->encrypted = encrypted;
821
822 m->has_verity = verity && verity->data_path;
823 m->verity_ready = verity_settings_data_covers(verity, PARTITION_ROOT);
824
825 m->has_verity_sig = false; /* signature not embedded, must be specified */
826 m->verity_sig_ready = m->verity_ready && verity->root_hash_sig;
827
828 m->image_uuid = uuid;
829
830 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
831 if (options) {
832 o = strdup(options);
833 if (!o)
834 return -ENOMEM;
835 }
836
837 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
838 .found = true,
839 .rw = !m->verity_ready && !fstype_is_ro(fstype),
840 .partno = -1,
841 .architecture = _ARCHITECTURE_INVALID,
842 .fstype = TAKE_PTR(t),
843 .node = TAKE_PTR(n),
844 .mount_options = TAKE_PTR(o),
845 .mount_node_fd = TAKE_FD(mount_node_fd),
846 .offset = 0,
847 .size = UINT64_MAX,
848 };
849
850 return 0;
851 }
852 }
853
854 (void) blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
855 if (!pttype)
856 return -ENOPKG;
857
858 is_gpt = streq_ptr(pttype, "gpt");
859 is_mbr = streq_ptr(pttype, "dos");
860
861 if (!is_gpt && ((flags & DISSECT_IMAGE_GPT_ONLY) || !is_mbr))
862 return -ENOPKG;
863
864 /* We support external verity data partitions only if the image has no partition table */
865 if (verity && verity->data_path)
866 return -EBADR;
867
868 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
869 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
870 * do partition scanning. */
871 r = blockdev_partscan_enabled(fd);
872 if (r < 0)
873 return r;
874 if (r == 0)
875 return -EPROTONOSUPPORT;
876 }
877
878 (void) blkid_probe_lookup_value(b, "PTUUID", &sptuuid, NULL);
879 if (sptuuid) {
880 r = sd_id128_from_string(sptuuid, &m->image_uuid);
881 if (r < 0)
882 log_debug_errno(r, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid);
883 }
884
885 errno = 0;
886 pl = blkid_probe_get_partitions(b);
887 if (!pl)
888 return errno_or_else(ENOMEM);
889
890 errno = 0;
891 n_partitions = blkid_partlist_numof_partitions(pl);
892 if (n_partitions < 0)
893 return errno_or_else(EIO);
894
895 for (int i = 0; i < n_partitions; i++) {
896 _cleanup_free_ char *node = NULL;
897 unsigned long long pflags;
898 blkid_loff_t start, size;
899 blkid_partition pp;
900 int nr;
901
902 errno = 0;
903 pp = blkid_partlist_get_partition(pl, i);
904 if (!pp)
905 return errno_or_else(EIO);
906
907 pflags = blkid_partition_get_flags(pp);
908
909 errno = 0;
910 nr = blkid_partition_get_partno(pp);
911 if (nr < 0)
912 return errno_or_else(EIO);
913
914 errno = 0;
915 start = blkid_partition_get_start(pp);
916 if (start < 0)
917 return errno_or_else(EIO);
918
919 assert((uint64_t) start < UINT64_MAX/512);
920
921 errno = 0;
922 size = blkid_partition_get_size(pp);
923 if (size < 0)
924 return errno_or_else(EIO);
925
926 assert((uint64_t) size < UINT64_MAX/512);
927
928 /* While probing we need the non-diskseq device node name to access the thing, hence mask off
929 * DISSECT_IMAGE_DISKSEQ_DEVNODE. */
930 r = make_partition_devname(devname, diskseq, nr, flags & ~DISSECT_IMAGE_DISKSEQ_DEVNODE, &node);
931 if (r < 0)
932 return r;
933
934 /* So here's the thing: after the main ("whole") block device popped up it might take a while
935 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
936 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
937 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
938 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
939 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
940 * also good as the outcome is the same: the partition block device exists, and we can use
941 * it.
942 *
943 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
944 * partition already existent. */
945
946 if (FLAGS_SET(flags, DISSECT_IMAGE_ADD_PARTITION_DEVICES)) {
947 r = block_device_add_partition(fd, node, nr, (uint64_t) start * 512, (uint64_t) size * 512);
948 if (r < 0) {
949 if (r != -EBUSY)
950 return log_debug_errno(r, "BLKPG_ADD_PARTITION failed: %m");
951
952 log_debug_errno(r, "Kernel was quicker than us in adding partition %i.", nr);
953 } else
954 log_debug("We were quicker than kernel in adding partition %i.", nr);
955 }
956
957 if (is_gpt) {
958 const char *fstype = NULL, *label;
959 sd_id128_t type_id, id;
960 GptPartitionType type;
961 bool rw = true, growfs = false;
962
963 r = blkid_partition_get_uuid_id128(pp, &id);
964 if (r < 0) {
965 log_debug_errno(r, "Failed to read partition UUID, ignoring: %m");
966 continue;
967 }
968
969 r = blkid_partition_get_type_id128(pp, &type_id);
970 if (r < 0) {
971 log_debug_errno(r, "Failed to read partition type UUID, ignoring: %m");
972 continue;
973 }
974
975 type = gpt_partition_type_from_uuid(type_id);
976
977 label = blkid_partition_get_name(pp); /* libblkid returns NULL here if empty */
978
979 if (IN_SET(type.designator,
980 PARTITION_HOME,
981 PARTITION_SRV,
982 PARTITION_XBOOTLDR,
983 PARTITION_TMP)) {
984
985 check_partition_flags(node, pflags,
986 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
987
988 if (pflags & SD_GPT_FLAG_NO_AUTO)
989 continue;
990
991 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
992 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
993
994 } else if (type.designator == PARTITION_ESP) {
995
996 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
997 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
998 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
999 * Partitions"). */
1000
1001 if (pflags & SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL)
1002 continue;
1003
1004 fstype = "vfat";
1005
1006 } else if (type.designator == PARTITION_ROOT) {
1007
1008 check_partition_flags(node, pflags,
1009 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1010
1011 if (pflags & SD_GPT_FLAG_NO_AUTO)
1012 continue;
1013
1014 /* If a root ID is specified, ignore everything but the root id */
1015 if (!sd_id128_is_null(root_uuid) && !sd_id128_equal(root_uuid, id))
1016 continue;
1017
1018 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1019 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1020
1021 } else if (type.designator == PARTITION_ROOT_VERITY) {
1022
1023 check_partition_flags(node, pflags,
1024 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1025
1026 if (pflags & SD_GPT_FLAG_NO_AUTO)
1027 continue;
1028
1029 m->has_verity = true;
1030
1031 /* If no verity configuration is specified, then don't do verity */
1032 if (!verity)
1033 continue;
1034 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1035 continue;
1036
1037 /* If root hash is specified, then ignore everything but the root id */
1038 if (!sd_id128_is_null(root_verity_uuid) && !sd_id128_equal(root_verity_uuid, id))
1039 continue;
1040
1041 fstype = "DM_verity_hash";
1042 rw = false;
1043
1044 } else if (type.designator == PARTITION_ROOT_VERITY_SIG) {
1045
1046 check_partition_flags(node, pflags,
1047 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1048
1049 if (pflags & SD_GPT_FLAG_NO_AUTO)
1050 continue;
1051
1052 m->has_verity_sig = true;
1053
1054 if (!verity)
1055 continue;
1056 if (verity->designator >= 0 && verity->designator != PARTITION_ROOT)
1057 continue;
1058
1059 fstype = "verity_hash_signature";
1060 rw = false;
1061
1062 } else if (type.designator == PARTITION_USR) {
1063
1064 check_partition_flags(node, pflags,
1065 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1066
1067 if (pflags & SD_GPT_FLAG_NO_AUTO)
1068 continue;
1069
1070 /* If a usr ID is specified, ignore everything but the usr id */
1071 if (!sd_id128_is_null(usr_uuid) && !sd_id128_equal(usr_uuid, id))
1072 continue;
1073
1074 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1075 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1076
1077 } else if (type.designator == PARTITION_USR_VERITY) {
1078
1079 check_partition_flags(node, pflags,
1080 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1081
1082 if (pflags & SD_GPT_FLAG_NO_AUTO)
1083 continue;
1084
1085 m->has_verity = true;
1086
1087 if (!verity)
1088 continue;
1089 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1090 continue;
1091
1092 /* If usr hash is specified, then ignore everything but the usr id */
1093 if (!sd_id128_is_null(usr_verity_uuid) && !sd_id128_equal(usr_verity_uuid, id))
1094 continue;
1095
1096 fstype = "DM_verity_hash";
1097 rw = false;
1098
1099 } else if (type.designator == PARTITION_USR_VERITY_SIG) {
1100
1101 check_partition_flags(node, pflags,
1102 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY);
1103
1104 if (pflags & SD_GPT_FLAG_NO_AUTO)
1105 continue;
1106
1107 m->has_verity_sig = true;
1108
1109 if (!verity)
1110 continue;
1111 if (verity->designator >= 0 && verity->designator != PARTITION_USR)
1112 continue;
1113
1114 fstype = "verity_hash_signature";
1115 rw = false;
1116
1117 } else if (type.designator == PARTITION_SWAP) {
1118
1119 check_partition_flags(node, pflags, SD_GPT_FLAG_NO_AUTO);
1120
1121 if (pflags & SD_GPT_FLAG_NO_AUTO)
1122 continue;
1123
1124 /* Note: we don't set fstype = "swap" here, because we still need to probe if
1125 * it might be encrypted (i.e. fstype "crypt_LUKS") or unencrypted
1126 * (i.e. fstype "swap"), and the only way to figure that out is via fstype
1127 * probing. */
1128
1129 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
1130 } else if (sd_id128_equal(type.uuid, SD_GPT_LINUX_GENERIC)) {
1131
1132 check_partition_flags(node, pflags,
1133 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1134
1135 if (pflags & SD_GPT_FLAG_NO_AUTO)
1136 continue;
1137
1138 if (generic_node)
1139 multiple_generic = true;
1140 else {
1141 generic_nr = nr;
1142 generic_rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1143 generic_growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1144 generic_uuid = id;
1145 generic_node = TAKE_PTR(node);
1146 }
1147
1148 } else if (type.designator == PARTITION_VAR) {
1149
1150 check_partition_flags(node, pflags,
1151 SD_GPT_FLAG_NO_AUTO | SD_GPT_FLAG_READ_ONLY | SD_GPT_FLAG_GROWFS);
1152
1153 if (pflags & SD_GPT_FLAG_NO_AUTO)
1154 continue;
1155
1156 if (!FLAGS_SET(flags, DISSECT_IMAGE_RELAX_VAR_CHECK)) {
1157 sd_id128_t var_uuid;
1158
1159 /* For /var we insist that the uuid of the partition matches the
1160 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1161 * ID. Why? Unlike the other partitions /var is inherently
1162 * installation specific, hence we need to be careful not to mount it
1163 * in the wrong installation. By hashing the partition UUID from
1164 * /etc/machine-id we can securely bind the partition to the
1165 * installation. */
1166
1167 r = sd_id128_get_machine_app_specific(SD_GPT_VAR, &var_uuid);
1168 if (r < 0)
1169 return r;
1170
1171 if (!sd_id128_equal(var_uuid, id)) {
1172 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
1173 "(found: " SD_ID128_UUID_FORMAT_STR ", expected: " SD_ID128_UUID_FORMAT_STR "), ignoring.",
1174 SD_ID128_FORMAT_VAL(id), SD_ID128_FORMAT_VAL(var_uuid));
1175 continue;
1176 }
1177 }
1178
1179 rw = !(pflags & SD_GPT_FLAG_READ_ONLY);
1180 growfs = FLAGS_SET(pflags, SD_GPT_FLAG_GROWFS);
1181 }
1182
1183 if (type.designator != _PARTITION_DESIGNATOR_INVALID) {
1184 _cleanup_free_ char *t = NULL, *o = NULL, *l = NULL, *n = NULL;
1185 _cleanup_close_ int mount_node_fd = -EBADF;
1186 const char *options = NULL;
1187
1188 r = image_policy_may_use(policy, type.designator);
1189 if (r < 0)
1190 return r;
1191 if (r == 0) {
1192 /* Policy says: ignore; Remember this fact, so that we later can distinguish between "found but ignored" and "not found at all" */
1193
1194 if (!m->partitions[type.designator].found)
1195 m->partitions[type.designator].ignored = true;
1196
1197 continue;
1198 }
1199
1200 if (m->partitions[type.designator].found) {
1201 /* For most partition types the first one we see wins. Except for the
1202 * rootfs and /usr, where we do a version compare of the label, and
1203 * let the newest version win. This permits a simple A/B versioning
1204 * scheme in OS images. */
1205
1206 if (compare_arch(type.arch, m->partitions[type.designator].architecture) <= 0)
1207 continue;
1208
1209 if (!partition_designator_is_versioned(type.designator) ||
1210 strverscmp_improved(m->partitions[type.designator].label, label) >= 0)
1211 continue;
1212
1213 dissected_partition_done(m->partitions + type.designator);
1214 }
1215
1216 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES) &&
1217 type.designator != PARTITION_SWAP) {
1218 mount_node_fd = open_partition(node, /* is_partition = */ true, m->loop);
1219 if (mount_node_fd < 0)
1220 return mount_node_fd;
1221 }
1222
1223 r = make_partition_devname(devname, diskseq, nr, flags, &n);
1224 if (r < 0)
1225 return r;
1226
1227 if (fstype) {
1228 t = strdup(fstype);
1229 if (!t)
1230 return -ENOMEM;
1231 }
1232
1233 if (label) {
1234 l = strdup(label);
1235 if (!l)
1236 return -ENOMEM;
1237 }
1238
1239 options = mount_options_from_designator(mount_options, type.designator);
1240 if (options) {
1241 o = strdup(options);
1242 if (!o)
1243 return -ENOMEM;
1244 }
1245
1246 m->partitions[type.designator] = (DissectedPartition) {
1247 .found = true,
1248 .partno = nr,
1249 .rw = rw,
1250 .growfs = growfs,
1251 .architecture = type.arch,
1252 .node = TAKE_PTR(n),
1253 .fstype = TAKE_PTR(t),
1254 .label = TAKE_PTR(l),
1255 .uuid = id,
1256 .mount_options = TAKE_PTR(o),
1257 .mount_node_fd = TAKE_FD(mount_node_fd),
1258 .offset = (uint64_t) start * 512,
1259 .size = (uint64_t) size * 512,
1260 .gpt_flags = pflags,
1261 };
1262 }
1263
1264 } else if (is_mbr) {
1265
1266 switch (blkid_partition_get_type(pp)) {
1267
1268 case 0x83: /* Linux partition */
1269
1270 if (pflags != 0x80) /* Bootable flag */
1271 continue;
1272
1273 if (generic_node)
1274 multiple_generic = true;
1275 else {
1276 generic_nr = nr;
1277 generic_rw = true;
1278 generic_growfs = false;
1279 generic_node = TAKE_PTR(node);
1280 }
1281
1282 break;
1283
1284 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1285 _cleanup_close_ int mount_node_fd = -EBADF;
1286 _cleanup_free_ char *o = NULL, *n = NULL;
1287 sd_id128_t id = SD_ID128_NULL;
1288 const char *options = NULL;
1289
1290 r = image_policy_may_use(policy, PARTITION_XBOOTLDR);
1291 if (r < 0)
1292 return r;
1293 if (r == 0) { /* policy says: ignore */
1294 if (!m->partitions[PARTITION_XBOOTLDR].found)
1295 m->partitions[PARTITION_XBOOTLDR].ignored = true;
1296
1297 continue;
1298 }
1299
1300 /* First one wins */
1301 if (m->partitions[PARTITION_XBOOTLDR].found)
1302 continue;
1303
1304 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1305 mount_node_fd = open_partition(node, /* is_partition = */ true, m->loop);
1306 if (mount_node_fd < 0)
1307 return mount_node_fd;
1308 }
1309
1310 (void) blkid_partition_get_uuid_id128(pp, &id);
1311
1312 r = make_partition_devname(devname, diskseq, nr, flags, &n);
1313 if (r < 0)
1314 return r;
1315
1316 options = mount_options_from_designator(mount_options, PARTITION_XBOOTLDR);
1317 if (options) {
1318 o = strdup(options);
1319 if (!o)
1320 return -ENOMEM;
1321 }
1322
1323 m->partitions[PARTITION_XBOOTLDR] = (DissectedPartition) {
1324 .found = true,
1325 .partno = nr,
1326 .rw = true,
1327 .growfs = false,
1328 .architecture = _ARCHITECTURE_INVALID,
1329 .node = TAKE_PTR(n),
1330 .uuid = id,
1331 .mount_options = TAKE_PTR(o),
1332 .mount_node_fd = TAKE_FD(mount_node_fd),
1333 .offset = (uint64_t) start * 512,
1334 .size = (uint64_t) size * 512,
1335 };
1336
1337 break;
1338 }}
1339 }
1340 }
1341
1342 if (!m->partitions[PARTITION_ROOT].found &&
1343 (m->partitions[PARTITION_ROOT_VERITY].found ||
1344 m->partitions[PARTITION_ROOT_VERITY_SIG].found))
1345 return -EADDRNOTAVAIL; /* Verity found but no matching rootfs? Something is off, refuse. */
1346
1347 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1348 if (m->partitions[PARTITION_ROOT_VERITY_SIG].found && !m->partitions[PARTITION_ROOT_VERITY].found)
1349 return -EADDRNOTAVAIL;
1350
1351 if (!m->partitions[PARTITION_USR].found &&
1352 (m->partitions[PARTITION_USR_VERITY].found ||
1353 m->partitions[PARTITION_USR_VERITY_SIG].found))
1354 return -EADDRNOTAVAIL; /* as above */
1355
1356 /* as above */
1357 if (m->partitions[PARTITION_USR_VERITY_SIG].found && !m->partitions[PARTITION_USR_VERITY].found)
1358 return -EADDRNOTAVAIL;
1359
1360 /* If root and /usr are combined then insist that the architecture matches */
1361 if (m->partitions[PARTITION_ROOT].found &&
1362 m->partitions[PARTITION_USR].found &&
1363 (m->partitions[PARTITION_ROOT].architecture >= 0 &&
1364 m->partitions[PARTITION_USR].architecture >= 0 &&
1365 m->partitions[PARTITION_ROOT].architecture != m->partitions[PARTITION_USR].architecture))
1366 return -EADDRNOTAVAIL;
1367
1368 if (!m->partitions[PARTITION_ROOT].found &&
1369 !m->partitions[PARTITION_USR].found &&
1370 (flags & DISSECT_IMAGE_GENERIC_ROOT) &&
1371 (!verity || !verity->root_hash || verity->designator != PARTITION_USR)) {
1372
1373 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1374 * that. If the root hash was set however, then we won't fall back to a generic node, because
1375 * the root hash decides. */
1376
1377 /* If we didn't find a properly marked root partition, but we did find a single suitable
1378 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1379 if (multiple_generic)
1380 return -ENOTUNIQ;
1381
1382 /* If we didn't find a generic node, then we can't fix this up either */
1383 if (generic_node) {
1384 r = image_policy_may_use(policy, PARTITION_ROOT);
1385 if (r < 0)
1386 return r;
1387 if (r == 0)
1388 /* Policy says: ignore; remember that we did */
1389 m->partitions[PARTITION_ROOT].ignored = true;
1390 else {
1391 _cleanup_close_ int mount_node_fd = -EBADF;
1392 _cleanup_free_ char *o = NULL, *n = NULL;
1393 const char *options;
1394
1395 if (FLAGS_SET(flags, DISSECT_IMAGE_PIN_PARTITION_DEVICES)) {
1396 mount_node_fd = open_partition(generic_node, /* is_partition = */ true, m->loop);
1397 if (mount_node_fd < 0)
1398 return mount_node_fd;
1399 }
1400
1401 r = make_partition_devname(devname, diskseq, generic_nr, flags, &n);
1402 if (r < 0)
1403 return r;
1404
1405 options = mount_options_from_designator(mount_options, PARTITION_ROOT);
1406 if (options) {
1407 o = strdup(options);
1408 if (!o)
1409 return -ENOMEM;
1410 }
1411
1412 assert(generic_nr >= 0);
1413 m->partitions[PARTITION_ROOT] = (DissectedPartition) {
1414 .found = true,
1415 .rw = generic_rw,
1416 .growfs = generic_growfs,
1417 .partno = generic_nr,
1418 .architecture = _ARCHITECTURE_INVALID,
1419 .node = TAKE_PTR(n),
1420 .uuid = generic_uuid,
1421 .mount_options = TAKE_PTR(o),
1422 .mount_node_fd = TAKE_FD(mount_node_fd),
1423 .offset = UINT64_MAX,
1424 .size = UINT64_MAX,
1425 };
1426 }
1427 }
1428 }
1429
1430 /* 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 */
1431 if (FLAGS_SET(flags, DISSECT_IMAGE_REQUIRE_ROOT) &&
1432 !(m->partitions[PARTITION_ROOT].found || (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1433 return -ENXIO;
1434
1435 if (m->partitions[PARTITION_ROOT_VERITY].found) {
1436 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1437 if (m->partitions[PARTITION_USR_VERITY].found)
1438 return -ENOTUNIQ;
1439
1440 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1441 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1442 if (m->partitions[PARTITION_USR].found)
1443 return -EADDRNOTAVAIL;
1444 }
1445
1446 if (verity) {
1447 /* If a verity designator is specified, then insist that the matching partition exists */
1448 if (verity->designator >= 0 && !m->partitions[verity->designator].found)
1449 return -EADDRNOTAVAIL;
1450
1451 bool have_verity_sig_partition =
1452 m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR_VERITY_SIG : PARTITION_ROOT_VERITY_SIG].found;
1453
1454 if (verity->root_hash) {
1455 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1456 * Verity, set things up for it */
1457
1458 if (verity->designator < 0 || verity->designator == PARTITION_ROOT) {
1459 if (!m->partitions[PARTITION_ROOT_VERITY].found || !m->partitions[PARTITION_ROOT].found)
1460 return -EADDRNOTAVAIL;
1461
1462 /* If we found a verity setup, then the root partition is necessarily read-only. */
1463 m->partitions[PARTITION_ROOT].rw = false;
1464 m->verity_ready = true;
1465
1466 } else {
1467 assert(verity->designator == PARTITION_USR);
1468
1469 if (!m->partitions[PARTITION_USR_VERITY].found || !m->partitions[PARTITION_USR].found)
1470 return -EADDRNOTAVAIL;
1471
1472 m->partitions[PARTITION_USR].rw = false;
1473 m->verity_ready = true;
1474 }
1475
1476 if (m->verity_ready)
1477 m->verity_sig_ready = verity->root_hash_sig || have_verity_sig_partition;
1478
1479 } else if (have_verity_sig_partition) {
1480
1481 /* If we found an embedded signature partition, we are ready, too. */
1482
1483 m->verity_ready = m->verity_sig_ready = true;
1484 m->partitions[verity->designator == PARTITION_USR ? PARTITION_USR : PARTITION_ROOT].rw = false;
1485 }
1486 }
1487
1488 /* After we discovered all partitions let's see if the verity requirements match the policy. (Note:
1489 * we don't check encryption requirements here, because we haven't probed the file system yet, hence
1490 * don't know if this is encrypted or not) */
1491 for (PartitionDesignator di = 0; di < _PARTITION_DESIGNATOR_MAX; di++) {
1492 PartitionDesignator vi, si;
1493 PartitionPolicyFlags found_flags;
1494
1495 vi = partition_verity_of(di);
1496 si = partition_verity_sig_of(di);
1497
1498 /* Determine the verity protection level for this partition. */
1499 found_flags = m->partitions[di].found ?
1500 (vi >= 0 && m->partitions[vi].found ?
1501 (si >= 0 && m->partitions[si].found ? PARTITION_POLICY_SIGNED : PARTITION_POLICY_VERITY) :
1502 PARTITION_POLICY_ENCRYPTED|PARTITION_POLICY_UNPROTECTED) :
1503 (m->partitions[di].ignored ? PARTITION_POLICY_UNUSED : PARTITION_POLICY_ABSENT);
1504
1505 r = image_policy_check_protection(policy, di, found_flags);
1506 if (r < 0)
1507 return r;
1508
1509 if (m->partitions[di].found) {
1510 r = image_policy_check_partition_flags(policy, di, m->partitions[di].gpt_flags);
1511 if (r < 0)
1512 return r;
1513 }
1514 }
1515
1516 r = dissected_image_probe_filesystems(m, fd, policy);
1517 if (r < 0)
1518 return r;
1519
1520 return 0;
1521 }
1522 #endif
1523
1524 int dissect_image_file(
1525 const char *path,
1526 const VeritySettings *verity,
1527 const MountOptions *mount_options,
1528 const ImagePolicy *image_policy,
1529 DissectImageFlags flags,
1530 DissectedImage **ret) {
1531
1532 #if HAVE_BLKID
1533 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1534 _cleanup_close_ int fd = -EBADF;
1535 int r;
1536
1537 assert(path);
1538 assert(ret);
1539
1540 fd = open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1541 if (fd < 0)
1542 return -errno;
1543
1544 r = fd_verify_regular(fd);
1545 if (r < 0)
1546 return r;
1547
1548 r = dissected_image_new(path, &m);
1549 if (r < 0)
1550 return r;
1551
1552 r = probe_sector_size(fd, &m->sector_size);
1553 if (r < 0)
1554 return r;
1555
1556 r = dissect_image(m, fd, path, verity, mount_options, image_policy, flags);
1557 if (r < 0)
1558 return r;
1559
1560 *ret = TAKE_PTR(m);
1561 return 0;
1562 #else
1563 return -EOPNOTSUPP;
1564 #endif
1565 }
1566
1567 DissectedImage* dissected_image_unref(DissectedImage *m) {
1568 if (!m)
1569 return NULL;
1570
1571 /* First, clear dissected partitions. */
1572 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
1573 dissected_partition_done(m->partitions + i);
1574
1575 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1576 * DecryptedImage may try to deactivate partitions. */
1577 decrypted_image_unref(m->decrypted_image);
1578
1579 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1580 * remove existing partitions on the loopback block device. */
1581 loop_device_unref(m->loop);
1582
1583 free(m->image_name);
1584 free(m->hostname);
1585 strv_free(m->machine_info);
1586 strv_free(m->os_release);
1587 strv_free(m->initrd_release);
1588 strv_free(m->extension_release);
1589
1590 return mfree(m);
1591 }
1592
1593 static int is_loop_device(const char *path) {
1594 char s[SYS_BLOCK_PATH_MAX("/../loop/")];
1595 struct stat st;
1596
1597 assert(path);
1598
1599 if (stat(path, &st) < 0)
1600 return -errno;
1601
1602 if (!S_ISBLK(st.st_mode))
1603 return -ENOTBLK;
1604
1605 xsprintf_sys_block_path(s, "/loop/", st.st_dev);
1606 if (access(s, F_OK) < 0) {
1607 if (errno != ENOENT)
1608 return -errno;
1609
1610 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1611 xsprintf_sys_block_path(s, "/../loop/", st.st_dev);
1612 if (access(s, F_OK) < 0)
1613 return errno == ENOENT ? false : -errno;
1614 }
1615
1616 return true;
1617 }
1618
1619 static int run_fsck(int node_fd, const char *fstype) {
1620 int r, exit_status;
1621 pid_t pid;
1622
1623 assert(node_fd >= 0);
1624 assert(fstype);
1625
1626 r = fsck_exists_for_fstype(fstype);
1627 if (r < 0) {
1628 log_debug_errno(r, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype);
1629 return 0;
1630 }
1631 if (r == 0) {
1632 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd), fstype);
1633 return 0;
1634 }
1635
1636 r = safe_fork_full(
1637 "(fsck)",
1638 NULL,
1639 &node_fd, 1, /* Leave the node fd open */
1640 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG|FORK_REARRANGE_STDIO|FORK_CLOEXEC_OFF,
1641 &pid);
1642 if (r < 0)
1643 return log_debug_errno(r, "Failed to fork off fsck: %m");
1644 if (r == 0) {
1645 /* Child */
1646 execl("/sbin/fsck", "/sbin/fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd), NULL);
1647 log_open();
1648 log_debug_errno(errno, "Failed to execl() fsck: %m");
1649 _exit(FSCK_OPERATIONAL_ERROR);
1650 }
1651
1652 exit_status = wait_for_terminate_and_check("fsck", pid, 0);
1653 if (exit_status < 0)
1654 return log_debug_errno(exit_status, "Failed to fork off /sbin/fsck: %m");
1655
1656 if ((exit_status & ~FSCK_ERROR_CORRECTED) != FSCK_SUCCESS) {
1657 log_debug("fsck failed with exit status %i.", exit_status);
1658
1659 if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
1660 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "File system is corrupted, refusing.");
1661
1662 log_debug("Ignoring fsck error.");
1663 }
1664
1665 return 0;
1666 }
1667
1668 static int fs_grow(const char *node_path, const char *mount_path) {
1669 _cleanup_close_ int mount_fd = -EBADF, node_fd = -EBADF;
1670 uint64_t size, newsize;
1671 int r;
1672
1673 node_fd = open(node_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
1674 if (node_fd < 0)
1675 return log_debug_errno(errno, "Failed to open node device %s: %m", node_path);
1676
1677 if (ioctl(node_fd, BLKGETSIZE64, &size) != 0)
1678 return log_debug_errno(errno, "Failed to get block device size of %s: %m", node_path);
1679
1680 mount_fd = open(mount_path, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
1681 if (mount_fd < 0)
1682 return log_debug_errno(errno, "Failed to open mountd file system %s: %m", mount_path);
1683
1684 log_debug("Resizing \"%s\" to %"PRIu64" bytes...", mount_path, size);
1685 r = resize_fs(mount_fd, size, &newsize);
1686 if (r < 0)
1687 return log_debug_errno(r, "Failed to resize \"%s\" to %"PRIu64" bytes: %m", mount_path, size);
1688
1689 if (newsize == size)
1690 log_debug("Successfully resized \"%s\" to %s bytes.",
1691 mount_path, FORMAT_BYTES(newsize));
1692 else {
1693 assert(newsize < size);
1694 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
1695 mount_path, FORMAT_BYTES(newsize), size - newsize);
1696 }
1697
1698 return 0;
1699 }
1700
1701 int partition_pick_mount_options(
1702 PartitionDesignator d,
1703 const char *fstype,
1704 bool rw,
1705 bool discard,
1706 char **ret_options,
1707 unsigned long *ret_ms_flags) {
1708
1709 _cleanup_free_ char *options = NULL;
1710
1711 assert(ret_options);
1712
1713 /* Selects a baseline of bind mount flags, that should always apply.
1714 *
1715 * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
1716 *
1717 * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
1718 *
1719 * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
1720 * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
1721 * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
1722 * there anyway. */
1723
1724 unsigned long flags = MS_NODEV;
1725
1726 if (!rw)
1727 flags |= MS_RDONLY;
1728
1729 switch (d) {
1730
1731 case PARTITION_ESP:
1732 case PARTITION_XBOOTLDR:
1733 flags |= MS_NOSUID|MS_NOEXEC|ms_nosymfollow_supported();
1734
1735 /* The ESP might contain a pre-boot random seed. Let's make this unaccessible to regular
1736 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
1737 if (!fstype || fstype_can_umask(fstype))
1738 if (!strextend_with_separator(&options, ",", "umask=0077"))
1739 return -ENOMEM;
1740 break;
1741
1742 case PARTITION_TMP:
1743 flags |= MS_NOSUID;
1744 break;
1745
1746 default:
1747 break;
1748 }
1749
1750 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1751 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1752 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1753 * from the upper file system still get propagated through to the underlying file system,
1754 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1755 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1756 * carry a per file system table here.
1757 *
1758 * Note that this means that we might not be able to mount corrupted file systems as read-only
1759 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1760 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1761 * mount options for loopback devices this is the right choice, since otherwise using the same
1762 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1763 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1764 * access that actually modifies stuff work on such image files. Or to say this differently: if
1765 * people want their file systems to be fixed up they should just open them in writable mode, where
1766 * all these problems don't exist. */
1767 if (!rw && fstype && fstype_can_norecovery(fstype))
1768 if (!strextend_with_separator(&options, ",", "norecovery"))
1769 return -ENOMEM;
1770
1771 if (discard && fstype && fstype_can_discard(fstype))
1772 if (!strextend_with_separator(&options, ",", "discard"))
1773 return -ENOMEM;
1774
1775 if (!ret_ms_flags) /* Fold flags into option string if ret_flags specified as NULL */
1776 if (!strextend_with_separator(&options, ",",
1777 FLAGS_SET(flags, MS_RDONLY) ? "ro" : "rw",
1778 FLAGS_SET(flags, MS_NODEV) ? "nodev" : "dev",
1779 FLAGS_SET(flags, MS_NOSUID) ? "nosuid" : "suid",
1780 FLAGS_SET(flags, MS_NOEXEC) ? "noexec" : "exec",
1781 FLAGS_SET(flags, MS_NOSYMFOLLOW) ? "nosymfollow" : NULL))
1782 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
1783 return -ENOMEM;
1784
1785 if (ret_ms_flags)
1786 *ret_ms_flags = flags;
1787
1788 *ret_options = TAKE_PTR(options);
1789 return 0;
1790 }
1791
1792 static int mount_partition(
1793 PartitionDesignator d,
1794 DissectedPartition *m,
1795 const char *where,
1796 const char *directory,
1797 uid_t uid_shift,
1798 uid_t uid_range,
1799 DissectImageFlags flags) {
1800
1801 _cleanup_free_ char *chased = NULL, *options = NULL;
1802 bool rw, discard, remap_uid_gid = false;
1803 const char *p, *node, *fstype;
1804 unsigned long ms_flags;
1805 int r;
1806
1807 assert(m);
1808 assert(where);
1809
1810 if (m->mount_node_fd < 0)
1811 return 0;
1812
1813 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1814 node = FORMAT_PROC_FD_PATH(m->mount_node_fd);
1815 fstype = dissected_partition_fstype(m);
1816
1817 if (!fstype)
1818 return -EAFNOSUPPORT;
1819 r = dissect_fstype_ok(fstype);
1820 if (r < 0)
1821 return r;
1822 if (!r)
1823 return -EIDRM; /* Recognizable error */
1824
1825 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1826 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1827 * case. */
1828 if (streq(fstype, "crypto_LUKS"))
1829 return -EUNATCH;
1830
1831 rw = m->rw && !(flags & DISSECT_IMAGE_MOUNT_READ_ONLY);
1832
1833 discard = ((flags & DISSECT_IMAGE_DISCARD) ||
1834 ((flags & DISSECT_IMAGE_DISCARD_ON_LOOP) && is_loop_device(m->node) > 0));
1835
1836 if (FLAGS_SET(flags, DISSECT_IMAGE_FSCK) && rw) {
1837 r = run_fsck(m->mount_node_fd, fstype);
1838 if (r < 0)
1839 return r;
1840 }
1841
1842 if (directory) {
1843 /* Automatically create missing mount points inside the image, if necessary. */
1844 r = mkdir_p_root(where, directory, uid_shift, (gid_t) uid_shift, 0755);
1845 if (r < 0 && r != -EROFS)
1846 return r;
1847
1848 r = chase(directory, where, CHASE_PREFIX_ROOT, &chased, NULL);
1849 if (r < 0)
1850 return r;
1851
1852 p = chased;
1853 } else {
1854 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1855 * image (as the branch above does) but the host hierarchy, and the created directory might
1856 * survive our mount in the host hierarchy hence. */
1857 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1858 r = mkdir_p(where, 0755);
1859 if (r < 0)
1860 return r;
1861 }
1862
1863 p = where;
1864 }
1865
1866 r = partition_pick_mount_options(d, dissected_partition_fstype(m), rw, discard, &options, &ms_flags);
1867 if (r < 0)
1868 return r;
1869
1870 if (uid_is_valid(uid_shift) && uid_shift != 0) {
1871
1872 if (fstype_can_uid_gid(fstype)) {
1873 _cleanup_free_ char *uid_option = NULL;
1874
1875 if (asprintf(&uid_option, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1876 return -ENOMEM;
1877
1878 if (!strextend_with_separator(&options, ",", uid_option))
1879 return -ENOMEM;
1880 } else if (FLAGS_SET(flags, DISSECT_IMAGE_MOUNT_IDMAPPED))
1881 remap_uid_gid = true;
1882 }
1883
1884 if (!isempty(m->mount_options))
1885 if (!strextend_with_separator(&options, ",", m->mount_options))
1886 return -ENOMEM;
1887
1888 r = mount_nofollow_verbose(LOG_DEBUG, node, p, fstype, ms_flags, options);
1889 if (r < 0)
1890 return r;
1891
1892 if (rw && m->growfs && FLAGS_SET(flags, DISSECT_IMAGE_GROWFS))
1893 (void) fs_grow(node, p);
1894
1895 if (remap_uid_gid) {
1896 r = remount_idmap(p, uid_shift, uid_range, UID_INVALID, REMOUNT_IDMAPPING_HOST_ROOT);
1897 if (r < 0)
1898 return r;
1899 }
1900
1901 return 1;
1902 }
1903
1904 static int mount_root_tmpfs(const char *where, uid_t uid_shift, DissectImageFlags flags) {
1905 _cleanup_free_ char *options = NULL;
1906 int r;
1907
1908 assert(where);
1909
1910 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1911
1912 if (FLAGS_SET(flags, DISSECT_IMAGE_MKDIR)) {
1913 r = mkdir_p(where, 0755);
1914 if (r < 0)
1915 return r;
1916 }
1917
1918 if (uid_is_valid(uid_shift)) {
1919 if (asprintf(&options, "uid=" UID_FMT ",gid=" GID_FMT, uid_shift, (gid_t) uid_shift) < 0)
1920 return -ENOMEM;
1921 }
1922
1923 r = mount_nofollow_verbose(LOG_DEBUG, "rootfs", where, "tmpfs", MS_NODEV, options);
1924 if (r < 0)
1925 return r;
1926
1927 return 1;
1928 }
1929
1930 int dissected_image_mount(
1931 DissectedImage *m,
1932 const char *where,
1933 uid_t uid_shift,
1934 uid_t uid_range,
1935 DissectImageFlags flags) {
1936
1937 int r, xbootldr_mounted;
1938
1939 assert(m);
1940 assert(where);
1941
1942 /* Returns:
1943 *
1944 * -ENXIO → No root partition found
1945 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1946 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1947 * -EUCLEAN → fsck for file system failed
1948 * -EBUSY → File system already mounted/used elsewhere (kernel)
1949 * -EAFNOSUPPORT → File system type not supported or not known
1950 * -EIDRM → File system is not among allowlisted "common" file systems
1951 */
1952
1953 if (!(m->partitions[PARTITION_ROOT].found ||
1954 (m->partitions[PARTITION_USR].found && FLAGS_SET(flags, DISSECT_IMAGE_USR_NO_ROOT))))
1955 return -ENXIO; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1956
1957 if ((flags & DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY) == 0) {
1958
1959 /* First mount the root fs. If there's none we use a tmpfs. */
1960 if (m->partitions[PARTITION_ROOT].found)
1961 r = mount_partition(PARTITION_ROOT, m->partitions + PARTITION_ROOT, where, NULL, uid_shift, uid_range, flags);
1962 else
1963 r = mount_root_tmpfs(where, uid_shift, flags);
1964 if (r < 0)
1965 return r;
1966
1967 /* For us mounting root always means mounting /usr as well */
1968 r = mount_partition(PARTITION_USR, m->partitions + PARTITION_USR, where, "/usr", uid_shift, uid_range, flags);
1969 if (r < 0)
1970 return r;
1971
1972 if ((flags & (DISSECT_IMAGE_VALIDATE_OS|DISSECT_IMAGE_VALIDATE_OS_EXT)) != 0) {
1973 /* If either one of the validation flags are set, ensure that the image qualifies
1974 * as one or the other (or both). */
1975 bool ok = false;
1976
1977 if (FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS)) {
1978 r = path_is_os_tree(where);
1979 if (r < 0)
1980 return r;
1981 if (r > 0)
1982 ok = true;
1983 }
1984 if (!ok && FLAGS_SET(flags, DISSECT_IMAGE_VALIDATE_OS_EXT)) {
1985 r = extension_has_forbidden_content(where);
1986 if (r < 0)
1987 return r;
1988 if (r == 0) {
1989 r = path_is_extension_tree(where, m->image_name, FLAGS_SET(flags, DISSECT_IMAGE_RELAX_SYSEXT_CHECK));
1990 if (r < 0)
1991 return r;
1992 if (r > 0)
1993 ok = true;
1994 }
1995 }
1996
1997 if (!ok)
1998 return -ENOMEDIUM;
1999 }
2000 }
2001
2002 if (flags & DISSECT_IMAGE_MOUNT_ROOT_ONLY)
2003 return 0;
2004
2005 r = mount_partition(PARTITION_HOME, m->partitions + PARTITION_HOME, where, "/home", uid_shift, uid_range, flags);
2006 if (r < 0)
2007 return r;
2008
2009 r = mount_partition(PARTITION_SRV, m->partitions + PARTITION_SRV, where, "/srv", uid_shift, uid_range, flags);
2010 if (r < 0)
2011 return r;
2012
2013 r = mount_partition(PARTITION_VAR, m->partitions + PARTITION_VAR, where, "/var", uid_shift, uid_range, flags);
2014 if (r < 0)
2015 return r;
2016
2017 r = mount_partition(PARTITION_TMP, m->partitions + PARTITION_TMP, where, "/var/tmp", uid_shift, uid_range, flags);
2018 if (r < 0)
2019 return r;
2020
2021 xbootldr_mounted = mount_partition(PARTITION_XBOOTLDR, m->partitions + PARTITION_XBOOTLDR, where, "/boot", uid_shift, uid_range, flags);
2022 if (xbootldr_mounted < 0)
2023 return xbootldr_mounted;
2024
2025 if (m->partitions[PARTITION_ESP].found) {
2026 int esp_done = false;
2027
2028 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
2029 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
2030
2031 r = chase("/efi", where, CHASE_PREFIX_ROOT, NULL, NULL);
2032 if (r < 0) {
2033 if (r != -ENOENT)
2034 return r;
2035
2036 /* /efi doesn't exist. Let's see if /boot is suitable then */
2037
2038 if (!xbootldr_mounted) {
2039 _cleanup_free_ char *p = NULL;
2040
2041 r = chase("/boot", where, CHASE_PREFIX_ROOT, &p, NULL);
2042 if (r < 0) {
2043 if (r != -ENOENT)
2044 return r;
2045 } else if (dir_is_empty(p, /* ignore_hidden_or_backup= */ false) > 0) {
2046 /* It exists and is an empty directory. Let's mount the ESP there. */
2047 r = mount_partition(PARTITION_ESP, m->partitions + PARTITION_ESP, where, "/boot", uid_shift, uid_range, flags);
2048 if (r < 0)
2049 return r;
2050
2051 esp_done = true;
2052 }
2053 }
2054 }
2055
2056 if (!esp_done) {
2057 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
2058
2059 r = mount_partition(PARTITION_ESP, m->partitions + PARTITION_ESP, where, "/efi", uid_shift, uid_range, flags);
2060 if (r < 0)
2061 return r;
2062 }
2063 }
2064
2065 return 0;
2066 }
2067
2068 int dissected_image_mount_and_warn(
2069 DissectedImage *m,
2070 const char *where,
2071 uid_t uid_shift,
2072 uid_t uid_range,
2073 DissectImageFlags flags) {
2074
2075 int r;
2076
2077 assert(m);
2078 assert(where);
2079
2080 r = dissected_image_mount(m, where, uid_shift, uid_range, flags);
2081 if (r == -ENXIO)
2082 return log_error_errno(r, "Not root file system found in image.");
2083 if (r == -EMEDIUMTYPE)
2084 return log_error_errno(r, "No suitable os-release/extension-release file in image found.");
2085 if (r == -EUNATCH)
2086 return log_error_errno(r, "Encrypted file system discovered, but decryption not requested.");
2087 if (r == -EUCLEAN)
2088 return log_error_errno(r, "File system check on image failed.");
2089 if (r == -EBUSY)
2090 return log_error_errno(r, "File system already mounted elsewhere.");
2091 if (r == -EAFNOSUPPORT)
2092 return log_error_errno(r, "File system type not supported or not known.");
2093 if (r == -EIDRM)
2094 return log_error_errno(r, "File system is too uncommon, refused.");
2095 if (r < 0)
2096 return log_error_errno(r, "Failed to mount image: %m");
2097
2098 return r;
2099 }
2100
2101 #if HAVE_LIBCRYPTSETUP
2102 struct DecryptedPartition {
2103 struct crypt_device *device;
2104 char *name;
2105 bool relinquished;
2106 };
2107 #endif
2108
2109 typedef struct DecryptedPartition DecryptedPartition;
2110
2111 struct DecryptedImage {
2112 unsigned n_ref;
2113 DecryptedPartition *decrypted;
2114 size_t n_decrypted;
2115 };
2116
2117 static DecryptedImage* decrypted_image_free(DecryptedImage *d) {
2118 #if HAVE_LIBCRYPTSETUP
2119 int r;
2120
2121 if (!d)
2122 return NULL;
2123
2124 for (size_t i = 0; i < d->n_decrypted; i++) {
2125 DecryptedPartition *p = d->decrypted + i;
2126
2127 if (p->device && p->name && !p->relinquished) {
2128 _cleanup_free_ char *node = NULL;
2129
2130 node = path_join("/dev/mapper", p->name);
2131 if (node) {
2132 r = btrfs_forget_device(node);
2133 if (r < 0 && r != -ENOENT)
2134 log_debug_errno(r, "Failed to forget btrfs device %s, ignoring: %m", node);
2135 } else
2136 log_oom_debug();
2137
2138 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2139 r = sym_crypt_deactivate_by_name(p->device, p->name, CRYPT_DEACTIVATE_DEFERRED);
2140 if (r < 0)
2141 log_debug_errno(r, "Failed to deactivate encrypted partition %s", p->name);
2142 }
2143
2144 if (p->device)
2145 sym_crypt_free(p->device);
2146 free(p->name);
2147 }
2148
2149 free(d->decrypted);
2150 free(d);
2151 #endif
2152 return NULL;
2153 }
2154
2155 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage, decrypted_image, decrypted_image_free);
2156
2157 #if HAVE_LIBCRYPTSETUP
2158 static int decrypted_image_new(DecryptedImage **ret) {
2159 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2160
2161 assert(ret);
2162
2163 d = new(DecryptedImage, 1);
2164 if (!d)
2165 return -ENOMEM;
2166
2167 *d = (DecryptedImage) {
2168 .n_ref = 1,
2169 };
2170
2171 *ret = TAKE_PTR(d);
2172 return 0;
2173 }
2174
2175 static int make_dm_name_and_node(const void *original_node, const char *suffix, char **ret_name, char **ret_node) {
2176 _cleanup_free_ char *name = NULL, *node = NULL;
2177 const char *base;
2178
2179 assert(original_node);
2180 assert(suffix);
2181 assert(ret_name);
2182 assert(ret_node);
2183
2184 base = strrchr(original_node, '/');
2185 if (!base)
2186 base = original_node;
2187 else
2188 base++;
2189 if (isempty(base))
2190 return -EINVAL;
2191
2192 name = strjoin(base, suffix);
2193 if (!name)
2194 return -ENOMEM;
2195 if (!filename_is_valid(name))
2196 return -EINVAL;
2197
2198 node = path_join(sym_crypt_get_dir(), name);
2199 if (!node)
2200 return -ENOMEM;
2201
2202 *ret_name = TAKE_PTR(name);
2203 *ret_node = TAKE_PTR(node);
2204
2205 return 0;
2206 }
2207
2208 static int decrypt_partition(
2209 DissectedPartition *m,
2210 const char *passphrase,
2211 DissectImageFlags flags,
2212 DecryptedImage *d) {
2213
2214 _cleanup_free_ char *node = NULL, *name = NULL;
2215 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2216 _cleanup_close_ int fd = -EBADF;
2217 int r;
2218
2219 assert(m);
2220 assert(d);
2221
2222 if (!m->found || !m->node || !m->fstype)
2223 return 0;
2224
2225 if (!streq(m->fstype, "crypto_LUKS"))
2226 return 0;
2227
2228 if (!passphrase)
2229 return -ENOKEY;
2230
2231 r = dlopen_cryptsetup();
2232 if (r < 0)
2233 return r;
2234
2235 r = make_dm_name_and_node(m->node, "-decrypted", &name, &node);
2236 if (r < 0)
2237 return r;
2238
2239 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2240 return -ENOMEM;
2241
2242 r = sym_crypt_init(&cd, m->node);
2243 if (r < 0)
2244 return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
2245
2246 cryptsetup_enable_logging(cd);
2247
2248 r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
2249 if (r < 0)
2250 return log_debug_errno(r, "Failed to load LUKS metadata: %m");
2251
2252 r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
2253 ((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) ? CRYPT_ACTIVATE_READONLY : 0) |
2254 ((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
2255 if (r < 0) {
2256 log_debug_errno(r, "Failed to activate LUKS device: %m");
2257 return r == -EPERM ? -EKEYREJECTED : r;
2258 }
2259
2260 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2261 if (fd < 0)
2262 return log_debug_errno(errno, "Failed to open %s: %m", node);
2263
2264 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2265 .name = TAKE_PTR(name),
2266 .device = TAKE_PTR(cd),
2267 };
2268
2269 m->decrypted_node = TAKE_PTR(node);
2270 close_and_replace(m->mount_node_fd, fd);
2271
2272 return 0;
2273 }
2274
2275 static int verity_can_reuse(
2276 const VeritySettings *verity,
2277 const char *name,
2278 struct crypt_device **ret_cd) {
2279
2280 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2281 _cleanup_free_ char *root_hash_existing = NULL;
2282 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2283 struct crypt_params_verity crypt_params = {};
2284 size_t root_hash_existing_size;
2285 int r;
2286
2287 assert(verity);
2288 assert(name);
2289 assert(ret_cd);
2290
2291 r = sym_crypt_init_by_name(&cd, name);
2292 if (r < 0)
2293 return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
2294
2295 cryptsetup_enable_logging(cd);
2296
2297 r = sym_crypt_get_verity_info(cd, &crypt_params);
2298 if (r < 0)
2299 return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
2300
2301 root_hash_existing_size = verity->root_hash_size;
2302 root_hash_existing = malloc0(root_hash_existing_size);
2303 if (!root_hash_existing)
2304 return -ENOMEM;
2305
2306 r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing, &root_hash_existing_size, NULL, 0);
2307 if (r < 0)
2308 return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
2309 if (verity->root_hash_size != root_hash_existing_size ||
2310 memcmp(root_hash_existing, verity->root_hash, verity->root_hash_size) != 0)
2311 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
2312
2313 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2314 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2315 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2316 * signing for the new one, and vice versa. */
2317 if (!!verity->root_hash_sig != !!(crypt_params.flags & CRYPT_VERITY_ROOT_HASH_SIGNATURE))
2318 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
2319 #endif
2320
2321 *ret_cd = TAKE_PTR(cd);
2322 return 0;
2323 }
2324
2325 static inline char* dm_deferred_remove_clean(char *name) {
2326 if (!name)
2327 return NULL;
2328
2329 (void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
2330 return mfree(name);
2331 }
2332 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
2333
2334 static int validate_signature_userspace(const VeritySettings *verity) {
2335 #if HAVE_OPENSSL
2336 _cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
2337 _cleanup_strv_free_ char **certs = NULL;
2338 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
2339 _cleanup_free_ char *s = NULL;
2340 _cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
2341 * of declaration in place, please */
2342 const unsigned char *d;
2343 int r;
2344
2345 assert(verity);
2346 assert(verity->root_hash);
2347 assert(verity->root_hash_sig);
2348
2349 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
2350 * userspace validation. */
2351
2352 r = conf_files_list_nulstr(&certs, ".crt", NULL, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
2353 if (r < 0)
2354 return log_debug_errno(r, "Failed to enumerate certificates: %m");
2355 if (strv_isempty(certs)) {
2356 log_debug("No userspace dm-verity certificates found.");
2357 return 0;
2358 }
2359
2360 d = verity->root_hash_sig;
2361 p7 = d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig_size);
2362 if (!p7)
2363 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
2364
2365 s = hexmem(verity->root_hash, verity->root_hash_size);
2366 if (!s)
2367 return log_oom_debug();
2368
2369 bio = BIO_new_mem_buf(s, strlen(s));
2370 if (!bio)
2371 return log_oom_debug();
2372
2373 sk = sk_X509_new_null();
2374 if (!sk)
2375 return log_oom_debug();
2376
2377 STRV_FOREACH(i, certs) {
2378 _cleanup_(X509_freep) X509 *c = NULL;
2379 _cleanup_fclose_ FILE *f = NULL;
2380
2381 f = fopen(*i, "re");
2382 if (!f) {
2383 log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
2384 continue;
2385 }
2386
2387 c = PEM_read_X509(f, NULL, NULL, NULL);
2388 if (!c) {
2389 log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
2390 continue;
2391 }
2392
2393 if (sk_X509_push(sk, c) == 0)
2394 return log_oom_debug();
2395
2396 TAKE_PTR(c);
2397 }
2398
2399 r = PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
2400 if (r)
2401 log_debug("Userspace PKCS#7 validation succeeded.");
2402 else
2403 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL));
2404
2405 return r;
2406 #else
2407 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2408 return 0;
2409 #endif
2410 }
2411
2412 static int do_crypt_activate_verity(
2413 struct crypt_device *cd,
2414 const char *name,
2415 const VeritySettings *verity) {
2416
2417 bool check_signature;
2418 int r;
2419
2420 assert(cd);
2421 assert(name);
2422 assert(verity);
2423
2424 if (verity->root_hash_sig) {
2425 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2426 if (r < 0 && r != -ENXIO)
2427 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2428
2429 check_signature = r != 0;
2430 } else
2431 check_signature = false;
2432
2433 if (check_signature) {
2434
2435 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2436 /* First, if we have support for signed keys in the kernel, then try that first. */
2437 r = sym_crypt_activate_by_signed_key(
2438 cd,
2439 name,
2440 verity->root_hash,
2441 verity->root_hash_size,
2442 verity->root_hash_sig,
2443 verity->root_hash_sig_size,
2444 CRYPT_ACTIVATE_READONLY);
2445 if (r >= 0)
2446 return r;
2447
2448 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
2449 #else
2450 log_debug("Activation of verity device with signature requested, but not supported via the kernel by %s due to missing crypt_activate_by_signed_key(), trying userspace validation instead.",
2451 program_invocation_short_name);
2452 #endif
2453
2454 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2455 * works we'll try to activate without telling the kernel the signature. */
2456
2457 r = validate_signature_userspace(verity);
2458 if (r < 0)
2459 return r;
2460 if (r == 0)
2461 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY),
2462 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2463 }
2464
2465 return sym_crypt_activate_by_volume_key(
2466 cd,
2467 name,
2468 verity->root_hash,
2469 verity->root_hash_size,
2470 CRYPT_ACTIVATE_READONLY);
2471 }
2472
2473 static usec_t verity_timeout(void) {
2474 usec_t t = 100 * USEC_PER_MSEC;
2475 const char *e;
2476 int r;
2477
2478 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2479 * Let's make the timeout configurable. */
2480
2481 e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2482 if (!e)
2483 return t;
2484
2485 r = parse_sec(e, &t);
2486 if (r < 0)
2487 log_debug_errno(r,
2488 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2489 "using the default timeout (%s).",
2490 FORMAT_TIMESPAN(t, USEC_PER_MSEC));
2491
2492 return t;
2493 }
2494
2495 static int verity_partition(
2496 PartitionDesignator designator,
2497 DissectedPartition *m,
2498 DissectedPartition *v,
2499 const VeritySettings *verity,
2500 DissectImageFlags flags,
2501 DecryptedImage *d) {
2502
2503 _cleanup_(sym_crypt_freep) struct crypt_device *cd = NULL;
2504 _cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
2505 _cleanup_free_ char *node = NULL, *name = NULL;
2506 _cleanup_close_ int mount_node_fd = -EBADF;
2507 int r;
2508
2509 assert(m);
2510 assert(v || (verity && verity->data_path));
2511
2512 if (!verity || !verity->root_hash)
2513 return 0;
2514 if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
2515 (verity->designator == designator)))
2516 return 0;
2517
2518 if (!m->found || !m->node || !m->fstype)
2519 return 0;
2520 if (!verity->data_path) {
2521 if (!v->found || !v->node || !v->fstype)
2522 return 0;
2523
2524 if (!streq(v->fstype, "DM_verity_hash"))
2525 return 0;
2526 }
2527
2528 r = dlopen_cryptsetup();
2529 if (r < 0)
2530 return r;
2531
2532 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2533 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2534 _cleanup_free_ char *root_hash_encoded = NULL;
2535
2536 root_hash_encoded = hexmem(verity->root_hash, verity->root_hash_size);
2537 if (!root_hash_encoded)
2538 return -ENOMEM;
2539
2540 r = make_dm_name_and_node(root_hash_encoded, "-verity", &name, &node);
2541 } else
2542 r = make_dm_name_and_node(m->node, "-verity", &name, &node);
2543 if (r < 0)
2544 return r;
2545
2546 r = sym_crypt_init(&cd, verity->data_path ?: v->node);
2547 if (r < 0)
2548 return r;
2549
2550 cryptsetup_enable_logging(cd);
2551
2552 r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
2553 if (r < 0)
2554 return r;
2555
2556 r = sym_crypt_set_data_device(cd, m->node);
2557 if (r < 0)
2558 return r;
2559
2560 if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
2561 return -ENOMEM;
2562
2563 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2564 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2565 * retry a few times before giving up. */
2566 for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
2567 _cleanup_(sym_crypt_freep) struct crypt_device *existing_cd = NULL;
2568 _cleanup_close_ int fd = -EBADF;
2569
2570 /* First, check if the device already exists. */
2571 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2572 if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
2573 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2574 if (fd >= 0)
2575 goto check; /* The device already exists. Let's check it. */
2576
2577 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2578 r = do_crypt_activate_verity(cd, name, verity);
2579 if (r >= 0)
2580 goto try_open; /* The device is activated. Let's open it. */
2581 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2582 * There's no way to distinguish this situation from a genuine error due to invalid
2583 * parameters, so immediately fall back to activating the device with a unique name.
2584 * Improvements in libcrypsetup can ensure this never happens:
2585 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2586 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2587 break;
2588 if (r == -ENODEV) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2589 goto try_again;
2590 if (!IN_SET(r,
2591 -EEXIST, /* Volume has already been opened and ready to be used. */
2592 -EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2593 return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
2594
2595 check:
2596 if (!restore_deferred_remove){
2597 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2598 r = dm_deferred_remove_cancel(name);
2599 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2600 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2601 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2602 if (IN_SET(r, -EBUSY, -ENXIO))
2603 goto try_again;
2604 if (r < 0)
2605 return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
2606
2607 restore_deferred_remove = strdup(name);
2608 if (!restore_deferred_remove)
2609 return log_oom_debug();
2610 }
2611
2612 r = verity_can_reuse(verity, name, &existing_cd);
2613 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2614 if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2615 break;
2616 if (IN_SET(r,
2617 -ENOENT, /* Removed?? */
2618 -EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2619 -ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2620 goto try_again;
2621 if (r < 0)
2622 return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
2623
2624 if (fd < 0) {
2625 /* devmapper might say that the device exists, but the devlink might not yet have been
2626 * created. Check and wait for the udev event in that case. */
2627 r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
2628 /* Fallback to activation with a unique device if it's taking too long */
2629 if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
2630 break;
2631 if (r < 0)
2632 return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
2633 }
2634
2635 try_open:
2636 if (fd < 0) {
2637 /* Now, the device is activated and devlink is created. Let's open it. */
2638 fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
2639 if (fd < 0) {
2640 if (!ERRNO_IS_DEVICE_ABSENT(errno))
2641 return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
2642
2643 /* The device has already been removed?? */
2644 goto try_again;
2645 }
2646 }
2647
2648 mount_node_fd = TAKE_FD(fd);
2649 if (existing_cd)
2650 crypt_free_and_replace(cd, existing_cd);
2651
2652 goto success;
2653
2654 try_again:
2655 /* Device is being removed by another process. Let's wait for a while. */
2656 (void) usleep(2 * USEC_PER_MSEC);
2657 }
2658
2659 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2660 if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
2661 /* Before trying to activate with unique name, we need to free crypt_device object.
2662 * Otherwise, we get error from libcryptsetup like the following:
2663 * ------
2664 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2665 * ------
2666 */
2667 sym_crypt_free(cd);
2668 cd = NULL;
2669 return verity_partition(designator, m, v, verity, flags & ~DISSECT_IMAGE_VERITY_SHARE, d);
2670 }
2671
2672 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
2673
2674 success:
2675 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2676 restore_deferred_remove = mfree(restore_deferred_remove);
2677
2678 d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
2679 .name = TAKE_PTR(name),
2680 .device = TAKE_PTR(cd),
2681 };
2682
2683 m->decrypted_node = TAKE_PTR(node);
2684 close_and_replace(m->mount_node_fd, mount_node_fd);
2685
2686 return 0;
2687 }
2688 #endif
2689
2690 int dissected_image_decrypt(
2691 DissectedImage *m,
2692 const char *passphrase,
2693 const VeritySettings *verity,
2694 DissectImageFlags flags) {
2695
2696 #if HAVE_LIBCRYPTSETUP
2697 _cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
2698 int r;
2699 #endif
2700
2701 assert(m);
2702 assert(!verity || verity->root_hash || verity->root_hash_size == 0);
2703
2704 /* Returns:
2705 *
2706 * = 0 → There was nothing to decrypt
2707 * > 0 → Decrypted successfully
2708 * -ENOKEY → There's something to decrypt but no key was supplied
2709 * -EKEYREJECTED → Passed key was not correct
2710 */
2711
2712 if (verity && verity->root_hash && verity->root_hash_size < sizeof(sd_id128_t))
2713 return -EINVAL;
2714
2715 if (!m->encrypted && !m->verity_ready)
2716 return 0;
2717
2718 #if HAVE_LIBCRYPTSETUP
2719 r = decrypted_image_new(&d);
2720 if (r < 0)
2721 return r;
2722
2723 for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
2724 DissectedPartition *p = m->partitions + i;
2725 PartitionDesignator k;
2726
2727 if (!p->found)
2728 continue;
2729
2730 r = decrypt_partition(p, passphrase, flags, d);
2731 if (r < 0)
2732 return r;
2733
2734 k = partition_verity_of(i);
2735 if (k >= 0) {
2736 r = verity_partition(i, p, m->partitions + k, verity, flags | DISSECT_IMAGE_VERITY_SHARE, d);
2737 if (r < 0)
2738 return r;
2739 }
2740
2741 if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
2742 r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, 0, UINT64_MAX, &p->decrypted_fstype);
2743 if (r < 0 && r != -EUCLEAN)
2744 return r;
2745 }
2746 }
2747
2748 m->decrypted_image = TAKE_PTR(d);
2749
2750 return 1;
2751 #else
2752 return -EOPNOTSUPP;
2753 #endif
2754 }
2755
2756 int dissected_image_decrypt_interactively(
2757 DissectedImage *m,
2758 const char *passphrase,
2759 const VeritySettings *verity,
2760 DissectImageFlags flags) {
2761
2762 _cleanup_strv_free_erase_ char **z = NULL;
2763 int n = 3, r;
2764
2765 if (passphrase)
2766 n--;
2767
2768 for (;;) {
2769 r = dissected_image_decrypt(m, passphrase, verity, flags);
2770 if (r >= 0)
2771 return r;
2772 if (r == -EKEYREJECTED)
2773 log_error_errno(r, "Incorrect passphrase, try again!");
2774 else if (r != -ENOKEY)
2775 return log_error_errno(r, "Failed to decrypt image: %m");
2776
2777 if (--n < 0)
2778 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
2779 "Too many retries.");
2780
2781 z = strv_free(z);
2782
2783 r = ask_password_auto("Please enter image passphrase:", NULL, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY, 0, &z);
2784 if (r < 0)
2785 return log_error_errno(r, "Failed to query for passphrase: %m");
2786
2787 passphrase = z[0];
2788 }
2789 }
2790
2791 static int decrypted_image_relinquish(DecryptedImage *d) {
2792 assert(d);
2793
2794 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2795 * boolean so that we don't clean it up ourselves either anymore */
2796
2797 #if HAVE_LIBCRYPTSETUP
2798 int r;
2799
2800 for (size_t i = 0; i < d->n_decrypted; i++) {
2801 DecryptedPartition *p = d->decrypted + i;
2802
2803 if (p->relinquished)
2804 continue;
2805
2806 r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
2807 if (r < 0)
2808 return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
2809
2810 p->relinquished = true;
2811 }
2812 #endif
2813
2814 return 0;
2815 }
2816
2817 int dissected_image_relinquish(DissectedImage *m) {
2818 int r;
2819
2820 assert(m);
2821
2822 if (m->decrypted_image) {
2823 r = decrypted_image_relinquish(m->decrypted_image);
2824 if (r < 0)
2825 return r;
2826 }
2827
2828 if (m->loop)
2829 loop_device_relinquish(m->loop);
2830
2831 return 0;
2832 }
2833
2834 static char *build_auxiliary_path(const char *image, const char *suffix) {
2835 const char *e;
2836 char *n;
2837
2838 assert(image);
2839 assert(suffix);
2840
2841 e = endswith(image, ".raw");
2842 if (!e)
2843 return strjoin(e, suffix);
2844
2845 n = new(char, e - image + strlen(suffix) + 1);
2846 if (!n)
2847 return NULL;
2848
2849 strcpy(mempcpy(n, image, e - image), suffix);
2850 return n;
2851 }
2852
2853 void verity_settings_done(VeritySettings *v) {
2854 assert(v);
2855
2856 v->root_hash = mfree(v->root_hash);
2857 v->root_hash_size = 0;
2858
2859 v->root_hash_sig = mfree(v->root_hash_sig);
2860 v->root_hash_sig_size = 0;
2861
2862 v->data_path = mfree(v->data_path);
2863 }
2864
2865 int verity_settings_load(
2866 VeritySettings *verity,
2867 const char *image,
2868 const char *root_hash_path,
2869 const char *root_hash_sig_path) {
2870
2871 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
2872 size_t root_hash_size = 0, root_hash_sig_size = 0;
2873 _cleanup_free_ char *verity_data_path = NULL;
2874 PartitionDesignator designator;
2875 int r;
2876
2877 assert(verity);
2878 assert(image);
2879 assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
2880
2881 /* If we are asked to load the root hash for a device node, exit early */
2882 if (is_device_path(image))
2883 return 0;
2884
2885 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2886 if (r < 0 && r != -ENXIO)
2887 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2888 if (r == 0)
2889 return 0;
2890
2891 designator = verity->designator;
2892
2893 /* We only fill in what isn't already filled in */
2894
2895 if (!verity->root_hash) {
2896 _cleanup_free_ char *text = NULL;
2897
2898 if (root_hash_path) {
2899 /* If explicitly specified it takes precedence */
2900 r = read_one_line_file(root_hash_path, &text);
2901 if (r < 0)
2902 return r;
2903
2904 if (designator < 0)
2905 designator = PARTITION_ROOT;
2906 } else {
2907 /* Otherwise look for xattr and separate file, and first for the data for root and if
2908 * that doesn't exist for /usr */
2909
2910 if (designator < 0 || designator == PARTITION_ROOT) {
2911 r = getxattr_malloc(image, "user.verity.roothash", &text);
2912 if (r < 0) {
2913 _cleanup_free_ char *p = NULL;
2914
2915 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
2916 return r;
2917
2918 p = build_auxiliary_path(image, ".roothash");
2919 if (!p)
2920 return -ENOMEM;
2921
2922 r = read_one_line_file(p, &text);
2923 if (r < 0 && r != -ENOENT)
2924 return r;
2925 }
2926
2927 if (text)
2928 designator = PARTITION_ROOT;
2929 }
2930
2931 if (!text && (designator < 0 || designator == PARTITION_USR)) {
2932 /* So in the "roothash" xattr/file name above the "root" of course primarily
2933 * refers to the root of the Verity Merkle tree. But coincidentally it also
2934 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2935 * two distinct concepts called "root". Taking benefit of this happy
2936 * coincidence we call the file with the root hash for the /usr/ file system
2937 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2938 * confusing. We thus drop the reference to the root of the Merkle tree, and
2939 * just indicate which file system it's about. */
2940 r = getxattr_malloc(image, "user.verity.usrhash", &text);
2941 if (r < 0) {
2942 _cleanup_free_ char *p = NULL;
2943
2944 if (r != -ENOENT && !ERRNO_IS_XATTR_ABSENT(r))
2945 return r;
2946
2947 p = build_auxiliary_path(image, ".usrhash");
2948 if (!p)
2949 return -ENOMEM;
2950
2951 r = read_one_line_file(p, &text);
2952 if (r < 0 && r != -ENOENT)
2953 return r;
2954 }
2955
2956 if (text)
2957 designator = PARTITION_USR;
2958 }
2959 }
2960
2961 if (text) {
2962 r = unhexmem(text, strlen(text), &root_hash, &root_hash_size);
2963 if (r < 0)
2964 return r;
2965 if (root_hash_size < sizeof(sd_id128_t))
2966 return -EINVAL;
2967 }
2968 }
2969
2970 if ((root_hash || verity->root_hash) && !verity->root_hash_sig) {
2971 if (root_hash_sig_path) {
2972 r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig, &root_hash_sig_size);
2973 if (r < 0 && r != -ENOENT)
2974 return r;
2975
2976 if (designator < 0)
2977 designator = PARTITION_ROOT;
2978 } else {
2979 if (designator < 0 || designator == PARTITION_ROOT) {
2980 _cleanup_free_ char *p = NULL;
2981
2982 /* Follow naming convention recommended by the relevant RFC:
2983 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2984 p = build_auxiliary_path(image, ".roothash.p7s");
2985 if (!p)
2986 return -ENOMEM;
2987
2988 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
2989 if (r < 0 && r != -ENOENT)
2990 return r;
2991 if (r >= 0)
2992 designator = PARTITION_ROOT;
2993 }
2994
2995 if (!root_hash_sig && (designator < 0 || designator == PARTITION_USR)) {
2996 _cleanup_free_ char *p = NULL;
2997
2998 p = build_auxiliary_path(image, ".usrhash.p7s");
2999 if (!p)
3000 return -ENOMEM;
3001
3002 r = read_full_file(p, (char**) &root_hash_sig, &root_hash_sig_size);
3003 if (r < 0 && r != -ENOENT)
3004 return r;
3005 if (r >= 0)
3006 designator = PARTITION_USR;
3007 }
3008 }
3009
3010 if (root_hash_sig && root_hash_sig_size == 0) /* refuse empty size signatures */
3011 return -EINVAL;
3012 }
3013
3014 if (!verity->data_path) {
3015 _cleanup_free_ char *p = NULL;
3016
3017 p = build_auxiliary_path(image, ".verity");
3018 if (!p)
3019 return -ENOMEM;
3020
3021 if (access(p, F_OK) < 0) {
3022 if (errno != ENOENT)
3023 return -errno;
3024 } else
3025 verity_data_path = TAKE_PTR(p);
3026 }
3027
3028 if (root_hash) {
3029 verity->root_hash = TAKE_PTR(root_hash);
3030 verity->root_hash_size = root_hash_size;
3031 }
3032
3033 if (root_hash_sig) {
3034 verity->root_hash_sig = TAKE_PTR(root_hash_sig);
3035 verity->root_hash_sig_size = root_hash_sig_size;
3036 }
3037
3038 if (verity_data_path)
3039 verity->data_path = TAKE_PTR(verity_data_path);
3040
3041 if (verity->designator < 0)
3042 verity->designator = designator;
3043
3044 return 1;
3045 }
3046
3047 int dissected_image_load_verity_sig_partition(
3048 DissectedImage *m,
3049 int fd,
3050 VeritySettings *verity) {
3051
3052 _cleanup_free_ void *root_hash = NULL, *root_hash_sig = NULL;
3053 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
3054 size_t root_hash_size, root_hash_sig_size;
3055 _cleanup_free_ char *buf = NULL;
3056 PartitionDesignator d;
3057 DissectedPartition *p;
3058 JsonVariant *rh, *sig;
3059 ssize_t n;
3060 char *e;
3061 int r;
3062
3063 assert(m);
3064 assert(fd >= 0);
3065 assert(verity);
3066
3067 if (verity->root_hash && verity->root_hash_sig) /* Already loaded? */
3068 return 0;
3069
3070 r = getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
3071 if (r < 0 && r != -ENXIO)
3072 log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
3073 if (r == 0)
3074 return 0;
3075
3076 d = partition_verity_sig_of(verity->designator < 0 ? PARTITION_ROOT : verity->designator);
3077 assert(d >= 0);
3078
3079 p = m->partitions + d;
3080 if (!p->found)
3081 return 0;
3082 if (p->offset == UINT64_MAX || p->size == UINT64_MAX)
3083 return -EINVAL;
3084
3085 if (p->size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
3086 return -EFBIG;
3087
3088 buf = new(char, p->size+1);
3089 if (!buf)
3090 return -ENOMEM;
3091
3092 n = pread(fd, buf, p->size, p->offset);
3093 if (n < 0)
3094 return -ENOMEM;
3095 if ((uint64_t) n != p->size)
3096 return -EIO;
3097
3098 e = memchr(buf, 0, p->size);
3099 if (e) {
3100 /* If we found a NUL byte then the rest of the data must be NUL too */
3101 if (!memeqzero(e, p->size - (e - buf)))
3102 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
3103 } else
3104 buf[p->size] = 0;
3105
3106 r = json_parse(buf, 0, &v, NULL, NULL);
3107 if (r < 0)
3108 return log_debug_errno(r, "Failed to parse signature JSON data: %m");
3109
3110 rh = json_variant_by_key(v, "rootHash");
3111 if (!rh)
3112 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
3113 if (!json_variant_is_string(rh))
3114 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'rootHash' field of signature JSON object is not a string.");
3115
3116 r = unhexmem(json_variant_string(rh), SIZE_MAX, &root_hash, &root_hash_size);
3117 if (r < 0)
3118 return log_debug_errno(r, "Failed to parse root hash field: %m");
3119
3120 /* Check if specified root hash matches if it is specified */
3121 if (verity->root_hash &&
3122 memcmp_nn(verity->root_hash, verity->root_hash_size, root_hash, root_hash_size) != 0) {
3123 _cleanup_free_ char *a = NULL, *b = NULL;
3124
3125 a = hexmem(root_hash, root_hash_size);
3126 b = hexmem(verity->root_hash, verity->root_hash_size);
3127
3128 return log_debug_errno(r, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a), strna(b));
3129 }
3130
3131 sig = json_variant_by_key(v, "signature");
3132 if (!sig)
3133 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
3134 if (!json_variant_is_string(sig))
3135 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'signature' field of signature JSON object is not a string.");
3136
3137 r = unbase64mem(json_variant_string(sig), SIZE_MAX, &root_hash_sig, &root_hash_sig_size);
3138 if (r < 0)
3139 return log_debug_errno(r, "Failed to parse signature field: %m");
3140
3141 free_and_replace(verity->root_hash, root_hash);
3142 verity->root_hash_size = root_hash_size;
3143
3144 free_and_replace(verity->root_hash_sig, root_hash_sig);
3145 verity->root_hash_sig_size = root_hash_sig_size;
3146
3147 return 1;
3148 }
3149
3150 int dissected_image_acquire_metadata(DissectedImage *m, DissectImageFlags extra_flags) {
3151
3152 enum {
3153 META_HOSTNAME,
3154 META_MACHINE_ID,
3155 META_MACHINE_INFO,
3156 META_OS_RELEASE,
3157 META_INITRD_RELEASE,
3158 META_EXTENSION_RELEASE,
3159 META_HAS_INIT_SYSTEM,
3160 _META_MAX,
3161 };
3162
3163 static const char *const paths[_META_MAX] = {
3164 [META_HOSTNAME] = "/etc/hostname\0",
3165 [META_MACHINE_ID] = "/etc/machine-id\0",
3166 [META_MACHINE_INFO] = "/etc/machine-info\0",
3167 [META_OS_RELEASE] = ("/etc/os-release\0"
3168 "/usr/lib/os-release\0"),
3169 [META_INITRD_RELEASE] = ("/etc/initrd-release\0"
3170 "/usr/lib/initrd-release\0"),
3171 [META_EXTENSION_RELEASE] = "extension-release\0", /* Used only for logging. */
3172 [META_HAS_INIT_SYSTEM] = "has-init-system\0", /* ditto */
3173 };
3174
3175 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **initrd_release = NULL, **extension_release = NULL;
3176 _cleanup_close_pair_ int error_pipe[2] = PIPE_EBADF;
3177 _cleanup_(rmdir_and_freep) char *t = NULL;
3178 _cleanup_(sigkill_waitp) pid_t child = 0;
3179 sd_id128_t machine_id = SD_ID128_NULL;
3180 _cleanup_free_ char *hostname = NULL;
3181 unsigned n_meta_initialized = 0;
3182 int fds[2 * _META_MAX], r, v;
3183 int has_init_system = -1;
3184 ssize_t n;
3185
3186 BLOCK_SIGNALS(SIGCHLD);
3187
3188 assert(m);
3189
3190 for (; n_meta_initialized < _META_MAX; n_meta_initialized ++) {
3191 if (!paths[n_meta_initialized]) {
3192 fds[2*n_meta_initialized] = fds[2*n_meta_initialized+1] = -EBADF;
3193 continue;
3194 }
3195
3196 if (pipe2(fds + 2*n_meta_initialized, O_CLOEXEC) < 0) {
3197 r = -errno;
3198 goto finish;
3199 }
3200 }
3201
3202 r = mkdtemp_malloc("/tmp/dissect-XXXXXX", &t);
3203 if (r < 0)
3204 goto finish;
3205
3206 if (pipe2(error_pipe, O_CLOEXEC) < 0) {
3207 r = -errno;
3208 goto finish;
3209 }
3210
3211 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, &child);
3212 if (r < 0)
3213 goto finish;
3214 if (r == 0) {
3215 /* Child in a new mount namespace */
3216 error_pipe[0] = safe_close(error_pipe[0]);
3217
3218 r = dissected_image_mount(
3219 m,
3220 t,
3221 UID_INVALID,
3222 UID_INVALID,
3223 extra_flags |
3224 DISSECT_IMAGE_READ_ONLY |
3225 DISSECT_IMAGE_MOUNT_ROOT_ONLY |
3226 DISSECT_IMAGE_USR_NO_ROOT);
3227 if (r < 0) {
3228 log_debug_errno(r, "Failed to mount dissected image: %m");
3229 goto inner_fail;
3230 }
3231
3232 for (unsigned k = 0; k < _META_MAX; k++) {
3233 _cleanup_close_ int fd = -ENOENT;
3234
3235 if (!paths[k])
3236 continue;
3237
3238 fds[2*k] = safe_close(fds[2*k]);
3239
3240 switch (k) {
3241
3242 case META_EXTENSION_RELEASE:
3243 /* As per the os-release spec, if the image is an extension it will have a file
3244 * named after the image name in extension-release.d/ - we use the image name
3245 * and try to resolve it with the extension-release helpers, as sometimes
3246 * the image names are mangled on deployment and do not match anymore.
3247 * Unlike other paths this is not fixed, and the image name
3248 * can be mangled on deployment, so by calling into the helper
3249 * we allow a fallback that matches on the first extension-release
3250 * file found in the directory, if one named after the image cannot
3251 * be found first. */
3252 r = open_extension_release(t, m->image_name, /* relax_extension_release_check= */ false, NULL, &fd);
3253 if (r < 0)
3254 fd = r; /* Propagate the error. */
3255 break;
3256
3257 case META_HAS_INIT_SYSTEM: {
3258 bool found = false;
3259
3260 FOREACH_STRING(init,
3261 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
3262 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
3263 "/sbin/init") { /* traditional path the Linux kernel invokes */
3264
3265 r = chase(init, t, CHASE_PREFIX_ROOT, NULL, NULL);
3266 if (r < 0) {
3267 if (r != -ENOENT)
3268 log_debug_errno(r, "Failed to resolve %s, ignoring: %m", init);
3269 } else {
3270 found = true;
3271 break;
3272 }
3273 }
3274
3275 r = loop_write(fds[2*k+1], &found, sizeof(found), false);
3276 if (r < 0)
3277 goto inner_fail;
3278
3279 continue;
3280 }
3281
3282 default:
3283 NULSTR_FOREACH(p, paths[k]) {
3284 fd = chase_and_open(p, t, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC|O_NOCTTY, NULL);
3285 if (fd >= 0)
3286 break;
3287 }
3288 }
3289
3290 if (fd < 0) {
3291 log_debug_errno(fd, "Failed to read %s file of image, ignoring: %m", paths[k]);
3292 fds[2*k+1] = safe_close(fds[2*k+1]);
3293 continue;
3294 }
3295
3296 r = copy_bytes(fd, fds[2*k+1], UINT64_MAX, 0);
3297 if (r < 0)
3298 goto inner_fail;
3299
3300 fds[2*k+1] = safe_close(fds[2*k+1]);
3301 }
3302
3303 _exit(EXIT_SUCCESS);
3304
3305 inner_fail:
3306 /* Let parent know the error */
3307 (void) write(error_pipe[1], &r, sizeof(r));
3308 _exit(EXIT_FAILURE);
3309 }
3310
3311 error_pipe[1] = safe_close(error_pipe[1]);
3312
3313 for (unsigned k = 0; k < _META_MAX; k++) {
3314 _cleanup_fclose_ FILE *f = NULL;
3315
3316 if (!paths[k])
3317 continue;
3318
3319 fds[2*k+1] = safe_close(fds[2*k+1]);
3320
3321 f = take_fdopen(&fds[2*k], "r");
3322 if (!f) {
3323 r = -errno;
3324 goto finish;
3325 }
3326
3327 switch (k) {
3328
3329 case META_HOSTNAME:
3330 r = read_etc_hostname_stream(f, &hostname);
3331 if (r < 0)
3332 log_debug_errno(r, "Failed to read /etc/hostname of image: %m");
3333
3334 break;
3335
3336 case META_MACHINE_ID: {
3337 _cleanup_free_ char *line = NULL;
3338
3339 r = read_line(f, LONG_LINE_MAX, &line);
3340 if (r < 0)
3341 log_debug_errno(r, "Failed to read /etc/machine-id of image: %m");
3342 else if (r == 33) {
3343 r = sd_id128_from_string(line, &machine_id);
3344 if (r < 0)
3345 log_debug_errno(r, "Image contains invalid /etc/machine-id: %s", line);
3346 } else if (r == 0)
3347 log_debug("/etc/machine-id file of image is empty.");
3348 else if (streq(line, "uninitialized"))
3349 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3350 else
3351 log_debug("/etc/machine-id file of image has unexpected length %i.", r);
3352
3353 break;
3354 }
3355
3356 case META_MACHINE_INFO:
3357 r = load_env_file_pairs(f, "machine-info", &machine_info);
3358 if (r < 0)
3359 log_debug_errno(r, "Failed to read /etc/machine-info of image: %m");
3360
3361 break;
3362
3363 case META_OS_RELEASE:
3364 r = load_env_file_pairs(f, "os-release", &os_release);
3365 if (r < 0)
3366 log_debug_errno(r, "Failed to read OS release file of image: %m");
3367
3368 break;
3369
3370 case META_INITRD_RELEASE:
3371 r = load_env_file_pairs(f, "initrd-release", &initrd_release);
3372 if (r < 0)
3373 log_debug_errno(r, "Failed to read initrd release file of image: %m");
3374
3375 break;
3376
3377 case META_EXTENSION_RELEASE:
3378 r = load_env_file_pairs(f, "extension-release", &extension_release);
3379 if (r < 0)
3380 log_debug_errno(r, "Failed to read extension release file of image: %m");
3381
3382 break;
3383
3384 case META_HAS_INIT_SYSTEM: {
3385 bool b = false;
3386 size_t nr;
3387
3388 errno = 0;
3389 nr = fread(&b, 1, sizeof(b), f);
3390 if (nr != sizeof(b))
3391 log_debug_errno(errno_or_else(EIO), "Failed to read has-init-system boolean: %m");
3392 else
3393 has_init_system = b;
3394
3395 break;
3396 }}
3397 }
3398
3399 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
3400 child = 0;
3401 if (r < 0)
3402 return r;
3403
3404 n = read(error_pipe[0], &v, sizeof(v));
3405 if (n < 0)
3406 return -errno;
3407 if (n == sizeof(v))
3408 return v; /* propagate error sent to us from child */
3409 if (n != 0)
3410 return -EIO;
3411
3412 if (r != EXIT_SUCCESS)
3413 return -EPROTO;
3414
3415 free_and_replace(m->hostname, hostname);
3416 m->machine_id = machine_id;
3417 strv_free_and_replace(m->machine_info, machine_info);
3418 strv_free_and_replace(m->os_release, os_release);
3419 strv_free_and_replace(m->initrd_release, initrd_release);
3420 strv_free_and_replace(m->extension_release, extension_release);
3421 m->has_init_system = has_init_system;
3422
3423 finish:
3424 for (unsigned k = 0; k < n_meta_initialized; k++)
3425 safe_close_pair(fds + 2*k);
3426
3427 return r;
3428 }
3429
3430 Architecture dissected_image_architecture(DissectedImage *img) {
3431 assert(img);
3432
3433 if (img->partitions[PARTITION_ROOT].found &&
3434 img->partitions[PARTITION_ROOT].architecture >= 0)
3435 return img->partitions[PARTITION_ROOT].architecture;
3436
3437 if (img->partitions[PARTITION_USR].found &&
3438 img->partitions[PARTITION_USR].architecture >= 0)
3439 return img->partitions[PARTITION_USR].architecture;
3440
3441 return _ARCHITECTURE_INVALID;
3442 }
3443
3444 int dissect_loop_device(
3445 LoopDevice *loop,
3446 const VeritySettings *verity,
3447 const MountOptions *mount_options,
3448 const ImagePolicy *image_policy,
3449 DissectImageFlags flags,
3450 DissectedImage **ret) {
3451
3452 #if HAVE_BLKID
3453 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
3454 int r;
3455
3456 assert(loop);
3457 assert(ret);
3458
3459 r = dissected_image_new(loop->backing_file ?: loop->node, &m);
3460 if (r < 0)
3461 return r;
3462
3463 m->loop = loop_device_ref(loop);
3464 m->sector_size = m->loop->sector_size;
3465
3466 r = dissect_image(m, loop->fd, loop->node, verity, mount_options, image_policy, flags);
3467 if (r < 0)
3468 return r;
3469
3470 *ret = TAKE_PTR(m);
3471 return 0;
3472 #else
3473 return -EOPNOTSUPP;
3474 #endif
3475 }
3476
3477 int dissect_loop_device_and_warn(
3478 LoopDevice *loop,
3479 const VeritySettings *verity,
3480 const MountOptions *mount_options,
3481 const ImagePolicy *image_policy,
3482 DissectImageFlags flags,
3483 DissectedImage **ret) {
3484
3485 const char *name;
3486 int r;
3487
3488 assert(loop);
3489 assert(loop->fd >= 0);
3490
3491 name = ASSERT_PTR(loop->backing_file ?: loop->node);
3492
3493 r = dissect_loop_device(loop, verity, mount_options, image_policy, flags, ret);
3494 switch (r) {
3495
3496 case -EOPNOTSUPP:
3497 return log_error_errno(r, "Dissecting images is not supported, compiled without blkid support.");
3498
3499 case -ENOPKG:
3500 return log_error_errno(r, "%s: Couldn't identify a suitable partition table or file system.", name);
3501
3502 case -ENOMEDIUM:
3503 return log_error_errno(r, "%s: The image does not pass validation.", name);
3504
3505 case -EADDRNOTAVAIL:
3506 return log_error_errno(r, "%s: No root partition for specified root hash found.", name);
3507
3508 case -ENOTUNIQ:
3509 return log_error_errno(r, "%s: Multiple suitable root partitions found in image.", name);
3510
3511 case -ENXIO:
3512 return log_error_errno(r, "%s: No suitable root partition found in image.", name);
3513
3514 case -EPROTONOSUPPORT:
3515 return log_error_errno(r, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name);
3516
3517 case -ENOTBLK:
3518 return log_error_errno(r, "%s: Image is not a block device.", name);
3519
3520 case -EBADR:
3521 return log_error_errno(r,
3522 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
3523 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
3524 name, strna(verity ? verity->data_path : NULL));
3525
3526 default:
3527 if (r < 0)
3528 return log_error_errno(r, "Failed to dissect image '%s': %m", name);
3529
3530 return r;
3531 }
3532 }
3533
3534 bool dissected_image_verity_candidate(const DissectedImage *image, PartitionDesignator partition_designator) {
3535 assert(image);
3536
3537 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3538 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3539 * images we only check the partition type.
3540 *
3541 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3542 * image. */
3543
3544 if (image->single_file_system)
3545 return partition_designator == PARTITION_ROOT && image->has_verity;
3546
3547 return partition_verity_of(partition_designator) >= 0;
3548 }
3549
3550 bool dissected_image_verity_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3551 PartitionDesignator k;
3552
3553 assert(image);
3554
3555 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3556 * works for the root partition, for others only if the associated verity partition was found. */
3557
3558 if (!image->verity_ready)
3559 return false;
3560
3561 if (image->single_file_system)
3562 return partition_designator == PARTITION_ROOT;
3563
3564 k = partition_verity_of(partition_designator);
3565 return k >= 0 && image->partitions[k].found;
3566 }
3567
3568 bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesignator partition_designator) {
3569 PartitionDesignator k;
3570
3571 assert(image);
3572
3573 /* Checks if this partition has verity signature data available that we can use. */
3574
3575 if (!image->verity_sig_ready)
3576 return false;
3577
3578 if (image->single_file_system)
3579 return partition_designator == PARTITION_ROOT;
3580
3581 k = partition_verity_sig_of(partition_designator);
3582 return k >= 0 && image->partitions[k].found;
3583 }
3584
3585 MountOptions* mount_options_free_all(MountOptions *options) {
3586 MountOptions *m;
3587
3588 while ((m = options)) {
3589 LIST_REMOVE(mount_options, options, m);
3590 free(m->options);
3591 free(m);
3592 }
3593
3594 return NULL;
3595 }
3596
3597 const char* mount_options_from_designator(const MountOptions *options, PartitionDesignator designator) {
3598 LIST_FOREACH(mount_options, m, options)
3599 if (designator == m->partition_designator && !isempty(m->options))
3600 return m->options;
3601
3602 return NULL;
3603 }
3604
3605 int mount_image_privately_interactively(
3606 const char *image,
3607 const ImagePolicy *image_policy,
3608 DissectImageFlags flags,
3609 char **ret_directory,
3610 int *ret_dir_fd,
3611 LoopDevice **ret_loop_device) {
3612
3613 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3614 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
3615 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3616 _cleanup_(rmdir_and_freep) char *created_dir = NULL;
3617 _cleanup_free_ char *temp = NULL;
3618 int r;
3619
3620 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3621 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3622 * easily. */
3623
3624 assert(image);
3625 assert(ret_directory);
3626 assert(ret_loop_device);
3627
3628 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
3629 flags |= DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3630 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
3631
3632 r = verity_settings_load(&verity, image, NULL, NULL);
3633 if (r < 0)
3634 return log_error_errno(r, "Failed to load root hash data: %m");
3635
3636 r = tempfn_random_child(NULL, program_invocation_short_name, &temp);
3637 if (r < 0)
3638 return log_error_errno(r, "Failed to generate temporary mount directory: %m");
3639
3640 r = loop_device_make_by_path(
3641 image,
3642 FLAGS_SET(flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : O_RDWR,
3643 /* sector_size= */ UINT32_MAX,
3644 FLAGS_SET(flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
3645 LOCK_SH,
3646 &d);
3647 if (r < 0)
3648 return log_error_errno(r, "Failed to set up loopback device for %s: %m", image);
3649
3650 r = dissect_loop_device_and_warn(
3651 d,
3652 &verity,
3653 /* mount_options= */ NULL,
3654 image_policy,
3655 flags,
3656 &dissected_image);
3657 if (r < 0)
3658 return r;
3659
3660 r = dissected_image_load_verity_sig_partition(dissected_image, d->fd, &verity);
3661 if (r < 0)
3662 return r;
3663
3664 r = dissected_image_decrypt_interactively(dissected_image, NULL, &verity, flags);
3665 if (r < 0)
3666 return r;
3667
3668 r = detach_mount_namespace();
3669 if (r < 0)
3670 return log_error_errno(r, "Failed to detach mount namespace: %m");
3671
3672 r = mkdir_p(temp, 0700);
3673 if (r < 0)
3674 return log_error_errno(r, "Failed to create mount point: %m");
3675
3676 created_dir = TAKE_PTR(temp);
3677
3678 r = dissected_image_mount_and_warn(dissected_image, created_dir, UID_INVALID, UID_INVALID, flags);
3679 if (r < 0)
3680 return r;
3681
3682 r = loop_device_flock(d, LOCK_UN);
3683 if (r < 0)
3684 return r;
3685
3686 r = dissected_image_relinquish(dissected_image);
3687 if (r < 0)
3688 return log_error_errno(r, "Failed to relinquish DM and loopback block devices: %m");
3689
3690 if (ret_dir_fd) {
3691 _cleanup_close_ int dir_fd = -EBADF;
3692
3693 dir_fd = open(created_dir, O_CLOEXEC|O_DIRECTORY);
3694 if (dir_fd < 0)
3695 return log_error_errno(errno, "Failed to open mount point directory: %m");
3696
3697 *ret_dir_fd = TAKE_FD(dir_fd);
3698 }
3699
3700 *ret_directory = TAKE_PTR(created_dir);
3701 *ret_loop_device = TAKE_PTR(d);
3702
3703 return 0;
3704 }
3705
3706 static bool mount_options_relax_extension_release_checks(const MountOptions *options) {
3707 if (!options)
3708 return false;
3709
3710 return string_contains_word(mount_options_from_designator(options, PARTITION_ROOT), ",", "x-systemd.relax-extension-release-check") ||
3711 string_contains_word(mount_options_from_designator(options, PARTITION_USR), ",", "x-systemd.relax-extension-release-check") ||
3712 string_contains_word(options->options, ",", "x-systemd.relax-extension-release-check");
3713 }
3714
3715 int verity_dissect_and_mount(
3716 int src_fd,
3717 const char *src,
3718 const char *dest,
3719 const MountOptions *options,
3720 const ImagePolicy *image_policy,
3721 const char *required_host_os_release_id,
3722 const char *required_host_os_release_version_id,
3723 const char *required_host_os_release_sysext_level,
3724 const char *required_sysext_scope) {
3725
3726 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3727 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
3728 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
3729 DissectImageFlags dissect_image_flags;
3730 bool relax_extension_release_check;
3731 int r;
3732
3733 assert(src);
3734 assert(dest);
3735
3736 relax_extension_release_check = mount_options_relax_extension_release_checks(options);
3737
3738 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3739 r = verity_settings_load(&verity, src, NULL, NULL);
3740 if (r < 0)
3741 return log_debug_errno(r, "Failed to load root hash: %m");
3742
3743 dissect_image_flags = (verity.data_path ? DISSECT_IMAGE_NO_PARTITION_TABLE : 0) |
3744 (relax_extension_release_check ? DISSECT_IMAGE_RELAX_SYSEXT_CHECK : 0) |
3745 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
3746 DISSECT_IMAGE_PIN_PARTITION_DEVICES;
3747
3748 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3749 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
3750 r = loop_device_make_by_path(
3751 src_fd >= 0 ? FORMAT_PROC_FD_PATH(src_fd) : src,
3752 /* open_flags= */ -1,
3753 /* sector_size= */ UINT32_MAX,
3754 verity.data_path ? 0 : LO_FLAGS_PARTSCAN,
3755 LOCK_SH,
3756 &loop_device);
3757 if (r < 0)
3758 return log_debug_errno(r, "Failed to create loop device for image: %m");
3759
3760 r = dissect_loop_device(
3761 loop_device,
3762 &verity,
3763 options,
3764 image_policy,
3765 dissect_image_flags,
3766 &dissected_image);
3767 /* No partition table? Might be a single-filesystem image, try again */
3768 if (!verity.data_path && r == -ENOPKG)
3769 r = dissect_loop_device(
3770 loop_device,
3771 &verity,
3772 options,
3773 image_policy,
3774 dissect_image_flags | DISSECT_IMAGE_NO_PARTITION_TABLE,
3775 &dissected_image);
3776 if (r < 0)
3777 return log_debug_errno(r, "Failed to dissect image: %m");
3778
3779 r = dissected_image_load_verity_sig_partition(dissected_image, loop_device->fd, &verity);
3780 if (r < 0)
3781 return r;
3782
3783 r = dissected_image_decrypt(
3784 dissected_image,
3785 NULL,
3786 &verity,
3787 dissect_image_flags);
3788 if (r < 0)
3789 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
3790
3791 r = mkdir_p_label(dest, 0755);
3792 if (r < 0)
3793 return log_debug_errno(r, "Failed to create destination directory %s: %m", dest);
3794 r = umount_recursive(dest, 0);
3795 if (r < 0)
3796 return log_debug_errno(r, "Failed to umount under destination directory %s: %m", dest);
3797
3798 r = dissected_image_mount(dissected_image, dest, UID_INVALID, UID_INVALID, dissect_image_flags);
3799 if (r < 0)
3800 return log_debug_errno(r, "Failed to mount image: %m");
3801
3802 r = loop_device_flock(loop_device, LOCK_UN);
3803 if (r < 0)
3804 return log_debug_errno(r, "Failed to unlock loopback device: %m");
3805
3806 /* If we got os-release values from the caller, then we need to match them with the image's
3807 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3808 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3809 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3810 * then a simple match on the ID will be performed. */
3811 if (required_host_os_release_id) {
3812 _cleanup_strv_free_ char **extension_release = NULL;
3813
3814 assert(!isempty(required_host_os_release_id));
3815
3816 r = load_extension_release_pairs(dest, dissected_image->image_name, relax_extension_release_check, &extension_release);
3817 if (r < 0)
3818 return log_debug_errno(r, "Failed to parse image %s extension-release metadata: %m", dissected_image->image_name);
3819
3820 r = extension_release_validate(
3821 dissected_image->image_name,
3822 required_host_os_release_id,
3823 required_host_os_release_version_id,
3824 required_host_os_release_sysext_level,
3825 required_sysext_scope,
3826 extension_release);
3827 if (r == 0)
3828 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", dissected_image->image_name);
3829 if (r < 0)
3830 return log_debug_errno(r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image->image_name);
3831 }
3832
3833 r = dissected_image_relinquish(dissected_image);
3834 if (r < 0)
3835 return log_debug_errno(r, "Failed to relinquish dissected image: %m");
3836
3837 return 0;
3838 }