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
;
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
);
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
;
437 _cleanup_close_
int mount_node_fd
= -1;
439 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
440 mount_node_fd
= open_partition(devname
, /* is_partition = */ false, m
->loop
);
441 if (mount_node_fd
< 0)
442 return mount_node_fd
;
445 /* OK, we have found a file system, that's our root partition then. */
446 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
458 m
->single_file_system
= true;
459 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
461 m
->has_verity
= verity
&& verity
->data_path
;
462 m
->verity_ready
= m
->has_verity
&&
464 (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
);
466 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
467 m
->verity_sig_ready
= m
->verity_ready
&&
468 verity
->root_hash_sig
;
470 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
477 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
479 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
481 .architecture
= _ARCHITECTURE_INVALID
,
482 .fstype
= TAKE_PTR(t
),
484 .mount_options
= TAKE_PTR(o
),
485 .mount_node_fd
= TAKE_FD(mount_node_fd
),
494 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
498 is_gpt
= streq_ptr(pttype
, "gpt");
499 is_mbr
= streq_ptr(pttype
, "dos");
501 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
504 /* We support external verity data partitions only if the image has no partition table */
505 if (verity
&& verity
->data_path
)
508 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
509 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
510 * do partition scanning. */
511 r
= blockdev_partscan_enabled(fd
);
515 return -EPROTONOSUPPORT
;
519 pl
= blkid_probe_get_partitions(b
);
521 return errno_or_else(ENOMEM
);
524 n_partitions
= blkid_partlist_numof_partitions(pl
);
525 if (n_partitions
< 0)
526 return errno_or_else(EIO
);
528 for (int i
= 0; i
< n_partitions
; i
++) {
529 _cleanup_free_
char *node
= NULL
;
530 unsigned long long pflags
;
531 blkid_loff_t start
, size
;
536 pp
= blkid_partlist_get_partition(pl
, i
);
538 return errno_or_else(EIO
);
540 pflags
= blkid_partition_get_flags(pp
);
543 nr
= blkid_partition_get_partno(pp
);
545 return errno_or_else(EIO
);
548 start
= blkid_partition_get_start(pp
);
550 return errno_or_else(EIO
);
552 assert((uint64_t) start
< UINT64_MAX
/512);
555 size
= blkid_partition_get_size(pp
);
557 return errno_or_else(EIO
);
559 assert((uint64_t) size
< UINT64_MAX
/512);
561 r
= make_partition_devname(devname
, nr
, &node
);
565 /* So here's the thing: after the main ("whole") block device popped up it might take a while
566 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
567 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
568 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
569 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
570 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
571 * also good as the outcome is the same: the partition block device exists, and we can use
574 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
575 * partition already existent. */
577 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
578 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
581 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
583 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
585 log_debug("We were quicker than kernel in adding partition %i.", nr
);
589 PartitionDesignator designator
= _PARTITION_DESIGNATOR_INVALID
;
590 Architecture architecture
= _ARCHITECTURE_INVALID
;
591 const char *stype
, *sid
, *fstype
= NULL
, *label
;
592 sd_id128_t type_id
, id
;
593 bool rw
= true, growfs
= false;
595 sid
= blkid_partition_get_uuid(pp
);
598 if (sd_id128_from_string(sid
, &id
) < 0)
601 stype
= blkid_partition_get_type_string(pp
);
604 if (sd_id128_from_string(stype
, &type_id
) < 0)
607 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
609 if (sd_id128_equal(type_id
, SD_GPT_HOME
)) {
611 check_partition_flags(node
, pflags
,
612 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
614 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
617 designator
= PARTITION_HOME
;
618 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
619 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
621 } else if (sd_id128_equal(type_id
, SD_GPT_SRV
)) {
623 check_partition_flags(node
, pflags
,
624 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
626 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
629 designator
= PARTITION_SRV
;
630 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
631 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
633 } else if (sd_id128_equal(type_id
, SD_GPT_ESP
)) {
635 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
636 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
637 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
640 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
643 designator
= PARTITION_ESP
;
646 } else if (sd_id128_equal(type_id
, SD_GPT_XBOOTLDR
)) {
648 check_partition_flags(node
, pflags
,
649 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
651 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
654 designator
= PARTITION_XBOOTLDR
;
655 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
656 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
658 } else if (gpt_partition_type_is_root(type_id
)) {
660 check_partition_flags(node
, pflags
,
661 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
663 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
666 /* If a root ID is specified, ignore everything but the root id */
667 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
670 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
671 designator
= PARTITION_ROOT_OF_ARCH(architecture
);
672 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
673 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
675 } else if (gpt_partition_type_is_root_verity(type_id
)) {
677 check_partition_flags(node
, pflags
,
678 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
680 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
683 m
->has_verity
= true;
685 /* If no verity configuration is specified, then don't do verity */
688 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
691 /* If root hash is specified, then ignore everything but the root id */
692 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
695 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
696 designator
= PARTITION_VERITY_OF(PARTITION_ROOT_OF_ARCH(architecture
));
697 fstype
= "DM_verity_hash";
700 } else if (gpt_partition_type_is_root_verity_sig(type_id
)) {
702 check_partition_flags(node
, pflags
,
703 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
705 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
708 m
->has_verity_sig
= true;
712 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
715 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
716 designator
= PARTITION_VERITY_SIG_OF(PARTITION_ROOT_OF_ARCH(architecture
));
717 fstype
= "verity_hash_signature";
720 } else if (gpt_partition_type_is_usr(type_id
)) {
722 check_partition_flags(node
, pflags
,
723 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
725 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
728 /* If a usr ID is specified, ignore everything but the usr id */
729 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
732 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
733 designator
= PARTITION_USR_OF_ARCH(architecture
);
734 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
735 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
737 } else if (gpt_partition_type_is_usr_verity(type_id
)) {
739 check_partition_flags(node
, pflags
,
740 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
742 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
745 m
->has_verity
= true;
749 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
752 /* If usr hash is specified, then ignore everything but the usr id */
753 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
756 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
757 designator
= PARTITION_VERITY_OF(PARTITION_USR_OF_ARCH(architecture
));
758 fstype
= "DM_verity_hash";
761 } else if (gpt_partition_type_is_usr_verity_sig(type_id
)) {
763 check_partition_flags(node
, pflags
,
764 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
766 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
769 m
->has_verity_sig
= true;
773 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
776 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
777 designator
= PARTITION_VERITY_SIG_OF(PARTITION_USR_OF_ARCH(architecture
));
778 fstype
= "verity_hash_signature";
781 } else if (sd_id128_equal(type_id
, SD_GPT_SWAP
)) {
783 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
785 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
788 designator
= PARTITION_SWAP
;
790 } else if (sd_id128_equal(type_id
, SD_GPT_LINUX_GENERIC
)) {
792 check_partition_flags(node
, pflags
,
793 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
795 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
799 multiple_generic
= true;
802 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
803 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
805 generic_node
= strdup(node
);
810 } else if (sd_id128_equal(type_id
, SD_GPT_TMP
)) {
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
)
818 designator
= PARTITION_TMP
;
819 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
820 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
822 } else if (sd_id128_equal(type_id
, SD_GPT_VAR
)) {
824 check_partition_flags(node
, pflags
,
825 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
827 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
830 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
833 /* For /var we insist that the uuid of the partition matches the
834 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
835 * ID. Why? Unlike the other partitions /var is inherently
836 * installation specific, hence we need to be careful not to mount it
837 * in the wrong installation. By hashing the partition UUID from
838 * /etc/machine-id we can securely bind the partition to the
841 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
845 if (!sd_id128_equal(var_uuid
, id
)) {
846 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
851 designator
= PARTITION_VAR
;
852 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
853 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
856 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
857 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
;
858 _cleanup_close_
int mount_node_fd
= -1;
859 const char *options
= NULL
;
861 if (m
->partitions
[designator
].found
) {
862 /* For most partition types the first one we see wins. Except for the
863 * rootfs and /usr, where we do a version compare of the label, and
864 * let the newest version win. This permits a simple A/B versioning
865 * scheme in OS images. */
867 if (!PARTITION_DESIGNATOR_VERSIONED(designator
) ||
868 strverscmp_improved(m
->partitions
[designator
].label
, label
) >= 0)
871 dissected_partition_done(m
->partitions
+ designator
);
874 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
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
, designator
);
899 m
->partitions
[designator
] = (DissectedPartition
) {
904 .architecture
= architecture
,
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 *sid
, *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 sid
= blkid_partition_get_uuid(pp
);
956 (void) sd_id128_from_string(sid
, &id
);
958 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
965 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
970 .architecture
= _ARCHITECTURE_INVALID
,
971 .node
= TAKE_PTR(node
),
973 .mount_options
= TAKE_PTR(o
),
974 .mount_node_fd
= TAKE_FD(mount_node_fd
),
975 .offset
= (uint64_t) start
* 512,
976 .size
= (uint64_t) size
* 512,
984 if (m
->partitions
[PARTITION_ROOT
].found
) {
985 /* If we found the primary arch, then invalidate the secondary and other arch to avoid any
986 * ambiguities, since we never want to mount the secondary or other arch in this case. */
987 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
988 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
989 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
].found
= false;
990 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
991 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
992 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
= false;
994 m
->partitions
[PARTITION_ROOT_OTHER
].found
= false;
995 m
->partitions
[PARTITION_ROOT_OTHER_VERITY
].found
= false;
996 m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
].found
= false;
997 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
998 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
999 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1001 } else if (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
1002 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
)
1003 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
1005 else if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
1007 /* No root partition found but there's one for the secondary architecture? Then upgrade
1008 * secondary arch to first and invalidate the other arch. */
1010 log_debug("No root partition found of the native architecture, falling back to a root "
1011 "partition of the secondary architecture.");
1013 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
1014 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
1015 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
1016 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
1017 m
->partitions
[PARTITION_ROOT_VERITY_SIG
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
];
1018 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
]);
1020 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_SECONDARY
];
1021 zero(m
->partitions
[PARTITION_USR_SECONDARY
]);
1022 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY
];
1023 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
1024 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
];
1025 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
]);
1027 m
->partitions
[PARTITION_ROOT_OTHER
].found
= false;
1028 m
->partitions
[PARTITION_ROOT_OTHER_VERITY
].found
= false;
1029 m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
].found
= false;
1030 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1031 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1032 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1034 } else if (m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
||
1035 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
].found
)
1036 return -EADDRNOTAVAIL
; /* as above */
1038 else if (m
->partitions
[PARTITION_ROOT_OTHER
].found
) {
1040 /* No root or secondary partition found but there's one for another architecture? Then
1041 * upgrade the other architecture to first. */
1043 log_debug("No root partition found of the native architecture or the secondary architecture, "
1044 "falling back to a root partition of a non-native architecture (%s).",
1045 architecture_to_string(m
->partitions
[PARTITION_ROOT_OTHER
].architecture
));
1047 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_OTHER
];
1048 zero(m
->partitions
[PARTITION_ROOT_OTHER
]);
1049 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_OTHER_VERITY
];
1050 zero(m
->partitions
[PARTITION_ROOT_OTHER_VERITY
]);
1051 m
->partitions
[PARTITION_ROOT_VERITY_SIG
] = m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
];
1052 zero(m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
]);
1054 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_OTHER
];
1055 zero(m
->partitions
[PARTITION_USR_OTHER
]);
1056 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_OTHER_VERITY
];
1057 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY
]);
1058 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
];
1059 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
]);
1062 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1063 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
1064 return -EADDRNOTAVAIL
;
1066 if (m
->partitions
[PARTITION_USR
].found
) {
1067 /* Invalidate secondary and other arch /usr/ if we found the primary arch */
1068 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
1069 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
1070 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
= false;
1072 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1073 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1074 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1076 } else if (m
->partitions
[PARTITION_USR_VERITY
].found
||
1077 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
)
1078 return -EADDRNOTAVAIL
; /* as above */
1080 else if (m
->partitions
[PARTITION_USR_SECONDARY
].found
) {
1082 log_debug("No usr partition found of the native architecture, falling back to a usr "
1083 "partition of the secondary architecture.");
1085 /* Upgrade secondary arch to primary */
1086 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_SECONDARY
];
1087 zero(m
->partitions
[PARTITION_USR_SECONDARY
]);
1088 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY
];
1089 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
1090 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
];
1091 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
]);
1093 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1094 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1095 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1097 } else if (m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
||
1098 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
)
1099 return -EADDRNOTAVAIL
; /* as above */
1101 else if (m
->partitions
[PARTITION_USR_OTHER
].found
) {
1103 log_debug("No usr partition found of the native architecture or the secondary architecture, "
1104 "falling back to a usr partition of a non-native architecture (%s).",
1105 architecture_to_string(m
->partitions
[PARTITION_ROOT_OTHER
].architecture
));
1107 /* Upgrade other arch to primary */
1108 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_OTHER
];
1109 zero(m
->partitions
[PARTITION_USR_OTHER
]);
1110 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_OTHER_VERITY
];
1111 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY
]);
1112 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
];
1113 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
]);
1116 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1117 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1118 return -EADDRNOTAVAIL
;
1120 /* If root and /usr are combined then insist that the architecture matches */
1121 if (m
->partitions
[PARTITION_ROOT
].found
&&
1122 m
->partitions
[PARTITION_USR
].found
&&
1123 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1124 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1125 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1126 return -EADDRNOTAVAIL
;
1128 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1129 !m
->partitions
[PARTITION_USR
].found
&&
1130 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1131 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1133 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1134 * that. If the root hash was set however, then we won't fall back to a generic node, because
1135 * the root hash decides. */
1137 /* If we didn't find a properly marked root partition, but we did find a single suitable
1138 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1139 if (multiple_generic
)
1142 /* If we didn't find a generic node, then we can't fix this up either */
1144 _cleanup_close_
int mount_node_fd
= -1;
1145 _cleanup_free_
char *o
= NULL
;
1146 const char *options
;
1148 if (FLAGS_SET(flags
, DISSECT_IMAGE_OPEN_PARTITION_DEVICES
)) {
1149 mount_node_fd
= open_partition(generic_node
, /* is_partition = */ true, m
->loop
);
1150 if (mount_node_fd
< 0)
1151 return mount_node_fd
;
1154 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1156 o
= strdup(options
);
1161 assert(generic_nr
>= 0);
1162 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1165 .growfs
= generic_growfs
,
1166 .partno
= generic_nr
,
1167 .architecture
= _ARCHITECTURE_INVALID
,
1168 .node
= TAKE_PTR(generic_node
),
1169 .uuid
= generic_uuid
,
1170 .mount_options
= TAKE_PTR(o
),
1171 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1172 .offset
= UINT64_MAX
,
1178 /* 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 */
1179 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1180 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1183 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1184 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1185 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1188 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1189 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1190 if (m
->partitions
[PARTITION_USR
].found
)
1191 return -EADDRNOTAVAIL
;
1195 /* If a verity designator is specified, then insist that the matching partition exists */
1196 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1197 return -EADDRNOTAVAIL
;
1199 bool have_verity_sig_partition
=
1200 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR_VERITY_SIG
: PARTITION_ROOT_VERITY_SIG
].found
;
1202 if (verity
->root_hash
) {
1203 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1204 * Verity, set things up for it */
1206 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1207 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1208 return -EADDRNOTAVAIL
;
1210 /* If we found a verity setup, then the root partition is necessarily read-only. */
1211 m
->partitions
[PARTITION_ROOT
].rw
= false;
1212 m
->verity_ready
= true;
1215 assert(verity
->designator
== PARTITION_USR
);
1217 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1218 return -EADDRNOTAVAIL
;
1220 m
->partitions
[PARTITION_USR
].rw
= false;
1221 m
->verity_ready
= true;
1224 if (m
->verity_ready
)
1225 m
->verity_sig_ready
= verity
->root_hash_sig
|| have_verity_sig_partition
;
1227 } else if (have_verity_sig_partition
) {
1229 /* If we found an embedded signature partition, we are ready, too. */
1231 m
->verity_ready
= m
->verity_sig_ready
= true;
1232 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR
: PARTITION_ROOT
].rw
= false;
1240 int dissect_image_file(
1242 const VeritySettings
*verity
,
1243 const MountOptions
*mount_options
,
1244 DissectImageFlags flags
,
1245 DissectedImage
**ret
) {
1248 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1249 _cleanup_close_
int fd
= -1;
1253 assert((flags
& DISSECT_IMAGE_BLOCK_DEVICE
) == 0);
1256 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1260 r
= fd_verify_regular(fd
);
1264 r
= dissected_image_new(path
, &m
);
1268 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, flags
);
1279 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1283 /* First, clear dissected partitions. */
1284 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1285 dissected_partition_done(m
->partitions
+ i
);
1287 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1288 * DecryptedImage may try to deactivate partitions. */
1289 decrypted_image_unref(m
->decrypted_image
);
1291 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1292 * remove existing partitions on the loopback block device. */
1293 loop_device_unref(m
->loop
);
1295 free(m
->image_name
);
1297 strv_free(m
->machine_info
);
1298 strv_free(m
->os_release
);
1299 strv_free(m
->initrd_release
);
1300 strv_free(m
->extension_release
);
1305 static int is_loop_device(const char *path
) {
1306 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1311 if (stat(path
, &st
) < 0)
1314 if (!S_ISBLK(st
.st_mode
))
1317 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1318 if (access(s
, F_OK
) < 0) {
1319 if (errno
!= ENOENT
)
1322 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1323 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1324 if (access(s
, F_OK
) < 0)
1325 return errno
== ENOENT
? false : -errno
;
1331 static int run_fsck(int node_fd
, const char *fstype
) {
1335 assert(node_fd
>= 0);
1338 r
= fsck_exists_for_fstype(fstype
);
1340 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1344 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd
), fstype
);
1350 &node_fd
, 1, /* Leave the node fd open */
1351 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
|FORK_CLOEXEC_OFF
,
1354 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1357 execl("/sbin/fsck", "/sbin/fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd
), NULL
);
1359 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1360 _exit(FSCK_OPERATIONAL_ERROR
);
1363 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1364 if (exit_status
< 0)
1365 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
1367 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1368 log_debug("fsck failed with exit status %i.", exit_status
);
1370 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1371 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1373 log_debug("Ignoring fsck error.");
1379 static int fs_grow(const char *node_path
, const char *mount_path
) {
1380 _cleanup_close_
int mount_fd
= -1, node_fd
= -1;
1381 uint64_t size
, newsize
;
1384 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1386 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1388 if (ioctl(node_fd
, BLKGETSIZE64
, &size
) != 0)
1389 return log_debug_errno(errno
, "Failed to get block device size of %s: %m", node_path
);
1391 mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1393 return log_debug_errno(errno
, "Failed to open mountd file system %s: %m", mount_path
);
1395 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", mount_path
, size
);
1396 r
= resize_fs(mount_fd
, size
, &newsize
);
1398 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", mount_path
, size
);
1400 if (newsize
== size
)
1401 log_debug("Successfully resized \"%s\" to %s bytes.",
1402 mount_path
, FORMAT_BYTES(newsize
));
1404 assert(newsize
< size
);
1405 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1406 mount_path
, FORMAT_BYTES(newsize
), size
- newsize
);
1412 static int mount_partition(
1413 DissectedPartition
*m
,
1415 const char *directory
,
1418 DissectImageFlags flags
) {
1420 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1421 const char *p
, *node
, *fstype
;
1422 bool rw
, remap_uid_gid
= false;
1428 if (m
->mount_node_fd
< 0)
1431 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1432 node
= FORMAT_PROC_FD_PATH(m
->mount_node_fd
);
1433 fstype
= m
->decrypted_node
? m
->decrypted_fstype
: m
->fstype
;
1436 return -EAFNOSUPPORT
;
1438 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1439 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1441 if (streq(fstype
, "crypto_LUKS"))
1444 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
1446 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1447 r
= run_fsck(m
->mount_node_fd
, fstype
);
1453 /* Automatically create missing mount points inside the image, if necessary. */
1454 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
1455 if (r
< 0 && r
!= -EROFS
)
1458 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1464 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1465 * image (as the branch above does) but the host hierarchy, and the created directory might
1466 * survive our mount in the host hierarchy hence. */
1467 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1468 r
= mkdir_p(where
, 0755);
1476 /* If requested, turn on discard support. */
1477 if (fstype_can_discard(fstype
) &&
1478 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1479 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
) > 0))) {
1480 options
= strdup("discard");
1485 if (uid_is_valid(uid_shift
) && uid_shift
!= 0) {
1487 if (fstype_can_uid_gid(fstype
)) {
1488 _cleanup_free_
char *uid_option
= NULL
;
1490 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1493 if (!strextend_with_separator(&options
, ",", uid_option
))
1495 } else if (FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
))
1496 remap_uid_gid
= true;
1499 if (!isempty(m
->mount_options
))
1500 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
1503 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1504 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1505 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1506 * from the upper file system still get propagated through to the underlying file system,
1507 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1508 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1509 * carry a per file system table here.
1511 * Note that this means that we might not be able to mount corrupted file systems as read-only
1512 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1513 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1514 * mount options for loopback devices this is the right choice, since otherwise using the same
1515 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1516 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1517 * access that actually modifies stuff work on such image files. Or to say this differently: if
1518 * people want their file systems to be fixed up they should just open them in writable mode, where
1519 * all these problems don't exist. */
1520 if (!rw
&& STRPTR_IN_SET(fstype
, "ext3", "ext4", "xfs", "btrfs"))
1521 if (!strextend_with_separator(&options
, ",", "norecovery"))
1524 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1528 if (rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
))
1529 (void) fs_grow(node
, p
);
1531 if (remap_uid_gid
) {
1532 r
= remount_idmap(p
, uid_shift
, uid_range
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
1540 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1541 _cleanup_free_
char *options
= NULL
;
1546 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1548 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1549 r
= mkdir_p(where
, 0755);
1554 if (uid_is_valid(uid_shift
)) {
1555 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1559 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
1566 int dissected_image_mount(
1571 DissectImageFlags flags
) {
1573 int r
, xbootldr_mounted
;
1580 * -ENXIO → No root partition found
1581 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1582 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1583 * -EUCLEAN → fsck for file system failed
1584 * -EBUSY → File system already mounted/used elsewhere (kernel)
1585 * -EAFNOSUPPORT → File system type not supported or not known
1588 if (!(m
->partitions
[PARTITION_ROOT
].found
||
1589 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1590 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1592 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1594 /* First mount the root fs. If there's none we use a tmpfs. */
1595 if (m
->partitions
[PARTITION_ROOT
].found
)
1596 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, flags
);
1598 r
= mount_root_tmpfs(where
, uid_shift
, flags
);
1602 /* For us mounting root always means mounting /usr as well */
1603 r
= mount_partition(m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, flags
);
1607 if ((flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
1608 /* If either one of the validation flags are set, ensure that the image qualifies
1609 * as one or the other (or both). */
1612 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
1613 r
= path_is_os_tree(where
);
1619 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
)) {
1620 r
= path_is_extension_tree(where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_SYSEXT_CHECK
));
1632 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1635 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, flags
);
1639 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, flags
);
1643 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, flags
);
1647 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, flags
);
1651 xbootldr_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, flags
);
1652 if (xbootldr_mounted
< 0)
1653 return xbootldr_mounted
;
1655 if (m
->partitions
[PARTITION_ESP
].found
) {
1656 int esp_done
= false;
1658 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1659 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1661 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1666 /* /efi doesn't exist. Let's see if /boot is suitable then */
1668 if (!xbootldr_mounted
) {
1669 _cleanup_free_
char *p
= NULL
;
1671 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1675 } else if (dir_is_empty(p
, /* ignore_hidden_or_backup= */ false) > 0) {
1676 /* It exists and is an empty directory. Let's mount the ESP there. */
1677 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, uid_range
, flags
);
1687 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1689 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, uid_range
, flags
);
1698 int dissected_image_mount_and_warn(
1703 DissectImageFlags flags
) {
1710 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, flags
);
1712 return log_error_errno(r
, "Not root file system found in image.");
1713 if (r
== -EMEDIUMTYPE
)
1714 return log_error_errno(r
, "No suitable os-release/extension-release file in image found.");
1716 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
1718 return log_error_errno(r
, "File system check on image failed.");
1720 return log_error_errno(r
, "File system already mounted elsewhere.");
1721 if (r
== -EAFNOSUPPORT
)
1722 return log_error_errno(r
, "File system type not supported or not known.");
1724 return log_error_errno(r
, "Failed to mount image: %m");
1729 #if HAVE_LIBCRYPTSETUP
1730 struct DecryptedPartition
{
1731 struct crypt_device
*device
;
1737 typedef struct DecryptedPartition DecryptedPartition
;
1739 struct DecryptedImage
{
1741 DecryptedPartition
*decrypted
;
1745 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
1746 #if HAVE_LIBCRYPTSETUP
1752 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
1753 DecryptedPartition
*p
= d
->decrypted
+ i
;
1755 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1756 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
1757 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1759 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1763 sym_crypt_free(p
->device
);
1773 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
1775 #if HAVE_LIBCRYPTSETUP
1776 static int decrypted_image_new(DecryptedImage
**ret
) {
1777 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1781 d
= new(DecryptedImage
, 1);
1785 *d
= (DecryptedImage
) {
1793 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1794 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1797 assert(original_node
);
1802 base
= strrchr(original_node
, '/');
1804 base
= original_node
;
1810 name
= strjoin(base
, suffix
);
1813 if (!filename_is_valid(name
))
1816 node
= path_join(sym_crypt_get_dir(), name
);
1820 *ret_name
= TAKE_PTR(name
);
1821 *ret_node
= TAKE_PTR(node
);
1826 static int decrypt_partition(
1827 DissectedPartition
*m
,
1828 const char *passphrase
,
1829 DissectImageFlags flags
,
1830 DecryptedImage
*d
) {
1832 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1833 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1834 _cleanup_close_
int fd
= -1;
1840 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1843 if (!streq(m
->fstype
, "crypto_LUKS"))
1849 r
= dlopen_cryptsetup();
1853 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1857 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
1860 r
= sym_crypt_init(&cd
, m
->node
);
1862 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1864 cryptsetup_enable_logging(cd
);
1866 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
1868 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1870 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1871 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1872 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1874 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1875 return r
== -EPERM
? -EKEYREJECTED
: r
;
1878 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
1880 return log_debug_errno(errno
, "Failed to open %s: %m", node
);
1882 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
1883 .name
= TAKE_PTR(name
),
1884 .device
= TAKE_PTR(cd
),
1887 m
->decrypted_node
= TAKE_PTR(node
);
1888 close_and_replace(m
->mount_node_fd
, fd
);
1893 static int verity_can_reuse(
1894 const VeritySettings
*verity
,
1896 struct crypt_device
**ret_cd
) {
1898 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1899 _cleanup_free_
char *root_hash_existing
= NULL
;
1900 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1901 struct crypt_params_verity crypt_params
= {};
1902 size_t root_hash_existing_size
;
1909 r
= sym_crypt_init_by_name(&cd
, name
);
1911 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1913 cryptsetup_enable_logging(cd
);
1915 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
1917 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1919 root_hash_existing_size
= verity
->root_hash_size
;
1920 root_hash_existing
= malloc0(root_hash_existing_size
);
1921 if (!root_hash_existing
)
1924 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1926 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1927 if (verity
->root_hash_size
!= root_hash_existing_size
||
1928 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
1929 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1931 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1932 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1933 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1934 * signing for the new one, and vice versa. */
1935 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1936 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1939 *ret_cd
= TAKE_PTR(cd
);
1943 static inline char* dm_deferred_remove_clean(char *name
) {
1947 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1950 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1952 static int validate_signature_userspace(const VeritySettings
*verity
) {
1954 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
1955 _cleanup_strv_free_
char **certs
= NULL
;
1956 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
1957 _cleanup_free_
char *s
= NULL
;
1958 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
1959 * of declaration in place, please */
1960 const unsigned char *d
;
1964 assert(verity
->root_hash
);
1965 assert(verity
->root_hash_sig
);
1967 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
1968 * userspace validation. */
1970 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
1972 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
1973 if (strv_isempty(certs
)) {
1974 log_debug("No userspace dm-verity certificates found.");
1978 d
= verity
->root_hash_sig
;
1979 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
1981 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
1983 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
1985 return log_oom_debug();
1987 bio
= BIO_new_mem_buf(s
, strlen(s
));
1989 return log_oom_debug();
1991 sk
= sk_X509_new_null();
1993 return log_oom_debug();
1995 STRV_FOREACH(i
, certs
) {
1996 _cleanup_(X509_freep
) X509
*c
= NULL
;
1997 _cleanup_fclose_
FILE *f
= NULL
;
1999 f
= fopen(*i
, "re");
2001 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
2005 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
2007 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
2011 if (sk_X509_push(sk
, c
) == 0)
2012 return log_oom_debug();
2017 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
2019 log_debug("Userspace PKCS#7 validation succeeded.");
2021 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
2025 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2030 static int do_crypt_activate_verity(
2031 struct crypt_device
*cd
,
2033 const VeritySettings
*verity
) {
2035 bool check_signature
;
2042 if (verity
->root_hash_sig
) {
2043 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2044 if (r
< 0 && r
!= -ENXIO
)
2045 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2047 check_signature
= r
!= 0;
2049 check_signature
= false;
2051 if (check_signature
) {
2053 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2054 /* First, if we have support for signed keys in the kernel, then try that first. */
2055 r
= sym_crypt_activate_by_signed_key(
2059 verity
->root_hash_size
,
2060 verity
->root_hash_sig
,
2061 verity
->root_hash_sig_size
,
2062 CRYPT_ACTIVATE_READONLY
);
2066 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
2068 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.",
2069 program_invocation_short_name
);
2072 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2073 * works we'll try to activate without telling the kernel the signature. */
2075 r
= validate_signature_userspace(verity
);
2079 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY
),
2080 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2083 return sym_crypt_activate_by_volume_key(
2087 verity
->root_hash_size
,
2088 CRYPT_ACTIVATE_READONLY
);
2091 static usec_t
verity_timeout(void) {
2092 usec_t t
= 100 * USEC_PER_MSEC
;
2096 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2097 * Let's make the timeout configurable. */
2099 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2103 r
= parse_sec(e
, &t
);
2106 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2107 "using the default timeout (%s).",
2108 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
2113 static int verity_partition(
2114 PartitionDesignator designator
,
2115 DissectedPartition
*m
,
2116 DissectedPartition
*v
,
2117 const VeritySettings
*verity
,
2118 DissectImageFlags flags
,
2119 DecryptedImage
*d
) {
2121 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2122 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2123 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2124 _cleanup_close_
int mount_node_fd
= -1;
2128 assert(v
|| (verity
&& verity
->data_path
));
2130 if (!verity
|| !verity
->root_hash
)
2132 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2133 (verity
->designator
== designator
)))
2136 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2138 if (!verity
->data_path
) {
2139 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2142 if (!streq(v
->fstype
, "DM_verity_hash"))
2146 r
= dlopen_cryptsetup();
2150 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2151 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2152 _cleanup_free_
char *root_hash_encoded
= NULL
;
2154 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2155 if (!root_hash_encoded
)
2158 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2160 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2164 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2168 cryptsetup_enable_logging(cd
);
2170 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2174 r
= sym_crypt_set_data_device(cd
, m
->node
);
2178 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2181 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2182 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2183 * retry a few times before giving up. */
2184 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2185 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2186 _cleanup_close_
int fd
= -1;
2188 /* First, check if the device already exists. */
2189 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2190 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2191 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2193 goto check
; /* The device already exists. Let's check it. */
2195 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2196 r
= do_crypt_activate_verity(cd
, name
, verity
);
2198 goto try_open
; /* The device is activated. Let's open it. */
2199 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2200 * There's no way to distinguish this situation from a genuine error due to invalid
2201 * parameters, so immediately fall back to activating the device with a unique name.
2202 * Improvements in libcrypsetup can ensure this never happens:
2203 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2204 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2206 if (r
== -ENODEV
) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2209 -EEXIST
, /* Volume has already been opened and ready to be used. */
2210 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2211 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2214 if (!restore_deferred_remove
){
2215 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2216 r
= dm_deferred_remove_cancel(name
);
2217 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2218 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2219 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2220 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2223 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2225 restore_deferred_remove
= strdup(name
);
2226 if (!restore_deferred_remove
)
2227 return log_oom_debug();
2230 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2231 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2232 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2235 -ENOENT
, /* Removed?? */
2236 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2237 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2240 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2243 /* devmapper might say that the device exists, but the devlink might not yet have been
2244 * created. Check and wait for the udev event in that case. */
2245 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2246 /* Fallback to activation with a unique device if it's taking too long */
2247 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2250 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2255 /* Now, the device is activated and devlink is created. Let's open it. */
2256 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2258 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
2259 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2261 /* The device has already been removed?? */
2266 mount_node_fd
= TAKE_FD(fd
);
2268 crypt_free_and_replace(cd
, existing_cd
);
2273 /* Device is being removed by another process. Let's wait for a while. */
2274 (void) usleep(2 * USEC_PER_MSEC
);
2277 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2278 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2279 /* Before trying to activate with unique name, we need to free crypt_device object.
2280 * Otherwise, we get error from libcryptsetup like the following:
2282 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2287 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2290 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2293 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2294 restore_deferred_remove
= mfree(restore_deferred_remove
);
2296 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2297 .name
= TAKE_PTR(name
),
2298 .device
= TAKE_PTR(cd
),
2301 m
->decrypted_node
= TAKE_PTR(node
);
2302 close_and_replace(m
->mount_node_fd
, mount_node_fd
);
2308 int dissected_image_decrypt(
2310 const char *passphrase
,
2311 const VeritySettings
*verity
,
2312 DissectImageFlags flags
) {
2314 #if HAVE_LIBCRYPTSETUP
2315 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2320 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
2324 * = 0 → There was nothing to decrypt
2325 * > 0 → Decrypted successfully
2326 * -ENOKEY → There's something to decrypt but no key was supplied
2327 * -EKEYREJECTED → Passed key was not correct
2330 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
2333 if (!m
->encrypted
&& !m
->verity_ready
)
2336 #if HAVE_LIBCRYPTSETUP
2337 r
= decrypted_image_new(&d
);
2341 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
2342 DissectedPartition
*p
= m
->partitions
+ i
;
2343 PartitionDesignator k
;
2348 r
= decrypt_partition(p
, passphrase
, flags
, d
);
2352 k
= PARTITION_VERITY_OF(i
);
2354 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
2359 if (!p
->decrypted_fstype
&& p
->mount_node_fd
>= 0 && p
->decrypted_node
) {
2360 r
= probe_filesystem_full(p
->mount_node_fd
, p
->decrypted_node
, &p
->decrypted_fstype
);
2361 if (r
< 0 && r
!= -EUCLEAN
)
2366 m
->decrypted_image
= TAKE_PTR(d
);
2374 int dissected_image_decrypt_interactively(
2376 const char *passphrase
,
2377 const VeritySettings
*verity
,
2378 DissectImageFlags flags
) {
2380 _cleanup_strv_free_erase_
char **z
= NULL
;
2387 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
2390 if (r
== -EKEYREJECTED
)
2391 log_error_errno(r
, "Incorrect passphrase, try again!");
2392 else if (r
!= -ENOKEY
)
2393 return log_error_errno(r
, "Failed to decrypt image: %m");
2396 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
2397 "Too many retries.");
2401 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY
, 0, &z
);
2403 return log_error_errno(r
, "Failed to query for passphrase: %m");
2409 static int decrypted_image_relinquish(DecryptedImage
*d
) {
2412 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2413 * boolean so that we don't clean it up ourselves either anymore */
2415 #if HAVE_LIBCRYPTSETUP
2418 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2419 DecryptedPartition
*p
= d
->decrypted
+ i
;
2421 if (p
->relinquished
)
2424 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2426 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
2428 p
->relinquished
= true;
2435 int dissected_image_relinquish(DissectedImage
*m
) {
2440 if (m
->decrypted_image
) {
2441 r
= decrypted_image_relinquish(m
->decrypted_image
);
2447 loop_device_relinquish(m
->loop
);
2452 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
2459 e
= endswith(image
, ".raw");
2461 return strjoin(e
, suffix
);
2463 n
= new(char, e
- image
+ strlen(suffix
) + 1);
2467 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
2471 void verity_settings_done(VeritySettings
*v
) {
2474 v
->root_hash
= mfree(v
->root_hash
);
2475 v
->root_hash_size
= 0;
2477 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
2478 v
->root_hash_sig_size
= 0;
2480 v
->data_path
= mfree(v
->data_path
);
2483 int verity_settings_load(
2484 VeritySettings
*verity
,
2486 const char *root_hash_path
,
2487 const char *root_hash_sig_path
) {
2489 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2490 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
2491 _cleanup_free_
char *verity_data_path
= NULL
;
2492 PartitionDesignator designator
;
2497 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
2499 /* If we are asked to load the root hash for a device node, exit early */
2500 if (is_device_path(image
))
2503 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2504 if (r
< 0 && r
!= -ENXIO
)
2505 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2509 designator
= verity
->designator
;
2511 /* We only fill in what isn't already filled in */
2513 if (!verity
->root_hash
) {
2514 _cleanup_free_
char *text
= NULL
;
2516 if (root_hash_path
) {
2517 /* If explicitly specified it takes precedence */
2518 r
= read_one_line_file(root_hash_path
, &text
);
2523 designator
= PARTITION_ROOT
;
2525 /* Otherwise look for xattr and separate file, and first for the data for root and if
2526 * that doesn't exist for /usr */
2528 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2529 r
= getxattr_malloc(image
, "user.verity.roothash", &text
);
2531 _cleanup_free_
char *p
= NULL
;
2533 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2536 p
= build_auxiliary_path(image
, ".roothash");
2540 r
= read_one_line_file(p
, &text
);
2541 if (r
< 0 && r
!= -ENOENT
)
2546 designator
= PARTITION_ROOT
;
2549 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2550 /* So in the "roothash" xattr/file name above the "root" of course primarily
2551 * refers to the root of the Verity Merkle tree. But coincidentally it also
2552 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2553 * two distinct concepts called "root". Taking benefit of this happy
2554 * coincidence we call the file with the root hash for the /usr/ file system
2555 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2556 * confusing. We thus drop the reference to the root of the Merkle tree, and
2557 * just indicate which file system it's about. */
2558 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
);
2560 _cleanup_free_
char *p
= NULL
;
2562 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2565 p
= build_auxiliary_path(image
, ".usrhash");
2569 r
= read_one_line_file(p
, &text
);
2570 if (r
< 0 && r
!= -ENOENT
)
2575 designator
= PARTITION_USR
;
2580 r
= unhexmem(text
, strlen(text
), &root_hash
, &root_hash_size
);
2583 if (root_hash_size
< sizeof(sd_id128_t
))
2588 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
2589 if (root_hash_sig_path
) {
2590 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2591 if (r
< 0 && r
!= -ENOENT
)
2595 designator
= PARTITION_ROOT
;
2597 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2598 _cleanup_free_
char *p
= NULL
;
2600 /* Follow naming convention recommended by the relevant RFC:
2601 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2602 p
= build_auxiliary_path(image
, ".roothash.p7s");
2606 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2607 if (r
< 0 && r
!= -ENOENT
)
2610 designator
= PARTITION_ROOT
;
2613 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2614 _cleanup_free_
char *p
= NULL
;
2616 p
= build_auxiliary_path(image
, ".usrhash.p7s");
2620 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2621 if (r
< 0 && r
!= -ENOENT
)
2624 designator
= PARTITION_USR
;
2628 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
2632 if (!verity
->data_path
) {
2633 _cleanup_free_
char *p
= NULL
;
2635 p
= build_auxiliary_path(image
, ".verity");
2639 if (access(p
, F_OK
) < 0) {
2640 if (errno
!= ENOENT
)
2643 verity_data_path
= TAKE_PTR(p
);
2647 verity
->root_hash
= TAKE_PTR(root_hash
);
2648 verity
->root_hash_size
= root_hash_size
;
2651 if (root_hash_sig
) {
2652 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
2653 verity
->root_hash_sig_size
= root_hash_sig_size
;
2656 if (verity_data_path
)
2657 verity
->data_path
= TAKE_PTR(verity_data_path
);
2659 if (verity
->designator
< 0)
2660 verity
->designator
= designator
;
2665 int dissected_image_load_verity_sig_partition(
2668 VeritySettings
*verity
) {
2670 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2671 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
2672 size_t root_hash_size
, root_hash_sig_size
;
2673 _cleanup_free_
char *buf
= NULL
;
2674 PartitionDesignator d
;
2675 DissectedPartition
*p
;
2676 JsonVariant
*rh
, *sig
;
2685 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
2688 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2689 if (r
< 0 && r
!= -ENXIO
)
2690 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2694 d
= PARTITION_VERITY_SIG_OF(verity
->designator
< 0 ? PARTITION_ROOT
: verity
->designator
);
2697 p
= m
->partitions
+ d
;
2700 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
2703 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2706 buf
= new(char, p
->size
+1);
2710 n
= pread(fd
, buf
, p
->size
, p
->offset
);
2713 if ((uint64_t) n
!= p
->size
)
2716 e
= memchr(buf
, 0, p
->size
);
2718 /* If we found a NUL byte then the rest of the data must be NUL too */
2719 if (!memeqzero(e
, p
->size
- (e
- buf
)))
2720 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
2724 r
= json_parse(buf
, 0, &v
, NULL
, NULL
);
2726 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
2728 rh
= json_variant_by_key(v
, "rootHash");
2730 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
2731 if (!json_variant_is_string(rh
))
2732 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'rootHash' field of signature JSON object is not a string.");
2734 r
= unhexmem(json_variant_string(rh
), SIZE_MAX
, &root_hash
, &root_hash_size
);
2736 return log_debug_errno(r
, "Failed to parse root hash field: %m");
2738 /* Check if specified root hash matches if it is specified */
2739 if (verity
->root_hash
&&
2740 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
2741 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
2743 a
= hexmem(root_hash
, root_hash_size
);
2744 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2746 return log_debug_errno(r
, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
2749 sig
= json_variant_by_key(v
, "signature");
2751 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
2752 if (!json_variant_is_string(sig
))
2753 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'signature' field of signature JSON object is not a string.");
2755 r
= unbase64mem(json_variant_string(sig
), SIZE_MAX
, &root_hash_sig
, &root_hash_sig_size
);
2757 return log_debug_errno(r
, "Failed to parse signature field: %m");
2759 free_and_replace(verity
->root_hash
, root_hash
);
2760 verity
->root_hash_size
= root_hash_size
;
2762 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
2763 verity
->root_hash_sig_size
= root_hash_sig_size
;
2768 int dissected_image_acquire_metadata(DissectedImage
*m
, DissectImageFlags extra_flags
) {
2775 META_INITRD_RELEASE
,
2776 META_EXTENSION_RELEASE
,
2777 META_HAS_INIT_SYSTEM
,
2781 static const char *const paths
[_META_MAX
] = {
2782 [META_HOSTNAME
] = "/etc/hostname\0",
2783 [META_MACHINE_ID
] = "/etc/machine-id\0",
2784 [META_MACHINE_INFO
] = "/etc/machine-info\0",
2785 [META_OS_RELEASE
] = ("/etc/os-release\0"
2786 "/usr/lib/os-release\0"),
2787 [META_INITRD_RELEASE
] = ("/etc/initrd-release\0"
2788 "/usr/lib/initrd-release\0"),
2789 [META_EXTENSION_RELEASE
] = "extension-release\0", /* Used only for logging. */
2790 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
2793 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **initrd_release
= NULL
, **extension_release
= NULL
;
2794 _cleanup_close_pair_
int error_pipe
[2] = { -1, -1 };
2795 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
2796 _cleanup_(sigkill_waitp
) pid_t child
= 0;
2797 sd_id128_t machine_id
= SD_ID128_NULL
;
2798 _cleanup_free_
char *hostname
= NULL
;
2799 unsigned n_meta_initialized
= 0;
2800 int fds
[2 * _META_MAX
], r
, v
;
2801 int has_init_system
= -1;
2804 BLOCK_SIGNALS(SIGCHLD
);
2808 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
2809 if (!paths
[n_meta_initialized
]) {
2810 fds
[2*n_meta_initialized
] = fds
[2*n_meta_initialized
+1] = -1;
2814 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
2820 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
2824 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
2829 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
2833 /* Child in a new mount namespace */
2834 error_pipe
[0] = safe_close(error_pipe
[0]);
2836 r
= dissected_image_mount(
2842 DISSECT_IMAGE_READ_ONLY
|
2843 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
2844 DISSECT_IMAGE_USR_NO_ROOT
);
2846 log_debug_errno(r
, "Failed to mount dissected image: %m");
2850 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2851 _cleanup_close_
int fd
= -ENOENT
;
2857 fds
[2*k
] = safe_close(fds
[2*k
]);
2861 case META_EXTENSION_RELEASE
:
2862 /* As per the os-release spec, if the image is an extension it will have a file
2863 * named after the image name in extension-release.d/ - we use the image name
2864 * and try to resolve it with the extension-release helpers, as sometimes
2865 * the image names are mangled on deployment and do not match anymore.
2866 * Unlike other paths this is not fixed, and the image name
2867 * can be mangled on deployment, so by calling into the helper
2868 * we allow a fallback that matches on the first extension-release
2869 * file found in the directory, if one named after the image cannot
2870 * be found first. */
2871 r
= open_extension_release(t
, m
->image_name
, /* relax_extension_release_check= */ false, NULL
, &fd
);
2873 fd
= r
; /* Propagate the error. */
2876 case META_HAS_INIT_SYSTEM
: {
2879 FOREACH_STRING(init
,
2880 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
2881 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
2882 "/sbin/init") { /* traditional path the Linux kernel invokes */
2884 r
= chase_symlinks(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
2887 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
2894 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
), false);
2902 NULSTR_FOREACH(p
, paths
[k
]) {
2903 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
2910 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
2911 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2915 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
2919 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2922 _exit(EXIT_SUCCESS
);
2925 /* Let parent know the error */
2926 (void) write(error_pipe
[1], &r
, sizeof(r
));
2927 _exit(EXIT_FAILURE
);
2930 error_pipe
[1] = safe_close(error_pipe
[1]);
2932 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2933 _cleanup_fclose_
FILE *f
= NULL
;
2938 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2940 f
= take_fdopen(&fds
[2*k
], "r");
2949 r
= read_etc_hostname_stream(f
, &hostname
);
2951 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
2955 case META_MACHINE_ID
: {
2956 _cleanup_free_
char *line
= NULL
;
2958 r
= read_line(f
, LONG_LINE_MAX
, &line
);
2960 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
2962 r
= sd_id128_from_string(line
, &machine_id
);
2964 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
2966 log_debug("/etc/machine-id file of image is empty.");
2967 else if (streq(line
, "uninitialized"))
2968 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
2970 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
2975 case META_MACHINE_INFO
:
2976 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
2978 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
2982 case META_OS_RELEASE
:
2983 r
= load_env_file_pairs(f
, "os-release", &os_release
);
2985 log_debug_errno(r
, "Failed to read OS release file of image: %m");
2989 case META_INITRD_RELEASE
:
2990 r
= load_env_file_pairs(f
, "initrd-release", &initrd_release
);
2992 log_debug_errno(r
, "Failed to read initrd release file of image: %m");
2996 case META_EXTENSION_RELEASE
:
2997 r
= load_env_file_pairs(f
, "extension-release", &extension_release
);
2999 log_debug_errno(r
, "Failed to read extension release file of image: %m");
3003 case META_HAS_INIT_SYSTEM
: {
3008 nr
= fread(&b
, 1, sizeof(b
), f
);
3009 if (nr
!= sizeof(b
))
3010 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
3012 has_init_system
= b
;
3018 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
3023 n
= read(error_pipe
[0], &v
, sizeof(v
));
3027 return v
; /* propagate error sent to us from child */
3031 if (r
!= EXIT_SUCCESS
)
3034 free_and_replace(m
->hostname
, hostname
);
3035 m
->machine_id
= machine_id
;
3036 strv_free_and_replace(m
->machine_info
, machine_info
);
3037 strv_free_and_replace(m
->os_release
, os_release
);
3038 strv_free_and_replace(m
->initrd_release
, initrd_release
);
3039 strv_free_and_replace(m
->extension_release
, extension_release
);
3040 m
->has_init_system
= has_init_system
;
3043 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
3044 safe_close_pair(fds
+ 2*k
);
3049 int dissect_loop_device(
3051 const VeritySettings
*verity
,
3052 const MountOptions
*mount_options
,
3053 DissectImageFlags flags
,
3054 DissectedImage
**ret
) {
3057 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
3063 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
3067 m
->loop
= loop_device_ref(loop
);
3069 r
= dissect_image(m
, loop
->fd
, loop
->node
, verity
, mount_options
, flags
| DISSECT_IMAGE_BLOCK_DEVICE
);
3073 r
= dissected_image_probe_filesystem(m
);
3084 int dissect_loop_device_and_warn(
3086 const VeritySettings
*verity
,
3087 const MountOptions
*mount_options
,
3088 DissectImageFlags flags
,
3089 DissectedImage
**ret
) {
3095 assert(loop
->fd
>= 0);
3097 name
= ASSERT_PTR(loop
->backing_file
?: loop
->node
);
3099 r
= dissect_loop_device(loop
, verity
, mount_options
, flags
, ret
);
3103 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
3106 return log_error_errno(r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
3109 return log_error_errno(r
, "%s: The image does not pass validation.", name
);
3111 case -EADDRNOTAVAIL
:
3112 return log_error_errno(r
, "%s: No root partition for specified root hash found.", name
);
3115 return log_error_errno(r
, "%s: Multiple suitable root partitions found in image.", name
);
3118 return log_error_errno(r
, "%s: No suitable root partition found in image.", name
);
3120 case -EPROTONOSUPPORT
:
3121 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
3124 return log_error_errno(r
, "%s: Image is not a block device.", name
);
3127 return log_error_errno(r
,
3128 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
3129 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
3130 name
, strna(verity
? verity
->data_path
: NULL
));
3134 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
3140 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3143 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3144 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3145 * images we only check the partition type.
3147 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3150 if (image
->single_file_system
)
3151 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
3153 return PARTITION_VERITY_OF(partition_designator
) >= 0;
3156 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3157 PartitionDesignator k
;
3161 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3162 * works for the root partition, for others only if the associated verity partition was found. */
3164 if (!image
->verity_ready
)
3167 if (image
->single_file_system
)
3168 return partition_designator
== PARTITION_ROOT
;
3170 k
= PARTITION_VERITY_OF(partition_designator
);
3171 return k
>= 0 && image
->partitions
[k
].found
;
3174 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3175 PartitionDesignator k
;
3179 /* Checks if this partition has verity signature data available that we can use. */
3181 if (!image
->verity_sig_ready
)
3184 if (image
->single_file_system
)
3185 return partition_designator
== PARTITION_ROOT
;
3187 k
= PARTITION_VERITY_SIG_OF(partition_designator
);
3188 return k
>= 0 && image
->partitions
[k
].found
;
3191 MountOptions
* mount_options_free_all(MountOptions
*options
) {
3194 while ((m
= options
)) {
3195 LIST_REMOVE(mount_options
, options
, m
);
3203 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
3204 LIST_FOREACH(mount_options
, m
, options
)
3205 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
3211 int mount_image_privately_interactively(
3213 DissectImageFlags flags
,
3214 char **ret_directory
,
3215 LoopDevice
**ret_loop_device
) {
3217 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3218 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3219 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3220 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
3221 _cleanup_free_
char *temp
= NULL
;
3224 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3225 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3229 assert(ret_directory
);
3230 assert(ret_loop_device
);
3232 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
3234 return log_error_errno(r
, "Failed to load root hash data: %m");
3236 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
3238 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
3240 r
= loop_device_make_by_path(
3242 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
3243 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
3247 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
3249 r
= dissect_loop_device_and_warn(d
, &verity
, NULL
, flags
, &dissected_image
);
3253 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
3257 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
3261 r
= detach_mount_namespace();
3263 return log_error_errno(r
, "Failed to detach mount namespace: %m");
3265 r
= mkdir_p(temp
, 0700);
3267 return log_error_errno(r
, "Failed to create mount point: %m");
3269 created_dir
= TAKE_PTR(temp
);
3271 r
= dissected_image_mount_and_warn(dissected_image
, created_dir
, UID_INVALID
, UID_INVALID
, flags
);
3275 r
= loop_device_flock(d
, LOCK_UN
);
3279 r
= dissected_image_relinquish(dissected_image
);
3281 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
3283 *ret_directory
= TAKE_PTR(created_dir
);
3284 *ret_loop_device
= TAKE_PTR(d
);
3289 static const char *const partition_designator_table
[] = {
3290 [PARTITION_ROOT
] = "root",
3291 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
3292 [PARTITION_ROOT_OTHER
] = "root-other",
3293 [PARTITION_USR
] = "usr",
3294 [PARTITION_USR_SECONDARY
] = "usr-secondary",
3295 [PARTITION_USR_OTHER
] = "usr-other",
3296 [PARTITION_HOME
] = "home",
3297 [PARTITION_SRV
] = "srv",
3298 [PARTITION_ESP
] = "esp",
3299 [PARTITION_XBOOTLDR
] = "xbootldr",
3300 [PARTITION_SWAP
] = "swap",
3301 [PARTITION_ROOT_VERITY
] = "root-verity",
3302 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
3303 [PARTITION_ROOT_OTHER_VERITY
] = "root-other-verity",
3304 [PARTITION_USR_VERITY
] = "usr-verity",
3305 [PARTITION_USR_SECONDARY_VERITY
] = "usr-secondary-verity",
3306 [PARTITION_USR_OTHER_VERITY
] = "usr-other-verity",
3307 [PARTITION_ROOT_VERITY_SIG
] = "root-verity-sig",
3308 [PARTITION_ROOT_SECONDARY_VERITY_SIG
] = "root-secondary-verity-sig",
3309 [PARTITION_ROOT_OTHER_VERITY_SIG
] = "root-other-verity-sig",
3310 [PARTITION_USR_VERITY_SIG
] = "usr-verity-sig",
3311 [PARTITION_USR_SECONDARY_VERITY_SIG
] = "usr-secondary-verity-sig",
3312 [PARTITION_USR_OTHER_VERITY_SIG
] = "usr-other-verity-sig",
3313 [PARTITION_TMP
] = "tmp",
3314 [PARTITION_VAR
] = "var",
3317 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
3321 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
3322 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
3323 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
3326 int verity_dissect_and_mount(
3330 const MountOptions
*options
,
3331 const char *required_host_os_release_id
,
3332 const char *required_host_os_release_version_id
,
3333 const char *required_host_os_release_sysext_level
,
3334 const char *required_sysext_scope
) {
3336 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
3337 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3338 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3339 DissectImageFlags dissect_image_flags
;
3340 bool relax_extension_release_check
;
3346 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
3348 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3349 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
3351 return log_debug_errno(r
, "Failed to load root hash: %m");
3353 dissect_image_flags
= (verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
3354 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_SYSEXT_CHECK
: 0);
3356 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3357 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
3358 r
= loop_device_make_by_path(
3359 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
3361 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
3365 return log_debug_errno(r
, "Failed to create loop device for image: %m");
3367 r
= dissect_loop_device(
3371 dissect_image_flags
,
3373 /* No partition table? Might be a single-filesystem image, try again */
3374 if (!verity
.data_path
&& r
== -ENOPKG
)
3375 r
= dissect_loop_device(
3379 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
3382 return log_debug_errno(r
, "Failed to dissect image: %m");
3384 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, &verity
);
3388 r
= dissected_image_decrypt(
3392 dissect_image_flags
);
3394 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
3396 r
= mkdir_p_label(dest
, 0755);
3398 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
3399 r
= umount_recursive(dest
, 0);
3401 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
3403 r
= dissected_image_mount(dissected_image
, dest
, UID_INVALID
, UID_INVALID
, dissect_image_flags
);
3405 return log_debug_errno(r
, "Failed to mount image: %m");
3407 r
= loop_device_flock(loop_device
, LOCK_UN
);
3409 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
3411 /* If we got os-release values from the caller, then we need to match them with the image's
3412 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3413 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3414 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3415 * then a simple match on the ID will be performed. */
3416 if (required_host_os_release_id
) {
3417 _cleanup_strv_free_
char **extension_release
= NULL
;
3419 assert(!isempty(required_host_os_release_id
));
3421 r
= load_extension_release_pairs(dest
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
3423 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
3425 r
= extension_release_validate(
3426 dissected_image
->image_name
,
3427 required_host_os_release_id
,
3428 required_host_os_release_version_id
,
3429 required_host_os_release_sysext_level
,
3430 required_sysext_scope
,
3433 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
3435 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
3438 r
= dissected_image_relinquish(dissected_image
);
3440 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
3445 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, PartitionDesignator
);