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