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 compare_arch(Architecture a
, Architecture b
) {
340 if (a
== native_architecture())
343 if (b
== native_architecture())
346 #ifdef ARCHITECTURE_SECONDARY
347 if (a
== ARCHITECTURE_SECONDARY
)
350 if (b
== ARCHITECTURE_SECONDARY
)
357 static int dissect_image(
361 const VeritySettings
*verity
,
362 const MountOptions
*mount_options
,
363 DissectImageFlags flags
) {
365 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
366 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
367 bool is_gpt
, is_mbr
, multiple_generic
= false,
368 generic_rw
= false, /* initialize to appease gcc */
369 generic_growfs
= false;
370 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
371 _cleanup_free_
char *generic_node
= NULL
;
372 sd_id128_t generic_uuid
= SD_ID128_NULL
;
373 const char *pttype
= NULL
, *sptuuid
= NULL
;
375 int r
, generic_nr
= -1, n_partitions
;
380 assert(!verity
|| verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
381 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
382 assert(!verity
|| verity
->root_hash_sig
|| verity
->root_hash_sig_size
== 0);
383 assert(!verity
|| (verity
->root_hash
|| !verity
->root_hash_sig
));
384 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
386 /* Probes a disk image, and returns information about what it found in *ret.
388 * Returns -ENOPKG if no suitable partition table or file system could be found.
389 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
390 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
391 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
393 if (verity
&& verity
->root_hash
) {
394 sd_id128_t fsuuid
, vuuid
;
396 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
397 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
398 * the final 128bit. */
400 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
403 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
404 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
406 if (sd_id128_is_null(fsuuid
))
408 if (sd_id128_is_null(vuuid
))
411 /* If the verity data declares it's for the /usr partition, then search for that, in all
412 * other cases assume it's for the root partition. */
413 if (verity
->designator
== PARTITION_USR
) {
415 usr_verity_uuid
= vuuid
;
418 root_verity_uuid
= vuuid
;
422 b
= blkid_new_probe();
427 r
= blkid_probe_set_device(b
, fd
, 0, 0);
429 return errno_or_else(ENOMEM
);
431 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
432 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
433 blkid_probe_enable_superblocks(b
, 1);
434 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
|BLKID_SUBLKS_UUID
);
437 blkid_probe_enable_partitions(b
, 1);
438 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
441 r
= blkid_do_safeprobe(b
);
442 if (IN_SET(r
, -2, 1))
443 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
445 return errno_or_else(EIO
);
447 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
448 (flags
& DISSECT_IMAGE_GENERIC_ROOT
)) ||
449 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
450 const char *usage
= NULL
;
452 /* If flags permit this, also allow using non-partitioned single-filesystem images */
454 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
455 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
456 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
457 const char *fstype
= NULL
, *options
= NULL
, *suuid
= NULL
;
458 _cleanup_close_
int mount_node_fd
= -1;
459 sd_id128_t uuid
= SD_ID128_NULL
;
461 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
462 mount_node_fd
= open_partition(devname
, /* is_partition = */ false, m
->loop
);
463 if (mount_node_fd
< 0)
464 return mount_node_fd
;
467 /* OK, we have found a file system, that's our root partition then. */
468 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
469 (void) blkid_probe_lookup_value(b
, "UUID", &suuid
, NULL
);
478 /* blkid will return FAT's serial number as UUID, hence it is quite possible
479 * that parsing this will fail. We'll ignore the ID, since it's just too
480 * short to be useful as tru identifier. */
481 r
= sd_id128_from_string(suuid
, &uuid
);
483 log_debug_errno(r
, "Failed to parse file system UUID '%s', ignoring: %m", suuid
);
490 m
->single_file_system
= true;
491 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
493 m
->has_verity
= verity
&& verity
->data_path
;
494 m
->verity_ready
= m
->has_verity
&&
496 (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
);
498 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
499 m
->verity_sig_ready
= m
->verity_ready
&&
500 verity
->root_hash_sig
;
502 m
->image_uuid
= uuid
;
504 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
511 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
513 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
515 .architecture
= _ARCHITECTURE_INVALID
,
516 .fstype
= TAKE_PTR(t
),
518 .mount_options
= TAKE_PTR(o
),
519 .mount_node_fd
= TAKE_FD(mount_node_fd
),
528 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
532 is_gpt
= streq_ptr(pttype
, "gpt");
533 is_mbr
= streq_ptr(pttype
, "dos");
535 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
538 /* We support external verity data partitions only if the image has no partition table */
539 if (verity
&& verity
->data_path
)
542 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
543 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
544 * do partition scanning. */
545 r
= blockdev_partscan_enabled(fd
);
549 return -EPROTONOSUPPORT
;
552 (void) blkid_probe_lookup_value(b
, "PTUUID", &sptuuid
, NULL
);
554 r
= sd_id128_from_string(sptuuid
, &m
->image_uuid
);
556 log_debug_errno(r
, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid
);
560 pl
= blkid_probe_get_partitions(b
);
562 return errno_or_else(ENOMEM
);
565 n_partitions
= blkid_partlist_numof_partitions(pl
);
566 if (n_partitions
< 0)
567 return errno_or_else(EIO
);
569 for (int i
= 0; i
< n_partitions
; i
++) {
570 _cleanup_free_
char *node
= NULL
;
571 unsigned long long pflags
;
572 blkid_loff_t start
, size
;
577 pp
= blkid_partlist_get_partition(pl
, i
);
579 return errno_or_else(EIO
);
581 pflags
= blkid_partition_get_flags(pp
);
584 nr
= blkid_partition_get_partno(pp
);
586 return errno_or_else(EIO
);
589 start
= blkid_partition_get_start(pp
);
591 return errno_or_else(EIO
);
593 assert((uint64_t) start
< UINT64_MAX
/512);
596 size
= blkid_partition_get_size(pp
);
598 return errno_or_else(EIO
);
600 assert((uint64_t) size
< UINT64_MAX
/512);
602 r
= make_partition_devname(devname
, nr
, &node
);
606 /* So here's the thing: after the main ("whole") block device popped up it might take a while
607 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
608 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
609 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
610 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
611 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
612 * also good as the outcome is the same: the partition block device exists, and we can use
615 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
616 * partition already existent. */
618 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
619 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
622 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
624 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
626 log_debug("We were quicker than kernel in adding partition %i.", nr
);
630 const char *fstype
= NULL
, *label
;
631 sd_id128_t type_id
, id
;
632 GptPartitionType type
;
633 bool rw
= true, growfs
= false;
635 r
= blkid_partition_get_uuid_id128(pp
, &id
);
637 log_debug_errno(r
, "Failed to read partition UUID, ignoring: %m");
641 r
= blkid_partition_get_type_id128(pp
, &type_id
);
643 log_debug_errno(r
, "Failed to read partition type UUID, ignoring: %m");
647 type
= gpt_partition_type_from_uuid(type_id
);
649 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
651 if (IN_SET(type
.designator
,
657 check_partition_flags(node
, pflags
,
658 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
660 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
663 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
664 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
666 } else if (type
.designator
== PARTITION_ESP
) {
668 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
669 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
670 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
673 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
678 } else if (type
.designator
== PARTITION_ROOT
) {
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 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
691 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
693 } else if (type
.designator
== PARTITION_ROOT_VERITY
) {
695 check_partition_flags(node
, pflags
,
696 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
698 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
701 m
->has_verity
= true;
703 /* If no verity configuration is specified, then don't do verity */
706 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
709 /* If root hash is specified, then ignore everything but the root id */
710 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
713 fstype
= "DM_verity_hash";
716 } else if (type
.designator
== PARTITION_ROOT_VERITY_SIG
) {
718 check_partition_flags(node
, pflags
,
719 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
721 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
724 m
->has_verity_sig
= true;
728 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
731 fstype
= "verity_hash_signature";
734 } else if (type
.designator
== PARTITION_USR
) {
736 check_partition_flags(node
, pflags
,
737 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
739 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
742 /* If a usr ID is specified, ignore everything but the usr id */
743 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
746 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
747 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
749 } else if (type
.designator
== PARTITION_USR_VERITY
) {
751 check_partition_flags(node
, pflags
,
752 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
754 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
757 m
->has_verity
= true;
761 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
764 /* If usr hash is specified, then ignore everything but the usr id */
765 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
768 fstype
= "DM_verity_hash";
771 } else if (type
.designator
== PARTITION_USR_VERITY_SIG
) {
773 check_partition_flags(node
, pflags
,
774 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
776 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
779 m
->has_verity_sig
= true;
783 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
786 fstype
= "verity_hash_signature";
789 } else if (type
.designator
== PARTITION_SWAP
) {
791 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
793 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
798 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
799 } else if (sd_id128_equal(type
.uuid
, SD_GPT_LINUX_GENERIC
)) {
801 check_partition_flags(node
, pflags
,
802 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
804 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
808 multiple_generic
= true;
811 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
812 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
814 generic_node
= strdup(node
);
819 } else if (type
.designator
== PARTITION_VAR
) {
821 check_partition_flags(node
, pflags
,
822 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
824 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
827 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
830 /* For /var we insist that the uuid of the partition matches the
831 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
832 * ID. Why? Unlike the other partitions /var is inherently
833 * installation specific, hence we need to be careful not to mount it
834 * in the wrong installation. By hashing the partition UUID from
835 * /etc/machine-id we can securely bind the partition to the
838 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
842 if (!sd_id128_equal(var_uuid
, id
)) {
843 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
848 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
849 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
852 if (type
.designator
!= _PARTITION_DESIGNATOR_INVALID
) {
853 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
;
854 _cleanup_close_
int mount_node_fd
= -1;
855 const char *options
= NULL
;
857 if (m
->partitions
[type
.designator
].found
) {
858 /* For most partition types the first one we see wins. Except for the
859 * rootfs and /usr, where we do a version compare of the label, and
860 * let the newest version win. This permits a simple A/B versioning
861 * scheme in OS images. */
863 if (compare_arch(type
.arch
, m
->partitions
[type
.designator
].architecture
) <= 0)
866 if (!partition_designator_is_versioned(type
.designator
) ||
867 strverscmp_improved(m
->partitions
[type
.designator
].label
, label
) >= 0)
870 dissected_partition_done(m
->partitions
+ type
.designator
);
873 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
) &&
874 type
.designator
!= PARTITION_SWAP
) {
875 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
876 if (mount_node_fd
< 0)
877 return mount_node_fd
;
892 options
= mount_options_from_designator(mount_options
, type
.designator
);
899 m
->partitions
[type
.designator
] = (DissectedPartition
) {
904 .architecture
= type
.arch
,
905 .node
= TAKE_PTR(node
),
906 .fstype
= TAKE_PTR(t
),
907 .label
= TAKE_PTR(l
),
909 .mount_options
= TAKE_PTR(o
),
910 .mount_node_fd
= TAKE_FD(mount_node_fd
),
911 .offset
= (uint64_t) start
* 512,
912 .size
= (uint64_t) size
* 512,
918 switch (blkid_partition_get_type(pp
)) {
920 case 0x83: /* Linux partition */
922 if (pflags
!= 0x80) /* Bootable flag */
926 multiple_generic
= true;
930 generic_growfs
= false;
931 generic_node
= strdup(node
);
938 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
939 _cleanup_close_
int mount_node_fd
= -1;
940 _cleanup_free_
char *o
= NULL
;
941 sd_id128_t id
= SD_ID128_NULL
;
942 const char *options
= NULL
;
945 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
948 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
949 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
950 if (mount_node_fd
< 0)
951 return mount_node_fd
;
954 (void) blkid_partition_get_uuid_id128(pp
, &id
);
956 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
963 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
968 .architecture
= _ARCHITECTURE_INVALID
,
969 .node
= TAKE_PTR(node
),
971 .mount_options
= TAKE_PTR(o
),
972 .mount_node_fd
= TAKE_FD(mount_node_fd
),
973 .offset
= (uint64_t) start
* 512,
974 .size
= (uint64_t) size
* 512,
982 if (!m
->partitions
[PARTITION_ROOT
].found
&&
983 (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
984 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
))
985 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
987 /* Hmm, we found a signature partition but no Verity data? Something is off. */
988 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
989 return -EADDRNOTAVAIL
;
991 if (!m
->partitions
[PARTITION_USR
].found
&&
992 (m
->partitions
[PARTITION_USR_VERITY
].found
||
993 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
))
994 return -EADDRNOTAVAIL
; /* as above */
997 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
998 return -EADDRNOTAVAIL
;
1000 /* If root and /usr are combined then insist that the architecture matches */
1001 if (m
->partitions
[PARTITION_ROOT
].found
&&
1002 m
->partitions
[PARTITION_USR
].found
&&
1003 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1004 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1005 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1006 return -EADDRNOTAVAIL
;
1008 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1009 !m
->partitions
[PARTITION_USR
].found
&&
1010 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1011 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1013 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1014 * that. If the root hash was set however, then we won't fall back to a generic node, because
1015 * the root hash decides. */
1017 /* If we didn't find a properly marked root partition, but we did find a single suitable
1018 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1019 if (multiple_generic
)
1022 /* If we didn't find a generic node, then we can't fix this up either */
1024 _cleanup_close_
int mount_node_fd
= -1;
1025 _cleanup_free_
char *o
= NULL
;
1026 const char *options
;
1028 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
1029 mount_node_fd
= open_partition(generic_node
, /* is_partition = */ true, m
->loop
);
1030 if (mount_node_fd
< 0)
1031 return mount_node_fd
;
1034 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1036 o
= strdup(options
);
1041 assert(generic_nr
>= 0);
1042 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1045 .growfs
= generic_growfs
,
1046 .partno
= generic_nr
,
1047 .architecture
= _ARCHITECTURE_INVALID
,
1048 .node
= TAKE_PTR(generic_node
),
1049 .uuid
= generic_uuid
,
1050 .mount_options
= TAKE_PTR(o
),
1051 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1052 .offset
= UINT64_MAX
,
1058 /* Check if we have a root fs if we are told to do check. /usr alone is fine too, but only if appropriate flag for that is set too */
1059 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1060 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1063 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1064 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1065 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1068 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1069 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1070 if (m
->partitions
[PARTITION_USR
].found
)
1071 return -EADDRNOTAVAIL
;
1075 /* If a verity designator is specified, then insist that the matching partition exists */
1076 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1077 return -EADDRNOTAVAIL
;
1079 bool have_verity_sig_partition
=
1080 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR_VERITY_SIG
: PARTITION_ROOT_VERITY_SIG
].found
;
1082 if (verity
->root_hash
) {
1083 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1084 * Verity, set things up for it */
1086 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1087 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1088 return -EADDRNOTAVAIL
;
1090 /* If we found a verity setup, then the root partition is necessarily read-only. */
1091 m
->partitions
[PARTITION_ROOT
].rw
= false;
1092 m
->verity_ready
= true;
1095 assert(verity
->designator
== PARTITION_USR
);
1097 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1098 return -EADDRNOTAVAIL
;
1100 m
->partitions
[PARTITION_USR
].rw
= false;
1101 m
->verity_ready
= true;
1104 if (m
->verity_ready
)
1105 m
->verity_sig_ready
= verity
->root_hash_sig
|| have_verity_sig_partition
;
1107 } else if (have_verity_sig_partition
) {
1109 /* If we found an embedded signature partition, we are ready, too. */
1111 m
->verity_ready
= m
->verity_sig_ready
= true;
1112 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR
: PARTITION_ROOT
].rw
= false;
1120 int dissect_image_file(
1122 const VeritySettings
*verity
,
1123 const MountOptions
*mount_options
,
1124 DissectImageFlags flags
,
1125 DissectedImage
**ret
) {
1128 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1129 _cleanup_close_
int fd
= -1;
1133 assert((flags
& DISSECT_IMAGE_BLOCK_DEVICE
) == 0);
1136 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1140 r
= fd_verify_regular(fd
);
1144 r
= dissected_image_new(path
, &m
);
1148 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, flags
);
1159 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1163 /* First, clear dissected partitions. */
1164 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1165 dissected_partition_done(m
->partitions
+ i
);
1167 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1168 * DecryptedImage may try to deactivate partitions. */
1169 decrypted_image_unref(m
->decrypted_image
);
1171 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1172 * remove existing partitions on the loopback block device. */
1173 loop_device_unref(m
->loop
);
1175 free(m
->image_name
);
1177 strv_free(m
->machine_info
);
1178 strv_free(m
->os_release
);
1179 strv_free(m
->initrd_release
);
1180 strv_free(m
->extension_release
);
1185 static int is_loop_device(const char *path
) {
1186 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1191 if (stat(path
, &st
) < 0)
1194 if (!S_ISBLK(st
.st_mode
))
1197 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1198 if (access(s
, F_OK
) < 0) {
1199 if (errno
!= ENOENT
)
1202 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1203 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1204 if (access(s
, F_OK
) < 0)
1205 return errno
== ENOENT
? false : -errno
;
1211 static int run_fsck(int node_fd
, const char *fstype
) {
1215 assert(node_fd
>= 0);
1218 r
= fsck_exists_for_fstype(fstype
);
1220 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1224 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd
), fstype
);
1230 &node_fd
, 1, /* Leave the node fd open */
1231 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
|FORK_CLOEXEC_OFF
,
1234 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1237 execl("/sbin/fsck", "/sbin/fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd
), NULL
);
1239 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1240 _exit(FSCK_OPERATIONAL_ERROR
);
1243 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1244 if (exit_status
< 0)
1245 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
1247 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1248 log_debug("fsck failed with exit status %i.", exit_status
);
1250 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1251 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1253 log_debug("Ignoring fsck error.");
1259 static int fs_grow(const char *node_path
, const char *mount_path
) {
1260 _cleanup_close_
int mount_fd
= -1, node_fd
= -1;
1261 uint64_t size
, newsize
;
1264 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1266 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1268 if (ioctl(node_fd
, BLKGETSIZE64
, &size
) != 0)
1269 return log_debug_errno(errno
, "Failed to get block device size of %s: %m", node_path
);
1271 mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1273 return log_debug_errno(errno
, "Failed to open mountd file system %s: %m", mount_path
);
1275 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", mount_path
, size
);
1276 r
= resize_fs(mount_fd
, size
, &newsize
);
1278 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", mount_path
, size
);
1280 if (newsize
== size
)
1281 log_debug("Successfully resized \"%s\" to %s bytes.",
1282 mount_path
, FORMAT_BYTES(newsize
));
1284 assert(newsize
< size
);
1285 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1286 mount_path
, FORMAT_BYTES(newsize
), size
- newsize
);
1292 static int mount_partition(
1293 DissectedPartition
*m
,
1295 const char *directory
,
1298 DissectImageFlags flags
) {
1300 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1301 const char *p
, *node
, *fstype
;
1302 bool rw
, remap_uid_gid
= false;
1308 if (m
->mount_node_fd
< 0)
1311 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1312 node
= FORMAT_PROC_FD_PATH(m
->mount_node_fd
);
1313 fstype
= m
->decrypted_node
? m
->decrypted_fstype
: m
->fstype
;
1316 return -EAFNOSUPPORT
;
1318 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1319 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1321 if (streq(fstype
, "crypto_LUKS"))
1324 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
1326 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1327 r
= run_fsck(m
->mount_node_fd
, fstype
);
1333 /* Automatically create missing mount points inside the image, if necessary. */
1334 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
1335 if (r
< 0 && r
!= -EROFS
)
1338 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1344 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1345 * image (as the branch above does) but the host hierarchy, and the created directory might
1346 * survive our mount in the host hierarchy hence. */
1347 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1348 r
= mkdir_p(where
, 0755);
1356 /* If requested, turn on discard support. */
1357 if (fstype_can_discard(fstype
) &&
1358 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1359 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
) > 0))) {
1360 options
= strdup("discard");
1365 if (uid_is_valid(uid_shift
) && uid_shift
!= 0) {
1367 if (fstype_can_uid_gid(fstype
)) {
1368 _cleanup_free_
char *uid_option
= NULL
;
1370 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1373 if (!strextend_with_separator(&options
, ",", uid_option
))
1375 } else if (FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
))
1376 remap_uid_gid
= true;
1379 if (!isempty(m
->mount_options
))
1380 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
1383 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1384 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1385 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1386 * from the upper file system still get propagated through to the underlying file system,
1387 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1388 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1389 * carry a per file system table here.
1391 * Note that this means that we might not be able to mount corrupted file systems as read-only
1392 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1393 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1394 * mount options for loopback devices this is the right choice, since otherwise using the same
1395 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1396 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1397 * access that actually modifies stuff work on such image files. Or to say this differently: if
1398 * people want their file systems to be fixed up they should just open them in writable mode, where
1399 * all these problems don't exist. */
1400 if (!rw
&& STRPTR_IN_SET(fstype
, "ext3", "ext4", "xfs", "btrfs"))
1401 if (!strextend_with_separator(&options
, ",", "norecovery"))
1404 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1408 if (rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
))
1409 (void) fs_grow(node
, p
);
1411 if (remap_uid_gid
) {
1412 r
= remount_idmap(p
, uid_shift
, uid_range
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
1420 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1421 _cleanup_free_
char *options
= NULL
;
1426 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1428 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1429 r
= mkdir_p(where
, 0755);
1434 if (uid_is_valid(uid_shift
)) {
1435 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1439 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
1446 int dissected_image_mount(
1451 DissectImageFlags flags
) {
1453 int r
, xbootldr_mounted
;
1460 * -ENXIO → No root partition found
1461 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1462 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1463 * -EUCLEAN → fsck for file system failed
1464 * -EBUSY → File system already mounted/used elsewhere (kernel)
1465 * -EAFNOSUPPORT → File system type not supported or not known
1468 if (!(m
->partitions
[PARTITION_ROOT
].found
||
1469 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1470 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1472 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1474 /* First mount the root fs. If there's none we use a tmpfs. */
1475 if (m
->partitions
[PARTITION_ROOT
].found
)
1476 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, flags
);
1478 r
= mount_root_tmpfs(where
, uid_shift
, flags
);
1482 /* For us mounting root always means mounting /usr as well */
1483 r
= mount_partition(m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, flags
);
1487 if ((flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
1488 /* If either one of the validation flags are set, ensure that the image qualifies
1489 * as one or the other (or both). */
1492 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
1493 r
= path_is_os_tree(where
);
1499 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
)) {
1500 r
= path_is_extension_tree(where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_SYSEXT_CHECK
));
1512 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1515 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, flags
);
1519 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, flags
);
1523 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, flags
);
1527 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, flags
);
1531 xbootldr_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, flags
);
1532 if (xbootldr_mounted
< 0)
1533 return xbootldr_mounted
;
1535 if (m
->partitions
[PARTITION_ESP
].found
) {
1536 int esp_done
= false;
1538 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1539 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1541 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1546 /* /efi doesn't exist. Let's see if /boot is suitable then */
1548 if (!xbootldr_mounted
) {
1549 _cleanup_free_
char *p
= NULL
;
1551 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1555 } else if (dir_is_empty(p
, /* ignore_hidden_or_backup= */ false) > 0) {
1556 /* It exists and is an empty directory. Let's mount the ESP there. */
1557 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, uid_range
, flags
);
1567 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1569 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, uid_range
, flags
);
1578 int dissected_image_mount_and_warn(
1583 DissectImageFlags flags
) {
1590 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, flags
);
1592 return log_error_errno(r
, "Not root file system found in image.");
1593 if (r
== -EMEDIUMTYPE
)
1594 return log_error_errno(r
, "No suitable os-release/extension-release file in image found.");
1596 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
1598 return log_error_errno(r
, "File system check on image failed.");
1600 return log_error_errno(r
, "File system already mounted elsewhere.");
1601 if (r
== -EAFNOSUPPORT
)
1602 return log_error_errno(r
, "File system type not supported or not known.");
1604 return log_error_errno(r
, "Failed to mount image: %m");
1609 #if HAVE_LIBCRYPTSETUP
1610 struct DecryptedPartition
{
1611 struct crypt_device
*device
;
1617 typedef struct DecryptedPartition DecryptedPartition
;
1619 struct DecryptedImage
{
1621 DecryptedPartition
*decrypted
;
1625 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
1626 #if HAVE_LIBCRYPTSETUP
1632 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
1633 DecryptedPartition
*p
= d
->decrypted
+ i
;
1635 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1636 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
1637 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1639 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1643 sym_crypt_free(p
->device
);
1653 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
1655 #if HAVE_LIBCRYPTSETUP
1656 static int decrypted_image_new(DecryptedImage
**ret
) {
1657 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1661 d
= new(DecryptedImage
, 1);
1665 *d
= (DecryptedImage
) {
1673 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1674 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1677 assert(original_node
);
1682 base
= strrchr(original_node
, '/');
1684 base
= original_node
;
1690 name
= strjoin(base
, suffix
);
1693 if (!filename_is_valid(name
))
1696 node
= path_join(sym_crypt_get_dir(), name
);
1700 *ret_name
= TAKE_PTR(name
);
1701 *ret_node
= TAKE_PTR(node
);
1706 static int decrypt_partition(
1707 DissectedPartition
*m
,
1708 const char *passphrase
,
1709 DissectImageFlags flags
,
1710 DecryptedImage
*d
) {
1712 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1713 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1714 _cleanup_close_
int fd
= -1;
1720 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1723 if (!streq(m
->fstype
, "crypto_LUKS"))
1729 r
= dlopen_cryptsetup();
1733 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1737 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
1740 r
= sym_crypt_init(&cd
, m
->node
);
1742 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1744 cryptsetup_enable_logging(cd
);
1746 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
1748 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1750 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1751 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1752 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1754 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1755 return r
== -EPERM
? -EKEYREJECTED
: r
;
1758 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
1760 return log_debug_errno(errno
, "Failed to open %s: %m", node
);
1762 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
1763 .name
= TAKE_PTR(name
),
1764 .device
= TAKE_PTR(cd
),
1767 m
->decrypted_node
= TAKE_PTR(node
);
1768 close_and_replace(m
->mount_node_fd
, fd
);
1773 static int verity_can_reuse(
1774 const VeritySettings
*verity
,
1776 struct crypt_device
**ret_cd
) {
1778 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1779 _cleanup_free_
char *root_hash_existing
= NULL
;
1780 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1781 struct crypt_params_verity crypt_params
= {};
1782 size_t root_hash_existing_size
;
1789 r
= sym_crypt_init_by_name(&cd
, name
);
1791 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1793 cryptsetup_enable_logging(cd
);
1795 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
1797 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1799 root_hash_existing_size
= verity
->root_hash_size
;
1800 root_hash_existing
= malloc0(root_hash_existing_size
);
1801 if (!root_hash_existing
)
1804 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1806 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1807 if (verity
->root_hash_size
!= root_hash_existing_size
||
1808 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
1809 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1811 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1812 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1813 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1814 * signing for the new one, and vice versa. */
1815 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1816 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1819 *ret_cd
= TAKE_PTR(cd
);
1823 static inline char* dm_deferred_remove_clean(char *name
) {
1827 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1830 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1832 static int validate_signature_userspace(const VeritySettings
*verity
) {
1834 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
1835 _cleanup_strv_free_
char **certs
= NULL
;
1836 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
1837 _cleanup_free_
char *s
= NULL
;
1838 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
1839 * of declaration in place, please */
1840 const unsigned char *d
;
1844 assert(verity
->root_hash
);
1845 assert(verity
->root_hash_sig
);
1847 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
1848 * userspace validation. */
1850 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
1852 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
1853 if (strv_isempty(certs
)) {
1854 log_debug("No userspace dm-verity certificates found.");
1858 d
= verity
->root_hash_sig
;
1859 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
1861 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
1863 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
1865 return log_oom_debug();
1867 bio
= BIO_new_mem_buf(s
, strlen(s
));
1869 return log_oom_debug();
1871 sk
= sk_X509_new_null();
1873 return log_oom_debug();
1875 STRV_FOREACH(i
, certs
) {
1876 _cleanup_(X509_freep
) X509
*c
= NULL
;
1877 _cleanup_fclose_
FILE *f
= NULL
;
1879 f
= fopen(*i
, "re");
1881 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
1885 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
1887 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
1891 if (sk_X509_push(sk
, c
) == 0)
1892 return log_oom_debug();
1897 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
1899 log_debug("Userspace PKCS#7 validation succeeded.");
1901 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
1905 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
1910 static int do_crypt_activate_verity(
1911 struct crypt_device
*cd
,
1913 const VeritySettings
*verity
) {
1915 bool check_signature
;
1922 if (verity
->root_hash_sig
) {
1923 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
1924 if (r
< 0 && r
!= -ENXIO
)
1925 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
1927 check_signature
= r
!= 0;
1929 check_signature
= false;
1931 if (check_signature
) {
1933 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1934 /* First, if we have support for signed keys in the kernel, then try that first. */
1935 r
= sym_crypt_activate_by_signed_key(
1939 verity
->root_hash_size
,
1940 verity
->root_hash_sig
,
1941 verity
->root_hash_sig_size
,
1942 CRYPT_ACTIVATE_READONLY
);
1946 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
1948 log_debug("Activation of verity device with signature requested, but not supported via the kernel by %s due to missing crypt_activate_by_signed_key(), trying userspace validation instead.",
1949 program_invocation_short_name
);
1952 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
1953 * works we'll try to activate without telling the kernel the signature. */
1955 r
= validate_signature_userspace(verity
);
1959 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY
),
1960 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
1963 return sym_crypt_activate_by_volume_key(
1967 verity
->root_hash_size
,
1968 CRYPT_ACTIVATE_READONLY
);
1971 static usec_t
verity_timeout(void) {
1972 usec_t t
= 100 * USEC_PER_MSEC
;
1976 /* On slower machines, like non-KVM vm, setting up device may take a long time.
1977 * Let's make the timeout configurable. */
1979 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
1983 r
= parse_sec(e
, &t
);
1986 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
1987 "using the default timeout (%s).",
1988 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
1993 static int verity_partition(
1994 PartitionDesignator designator
,
1995 DissectedPartition
*m
,
1996 DissectedPartition
*v
,
1997 const VeritySettings
*verity
,
1998 DissectImageFlags flags
,
1999 DecryptedImage
*d
) {
2001 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2002 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2003 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2004 _cleanup_close_
int mount_node_fd
= -1;
2008 assert(v
|| (verity
&& verity
->data_path
));
2010 if (!verity
|| !verity
->root_hash
)
2012 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2013 (verity
->designator
== designator
)))
2016 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2018 if (!verity
->data_path
) {
2019 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2022 if (!streq(v
->fstype
, "DM_verity_hash"))
2026 r
= dlopen_cryptsetup();
2030 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2031 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2032 _cleanup_free_
char *root_hash_encoded
= NULL
;
2034 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2035 if (!root_hash_encoded
)
2038 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2040 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2044 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2048 cryptsetup_enable_logging(cd
);
2050 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2054 r
= sym_crypt_set_data_device(cd
, m
->node
);
2058 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2061 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2062 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2063 * retry a few times before giving up. */
2064 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2065 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2066 _cleanup_close_
int fd
= -1;
2068 /* First, check if the device already exists. */
2069 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2070 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2071 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2073 goto check
; /* The device already exists. Let's check it. */
2075 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2076 r
= do_crypt_activate_verity(cd
, name
, verity
);
2078 goto try_open
; /* The device is activated. Let's open it. */
2079 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2080 * There's no way to distinguish this situation from a genuine error due to invalid
2081 * parameters, so immediately fall back to activating the device with a unique name.
2082 * Improvements in libcrypsetup can ensure this never happens:
2083 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2084 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2086 if (r
== -ENODEV
) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2089 -EEXIST
, /* Volume has already been opened and ready to be used. */
2090 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2091 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2094 if (!restore_deferred_remove
){
2095 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2096 r
= dm_deferred_remove_cancel(name
);
2097 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2098 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2099 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2100 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2103 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2105 restore_deferred_remove
= strdup(name
);
2106 if (!restore_deferred_remove
)
2107 return log_oom_debug();
2110 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2111 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2112 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2115 -ENOENT
, /* Removed?? */
2116 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2117 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2120 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2123 /* devmapper might say that the device exists, but the devlink might not yet have been
2124 * created. Check and wait for the udev event in that case. */
2125 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2126 /* Fallback to activation with a unique device if it's taking too long */
2127 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2130 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2135 /* Now, the device is activated and devlink is created. Let's open it. */
2136 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2138 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
2139 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2141 /* The device has already been removed?? */
2146 mount_node_fd
= TAKE_FD(fd
);
2148 crypt_free_and_replace(cd
, existing_cd
);
2153 /* Device is being removed by another process. Let's wait for a while. */
2154 (void) usleep(2 * USEC_PER_MSEC
);
2157 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2158 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2159 /* Before trying to activate with unique name, we need to free crypt_device object.
2160 * Otherwise, we get error from libcryptsetup like the following:
2162 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2167 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2170 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2173 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2174 restore_deferred_remove
= mfree(restore_deferred_remove
);
2176 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2177 .name
= TAKE_PTR(name
),
2178 .device
= TAKE_PTR(cd
),
2181 m
->decrypted_node
= TAKE_PTR(node
);
2182 close_and_replace(m
->mount_node_fd
, mount_node_fd
);
2188 int dissected_image_decrypt(
2190 const char *passphrase
,
2191 const VeritySettings
*verity
,
2192 DissectImageFlags flags
) {
2194 #if HAVE_LIBCRYPTSETUP
2195 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2200 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
2204 * = 0 → There was nothing to decrypt
2205 * > 0 → Decrypted successfully
2206 * -ENOKEY → There's something to decrypt but no key was supplied
2207 * -EKEYREJECTED → Passed key was not correct
2210 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
2213 if (!m
->encrypted
&& !m
->verity_ready
)
2216 #if HAVE_LIBCRYPTSETUP
2217 r
= decrypted_image_new(&d
);
2221 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
2222 DissectedPartition
*p
= m
->partitions
+ i
;
2223 PartitionDesignator k
;
2228 r
= decrypt_partition(p
, passphrase
, flags
, d
);
2232 k
= partition_verity_of(i
);
2234 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
2239 if (!p
->decrypted_fstype
&& p
->mount_node_fd
>= 0 && p
->decrypted_node
) {
2240 r
= probe_filesystem_full(p
->mount_node_fd
, p
->decrypted_node
, &p
->decrypted_fstype
);
2241 if (r
< 0 && r
!= -EUCLEAN
)
2246 m
->decrypted_image
= TAKE_PTR(d
);
2254 int dissected_image_decrypt_interactively(
2256 const char *passphrase
,
2257 const VeritySettings
*verity
,
2258 DissectImageFlags flags
) {
2260 _cleanup_strv_free_erase_
char **z
= NULL
;
2267 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
2270 if (r
== -EKEYREJECTED
)
2271 log_error_errno(r
, "Incorrect passphrase, try again!");
2272 else if (r
!= -ENOKEY
)
2273 return log_error_errno(r
, "Failed to decrypt image: %m");
2276 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
2277 "Too many retries.");
2281 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY
, 0, &z
);
2283 return log_error_errno(r
, "Failed to query for passphrase: %m");
2289 static int decrypted_image_relinquish(DecryptedImage
*d
) {
2292 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2293 * boolean so that we don't clean it up ourselves either anymore */
2295 #if HAVE_LIBCRYPTSETUP
2298 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2299 DecryptedPartition
*p
= d
->decrypted
+ i
;
2301 if (p
->relinquished
)
2304 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2306 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
2308 p
->relinquished
= true;
2315 int dissected_image_relinquish(DissectedImage
*m
) {
2320 if (m
->decrypted_image
) {
2321 r
= decrypted_image_relinquish(m
->decrypted_image
);
2327 loop_device_relinquish(m
->loop
);
2332 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
2339 e
= endswith(image
, ".raw");
2341 return strjoin(e
, suffix
);
2343 n
= new(char, e
- image
+ strlen(suffix
) + 1);
2347 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
2351 void verity_settings_done(VeritySettings
*v
) {
2354 v
->root_hash
= mfree(v
->root_hash
);
2355 v
->root_hash_size
= 0;
2357 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
2358 v
->root_hash_sig_size
= 0;
2360 v
->data_path
= mfree(v
->data_path
);
2363 int verity_settings_load(
2364 VeritySettings
*verity
,
2366 const char *root_hash_path
,
2367 const char *root_hash_sig_path
) {
2369 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2370 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
2371 _cleanup_free_
char *verity_data_path
= NULL
;
2372 PartitionDesignator designator
;
2377 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
2379 /* If we are asked to load the root hash for a device node, exit early */
2380 if (is_device_path(image
))
2383 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2384 if (r
< 0 && r
!= -ENXIO
)
2385 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2389 designator
= verity
->designator
;
2391 /* We only fill in what isn't already filled in */
2393 if (!verity
->root_hash
) {
2394 _cleanup_free_
char *text
= NULL
;
2396 if (root_hash_path
) {
2397 /* If explicitly specified it takes precedence */
2398 r
= read_one_line_file(root_hash_path
, &text
);
2403 designator
= PARTITION_ROOT
;
2405 /* Otherwise look for xattr and separate file, and first for the data for root and if
2406 * that doesn't exist for /usr */
2408 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2409 r
= getxattr_malloc(image
, "user.verity.roothash", &text
);
2411 _cleanup_free_
char *p
= NULL
;
2413 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2416 p
= build_auxiliary_path(image
, ".roothash");
2420 r
= read_one_line_file(p
, &text
);
2421 if (r
< 0 && r
!= -ENOENT
)
2426 designator
= PARTITION_ROOT
;
2429 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2430 /* So in the "roothash" xattr/file name above the "root" of course primarily
2431 * refers to the root of the Verity Merkle tree. But coincidentally it also
2432 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2433 * two distinct concepts called "root". Taking benefit of this happy
2434 * coincidence we call the file with the root hash for the /usr/ file system
2435 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2436 * confusing. We thus drop the reference to the root of the Merkle tree, and
2437 * just indicate which file system it's about. */
2438 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
);
2440 _cleanup_free_
char *p
= NULL
;
2442 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2445 p
= build_auxiliary_path(image
, ".usrhash");
2449 r
= read_one_line_file(p
, &text
);
2450 if (r
< 0 && r
!= -ENOENT
)
2455 designator
= PARTITION_USR
;
2460 r
= unhexmem(text
, strlen(text
), &root_hash
, &root_hash_size
);
2463 if (root_hash_size
< sizeof(sd_id128_t
))
2468 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
2469 if (root_hash_sig_path
) {
2470 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2471 if (r
< 0 && r
!= -ENOENT
)
2475 designator
= PARTITION_ROOT
;
2477 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2478 _cleanup_free_
char *p
= NULL
;
2480 /* Follow naming convention recommended by the relevant RFC:
2481 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2482 p
= build_auxiliary_path(image
, ".roothash.p7s");
2486 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2487 if (r
< 0 && r
!= -ENOENT
)
2490 designator
= PARTITION_ROOT
;
2493 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2494 _cleanup_free_
char *p
= NULL
;
2496 p
= build_auxiliary_path(image
, ".usrhash.p7s");
2500 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2501 if (r
< 0 && r
!= -ENOENT
)
2504 designator
= PARTITION_USR
;
2508 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
2512 if (!verity
->data_path
) {
2513 _cleanup_free_
char *p
= NULL
;
2515 p
= build_auxiliary_path(image
, ".verity");
2519 if (access(p
, F_OK
) < 0) {
2520 if (errno
!= ENOENT
)
2523 verity_data_path
= TAKE_PTR(p
);
2527 verity
->root_hash
= TAKE_PTR(root_hash
);
2528 verity
->root_hash_size
= root_hash_size
;
2531 if (root_hash_sig
) {
2532 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
2533 verity
->root_hash_sig_size
= root_hash_sig_size
;
2536 if (verity_data_path
)
2537 verity
->data_path
= TAKE_PTR(verity_data_path
);
2539 if (verity
->designator
< 0)
2540 verity
->designator
= designator
;
2545 int dissected_image_load_verity_sig_partition(
2548 VeritySettings
*verity
) {
2550 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2551 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
2552 size_t root_hash_size
, root_hash_sig_size
;
2553 _cleanup_free_
char *buf
= NULL
;
2554 PartitionDesignator d
;
2555 DissectedPartition
*p
;
2556 JsonVariant
*rh
, *sig
;
2565 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
2568 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2569 if (r
< 0 && r
!= -ENXIO
)
2570 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2574 d
= partition_verity_sig_of(verity
->designator
< 0 ? PARTITION_ROOT
: verity
->designator
);
2577 p
= m
->partitions
+ d
;
2580 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
2583 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2586 buf
= new(char, p
->size
+1);
2590 n
= pread(fd
, buf
, p
->size
, p
->offset
);
2593 if ((uint64_t) n
!= p
->size
)
2596 e
= memchr(buf
, 0, p
->size
);
2598 /* If we found a NUL byte then the rest of the data must be NUL too */
2599 if (!memeqzero(e
, p
->size
- (e
- buf
)))
2600 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
2604 r
= json_parse(buf
, 0, &v
, NULL
, NULL
);
2606 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
2608 rh
= json_variant_by_key(v
, "rootHash");
2610 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
2611 if (!json_variant_is_string(rh
))
2612 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'rootHash' field of signature JSON object is not a string.");
2614 r
= unhexmem(json_variant_string(rh
), SIZE_MAX
, &root_hash
, &root_hash_size
);
2616 return log_debug_errno(r
, "Failed to parse root hash field: %m");
2618 /* Check if specified root hash matches if it is specified */
2619 if (verity
->root_hash
&&
2620 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
2621 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
2623 a
= hexmem(root_hash
, root_hash_size
);
2624 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2626 return log_debug_errno(r
, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
2629 sig
= json_variant_by_key(v
, "signature");
2631 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
2632 if (!json_variant_is_string(sig
))
2633 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'signature' field of signature JSON object is not a string.");
2635 r
= unbase64mem(json_variant_string(sig
), SIZE_MAX
, &root_hash_sig
, &root_hash_sig_size
);
2637 return log_debug_errno(r
, "Failed to parse signature field: %m");
2639 free_and_replace(verity
->root_hash
, root_hash
);
2640 verity
->root_hash_size
= root_hash_size
;
2642 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
2643 verity
->root_hash_sig_size
= root_hash_sig_size
;
2648 int dissected_image_acquire_metadata(DissectedImage
*m
, DissectImageFlags extra_flags
) {
2655 META_INITRD_RELEASE
,
2656 META_EXTENSION_RELEASE
,
2657 META_HAS_INIT_SYSTEM
,
2661 static const char *const paths
[_META_MAX
] = {
2662 [META_HOSTNAME
] = "/etc/hostname\0",
2663 [META_MACHINE_ID
] = "/etc/machine-id\0",
2664 [META_MACHINE_INFO
] = "/etc/machine-info\0",
2665 [META_OS_RELEASE
] = ("/etc/os-release\0"
2666 "/usr/lib/os-release\0"),
2667 [META_INITRD_RELEASE
] = ("/etc/initrd-release\0"
2668 "/usr/lib/initrd-release\0"),
2669 [META_EXTENSION_RELEASE
] = "extension-release\0", /* Used only for logging. */
2670 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
2673 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **initrd_release
= NULL
, **extension_release
= NULL
;
2674 _cleanup_close_pair_
int error_pipe
[2] = { -1, -1 };
2675 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
2676 _cleanup_(sigkill_waitp
) pid_t child
= 0;
2677 sd_id128_t machine_id
= SD_ID128_NULL
;
2678 _cleanup_free_
char *hostname
= NULL
;
2679 unsigned n_meta_initialized
= 0;
2680 int fds
[2 * _META_MAX
], r
, v
;
2681 int has_init_system
= -1;
2684 BLOCK_SIGNALS(SIGCHLD
);
2688 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
2689 if (!paths
[n_meta_initialized
]) {
2690 fds
[2*n_meta_initialized
] = fds
[2*n_meta_initialized
+1] = -1;
2694 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
2700 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
2704 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
2709 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
2713 /* Child in a new mount namespace */
2714 error_pipe
[0] = safe_close(error_pipe
[0]);
2716 r
= dissected_image_mount(
2722 DISSECT_IMAGE_READ_ONLY
|
2723 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
2724 DISSECT_IMAGE_USR_NO_ROOT
);
2726 log_debug_errno(r
, "Failed to mount dissected image: %m");
2730 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2731 _cleanup_close_
int fd
= -ENOENT
;
2736 fds
[2*k
] = safe_close(fds
[2*k
]);
2740 case META_EXTENSION_RELEASE
:
2741 /* As per the os-release spec, if the image is an extension it will have a file
2742 * named after the image name in extension-release.d/ - we use the image name
2743 * and try to resolve it with the extension-release helpers, as sometimes
2744 * the image names are mangled on deployment and do not match anymore.
2745 * Unlike other paths this is not fixed, and the image name
2746 * can be mangled on deployment, so by calling into the helper
2747 * we allow a fallback that matches on the first extension-release
2748 * file found in the directory, if one named after the image cannot
2749 * be found first. */
2750 r
= open_extension_release(t
, m
->image_name
, /* relax_extension_release_check= */ false, NULL
, &fd
);
2752 fd
= r
; /* Propagate the error. */
2755 case META_HAS_INIT_SYSTEM
: {
2758 FOREACH_STRING(init
,
2759 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
2760 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
2761 "/sbin/init") { /* traditional path the Linux kernel invokes */
2763 r
= chase_symlinks(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
2766 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
2773 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
), false);
2781 NULSTR_FOREACH(p
, paths
[k
]) {
2782 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
2789 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
2790 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2794 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
2798 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2801 _exit(EXIT_SUCCESS
);
2804 /* Let parent know the error */
2805 (void) write(error_pipe
[1], &r
, sizeof(r
));
2806 _exit(EXIT_FAILURE
);
2809 error_pipe
[1] = safe_close(error_pipe
[1]);
2811 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2812 _cleanup_fclose_
FILE *f
= NULL
;
2817 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2819 f
= take_fdopen(&fds
[2*k
], "r");
2828 r
= read_etc_hostname_stream(f
, &hostname
);
2830 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
2834 case META_MACHINE_ID
: {
2835 _cleanup_free_
char *line
= NULL
;
2837 r
= read_line(f
, LONG_LINE_MAX
, &line
);
2839 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
2841 r
= sd_id128_from_string(line
, &machine_id
);
2843 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
2845 log_debug("/etc/machine-id file of image is empty.");
2846 else if (streq(line
, "uninitialized"))
2847 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
2849 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
2854 case META_MACHINE_INFO
:
2855 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
2857 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
2861 case META_OS_RELEASE
:
2862 r
= load_env_file_pairs(f
, "os-release", &os_release
);
2864 log_debug_errno(r
, "Failed to read OS release file of image: %m");
2868 case META_INITRD_RELEASE
:
2869 r
= load_env_file_pairs(f
, "initrd-release", &initrd_release
);
2871 log_debug_errno(r
, "Failed to read initrd release file of image: %m");
2875 case META_EXTENSION_RELEASE
:
2876 r
= load_env_file_pairs(f
, "extension-release", &extension_release
);
2878 log_debug_errno(r
, "Failed to read extension release file of image: %m");
2882 case META_HAS_INIT_SYSTEM
: {
2887 nr
= fread(&b
, 1, sizeof(b
), f
);
2888 if (nr
!= sizeof(b
))
2889 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
2891 has_init_system
= b
;
2897 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
2902 n
= read(error_pipe
[0], &v
, sizeof(v
));
2906 return v
; /* propagate error sent to us from child */
2910 if (r
!= EXIT_SUCCESS
)
2913 free_and_replace(m
->hostname
, hostname
);
2914 m
->machine_id
= machine_id
;
2915 strv_free_and_replace(m
->machine_info
, machine_info
);
2916 strv_free_and_replace(m
->os_release
, os_release
);
2917 strv_free_and_replace(m
->initrd_release
, initrd_release
);
2918 strv_free_and_replace(m
->extension_release
, extension_release
);
2919 m
->has_init_system
= has_init_system
;
2922 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
2923 safe_close_pair(fds
+ 2*k
);
2928 int dissect_loop_device(
2930 const VeritySettings
*verity
,
2931 const MountOptions
*mount_options
,
2932 DissectImageFlags flags
,
2933 DissectedImage
**ret
) {
2936 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
2942 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
2946 m
->loop
= loop_device_ref(loop
);
2948 r
= dissect_image(m
, loop
->fd
, loop
->node
, verity
, mount_options
, flags
| DISSECT_IMAGE_BLOCK_DEVICE
);
2952 r
= dissected_image_probe_filesystem(m
);
2963 int dissect_loop_device_and_warn(
2965 const VeritySettings
*verity
,
2966 const MountOptions
*mount_options
,
2967 DissectImageFlags flags
,
2968 DissectedImage
**ret
) {
2974 assert(loop
->fd
>= 0);
2976 name
= ASSERT_PTR(loop
->backing_file
?: loop
->node
);
2978 r
= dissect_loop_device(loop
, verity
, mount_options
, flags
, ret
);
2982 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
2985 return log_error_errno(r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
2988 return log_error_errno(r
, "%s: The image does not pass validation.", name
);
2990 case -EADDRNOTAVAIL
:
2991 return log_error_errno(r
, "%s: No root partition for specified root hash found.", name
);
2994 return log_error_errno(r
, "%s: Multiple suitable root partitions found in image.", name
);
2997 return log_error_errno(r
, "%s: No suitable root partition found in image.", name
);
2999 case -EPROTONOSUPPORT
:
3000 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
3003 return log_error_errno(r
, "%s: Image is not a block device.", name
);
3006 return log_error_errno(r
,
3007 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
3008 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
3009 name
, strna(verity
? verity
->data_path
: NULL
));
3013 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
3019 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3022 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3023 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3024 * images we only check the partition type.
3026 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3029 if (image
->single_file_system
)
3030 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
3032 return partition_verity_of(partition_designator
) >= 0;
3035 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3036 PartitionDesignator k
;
3040 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3041 * works for the root partition, for others only if the associated verity partition was found. */
3043 if (!image
->verity_ready
)
3046 if (image
->single_file_system
)
3047 return partition_designator
== PARTITION_ROOT
;
3049 k
= partition_verity_of(partition_designator
);
3050 return k
>= 0 && image
->partitions
[k
].found
;
3053 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3054 PartitionDesignator k
;
3058 /* Checks if this partition has verity signature data available that we can use. */
3060 if (!image
->verity_sig_ready
)
3063 if (image
->single_file_system
)
3064 return partition_designator
== PARTITION_ROOT
;
3066 k
= partition_verity_sig_of(partition_designator
);
3067 return k
>= 0 && image
->partitions
[k
].found
;
3070 MountOptions
* mount_options_free_all(MountOptions
*options
) {
3073 while ((m
= options
)) {
3074 LIST_REMOVE(mount_options
, options
, m
);
3082 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
3083 LIST_FOREACH(mount_options
, m
, options
)
3084 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
3090 int mount_image_privately_interactively(
3092 DissectImageFlags flags
,
3093 char **ret_directory
,
3094 LoopDevice
**ret_loop_device
) {
3096 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3097 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3098 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3099 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
3100 _cleanup_free_
char *temp
= NULL
;
3103 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3104 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3108 assert(ret_directory
);
3109 assert(ret_loop_device
);
3111 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
3113 return log_error_errno(r
, "Failed to load root hash data: %m");
3115 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
3117 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
3119 r
= loop_device_make_by_path(
3121 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
3122 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
3126 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
3128 r
= dissect_loop_device_and_warn(d
, &verity
, NULL
, flags
, &dissected_image
);
3132 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
3136 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
3140 r
= detach_mount_namespace();
3142 return log_error_errno(r
, "Failed to detach mount namespace: %m");
3144 r
= mkdir_p(temp
, 0700);
3146 return log_error_errno(r
, "Failed to create mount point: %m");
3148 created_dir
= TAKE_PTR(temp
);
3150 r
= dissected_image_mount_and_warn(dissected_image
, created_dir
, UID_INVALID
, UID_INVALID
, flags
);
3154 r
= loop_device_flock(d
, LOCK_UN
);
3158 r
= dissected_image_relinquish(dissected_image
);
3160 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
3162 *ret_directory
= TAKE_PTR(created_dir
);
3163 *ret_loop_device
= TAKE_PTR(d
);
3168 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
3172 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
3173 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
3174 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
3177 int verity_dissect_and_mount(
3181 const MountOptions
*options
,
3182 const char *required_host_os_release_id
,
3183 const char *required_host_os_release_version_id
,
3184 const char *required_host_os_release_sysext_level
,
3185 const char *required_sysext_scope
) {
3187 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
3188 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3189 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3190 DissectImageFlags dissect_image_flags
;
3191 bool relax_extension_release_check
;
3197 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
3199 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3200 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
3202 return log_debug_errno(r
, "Failed to load root hash: %m");
3204 dissect_image_flags
= (verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
3205 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_SYSEXT_CHECK
: 0);
3207 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3208 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
3209 r
= loop_device_make_by_path(
3210 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
3212 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
3216 return log_debug_errno(r
, "Failed to create loop device for image: %m");
3218 r
= dissect_loop_device(
3222 dissect_image_flags
,
3224 /* No partition table? Might be a single-filesystem image, try again */
3225 if (!verity
.data_path
&& r
== -ENOPKG
)
3226 r
= dissect_loop_device(
3230 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
3233 return log_debug_errno(r
, "Failed to dissect image: %m");
3235 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, &verity
);
3239 r
= dissected_image_decrypt(
3243 dissect_image_flags
);
3245 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
3247 r
= mkdir_p_label(dest
, 0755);
3249 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
3250 r
= umount_recursive(dest
, 0);
3252 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
3254 r
= dissected_image_mount(dissected_image
, dest
, UID_INVALID
, UID_INVALID
, dissect_image_flags
);
3256 return log_debug_errno(r
, "Failed to mount image: %m");
3258 r
= loop_device_flock(loop_device
, LOCK_UN
);
3260 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
3262 /* If we got os-release values from the caller, then we need to match them with the image's
3263 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3264 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3265 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3266 * then a simple match on the ID will be performed. */
3267 if (required_host_os_release_id
) {
3268 _cleanup_strv_free_
char **extension_release
= NULL
;
3270 assert(!isempty(required_host_os_release_id
));
3272 r
= load_extension_release_pairs(dest
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
3274 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
3276 r
= extension_release_validate(
3277 dissected_image
->image_name
,
3278 required_host_os_release_id
,
3279 required_host_os_release_version_id
,
3280 required_host_os_release_sysext_level
,
3281 required_sysext_scope
,
3284 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
3286 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
3289 r
= dissected_image_relinquish(dissected_image
);
3291 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");