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