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