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