1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
7 #include <linux/dm-ioctl.h>
8 #include <linux/loop.h>
10 #include <sys/mount.h>
11 #include <sys/prctl.h>
16 #include <openssl/err.h>
17 #include <openssl/pem.h>
18 #include <openssl/x509.h>
21 #include "sd-device.h"
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"
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"
41 #include "extension-release.h"
45 #include "fsck-util.h"
47 #include "hexdecoct.h"
48 #include "hostname-setup.h"
49 #include "id128-util.h"
50 #include "import-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"
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"
69 #include "tmpfile-util.h"
70 #include "udev-util.h"
71 #include "user-util.h"
72 #include "xattr-util.h"
74 /* how many times to wait for the device nodes to appear */
75 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
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. */
83 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
84 _cleanup_free_
char *path_by_fd
= NULL
;
85 _cleanup_close_
int fd_close
= -1;
89 assert(fd
>= 0 || path
);
93 fd_close
= open(path
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
101 r
= fd_get_path(fd
, &path_by_fd
);
108 b
= blkid_new_probe();
113 r
= blkid_probe_set_device(b
, fd
, 0, 0);
115 return errno_or_else(ENOMEM
);
117 blkid_probe_enable_superblocks(b
, 1);
118 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
121 r
= blkid_do_safeprobe(b
);
125 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
126 "Results ambiguous for partition %s", path
);
128 return log_debug_errno(errno_or_else(EIO
), "Failed to probe partition %s: %m", path
);
130 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
135 log_debug("Probed fstype '%s' on partition %s.", fstype
, path
);
146 log_debug("No type detected on partition %s", path
);
155 static int dissected_image_probe_filesystem(DissectedImage
*m
) {
160 /* Fill in file system types if we don't know them yet. */
162 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
163 DissectedPartition
*p
= m
->partitions
+ i
;
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
)
174 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
177 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
187 static void check_partition_flags(
189 unsigned long long pflags
,
190 unsigned long long supported
) {
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
);
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
))
209 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
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
;
223 _cleanup_free_
char *filename
= NULL
;
225 r
= path_extract_filename(path
, &filename
);
229 r
= raw_strip_suffixes(filename
, &name
);
233 if (!image_name_is_valid(name
)) {
234 log_debug("Image name %s is not valid, ignoring.", strna(name
));
239 m
= new(DissectedImage
, 1);
243 *m
= (DissectedImage
) {
244 .has_init_system
= -1,
245 .image_name
= TAKE_PTR(name
),
248 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
249 m
->partitions
[i
] = DISSECTED_PARTITION_NULL
;
256 static void dissected_partition_done(DissectedPartition
*p
) {
262 free(p
->decrypted_fstype
);
263 free(p
->decrypted_node
);
264 free(p
->mount_options
);
265 safe_close(p
->mount_node_fd
);
267 *p
= DISSECTED_PARTITION_NULL
;
271 static int make_partition_devname(
272 const char *whole_devname
,
278 assert(whole_devname
);
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'. */
286 if (isempty(whole_devname
)) /* Make sure there *is* a last char */
289 need_p
= ascii_isdigit(whole_devname
[strlen(whole_devname
)-1]); /* Last char a digit? */
291 return asprintf(ret
, "%s%s%i", whole_devname
, need_p
? "p" : "", nr
);
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;
303 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
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
);
312 r
= sd_device_get_devnum(dev
, &devnum
);
316 if (loop
->devno
!= devnum
)
319 /* Also check diskseq. */
320 if (loop
->diskseq
> 0) {
323 r
= fd_get_diskseq(fd
, &diskseq
);
327 if (loop
->diskseq
!= diskseq
)
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
);
336 static int dissect_image(
340 const VeritySettings
*verity
,
341 const MountOptions
*mount_options
,
342 DissectImageFlags flags
) {
344 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
345 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
346 bool is_gpt
, is_mbr
, multiple_generic
= false,
347 generic_rw
= false, /* initialize to appease gcc */
348 generic_growfs
= false;
349 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
350 _cleanup_free_
char *generic_node
= NULL
;
351 sd_id128_t generic_uuid
= SD_ID128_NULL
;
352 const char *pttype
= NULL
, *sptuuid
= NULL
;
354 int r
, generic_nr
= -1, n_partitions
;
359 assert(!verity
|| verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
360 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
361 assert(!verity
|| verity
->root_hash_sig
|| verity
->root_hash_sig_size
== 0);
362 assert(!verity
|| (verity
->root_hash
|| !verity
->root_hash_sig
));
363 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
365 /* Probes a disk image, and returns information about what it found in *ret.
367 * Returns -ENOPKG if no suitable partition table or file system could be found.
368 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
369 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
370 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
372 if (verity
&& verity
->root_hash
) {
373 sd_id128_t fsuuid
, vuuid
;
375 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
376 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
377 * the final 128bit. */
379 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
382 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
383 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
385 if (sd_id128_is_null(fsuuid
))
387 if (sd_id128_is_null(vuuid
))
390 /* If the verity data declares it's for the /usr partition, then search for that, in all
391 * other cases assume it's for the root partition. */
392 if (verity
->designator
== PARTITION_USR
) {
394 usr_verity_uuid
= vuuid
;
397 root_verity_uuid
= vuuid
;
401 b
= blkid_new_probe();
406 r
= blkid_probe_set_device(b
, fd
, 0, 0);
408 return errno_or_else(ENOMEM
);
410 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
411 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
412 blkid_probe_enable_superblocks(b
, 1);
413 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
|BLKID_SUBLKS_UUID
);
416 blkid_probe_enable_partitions(b
, 1);
417 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
420 r
= blkid_do_safeprobe(b
);
421 if (IN_SET(r
, -2, 1))
422 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
424 return errno_or_else(EIO
);
426 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
427 (flags
& DISSECT_IMAGE_GENERIC_ROOT
)) ||
428 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
429 const char *usage
= NULL
;
431 /* If flags permit this, also allow using non-partitioned single-filesystem images */
433 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
434 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
435 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
436 const char *fstype
= NULL
, *options
= NULL
, *suuid
= NULL
;
437 _cleanup_close_
int mount_node_fd
= -1;
438 sd_id128_t uuid
= SD_ID128_NULL
;
440 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
441 mount_node_fd
= open_partition(devname
, /* is_partition = */ false, m
->loop
);
442 if (mount_node_fd
< 0)
443 return mount_node_fd
;
446 /* OK, we have found a file system, that's our root partition then. */
447 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
448 (void) blkid_probe_lookup_value(b
, "UUID", &suuid
, NULL
);
457 /* blkid will return FAT's serial number as UUID, hence it is quite possible
458 * that parsing this will fail. We'll ignore the ID, since it's just too
459 * short to be useful as tru identifier. */
460 r
= sd_id128_from_string(suuid
, &uuid
);
462 log_debug_errno(r
, "Failed to parse file system UUID '%s', ignoring: %m", suuid
);
469 m
->single_file_system
= true;
470 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
472 m
->has_verity
= verity
&& verity
->data_path
;
473 m
->verity_ready
= m
->has_verity
&&
475 (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
);
477 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
478 m
->verity_sig_ready
= m
->verity_ready
&&
479 verity
->root_hash_sig
;
481 m
->image_uuid
= uuid
;
483 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
490 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
492 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
494 .architecture
= _ARCHITECTURE_INVALID
,
495 .fstype
= TAKE_PTR(t
),
497 .mount_options
= TAKE_PTR(o
),
498 .mount_node_fd
= TAKE_FD(mount_node_fd
),
507 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
511 is_gpt
= streq_ptr(pttype
, "gpt");
512 is_mbr
= streq_ptr(pttype
, "dos");
514 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
517 /* We support external verity data partitions only if the image has no partition table */
518 if (verity
&& verity
->data_path
)
521 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
522 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
523 * do partition scanning. */
524 r
= blockdev_partscan_enabled(fd
);
528 return -EPROTONOSUPPORT
;
531 (void) blkid_probe_lookup_value(b
, "PTUUID", &sptuuid
, NULL
);
533 r
= sd_id128_from_string(sptuuid
, &m
->image_uuid
);
535 log_debug_errno(r
, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid
);
539 pl
= blkid_probe_get_partitions(b
);
541 return errno_or_else(ENOMEM
);
544 n_partitions
= blkid_partlist_numof_partitions(pl
);
545 if (n_partitions
< 0)
546 return errno_or_else(EIO
);
548 for (int i
= 0; i
< n_partitions
; i
++) {
549 _cleanup_free_
char *node
= NULL
;
550 unsigned long long pflags
;
551 blkid_loff_t start
, size
;
556 pp
= blkid_partlist_get_partition(pl
, i
);
558 return errno_or_else(EIO
);
560 pflags
= blkid_partition_get_flags(pp
);
563 nr
= blkid_partition_get_partno(pp
);
565 return errno_or_else(EIO
);
568 start
= blkid_partition_get_start(pp
);
570 return errno_or_else(EIO
);
572 assert((uint64_t) start
< UINT64_MAX
/512);
575 size
= blkid_partition_get_size(pp
);
577 return errno_or_else(EIO
);
579 assert((uint64_t) size
< UINT64_MAX
/512);
581 r
= make_partition_devname(devname
, nr
, &node
);
585 /* So here's the thing: after the main ("whole") block device popped up it might take a while
586 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
587 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
588 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
589 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
590 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
591 * also good as the outcome is the same: the partition block device exists, and we can use
594 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
595 * partition already existent. */
597 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
598 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
601 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
603 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
605 log_debug("We were quicker than kernel in adding partition %i.", nr
);
609 PartitionDesignator designator
= _PARTITION_DESIGNATOR_INVALID
;
610 Architecture architecture
= _ARCHITECTURE_INVALID
;
611 const char *stype
, *sid
, *fstype
= NULL
, *label
;
612 sd_id128_t type_id
, id
;
613 bool rw
= true, growfs
= false;
615 sid
= blkid_partition_get_uuid(pp
);
618 if (sd_id128_from_string(sid
, &id
) < 0)
621 stype
= blkid_partition_get_type_string(pp
);
624 if (sd_id128_from_string(stype
, &type_id
) < 0)
627 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
629 if (sd_id128_equal(type_id
, SD_GPT_HOME
)) {
631 check_partition_flags(node
, pflags
,
632 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
634 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
637 designator
= PARTITION_HOME
;
638 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
639 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
641 } else if (sd_id128_equal(type_id
, SD_GPT_SRV
)) {
643 check_partition_flags(node
, pflags
,
644 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
646 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
649 designator
= PARTITION_SRV
;
650 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
651 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
653 } else if (sd_id128_equal(type_id
, SD_GPT_ESP
)) {
655 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
656 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
657 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
660 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
663 designator
= PARTITION_ESP
;
666 } else if (sd_id128_equal(type_id
, SD_GPT_XBOOTLDR
)) {
668 check_partition_flags(node
, pflags
,
669 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
671 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
674 designator
= PARTITION_XBOOTLDR
;
675 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
676 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
678 } else if (gpt_partition_type_is_root(type_id
)) {
680 check_partition_flags(node
, pflags
,
681 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
683 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
686 /* If a root ID is specified, ignore everything but the root id */
687 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
690 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
691 designator
= partition_root_of_arch(architecture
);
692 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
693 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
695 } else if (gpt_partition_type_is_root_verity(type_id
)) {
697 check_partition_flags(node
, pflags
,
698 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
700 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
703 m
->has_verity
= true;
705 /* If no verity configuration is specified, then don't do verity */
708 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
711 /* If root hash is specified, then ignore everything but the root id */
712 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
715 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
716 designator
= partition_verity_of(partition_root_of_arch(architecture
));
717 fstype
= "DM_verity_hash";
720 } else if (gpt_partition_type_is_root_verity_sig(type_id
)) {
722 check_partition_flags(node
, pflags
,
723 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
725 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
728 m
->has_verity_sig
= true;
732 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
735 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
736 designator
= partition_verity_sig_of(partition_root_of_arch(architecture
));
737 fstype
= "verity_hash_signature";
740 } else if (gpt_partition_type_is_usr(type_id
)) {
742 check_partition_flags(node
, pflags
,
743 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
745 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
748 /* If a usr ID is specified, ignore everything but the usr id */
749 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
752 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
753 designator
= partition_usr_of_arch(architecture
);
754 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
755 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
757 } else if (gpt_partition_type_is_usr_verity(type_id
)) {
759 check_partition_flags(node
, pflags
,
760 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
762 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
765 m
->has_verity
= true;
769 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
772 /* If usr hash is specified, then ignore everything but the usr id */
773 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
776 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
777 designator
= partition_verity_of(partition_usr_of_arch(architecture
));
778 fstype
= "DM_verity_hash";
781 } else if (gpt_partition_type_is_usr_verity_sig(type_id
)) {
783 check_partition_flags(node
, pflags
,
784 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
786 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
789 m
->has_verity_sig
= true;
793 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
796 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
797 designator
= partition_verity_sig_of(partition_usr_of_arch(architecture
));
798 fstype
= "verity_hash_signature";
801 } else if (sd_id128_equal(type_id
, SD_GPT_SWAP
)) {
803 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
805 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
808 designator
= PARTITION_SWAP
;
810 } else if (sd_id128_equal(type_id
, SD_GPT_LINUX_GENERIC
)) {
812 check_partition_flags(node
, pflags
,
813 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
815 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
819 multiple_generic
= true;
822 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
823 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
825 generic_node
= strdup(node
);
830 } else if (sd_id128_equal(type_id
, SD_GPT_TMP
)) {
832 check_partition_flags(node
, pflags
,
833 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
835 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
838 designator
= PARTITION_TMP
;
839 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
840 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
842 } else if (sd_id128_equal(type_id
, SD_GPT_VAR
)) {
844 check_partition_flags(node
, pflags
,
845 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
847 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
850 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
853 /* For /var we insist that the uuid of the partition matches the
854 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
855 * ID. Why? Unlike the other partitions /var is inherently
856 * installation specific, hence we need to be careful not to mount it
857 * in the wrong installation. By hashing the partition UUID from
858 * /etc/machine-id we can securely bind the partition to the
861 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
865 if (!sd_id128_equal(var_uuid
, id
)) {
866 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
871 designator
= PARTITION_VAR
;
872 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
873 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
876 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
877 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
;
878 _cleanup_close_
int mount_node_fd
= -1;
879 const char *options
= NULL
;
881 if (m
->partitions
[designator
].found
) {
882 /* For most partition types the first one we see wins. Except for the
883 * rootfs and /usr, where we do a version compare of the label, and
884 * let the newest version win. This permits a simple A/B versioning
885 * scheme in OS images. */
887 if (!partition_designator_is_versioned(designator
) ||
888 strverscmp_improved(m
->partitions
[designator
].label
, label
) >= 0)
891 dissected_partition_done(m
->partitions
+ designator
);
894 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
895 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
896 if (mount_node_fd
< 0)
897 return mount_node_fd
;
912 options
= mount_options_from_designator(mount_options
, designator
);
919 m
->partitions
[designator
] = (DissectedPartition
) {
924 .architecture
= architecture
,
925 .node
= TAKE_PTR(node
),
926 .fstype
= TAKE_PTR(t
),
927 .label
= TAKE_PTR(l
),
929 .mount_options
= TAKE_PTR(o
),
930 .mount_node_fd
= TAKE_FD(mount_node_fd
),
931 .offset
= (uint64_t) start
* 512,
932 .size
= (uint64_t) size
* 512,
938 switch (blkid_partition_get_type(pp
)) {
940 case 0x83: /* Linux partition */
942 if (pflags
!= 0x80) /* Bootable flag */
946 multiple_generic
= true;
950 generic_growfs
= false;
951 generic_node
= strdup(node
);
958 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
959 _cleanup_close_
int mount_node_fd
= -1;
960 _cleanup_free_
char *o
= NULL
;
961 sd_id128_t id
= SD_ID128_NULL
;
962 const char *sid
, *options
= NULL
;
965 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
968 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
969 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
970 if (mount_node_fd
< 0)
971 return mount_node_fd
;
974 sid
= blkid_partition_get_uuid(pp
);
976 (void) sd_id128_from_string(sid
, &id
);
978 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
985 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
990 .architecture
= _ARCHITECTURE_INVALID
,
991 .node
= TAKE_PTR(node
),
993 .mount_options
= TAKE_PTR(o
),
994 .mount_node_fd
= TAKE_FD(mount_node_fd
),
995 .offset
= (uint64_t) start
* 512,
996 .size
= (uint64_t) size
* 512,
1004 if (m
->partitions
[PARTITION_ROOT
].found
) {
1005 /* If we found the primary arch, then invalidate the secondary and other arch to avoid any
1006 * ambiguities, since we never want to mount the secondary or other arch in this case. */
1007 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
1008 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
1009 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
].found
= false;
1010 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
1011 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
1012 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
= false;
1014 m
->partitions
[PARTITION_ROOT_OTHER
].found
= false;
1015 m
->partitions
[PARTITION_ROOT_OTHER_VERITY
].found
= false;
1016 m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
].found
= false;
1017 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1018 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1019 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1021 } else if (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
1022 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
)
1023 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
1025 else if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
1027 /* No root partition found but there's one for the secondary architecture? Then upgrade
1028 * secondary arch to first and invalidate the other arch. */
1030 log_debug("No root partition found of the native architecture, falling back to a root "
1031 "partition of the secondary architecture.");
1033 m
->partitions
[PARTITION_ROOT
] = TAKE_PARTITION(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
1034 m
->partitions
[PARTITION_ROOT_VERITY
] = TAKE_PARTITION(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
1035 m
->partitions
[PARTITION_ROOT_VERITY_SIG
] = TAKE_PARTITION(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
]);
1037 m
->partitions
[PARTITION_USR
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_SECONDARY
]);
1038 m
->partitions
[PARTITION_USR_VERITY
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
1039 m
->partitions
[PARTITION_USR_VERITY_SIG
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
]);
1041 m
->partitions
[PARTITION_ROOT_OTHER
].found
= false;
1042 m
->partitions
[PARTITION_ROOT_OTHER_VERITY
].found
= false;
1043 m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
].found
= false;
1044 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1045 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1046 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1048 } else if (m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
||
1049 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
].found
)
1050 return -EADDRNOTAVAIL
; /* as above */
1052 else if (m
->partitions
[PARTITION_ROOT_OTHER
].found
) {
1054 /* No root or secondary partition found but there's one for another architecture? Then
1055 * upgrade the other architecture to first. */
1057 log_debug("No root partition found of the native architecture or the secondary architecture, "
1058 "falling back to a root partition of a non-native architecture (%s).",
1059 architecture_to_string(m
->partitions
[PARTITION_ROOT_OTHER
].architecture
));
1061 m
->partitions
[PARTITION_ROOT
] = TAKE_PARTITION(m
->partitions
[PARTITION_ROOT_OTHER
]);
1062 m
->partitions
[PARTITION_ROOT_VERITY
] = TAKE_PARTITION(m
->partitions
[PARTITION_ROOT_OTHER_VERITY
]);
1063 m
->partitions
[PARTITION_ROOT_VERITY_SIG
] = TAKE_PARTITION(m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
]);
1065 m
->partitions
[PARTITION_USR
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_OTHER
]);
1066 m
->partitions
[PARTITION_USR_VERITY
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_OTHER_VERITY
]);
1067 m
->partitions
[PARTITION_USR_VERITY_SIG
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
]);
1070 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1071 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
1072 return -EADDRNOTAVAIL
;
1074 if (m
->partitions
[PARTITION_USR
].found
) {
1075 /* Invalidate secondary and other arch /usr/ if we found the primary arch */
1076 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
1077 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
1078 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
= false;
1080 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1081 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1082 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1084 } else if (m
->partitions
[PARTITION_USR_VERITY
].found
||
1085 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
)
1086 return -EADDRNOTAVAIL
; /* as above */
1088 else if (m
->partitions
[PARTITION_USR_SECONDARY
].found
) {
1090 log_debug("No usr partition found of the native architecture, falling back to a usr "
1091 "partition of the secondary architecture.");
1093 /* Upgrade secondary arch to primary */
1094 m
->partitions
[PARTITION_USR
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_SECONDARY
]);
1095 m
->partitions
[PARTITION_USR_VERITY
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
1096 m
->partitions
[PARTITION_USR_VERITY_SIG
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
]);
1098 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1099 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1100 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1102 } else if (m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
||
1103 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
)
1104 return -EADDRNOTAVAIL
; /* as above */
1106 else if (m
->partitions
[PARTITION_USR_OTHER
].found
) {
1108 log_debug("No usr partition found of the native architecture or the secondary architecture, "
1109 "falling back to a usr partition of a non-native architecture (%s).",
1110 architecture_to_string(m
->partitions
[PARTITION_ROOT_OTHER
].architecture
));
1112 /* Upgrade other arch to primary */
1113 m
->partitions
[PARTITION_USR
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_OTHER
]);
1114 m
->partitions
[PARTITION_USR_VERITY
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_OTHER_VERITY
]);
1115 m
->partitions
[PARTITION_USR_VERITY_SIG
] = TAKE_PARTITION(m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
]);
1118 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1119 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1120 return -EADDRNOTAVAIL
;
1122 /* If root and /usr are combined then insist that the architecture matches */
1123 if (m
->partitions
[PARTITION_ROOT
].found
&&
1124 m
->partitions
[PARTITION_USR
].found
&&
1125 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1126 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1127 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1128 return -EADDRNOTAVAIL
;
1130 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1131 !m
->partitions
[PARTITION_USR
].found
&&
1132 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1133 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1135 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1136 * that. If the root hash was set however, then we won't fall back to a generic node, because
1137 * the root hash decides. */
1139 /* If we didn't find a properly marked root partition, but we did find a single suitable
1140 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1141 if (multiple_generic
)
1144 /* If we didn't find a generic node, then we can't fix this up either */
1146 _cleanup_close_
int mount_node_fd
= -1;
1147 _cleanup_free_
char *o
= NULL
;
1148 const char *options
;
1150 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
1151 mount_node_fd
= open_partition(generic_node
, /* is_partition = */ true, m
->loop
);
1152 if (mount_node_fd
< 0)
1153 return mount_node_fd
;
1156 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1158 o
= strdup(options
);
1163 assert(generic_nr
>= 0);
1164 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1167 .growfs
= generic_growfs
,
1168 .partno
= generic_nr
,
1169 .architecture
= _ARCHITECTURE_INVALID
,
1170 .node
= TAKE_PTR(generic_node
),
1171 .uuid
= generic_uuid
,
1172 .mount_options
= TAKE_PTR(o
),
1173 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1174 .offset
= UINT64_MAX
,
1180 /* 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 */
1181 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1182 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1185 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1186 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1187 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1190 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1191 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1192 if (m
->partitions
[PARTITION_USR
].found
)
1193 return -EADDRNOTAVAIL
;
1197 /* If a verity designator is specified, then insist that the matching partition exists */
1198 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1199 return -EADDRNOTAVAIL
;
1201 bool have_verity_sig_partition
=
1202 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR_VERITY_SIG
: PARTITION_ROOT_VERITY_SIG
].found
;
1204 if (verity
->root_hash
) {
1205 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1206 * Verity, set things up for it */
1208 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1209 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1210 return -EADDRNOTAVAIL
;
1212 /* If we found a verity setup, then the root partition is necessarily read-only. */
1213 m
->partitions
[PARTITION_ROOT
].rw
= false;
1214 m
->verity_ready
= true;
1217 assert(verity
->designator
== PARTITION_USR
);
1219 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1220 return -EADDRNOTAVAIL
;
1222 m
->partitions
[PARTITION_USR
].rw
= false;
1223 m
->verity_ready
= true;
1226 if (m
->verity_ready
)
1227 m
->verity_sig_ready
= verity
->root_hash_sig
|| have_verity_sig_partition
;
1229 } else if (have_verity_sig_partition
) {
1231 /* If we found an embedded signature partition, we are ready, too. */
1233 m
->verity_ready
= m
->verity_sig_ready
= true;
1234 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR
: PARTITION_ROOT
].rw
= false;
1242 int dissect_image_file(
1244 const VeritySettings
*verity
,
1245 const MountOptions
*mount_options
,
1246 DissectImageFlags flags
,
1247 DissectedImage
**ret
) {
1250 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1251 _cleanup_close_
int fd
= -1;
1255 assert((flags
& DISSECT_IMAGE_BLOCK_DEVICE
) == 0);
1258 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1262 r
= fd_verify_regular(fd
);
1266 r
= dissected_image_new(path
, &m
);
1270 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, flags
);
1281 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1285 /* First, clear dissected partitions. */
1286 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1287 dissected_partition_done(m
->partitions
+ i
);
1289 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1290 * DecryptedImage may try to deactivate partitions. */
1291 decrypted_image_unref(m
->decrypted_image
);
1293 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1294 * remove existing partitions on the loopback block device. */
1295 loop_device_unref(m
->loop
);
1297 free(m
->image_name
);
1299 strv_free(m
->machine_info
);
1300 strv_free(m
->os_release
);
1301 strv_free(m
->initrd_release
);
1302 strv_free(m
->extension_release
);
1307 static int is_loop_device(const char *path
) {
1308 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1313 if (stat(path
, &st
) < 0)
1316 if (!S_ISBLK(st
.st_mode
))
1319 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1320 if (access(s
, F_OK
) < 0) {
1321 if (errno
!= ENOENT
)
1324 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1325 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1326 if (access(s
, F_OK
) < 0)
1327 return errno
== ENOENT
? false : -errno
;
1333 static int run_fsck(int node_fd
, const char *fstype
) {
1337 assert(node_fd
>= 0);
1340 r
= fsck_exists_for_fstype(fstype
);
1342 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1346 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd
), fstype
);
1352 &node_fd
, 1, /* Leave the node fd open */
1353 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
|FORK_CLOEXEC_OFF
,
1356 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1359 execl("/sbin/fsck", "/sbin/fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd
), NULL
);
1361 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1362 _exit(FSCK_OPERATIONAL_ERROR
);
1365 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1366 if (exit_status
< 0)
1367 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
1369 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1370 log_debug("fsck failed with exit status %i.", exit_status
);
1372 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1373 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1375 log_debug("Ignoring fsck error.");
1381 static int fs_grow(const char *node_path
, const char *mount_path
) {
1382 _cleanup_close_
int mount_fd
= -1, node_fd
= -1;
1383 uint64_t size
, newsize
;
1386 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1388 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1390 if (ioctl(node_fd
, BLKGETSIZE64
, &size
) != 0)
1391 return log_debug_errno(errno
, "Failed to get block device size of %s: %m", node_path
);
1393 mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1395 return log_debug_errno(errno
, "Failed to open mountd file system %s: %m", mount_path
);
1397 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", mount_path
, size
);
1398 r
= resize_fs(mount_fd
, size
, &newsize
);
1400 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", mount_path
, size
);
1402 if (newsize
== size
)
1403 log_debug("Successfully resized \"%s\" to %s bytes.",
1404 mount_path
, FORMAT_BYTES(newsize
));
1406 assert(newsize
< size
);
1407 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1408 mount_path
, FORMAT_BYTES(newsize
), size
- newsize
);
1414 static int mount_partition(
1415 DissectedPartition
*m
,
1417 const char *directory
,
1420 DissectImageFlags flags
) {
1422 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1423 const char *p
, *node
, *fstype
;
1424 bool rw
, remap_uid_gid
= false;
1430 if (m
->mount_node_fd
< 0)
1433 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1434 node
= FORMAT_PROC_FD_PATH(m
->mount_node_fd
);
1435 fstype
= m
->decrypted_node
? m
->decrypted_fstype
: m
->fstype
;
1438 return -EAFNOSUPPORT
;
1440 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1441 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1443 if (streq(fstype
, "crypto_LUKS"))
1446 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
1448 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1449 r
= run_fsck(m
->mount_node_fd
, fstype
);
1455 /* Automatically create missing mount points inside the image, if necessary. */
1456 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
1457 if (r
< 0 && r
!= -EROFS
)
1460 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1466 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1467 * image (as the branch above does) but the host hierarchy, and the created directory might
1468 * survive our mount in the host hierarchy hence. */
1469 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1470 r
= mkdir_p(where
, 0755);
1478 /* If requested, turn on discard support. */
1479 if (fstype_can_discard(fstype
) &&
1480 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1481 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
) > 0))) {
1482 options
= strdup("discard");
1487 if (uid_is_valid(uid_shift
) && uid_shift
!= 0) {
1489 if (fstype_can_uid_gid(fstype
)) {
1490 _cleanup_free_
char *uid_option
= NULL
;
1492 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1495 if (!strextend_with_separator(&options
, ",", uid_option
))
1497 } else if (FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
))
1498 remap_uid_gid
= true;
1501 if (!isempty(m
->mount_options
))
1502 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
1505 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1506 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1507 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1508 * from the upper file system still get propagated through to the underlying file system,
1509 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1510 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1511 * carry a per file system table here.
1513 * Note that this means that we might not be able to mount corrupted file systems as read-only
1514 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1515 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1516 * mount options for loopback devices this is the right choice, since otherwise using the same
1517 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1518 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1519 * access that actually modifies stuff work on such image files. Or to say this differently: if
1520 * people want their file systems to be fixed up they should just open them in writable mode, where
1521 * all these problems don't exist. */
1522 if (!rw
&& STRPTR_IN_SET(fstype
, "ext3", "ext4", "xfs", "btrfs"))
1523 if (!strextend_with_separator(&options
, ",", "norecovery"))
1526 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1530 if (rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
))
1531 (void) fs_grow(node
, p
);
1533 if (remap_uid_gid
) {
1534 r
= remount_idmap(p
, uid_shift
, uid_range
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
1542 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1543 _cleanup_free_
char *options
= NULL
;
1548 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1550 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1551 r
= mkdir_p(where
, 0755);
1556 if (uid_is_valid(uid_shift
)) {
1557 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1561 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
1568 int dissected_image_mount(
1573 DissectImageFlags flags
) {
1575 int r
, xbootldr_mounted
;
1582 * -ENXIO → No root partition found
1583 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1584 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1585 * -EUCLEAN → fsck for file system failed
1586 * -EBUSY → File system already mounted/used elsewhere (kernel)
1587 * -EAFNOSUPPORT → File system type not supported or not known
1590 if (!(m
->partitions
[PARTITION_ROOT
].found
||
1591 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1592 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1594 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1596 /* First mount the root fs. If there's none we use a tmpfs. */
1597 if (m
->partitions
[PARTITION_ROOT
].found
)
1598 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, flags
);
1600 r
= mount_root_tmpfs(where
, uid_shift
, flags
);
1604 /* For us mounting root always means mounting /usr as well */
1605 r
= mount_partition(m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, flags
);
1609 if ((flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
1610 /* If either one of the validation flags are set, ensure that the image qualifies
1611 * as one or the other (or both). */
1614 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
1615 r
= path_is_os_tree(where
);
1621 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
)) {
1622 r
= path_is_extension_tree(where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_SYSEXT_CHECK
));
1634 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1637 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, flags
);
1641 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, flags
);
1645 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, flags
);
1649 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, flags
);
1653 xbootldr_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, flags
);
1654 if (xbootldr_mounted
< 0)
1655 return xbootldr_mounted
;
1657 if (m
->partitions
[PARTITION_ESP
].found
) {
1658 int esp_done
= false;
1660 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1661 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1663 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1668 /* /efi doesn't exist. Let's see if /boot is suitable then */
1670 if (!xbootldr_mounted
) {
1671 _cleanup_free_
char *p
= NULL
;
1673 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1677 } else if (dir_is_empty(p
, /* ignore_hidden_or_backup= */ false) > 0) {
1678 /* It exists and is an empty directory. Let's mount the ESP there. */
1679 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, uid_range
, flags
);
1689 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1691 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, uid_range
, flags
);
1700 int dissected_image_mount_and_warn(
1705 DissectImageFlags flags
) {
1712 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, flags
);
1714 return log_error_errno(r
, "Not root file system found in image.");
1715 if (r
== -EMEDIUMTYPE
)
1716 return log_error_errno(r
, "No suitable os-release/extension-release file in image found.");
1718 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
1720 return log_error_errno(r
, "File system check on image failed.");
1722 return log_error_errno(r
, "File system already mounted elsewhere.");
1723 if (r
== -EAFNOSUPPORT
)
1724 return log_error_errno(r
, "File system type not supported or not known.");
1726 return log_error_errno(r
, "Failed to mount image: %m");
1731 #if HAVE_LIBCRYPTSETUP
1732 struct DecryptedPartition
{
1733 struct crypt_device
*device
;
1739 typedef struct DecryptedPartition DecryptedPartition
;
1741 struct DecryptedImage
{
1743 DecryptedPartition
*decrypted
;
1747 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
1748 #if HAVE_LIBCRYPTSETUP
1754 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
1755 DecryptedPartition
*p
= d
->decrypted
+ i
;
1757 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1758 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
1759 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1761 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1765 sym_crypt_free(p
->device
);
1775 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
1777 #if HAVE_LIBCRYPTSETUP
1778 static int decrypted_image_new(DecryptedImage
**ret
) {
1779 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1783 d
= new(DecryptedImage
, 1);
1787 *d
= (DecryptedImage
) {
1795 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1796 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1799 assert(original_node
);
1804 base
= strrchr(original_node
, '/');
1806 base
= original_node
;
1812 name
= strjoin(base
, suffix
);
1815 if (!filename_is_valid(name
))
1818 node
= path_join(sym_crypt_get_dir(), name
);
1822 *ret_name
= TAKE_PTR(name
);
1823 *ret_node
= TAKE_PTR(node
);
1828 static int decrypt_partition(
1829 DissectedPartition
*m
,
1830 const char *passphrase
,
1831 DissectImageFlags flags
,
1832 DecryptedImage
*d
) {
1834 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1835 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1836 _cleanup_close_
int fd
= -1;
1842 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1845 if (!streq(m
->fstype
, "crypto_LUKS"))
1851 r
= dlopen_cryptsetup();
1855 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1859 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
1862 r
= sym_crypt_init(&cd
, m
->node
);
1864 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1866 cryptsetup_enable_logging(cd
);
1868 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
1870 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1872 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1873 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1874 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1876 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1877 return r
== -EPERM
? -EKEYREJECTED
: r
;
1880 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
1882 return log_debug_errno(errno
, "Failed to open %s: %m", node
);
1884 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
1885 .name
= TAKE_PTR(name
),
1886 .device
= TAKE_PTR(cd
),
1889 m
->decrypted_node
= TAKE_PTR(node
);
1890 close_and_replace(m
->mount_node_fd
, fd
);
1895 static int verity_can_reuse(
1896 const VeritySettings
*verity
,
1898 struct crypt_device
**ret_cd
) {
1900 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1901 _cleanup_free_
char *root_hash_existing
= NULL
;
1902 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1903 struct crypt_params_verity crypt_params
= {};
1904 size_t root_hash_existing_size
;
1911 r
= sym_crypt_init_by_name(&cd
, name
);
1913 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1915 cryptsetup_enable_logging(cd
);
1917 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
1919 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1921 root_hash_existing_size
= verity
->root_hash_size
;
1922 root_hash_existing
= malloc0(root_hash_existing_size
);
1923 if (!root_hash_existing
)
1926 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1928 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1929 if (verity
->root_hash_size
!= root_hash_existing_size
||
1930 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
1931 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1933 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1934 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1935 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1936 * signing for the new one, and vice versa. */
1937 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1938 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1941 *ret_cd
= TAKE_PTR(cd
);
1945 static inline char* dm_deferred_remove_clean(char *name
) {
1949 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1952 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1954 static int validate_signature_userspace(const VeritySettings
*verity
) {
1956 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
1957 _cleanup_strv_free_
char **certs
= NULL
;
1958 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
1959 _cleanup_free_
char *s
= NULL
;
1960 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
1961 * of declaration in place, please */
1962 const unsigned char *d
;
1966 assert(verity
->root_hash
);
1967 assert(verity
->root_hash_sig
);
1969 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
1970 * userspace validation. */
1972 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
1974 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
1975 if (strv_isempty(certs
)) {
1976 log_debug("No userspace dm-verity certificates found.");
1980 d
= verity
->root_hash_sig
;
1981 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
1983 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
1985 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
1987 return log_oom_debug();
1989 bio
= BIO_new_mem_buf(s
, strlen(s
));
1991 return log_oom_debug();
1993 sk
= sk_X509_new_null();
1995 return log_oom_debug();
1997 STRV_FOREACH(i
, certs
) {
1998 _cleanup_(X509_freep
) X509
*c
= NULL
;
1999 _cleanup_fclose_
FILE *f
= NULL
;
2001 f
= fopen(*i
, "re");
2003 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
2007 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
2009 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
2013 if (sk_X509_push(sk
, c
) == 0)
2014 return log_oom_debug();
2019 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
2021 log_debug("Userspace PKCS#7 validation succeeded.");
2023 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
2027 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2032 static int do_crypt_activate_verity(
2033 struct crypt_device
*cd
,
2035 const VeritySettings
*verity
) {
2037 bool check_signature
;
2044 if (verity
->root_hash_sig
) {
2045 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2046 if (r
< 0 && r
!= -ENXIO
)
2047 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2049 check_signature
= r
!= 0;
2051 check_signature
= false;
2053 if (check_signature
) {
2055 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2056 /* First, if we have support for signed keys in the kernel, then try that first. */
2057 r
= sym_crypt_activate_by_signed_key(
2061 verity
->root_hash_size
,
2062 verity
->root_hash_sig
,
2063 verity
->root_hash_sig_size
,
2064 CRYPT_ACTIVATE_READONLY
);
2068 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
2070 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.",
2071 program_invocation_short_name
);
2074 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2075 * works we'll try to activate without telling the kernel the signature. */
2077 r
= validate_signature_userspace(verity
);
2081 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY
),
2082 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2085 return sym_crypt_activate_by_volume_key(
2089 verity
->root_hash_size
,
2090 CRYPT_ACTIVATE_READONLY
);
2093 static usec_t
verity_timeout(void) {
2094 usec_t t
= 100 * USEC_PER_MSEC
;
2098 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2099 * Let's make the timeout configurable. */
2101 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2105 r
= parse_sec(e
, &t
);
2108 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2109 "using the default timeout (%s).",
2110 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
2115 static int verity_partition(
2116 PartitionDesignator designator
,
2117 DissectedPartition
*m
,
2118 DissectedPartition
*v
,
2119 const VeritySettings
*verity
,
2120 DissectImageFlags flags
,
2121 DecryptedImage
*d
) {
2123 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2124 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2125 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2126 _cleanup_close_
int mount_node_fd
= -1;
2130 assert(v
|| (verity
&& verity
->data_path
));
2132 if (!verity
|| !verity
->root_hash
)
2134 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2135 (verity
->designator
== designator
)))
2138 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2140 if (!verity
->data_path
) {
2141 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2144 if (!streq(v
->fstype
, "DM_verity_hash"))
2148 r
= dlopen_cryptsetup();
2152 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2153 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2154 _cleanup_free_
char *root_hash_encoded
= NULL
;
2156 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2157 if (!root_hash_encoded
)
2160 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2162 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2166 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2170 cryptsetup_enable_logging(cd
);
2172 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2176 r
= sym_crypt_set_data_device(cd
, m
->node
);
2180 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2183 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2184 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2185 * retry a few times before giving up. */
2186 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2187 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2188 _cleanup_close_
int fd
= -1;
2190 /* First, check if the device already exists. */
2191 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2192 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2193 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2195 goto check
; /* The device already exists. Let's check it. */
2197 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2198 r
= do_crypt_activate_verity(cd
, name
, verity
);
2200 goto try_open
; /* The device is activated. Let's open it. */
2201 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2202 * There's no way to distinguish this situation from a genuine error due to invalid
2203 * parameters, so immediately fall back to activating the device with a unique name.
2204 * Improvements in libcrypsetup can ensure this never happens:
2205 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2206 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2208 if (r
== -ENODEV
) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2211 -EEXIST
, /* Volume has already been opened and ready to be used. */
2212 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2213 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2216 if (!restore_deferred_remove
){
2217 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2218 r
= dm_deferred_remove_cancel(name
);
2219 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2220 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2221 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2222 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2225 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2227 restore_deferred_remove
= strdup(name
);
2228 if (!restore_deferred_remove
)
2229 return log_oom_debug();
2232 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2233 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2234 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2237 -ENOENT
, /* Removed?? */
2238 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2239 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2242 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2245 /* devmapper might say that the device exists, but the devlink might not yet have been
2246 * created. Check and wait for the udev event in that case. */
2247 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2248 /* Fallback to activation with a unique device if it's taking too long */
2249 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2252 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2257 /* Now, the device is activated and devlink is created. Let's open it. */
2258 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2260 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
2261 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2263 /* The device has already been removed?? */
2268 mount_node_fd
= TAKE_FD(fd
);
2270 crypt_free_and_replace(cd
, existing_cd
);
2275 /* Device is being removed by another process. Let's wait for a while. */
2276 (void) usleep(2 * USEC_PER_MSEC
);
2279 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2280 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2281 /* Before trying to activate with unique name, we need to free crypt_device object.
2282 * Otherwise, we get error from libcryptsetup like the following:
2284 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2289 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2292 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2295 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2296 restore_deferred_remove
= mfree(restore_deferred_remove
);
2298 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2299 .name
= TAKE_PTR(name
),
2300 .device
= TAKE_PTR(cd
),
2303 m
->decrypted_node
= TAKE_PTR(node
);
2304 close_and_replace(m
->mount_node_fd
, mount_node_fd
);
2310 int dissected_image_decrypt(
2312 const char *passphrase
,
2313 const VeritySettings
*verity
,
2314 DissectImageFlags flags
) {
2316 #if HAVE_LIBCRYPTSETUP
2317 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2322 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
2326 * = 0 → There was nothing to decrypt
2327 * > 0 → Decrypted successfully
2328 * -ENOKEY → There's something to decrypt but no key was supplied
2329 * -EKEYREJECTED → Passed key was not correct
2332 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
2335 if (!m
->encrypted
&& !m
->verity_ready
)
2338 #if HAVE_LIBCRYPTSETUP
2339 r
= decrypted_image_new(&d
);
2343 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
2344 DissectedPartition
*p
= m
->partitions
+ i
;
2345 PartitionDesignator k
;
2350 r
= decrypt_partition(p
, passphrase
, flags
, d
);
2354 k
= partition_verity_of(i
);
2356 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
2361 if (!p
->decrypted_fstype
&& p
->mount_node_fd
>= 0 && p
->decrypted_node
) {
2362 r
= probe_filesystem_full(p
->mount_node_fd
, p
->decrypted_node
, &p
->decrypted_fstype
);
2363 if (r
< 0 && r
!= -EUCLEAN
)
2368 m
->decrypted_image
= TAKE_PTR(d
);
2376 int dissected_image_decrypt_interactively(
2378 const char *passphrase
,
2379 const VeritySettings
*verity
,
2380 DissectImageFlags flags
) {
2382 _cleanup_strv_free_erase_
char **z
= NULL
;
2389 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
2392 if (r
== -EKEYREJECTED
)
2393 log_error_errno(r
, "Incorrect passphrase, try again!");
2394 else if (r
!= -ENOKEY
)
2395 return log_error_errno(r
, "Failed to decrypt image: %m");
2398 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
2399 "Too many retries.");
2403 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY
, 0, &z
);
2405 return log_error_errno(r
, "Failed to query for passphrase: %m");
2411 static int decrypted_image_relinquish(DecryptedImage
*d
) {
2414 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2415 * boolean so that we don't clean it up ourselves either anymore */
2417 #if HAVE_LIBCRYPTSETUP
2420 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2421 DecryptedPartition
*p
= d
->decrypted
+ i
;
2423 if (p
->relinquished
)
2426 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2428 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
2430 p
->relinquished
= true;
2437 int dissected_image_relinquish(DissectedImage
*m
) {
2442 if (m
->decrypted_image
) {
2443 r
= decrypted_image_relinquish(m
->decrypted_image
);
2449 loop_device_relinquish(m
->loop
);
2454 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
2461 e
= endswith(image
, ".raw");
2463 return strjoin(e
, suffix
);
2465 n
= new(char, e
- image
+ strlen(suffix
) + 1);
2469 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
2473 void verity_settings_done(VeritySettings
*v
) {
2476 v
->root_hash
= mfree(v
->root_hash
);
2477 v
->root_hash_size
= 0;
2479 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
2480 v
->root_hash_sig_size
= 0;
2482 v
->data_path
= mfree(v
->data_path
);
2485 int verity_settings_load(
2486 VeritySettings
*verity
,
2488 const char *root_hash_path
,
2489 const char *root_hash_sig_path
) {
2491 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2492 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
2493 _cleanup_free_
char *verity_data_path
= NULL
;
2494 PartitionDesignator designator
;
2499 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
2501 /* If we are asked to load the root hash for a device node, exit early */
2502 if (is_device_path(image
))
2505 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2506 if (r
< 0 && r
!= -ENXIO
)
2507 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2511 designator
= verity
->designator
;
2513 /* We only fill in what isn't already filled in */
2515 if (!verity
->root_hash
) {
2516 _cleanup_free_
char *text
= NULL
;
2518 if (root_hash_path
) {
2519 /* If explicitly specified it takes precedence */
2520 r
= read_one_line_file(root_hash_path
, &text
);
2525 designator
= PARTITION_ROOT
;
2527 /* Otherwise look for xattr and separate file, and first for the data for root and if
2528 * that doesn't exist for /usr */
2530 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2531 r
= getxattr_malloc(image
, "user.verity.roothash", &text
);
2533 _cleanup_free_
char *p
= NULL
;
2535 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2538 p
= build_auxiliary_path(image
, ".roothash");
2542 r
= read_one_line_file(p
, &text
);
2543 if (r
< 0 && r
!= -ENOENT
)
2548 designator
= PARTITION_ROOT
;
2551 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2552 /* So in the "roothash" xattr/file name above the "root" of course primarily
2553 * refers to the root of the Verity Merkle tree. But coincidentally it also
2554 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2555 * two distinct concepts called "root". Taking benefit of this happy
2556 * coincidence we call the file with the root hash for the /usr/ file system
2557 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2558 * confusing. We thus drop the reference to the root of the Merkle tree, and
2559 * just indicate which file system it's about. */
2560 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
);
2562 _cleanup_free_
char *p
= NULL
;
2564 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2567 p
= build_auxiliary_path(image
, ".usrhash");
2571 r
= read_one_line_file(p
, &text
);
2572 if (r
< 0 && r
!= -ENOENT
)
2577 designator
= PARTITION_USR
;
2582 r
= unhexmem(text
, strlen(text
), &root_hash
, &root_hash_size
);
2585 if (root_hash_size
< sizeof(sd_id128_t
))
2590 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
2591 if (root_hash_sig_path
) {
2592 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2593 if (r
< 0 && r
!= -ENOENT
)
2597 designator
= PARTITION_ROOT
;
2599 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2600 _cleanup_free_
char *p
= NULL
;
2602 /* Follow naming convention recommended by the relevant RFC:
2603 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2604 p
= build_auxiliary_path(image
, ".roothash.p7s");
2608 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2609 if (r
< 0 && r
!= -ENOENT
)
2612 designator
= PARTITION_ROOT
;
2615 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2616 _cleanup_free_
char *p
= NULL
;
2618 p
= build_auxiliary_path(image
, ".usrhash.p7s");
2622 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2623 if (r
< 0 && r
!= -ENOENT
)
2626 designator
= PARTITION_USR
;
2630 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
2634 if (!verity
->data_path
) {
2635 _cleanup_free_
char *p
= NULL
;
2637 p
= build_auxiliary_path(image
, ".verity");
2641 if (access(p
, F_OK
) < 0) {
2642 if (errno
!= ENOENT
)
2645 verity_data_path
= TAKE_PTR(p
);
2649 verity
->root_hash
= TAKE_PTR(root_hash
);
2650 verity
->root_hash_size
= root_hash_size
;
2653 if (root_hash_sig
) {
2654 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
2655 verity
->root_hash_sig_size
= root_hash_sig_size
;
2658 if (verity_data_path
)
2659 verity
->data_path
= TAKE_PTR(verity_data_path
);
2661 if (verity
->designator
< 0)
2662 verity
->designator
= designator
;
2667 int dissected_image_load_verity_sig_partition(
2670 VeritySettings
*verity
) {
2672 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2673 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
2674 size_t root_hash_size
, root_hash_sig_size
;
2675 _cleanup_free_
char *buf
= NULL
;
2676 PartitionDesignator d
;
2677 DissectedPartition
*p
;
2678 JsonVariant
*rh
, *sig
;
2687 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
2690 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2691 if (r
< 0 && r
!= -ENXIO
)
2692 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2696 d
= partition_verity_sig_of(verity
->designator
< 0 ? PARTITION_ROOT
: verity
->designator
);
2699 p
= m
->partitions
+ d
;
2702 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
2705 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2708 buf
= new(char, p
->size
+1);
2712 n
= pread(fd
, buf
, p
->size
, p
->offset
);
2715 if ((uint64_t) n
!= p
->size
)
2718 e
= memchr(buf
, 0, p
->size
);
2720 /* If we found a NUL byte then the rest of the data must be NUL too */
2721 if (!memeqzero(e
, p
->size
- (e
- buf
)))
2722 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
2726 r
= json_parse(buf
, 0, &v
, NULL
, NULL
);
2728 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
2730 rh
= json_variant_by_key(v
, "rootHash");
2732 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
2733 if (!json_variant_is_string(rh
))
2734 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'rootHash' field of signature JSON object is not a string.");
2736 r
= unhexmem(json_variant_string(rh
), SIZE_MAX
, &root_hash
, &root_hash_size
);
2738 return log_debug_errno(r
, "Failed to parse root hash field: %m");
2740 /* Check if specified root hash matches if it is specified */
2741 if (verity
->root_hash
&&
2742 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
2743 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
2745 a
= hexmem(root_hash
, root_hash_size
);
2746 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2748 return log_debug_errno(r
, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
2751 sig
= json_variant_by_key(v
, "signature");
2753 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
2754 if (!json_variant_is_string(sig
))
2755 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'signature' field of signature JSON object is not a string.");
2757 r
= unbase64mem(json_variant_string(sig
), SIZE_MAX
, &root_hash_sig
, &root_hash_sig_size
);
2759 return log_debug_errno(r
, "Failed to parse signature field: %m");
2761 free_and_replace(verity
->root_hash
, root_hash
);
2762 verity
->root_hash_size
= root_hash_size
;
2764 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
2765 verity
->root_hash_sig_size
= root_hash_sig_size
;
2770 int dissected_image_acquire_metadata(DissectedImage
*m
, DissectImageFlags extra_flags
) {
2777 META_INITRD_RELEASE
,
2778 META_EXTENSION_RELEASE
,
2779 META_HAS_INIT_SYSTEM
,
2783 static const char *const paths
[_META_MAX
] = {
2784 [META_HOSTNAME
] = "/etc/hostname\0",
2785 [META_MACHINE_ID
] = "/etc/machine-id\0",
2786 [META_MACHINE_INFO
] = "/etc/machine-info\0",
2787 [META_OS_RELEASE
] = ("/etc/os-release\0"
2788 "/usr/lib/os-release\0"),
2789 [META_INITRD_RELEASE
] = ("/etc/initrd-release\0"
2790 "/usr/lib/initrd-release\0"),
2791 [META_EXTENSION_RELEASE
] = "extension-release\0", /* Used only for logging. */
2792 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
2795 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **initrd_release
= NULL
, **extension_release
= NULL
;
2796 _cleanup_close_pair_
int error_pipe
[2] = { -1, -1 };
2797 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
2798 _cleanup_(sigkill_waitp
) pid_t child
= 0;
2799 sd_id128_t machine_id
= SD_ID128_NULL
;
2800 _cleanup_free_
char *hostname
= NULL
;
2801 unsigned n_meta_initialized
= 0;
2802 int fds
[2 * _META_MAX
], r
, v
;
2803 int has_init_system
= -1;
2806 BLOCK_SIGNALS(SIGCHLD
);
2810 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
2811 if (!paths
[n_meta_initialized
]) {
2812 fds
[2*n_meta_initialized
] = fds
[2*n_meta_initialized
+1] = -1;
2816 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
2822 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
2826 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
2831 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
2835 /* Child in a new mount namespace */
2836 error_pipe
[0] = safe_close(error_pipe
[0]);
2838 r
= dissected_image_mount(
2844 DISSECT_IMAGE_READ_ONLY
|
2845 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
2846 DISSECT_IMAGE_USR_NO_ROOT
);
2848 log_debug_errno(r
, "Failed to mount dissected image: %m");
2852 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2853 _cleanup_close_
int fd
= -ENOENT
;
2858 fds
[2*k
] = safe_close(fds
[2*k
]);
2862 case META_EXTENSION_RELEASE
:
2863 /* As per the os-release spec, if the image is an extension it will have a file
2864 * named after the image name in extension-release.d/ - we use the image name
2865 * and try to resolve it with the extension-release helpers, as sometimes
2866 * the image names are mangled on deployment and do not match anymore.
2867 * Unlike other paths this is not fixed, and the image name
2868 * can be mangled on deployment, so by calling into the helper
2869 * we allow a fallback that matches on the first extension-release
2870 * file found in the directory, if one named after the image cannot
2871 * be found first. */
2872 r
= open_extension_release(t
, m
->image_name
, /* relax_extension_release_check= */ false, NULL
, &fd
);
2874 fd
= r
; /* Propagate the error. */
2877 case META_HAS_INIT_SYSTEM
: {
2880 FOREACH_STRING(init
,
2881 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
2882 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
2883 "/sbin/init") { /* traditional path the Linux kernel invokes */
2885 r
= chase_symlinks(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
2888 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
2895 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
), false);
2903 NULSTR_FOREACH(p
, paths
[k
]) {
2904 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
2911 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
2912 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2916 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
2920 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2923 _exit(EXIT_SUCCESS
);
2926 /* Let parent know the error */
2927 (void) write(error_pipe
[1], &r
, sizeof(r
));
2928 _exit(EXIT_FAILURE
);
2931 error_pipe
[1] = safe_close(error_pipe
[1]);
2933 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2934 _cleanup_fclose_
FILE *f
= NULL
;
2939 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2941 f
= take_fdopen(&fds
[2*k
], "r");
2950 r
= read_etc_hostname_stream(f
, &hostname
);
2952 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
2956 case META_MACHINE_ID
: {
2957 _cleanup_free_
char *line
= NULL
;
2959 r
= read_line(f
, LONG_LINE_MAX
, &line
);
2961 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
2963 r
= sd_id128_from_string(line
, &machine_id
);
2965 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
2967 log_debug("/etc/machine-id file of image is empty.");
2968 else if (streq(line
, "uninitialized"))
2969 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
2971 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
2976 case META_MACHINE_INFO
:
2977 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
2979 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
2983 case META_OS_RELEASE
:
2984 r
= load_env_file_pairs(f
, "os-release", &os_release
);
2986 log_debug_errno(r
, "Failed to read OS release file of image: %m");
2990 case META_INITRD_RELEASE
:
2991 r
= load_env_file_pairs(f
, "initrd-release", &initrd_release
);
2993 log_debug_errno(r
, "Failed to read initrd release file of image: %m");
2997 case META_EXTENSION_RELEASE
:
2998 r
= load_env_file_pairs(f
, "extension-release", &extension_release
);
3000 log_debug_errno(r
, "Failed to read extension release file of image: %m");
3004 case META_HAS_INIT_SYSTEM
: {
3009 nr
= fread(&b
, 1, sizeof(b
), f
);
3010 if (nr
!= sizeof(b
))
3011 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
3013 has_init_system
= b
;
3019 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
3024 n
= read(error_pipe
[0], &v
, sizeof(v
));
3028 return v
; /* propagate error sent to us from child */
3032 if (r
!= EXIT_SUCCESS
)
3035 free_and_replace(m
->hostname
, hostname
);
3036 m
->machine_id
= machine_id
;
3037 strv_free_and_replace(m
->machine_info
, machine_info
);
3038 strv_free_and_replace(m
->os_release
, os_release
);
3039 strv_free_and_replace(m
->initrd_release
, initrd_release
);
3040 strv_free_and_replace(m
->extension_release
, extension_release
);
3041 m
->has_init_system
= has_init_system
;
3044 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
3045 safe_close_pair(fds
+ 2*k
);
3050 int dissect_loop_device(
3052 const VeritySettings
*verity
,
3053 const MountOptions
*mount_options
,
3054 DissectImageFlags flags
,
3055 DissectedImage
**ret
) {
3058 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
3064 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
3068 m
->loop
= loop_device_ref(loop
);
3070 r
= dissect_image(m
, loop
->fd
, loop
->node
, verity
, mount_options
, flags
| DISSECT_IMAGE_BLOCK_DEVICE
);
3074 r
= dissected_image_probe_filesystem(m
);
3085 int dissect_loop_device_and_warn(
3087 const VeritySettings
*verity
,
3088 const MountOptions
*mount_options
,
3089 DissectImageFlags flags
,
3090 DissectedImage
**ret
) {
3096 assert(loop
->fd
>= 0);
3098 name
= ASSERT_PTR(loop
->backing_file
?: loop
->node
);
3100 r
= dissect_loop_device(loop
, verity
, mount_options
, flags
, ret
);
3104 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
3107 return log_error_errno(r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
3110 return log_error_errno(r
, "%s: The image does not pass validation.", name
);
3112 case -EADDRNOTAVAIL
:
3113 return log_error_errno(r
, "%s: No root partition for specified root hash found.", name
);
3116 return log_error_errno(r
, "%s: Multiple suitable root partitions found in image.", name
);
3119 return log_error_errno(r
, "%s: No suitable root partition found in image.", name
);
3121 case -EPROTONOSUPPORT
:
3122 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
3125 return log_error_errno(r
, "%s: Image is not a block device.", name
);
3128 return log_error_errno(r
,
3129 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
3130 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
3131 name
, strna(verity
? verity
->data_path
: NULL
));
3135 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
3141 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3144 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3145 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3146 * images we only check the partition type.
3148 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3151 if (image
->single_file_system
)
3152 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
3154 return partition_verity_of(partition_designator
) >= 0;
3157 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3158 PartitionDesignator k
;
3162 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3163 * works for the root partition, for others only if the associated verity partition was found. */
3165 if (!image
->verity_ready
)
3168 if (image
->single_file_system
)
3169 return partition_designator
== PARTITION_ROOT
;
3171 k
= partition_verity_of(partition_designator
);
3172 return k
>= 0 && image
->partitions
[k
].found
;
3175 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3176 PartitionDesignator k
;
3180 /* Checks if this partition has verity signature data available that we can use. */
3182 if (!image
->verity_sig_ready
)
3185 if (image
->single_file_system
)
3186 return partition_designator
== PARTITION_ROOT
;
3188 k
= partition_verity_sig_of(partition_designator
);
3189 return k
>= 0 && image
->partitions
[k
].found
;
3192 MountOptions
* mount_options_free_all(MountOptions
*options
) {
3195 while ((m
= options
)) {
3196 LIST_REMOVE(mount_options
, options
, m
);
3204 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
3205 LIST_FOREACH(mount_options
, m
, options
)
3206 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
3212 int mount_image_privately_interactively(
3214 DissectImageFlags flags
,
3215 char **ret_directory
,
3216 LoopDevice
**ret_loop_device
) {
3218 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3219 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3220 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3221 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
3222 _cleanup_free_
char *temp
= NULL
;
3225 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3226 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3230 assert(ret_directory
);
3231 assert(ret_loop_device
);
3233 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
3235 return log_error_errno(r
, "Failed to load root hash data: %m");
3237 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
3239 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
3241 r
= loop_device_make_by_path(
3243 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
3244 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
3248 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
3250 r
= dissect_loop_device_and_warn(d
, &verity
, NULL
, flags
, &dissected_image
);
3254 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
3258 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
3262 r
= detach_mount_namespace();
3264 return log_error_errno(r
, "Failed to detach mount namespace: %m");
3266 r
= mkdir_p(temp
, 0700);
3268 return log_error_errno(r
, "Failed to create mount point: %m");
3270 created_dir
= TAKE_PTR(temp
);
3272 r
= dissected_image_mount_and_warn(dissected_image
, created_dir
, UID_INVALID
, UID_INVALID
, flags
);
3276 r
= loop_device_flock(d
, LOCK_UN
);
3280 r
= dissected_image_relinquish(dissected_image
);
3282 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
3284 *ret_directory
= TAKE_PTR(created_dir
);
3285 *ret_loop_device
= TAKE_PTR(d
);
3290 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
3294 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
3295 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
3296 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
3299 int verity_dissect_and_mount(
3303 const MountOptions
*options
,
3304 const char *required_host_os_release_id
,
3305 const char *required_host_os_release_version_id
,
3306 const char *required_host_os_release_sysext_level
,
3307 const char *required_sysext_scope
) {
3309 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
3310 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3311 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3312 DissectImageFlags dissect_image_flags
;
3313 bool relax_extension_release_check
;
3319 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
3321 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3322 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
3324 return log_debug_errno(r
, "Failed to load root hash: %m");
3326 dissect_image_flags
= (verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
3327 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_SYSEXT_CHECK
: 0);
3329 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3330 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
3331 r
= loop_device_make_by_path(
3332 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
3334 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
3338 return log_debug_errno(r
, "Failed to create loop device for image: %m");
3340 r
= dissect_loop_device(
3344 dissect_image_flags
,
3346 /* No partition table? Might be a single-filesystem image, try again */
3347 if (!verity
.data_path
&& r
== -ENOPKG
)
3348 r
= dissect_loop_device(
3352 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
3355 return log_debug_errno(r
, "Failed to dissect image: %m");
3357 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, &verity
);
3361 r
= dissected_image_decrypt(
3365 dissect_image_flags
);
3367 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
3369 r
= mkdir_p_label(dest
, 0755);
3371 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
3372 r
= umount_recursive(dest
, 0);
3374 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
3376 r
= dissected_image_mount(dissected_image
, dest
, UID_INVALID
, UID_INVALID
, dissect_image_flags
);
3378 return log_debug_errno(r
, "Failed to mount image: %m");
3380 r
= loop_device_flock(loop_device
, LOCK_UN
);
3382 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
3384 /* If we got os-release values from the caller, then we need to match them with the image's
3385 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3386 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3387 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3388 * then a simple match on the ID will be performed. */
3389 if (required_host_os_release_id
) {
3390 _cleanup_strv_free_
char **extension_release
= NULL
;
3392 assert(!isempty(required_host_os_release_id
));
3394 r
= load_extension_release_pairs(dest
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
3396 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
3398 r
= extension_release_validate(
3399 dissected_image
->image_name
,
3400 required_host_os_release_id
,
3401 required_host_os_release_version_id
,
3402 required_host_os_release_sysext_level
,
3403 required_sysext_scope
,
3406 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
3408 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
3411 r
= dissected_image_relinquish(dissected_image
);
3413 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");