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