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"
31 #include "cryptsetup-util.h"
33 #include "device-nodes.h"
34 #include "device-util.h"
35 #include "discover-image.h"
36 #include "dissect-image.h"
40 #include "extension-release.h"
44 #include "fsck-util.h"
46 #include "hexdecoct.h"
47 #include "hostname-setup.h"
48 #include "id128-util.h"
49 #include "import-util.h"
51 #include "mkdir-label.h"
52 #include "mount-util.h"
53 #include "mountpoint-util.h"
54 #include "namespace-util.h"
55 #include "nulstr-util.h"
56 #include "openssl-util.h"
58 #include "path-util.h"
59 #include "process-util.h"
60 #include "raw-clone.h"
61 #include "resize-fs.h"
62 #include "signal-util.h"
63 #include "stat-util.h"
64 #include "stdio-util.h"
65 #include "string-table.h"
66 #include "string-util.h"
68 #include "tmpfile-util.h"
69 #include "udev-util.h"
70 #include "user-util.h"
71 #include "xattr-util.h"
73 /* how many times to wait for the device nodes to appear */
74 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
76 int probe_filesystem(const char *node
, char **ret_fstype
) {
77 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
78 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
79 * different error otherwise. */
82 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
87 b
= blkid_new_probe_from_filename(node
);
89 return errno_or_else(ENOMEM
);
91 blkid_probe_enable_superblocks(b
, 1);
92 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
95 r
= blkid_do_safeprobe(b
);
99 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
100 "Results ambiguous for partition %s", node
);
102 return log_debug_errno(errno_or_else(EIO
), "Failed to probe partition %s: %m", node
);
104 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
109 log_debug("Probed fstype '%s' on partition %s.", fstype
, node
);
120 log_debug("No type detected on partition %s", node
);
129 static int dissected_image_probe_filesystem(DissectedImage
*m
) {
134 /* Fill in file system types if we don't know them yet. */
136 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
137 DissectedPartition
*p
= m
->partitions
+ i
;
142 if (!p
->fstype
&& p
->node
) {
143 r
= probe_filesystem(p
->node
, &p
->fstype
);
144 if (r
< 0 && r
!= -EUCLEAN
)
148 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
151 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
161 static void check_partition_flags(
163 unsigned long long pflags
,
164 unsigned long long supported
) {
168 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
169 pflags
&= ~(supported
|
170 SD_GPT_FLAG_REQUIRED_PARTITION
|
171 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
|
172 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
177 /* If there are other bits set, then log about it, to make things discoverable */
178 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
179 unsigned long long bit
= 1ULL << i
;
180 if (!FLAGS_SET(pflags
, bit
))
183 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
189 static int dissected_image_new(const char *path
, DissectedImage
**ret
) {
190 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
191 _cleanup_free_
char *name
= NULL
;
197 _cleanup_free_
char *filename
= NULL
;
199 r
= path_extract_filename(path
, &filename
);
203 r
= raw_strip_suffixes(filename
, &name
);
207 if (!image_name_is_valid(name
)) {
208 log_debug("Image name %s is not valid, ignoring.", strna(name
));
213 m
= new(DissectedImage
, 1);
217 *m
= (DissectedImage
) {
218 .has_init_system
= -1,
219 .image_name
= TAKE_PTR(name
),
222 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
223 m
->partitions
[i
] = DISSECTED_PARTITION_NULL
;
230 static void dissected_partition_done(DissectedPartition
*p
) {
236 free(p
->decrypted_fstype
);
237 free(p
->decrypted_node
);
238 free(p
->mount_options
);
240 *p
= DISSECTED_PARTITION_NULL
;
244 static int make_partition_devname(
245 const char *whole_devname
,
251 assert(whole_devname
);
254 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition device
255 * name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole block device
256 * node name ends in a digit, then suffix a 'p', followed by the partition number. Otherwise, just
257 * suffix the partition number without any 'p'. */
259 if (isempty(whole_devname
)) /* Make sure there *is* a last char */
262 need_p
= ascii_isdigit(whole_devname
[strlen(whole_devname
)-1]); /* Last char a digit? */
264 return asprintf(ret
, "%s%s%i", whole_devname
, need_p
? "p" : "", nr
);
267 static int dissect_image(
271 const VeritySettings
*verity
,
272 const MountOptions
*mount_options
,
273 DissectImageFlags flags
) {
275 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
276 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
277 bool is_gpt
, is_mbr
, multiple_generic
= false,
278 generic_rw
= false, /* initialize to appease gcc */
279 generic_growfs
= false;
280 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
281 _cleanup_free_
char *generic_node
= NULL
;
282 sd_id128_t generic_uuid
= SD_ID128_NULL
;
283 const char *pttype
= NULL
;
285 int r
, generic_nr
= -1, n_partitions
;
290 assert(!verity
|| verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
291 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
292 assert(!verity
|| verity
->root_hash_sig
|| verity
->root_hash_sig_size
== 0);
293 assert(!verity
|| (verity
->root_hash
|| !verity
->root_hash_sig
));
294 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
296 /* Probes a disk image, and returns information about what it found in *ret.
298 * Returns -ENOPKG if no suitable partition table or file system could be found.
299 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
300 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
301 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that */
303 if (verity
&& verity
->root_hash
) {
304 sd_id128_t fsuuid
, vuuid
;
306 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
307 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
308 * the final 128bit. */
310 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
313 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
314 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
316 if (sd_id128_is_null(fsuuid
))
318 if (sd_id128_is_null(vuuid
))
321 /* If the verity data declares it's for the /usr partition, then search for that, in all
322 * other cases assume it's for the root partition. */
323 if (verity
->designator
== PARTITION_USR
) {
325 usr_verity_uuid
= vuuid
;
328 root_verity_uuid
= vuuid
;
332 b
= blkid_new_probe();
337 r
= blkid_probe_set_device(b
, fd
, 0, 0);
339 return errno_or_else(ENOMEM
);
341 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
342 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
343 blkid_probe_enable_superblocks(b
, 1);
344 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
347 blkid_probe_enable_partitions(b
, 1);
348 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
351 r
= blkid_do_safeprobe(b
);
352 if (IN_SET(r
, -2, 1))
353 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
355 return errno_or_else(EIO
);
357 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
358 (flags
& DISSECT_IMAGE_GENERIC_ROOT
)) ||
359 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
360 const char *usage
= NULL
;
362 /* If flags permit this, also allow using non-partitioned single-filesystem images */
364 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
365 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
366 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
367 const char *fstype
= NULL
, *options
= NULL
;
369 /* OK, we have found a file system, that's our root partition then. */
370 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
382 m
->single_file_system
= true;
383 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
385 m
->has_verity
= verity
&& verity
->data_path
;
386 m
->verity_ready
= m
->has_verity
&&
388 (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
);
390 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
391 m
->verity_sig_ready
= m
->verity_ready
&&
392 verity
->root_hash_sig
;
394 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
401 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
403 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
405 .architecture
= _ARCHITECTURE_INVALID
,
406 .fstype
= TAKE_PTR(t
),
408 .mount_options
= TAKE_PTR(o
),
417 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
421 is_gpt
= streq_ptr(pttype
, "gpt");
422 is_mbr
= streq_ptr(pttype
, "dos");
424 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
427 /* We support external verity data partitions only if the image has no partition table */
428 if (verity
&& verity
->data_path
)
431 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
432 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
433 * do partition scanning. */
434 r
= blockdev_partscan_enabled(fd
);
438 return -EPROTONOSUPPORT
;
442 pl
= blkid_probe_get_partitions(b
);
444 return errno_or_else(ENOMEM
);
447 n_partitions
= blkid_partlist_numof_partitions(pl
);
448 if (n_partitions
< 0)
449 return errno_or_else(EIO
);
451 for (int i
= 0; i
< n_partitions
; i
++) {
452 _cleanup_free_
char *node
= NULL
;
453 unsigned long long pflags
;
454 blkid_loff_t start
, size
;
459 pp
= blkid_partlist_get_partition(pl
, i
);
461 return errno_or_else(EIO
);
463 pflags
= blkid_partition_get_flags(pp
);
466 nr
= blkid_partition_get_partno(pp
);
468 return errno_or_else(EIO
);
471 start
= blkid_partition_get_start(pp
);
473 return errno_or_else(EIO
);
475 assert((uint64_t) start
< UINT64_MAX
/512);
478 size
= blkid_partition_get_size(pp
);
480 return errno_or_else(EIO
);
482 assert((uint64_t) size
< UINT64_MAX
/512);
484 r
= make_partition_devname(devname
, nr
, &node
);
488 /* So here's the thing: after the main ("whole") block device popped up it might take a while
489 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
490 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
491 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
492 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
493 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
494 * also good as the outcome is the same: the partition block device exists, and we can use
497 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
498 * partition already existent. */
500 if (FLAGS_SET(flags
, DISSECT_IMAGE_MANAGE_PARTITION_DEVICES
)) {
501 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
504 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
506 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
508 log_debug("We were quicker than kernel in adding partition %i.", nr
);
512 PartitionDesignator designator
= _PARTITION_DESIGNATOR_INVALID
;
513 Architecture architecture
= _ARCHITECTURE_INVALID
;
514 const char *stype
, *sid
, *fstype
= NULL
, *label
;
515 sd_id128_t type_id
, id
;
516 bool rw
= true, growfs
= false;
518 sid
= blkid_partition_get_uuid(pp
);
521 if (sd_id128_from_string(sid
, &id
) < 0)
524 stype
= blkid_partition_get_type_string(pp
);
527 if (sd_id128_from_string(stype
, &type_id
) < 0)
530 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
532 if (sd_id128_equal(type_id
, SD_GPT_HOME
)) {
534 check_partition_flags(node
, pflags
,
535 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
537 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
540 designator
= PARTITION_HOME
;
541 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
542 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
544 } else if (sd_id128_equal(type_id
, SD_GPT_SRV
)) {
546 check_partition_flags(node
, pflags
,
547 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
549 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
552 designator
= PARTITION_SRV
;
553 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
554 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
556 } else if (sd_id128_equal(type_id
, SD_GPT_ESP
)) {
558 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
559 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
560 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
563 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
566 designator
= PARTITION_ESP
;
569 } else if (sd_id128_equal(type_id
, SD_GPT_XBOOTLDR
)) {
571 check_partition_flags(node
, pflags
,
572 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
574 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
577 designator
= PARTITION_XBOOTLDR
;
578 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
579 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
581 } else if (gpt_partition_type_is_root(type_id
)) {
583 check_partition_flags(node
, pflags
,
584 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
586 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
589 /* If a root ID is specified, ignore everything but the root id */
590 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
593 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
594 designator
= PARTITION_ROOT_OF_ARCH(architecture
);
595 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
596 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
598 } else if (gpt_partition_type_is_root_verity(type_id
)) {
600 check_partition_flags(node
, pflags
,
601 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
603 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
606 m
->has_verity
= true;
608 /* If no verity configuration is specified, then don't do verity */
611 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
614 /* If root hash is specified, then ignore everything but the root id */
615 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
618 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
619 designator
= PARTITION_VERITY_OF(PARTITION_ROOT_OF_ARCH(architecture
));
620 fstype
= "DM_verity_hash";
623 } else if (gpt_partition_type_is_root_verity_sig(type_id
)) {
625 check_partition_flags(node
, pflags
,
626 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
628 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
631 m
->has_verity_sig
= true;
635 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
638 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
639 designator
= PARTITION_VERITY_SIG_OF(PARTITION_ROOT_OF_ARCH(architecture
));
640 fstype
= "verity_hash_signature";
643 } else if (gpt_partition_type_is_usr(type_id
)) {
645 check_partition_flags(node
, pflags
,
646 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
648 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
651 /* If a usr ID is specified, ignore everything but the usr id */
652 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
655 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
656 designator
= PARTITION_USR_OF_ARCH(architecture
);
657 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
658 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
660 } else if (gpt_partition_type_is_usr_verity(type_id
)) {
662 check_partition_flags(node
, pflags
,
663 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
665 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
668 m
->has_verity
= true;
672 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
675 /* If usr hash is specified, then ignore everything but the usr id */
676 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
679 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
680 designator
= PARTITION_VERITY_OF(PARTITION_USR_OF_ARCH(architecture
));
681 fstype
= "DM_verity_hash";
684 } else if (gpt_partition_type_is_usr_verity_sig(type_id
)) {
686 check_partition_flags(node
, pflags
,
687 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
689 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
692 m
->has_verity_sig
= true;
696 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
699 assert_se((architecture
= gpt_partition_type_uuid_to_arch(type_id
)) >= 0);
700 designator
= PARTITION_VERITY_SIG_OF(PARTITION_USR_OF_ARCH(architecture
));
701 fstype
= "verity_hash_signature";
704 } else if (sd_id128_equal(type_id
, SD_GPT_SWAP
)) {
706 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
708 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
711 designator
= PARTITION_SWAP
;
713 } else if (sd_id128_equal(type_id
, SD_GPT_LINUX_GENERIC
)) {
715 check_partition_flags(node
, pflags
,
716 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
718 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
722 multiple_generic
= true;
725 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
726 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
728 generic_node
= strdup(node
);
733 } else if (sd_id128_equal(type_id
, SD_GPT_TMP
)) {
735 check_partition_flags(node
, pflags
,
736 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
738 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
741 designator
= PARTITION_TMP
;
742 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
743 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
745 } else if (sd_id128_equal(type_id
, SD_GPT_VAR
)) {
747 check_partition_flags(node
, pflags
,
748 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
750 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
753 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
756 /* For /var we insist that the uuid of the partition matches the
757 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
758 * ID. Why? Unlike the other partitions /var is inherently
759 * installation specific, hence we need to be careful not to mount it
760 * in the wrong installation. By hashing the partition UUID from
761 * /etc/machine-id we can securely bind the partition to the
764 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
768 if (!sd_id128_equal(var_uuid
, id
)) {
769 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
774 designator
= PARTITION_VAR
;
775 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
776 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
779 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
780 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
;
781 const char *options
= NULL
;
783 if (m
->partitions
[designator
].found
) {
784 /* For most partition types the first one we see wins. Except for the
785 * rootfs and /usr, where we do a version compare of the label, and
786 * let the newest version win. This permits a simple A/B versioning
787 * scheme in OS images. */
789 if (!PARTITION_DESIGNATOR_VERSIONED(designator
) ||
790 strverscmp_improved(m
->partitions
[designator
].label
, label
) >= 0)
793 dissected_partition_done(m
->partitions
+ designator
);
808 options
= mount_options_from_designator(mount_options
, designator
);
815 m
->partitions
[designator
] = (DissectedPartition
) {
820 .architecture
= architecture
,
821 .node
= TAKE_PTR(node
),
822 .fstype
= TAKE_PTR(t
),
823 .label
= TAKE_PTR(l
),
825 .mount_options
= TAKE_PTR(o
),
826 .offset
= (uint64_t) start
* 512,
827 .size
= (uint64_t) size
* 512,
833 switch (blkid_partition_get_type(pp
)) {
835 case 0x83: /* Linux partition */
837 if (pflags
!= 0x80) /* Bootable flag */
841 multiple_generic
= true;
845 generic_growfs
= false;
846 generic_node
= strdup(node
);
853 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
854 _cleanup_free_
char *o
= NULL
;
855 sd_id128_t id
= SD_ID128_NULL
;
856 const char *sid
, *options
= NULL
;
859 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
862 sid
= blkid_partition_get_uuid(pp
);
864 (void) sd_id128_from_string(sid
, &id
);
866 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
873 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
878 .architecture
= _ARCHITECTURE_INVALID
,
879 .node
= TAKE_PTR(node
),
881 .mount_options
= TAKE_PTR(o
),
882 .offset
= (uint64_t) start
* 512,
883 .size
= (uint64_t) size
* 512,
891 if (m
->partitions
[PARTITION_ROOT
].found
) {
892 /* If we found the primary arch, then invalidate the secondary and other arch to avoid any
893 * ambiguities, since we never want to mount the secondary or other arch in this case. */
894 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
895 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
896 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
].found
= false;
897 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
898 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
899 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
= false;
901 m
->partitions
[PARTITION_ROOT_OTHER
].found
= false;
902 m
->partitions
[PARTITION_ROOT_OTHER_VERITY
].found
= false;
903 m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
].found
= false;
904 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
905 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
906 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
908 } else if (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
909 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
)
910 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
912 else if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
914 /* No root partition found but there's one for the secondary architecture? Then upgrade
915 * secondary arch to first and invalidate the other arch. */
917 log_debug("No root partition found of the native architecture, falling back to a root "
918 "partition of the secondary architecture.");
920 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
921 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
922 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
923 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
924 m
->partitions
[PARTITION_ROOT_VERITY_SIG
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
];
925 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
]);
927 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_SECONDARY
];
928 zero(m
->partitions
[PARTITION_USR_SECONDARY
]);
929 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY
];
930 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
931 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
];
932 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
]);
934 m
->partitions
[PARTITION_ROOT_OTHER
].found
= false;
935 m
->partitions
[PARTITION_ROOT_OTHER_VERITY
].found
= false;
936 m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
].found
= false;
937 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
938 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
939 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
941 } else if (m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
||
942 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY_SIG
].found
)
943 return -EADDRNOTAVAIL
; /* as above */
945 else if (m
->partitions
[PARTITION_ROOT_OTHER
].found
) {
947 /* No root or secondary partition found but there's one for another architecture? Then
948 * upgrade the other architecture to first. */
950 log_debug("No root partition found of the native architecture or the secondary architecture, "
951 "falling back to a root partition of a non-native architecture (%s).",
952 architecture_to_string(m
->partitions
[PARTITION_ROOT_OTHER
].architecture
));
954 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_OTHER
];
955 zero(m
->partitions
[PARTITION_ROOT_OTHER
]);
956 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_OTHER_VERITY
];
957 zero(m
->partitions
[PARTITION_ROOT_OTHER_VERITY
]);
958 m
->partitions
[PARTITION_ROOT_VERITY_SIG
] = m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
];
959 zero(m
->partitions
[PARTITION_ROOT_OTHER_VERITY_SIG
]);
961 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_OTHER
];
962 zero(m
->partitions
[PARTITION_USR_OTHER
]);
963 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_OTHER_VERITY
];
964 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY
]);
965 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
];
966 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
]);
969 /* Hmm, we found a signature partition but no Verity data? Something is off. */
970 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
971 return -EADDRNOTAVAIL
;
973 if (m
->partitions
[PARTITION_USR
].found
) {
974 /* Invalidate secondary and other arch /usr/ if we found the primary arch */
975 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
976 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
977 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
= false;
979 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
980 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
981 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
983 } else if (m
->partitions
[PARTITION_USR_VERITY
].found
||
984 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
)
985 return -EADDRNOTAVAIL
; /* as above */
987 else if (m
->partitions
[PARTITION_USR_SECONDARY
].found
) {
989 log_debug("No usr partition found of the native architecture, falling back to a usr "
990 "partition of the secondary architecture.");
992 /* Upgrade secondary arch to primary */
993 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_SECONDARY
];
994 zero(m
->partitions
[PARTITION_USR_SECONDARY
]);
995 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY
];
996 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
997 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
];
998 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
]);
1000 m
->partitions
[PARTITION_USR_OTHER
].found
= false;
1001 m
->partitions
[PARTITION_USR_OTHER_VERITY
].found
= false;
1002 m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
].found
= false;
1004 } else if (m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
||
1005 m
->partitions
[PARTITION_USR_SECONDARY_VERITY_SIG
].found
)
1006 return -EADDRNOTAVAIL
; /* as above */
1008 else if (m
->partitions
[PARTITION_USR_OTHER
].found
) {
1010 log_debug("No usr partition found of the native architecture or the secondary architecture, "
1011 "falling back to a usr partition of a non-native architecture (%s).",
1012 architecture_to_string(m
->partitions
[PARTITION_ROOT_OTHER
].architecture
));
1014 /* Upgrade other arch to primary */
1015 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_OTHER
];
1016 zero(m
->partitions
[PARTITION_USR_OTHER
]);
1017 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_OTHER_VERITY
];
1018 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY
]);
1019 m
->partitions
[PARTITION_USR_VERITY_SIG
] = m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
];
1020 zero(m
->partitions
[PARTITION_USR_OTHER_VERITY_SIG
]);
1023 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1024 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1025 return -EADDRNOTAVAIL
;
1027 /* If root and /usr are combined then insist that the architecture matches */
1028 if (m
->partitions
[PARTITION_ROOT
].found
&&
1029 m
->partitions
[PARTITION_USR
].found
&&
1030 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1031 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1032 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1033 return -EADDRNOTAVAIL
;
1035 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1036 !m
->partitions
[PARTITION_USR
].found
&&
1037 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1038 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1040 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1041 * that. If the root hash was set however, then we won't fall back to a generic node, because
1042 * the root hash decides. */
1044 /* If we didn't find a properly marked root partition, but we did find a single suitable
1045 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1046 if (multiple_generic
)
1049 /* If we didn't find a generic node, then we can't fix this up either */
1051 _cleanup_free_
char *o
= NULL
;
1052 const char *options
;
1054 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1056 o
= strdup(options
);
1061 assert(generic_nr
>= 0);
1062 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1065 .growfs
= generic_growfs
,
1066 .partno
= generic_nr
,
1067 .architecture
= _ARCHITECTURE_INVALID
,
1068 .node
= TAKE_PTR(generic_node
),
1069 .uuid
= generic_uuid
,
1070 .mount_options
= TAKE_PTR(o
),
1071 .offset
= UINT64_MAX
,
1077 /* 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 */
1078 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1079 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1082 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1083 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1084 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1087 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1088 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1089 if (m
->partitions
[PARTITION_USR
].found
)
1090 return -EADDRNOTAVAIL
;
1094 /* If a verity designator is specified, then insist that the matching partition exists */
1095 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1096 return -EADDRNOTAVAIL
;
1098 bool have_verity_sig_partition
=
1099 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR_VERITY_SIG
: PARTITION_ROOT_VERITY_SIG
].found
;
1101 if (verity
->root_hash
) {
1102 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1103 * Verity, set things up for it */
1105 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1106 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1107 return -EADDRNOTAVAIL
;
1109 /* If we found a verity setup, then the root partition is necessarily read-only. */
1110 m
->partitions
[PARTITION_ROOT
].rw
= false;
1111 m
->verity_ready
= true;
1114 assert(verity
->designator
== PARTITION_USR
);
1116 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1117 return -EADDRNOTAVAIL
;
1119 m
->partitions
[PARTITION_USR
].rw
= false;
1120 m
->verity_ready
= true;
1123 if (m
->verity_ready
)
1124 m
->verity_sig_ready
= verity
->root_hash_sig
|| have_verity_sig_partition
;
1126 } else if (have_verity_sig_partition
) {
1128 /* If we found an embedded signature partition, we are ready, too. */
1130 m
->verity_ready
= m
->verity_sig_ready
= true;
1131 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR
: PARTITION_ROOT
].rw
= false;
1139 int dissect_image_file(
1141 const VeritySettings
*verity
,
1142 const MountOptions
*mount_options
,
1143 DissectImageFlags flags
,
1144 DissectedImage
**ret
) {
1147 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1148 _cleanup_close_
int fd
= -1;
1152 assert((flags
& DISSECT_IMAGE_BLOCK_DEVICE
) == 0);
1155 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1159 r
= fd_verify_regular(fd
);
1163 r
= dissected_image_new(path
, &m
);
1167 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, flags
);
1178 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1182 /* First, clear dissected partitions. */
1183 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1184 dissected_partition_done(m
->partitions
+ i
);
1186 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1187 * DecryptedImage may try to deactivate partitions. */
1188 decrypted_image_unref(m
->decrypted_image
);
1190 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1191 * remove existing partitions on the loopback block device. */
1192 loop_device_unref(m
->loop
);
1194 free(m
->image_name
);
1196 strv_free(m
->machine_info
);
1197 strv_free(m
->os_release
);
1198 strv_free(m
->extension_release
);
1203 static int is_loop_device(const char *path
) {
1204 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1209 if (stat(path
, &st
) < 0)
1212 if (!S_ISBLK(st
.st_mode
))
1215 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1216 if (access(s
, F_OK
) < 0) {
1217 if (errno
!= ENOENT
)
1220 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1221 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1222 if (access(s
, F_OK
) < 0)
1223 return errno
== ENOENT
? false : -errno
;
1229 static int run_fsck(const char *node
, const char *fstype
) {
1236 r
= fsck_exists_for_fstype(fstype
);
1238 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1242 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
1246 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
1248 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1251 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
1253 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1254 _exit(FSCK_OPERATIONAL_ERROR
);
1257 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1258 if (exit_status
< 0)
1259 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
1261 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1262 log_debug("fsck failed with exit status %i.", exit_status
);
1264 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1265 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1267 log_debug("Ignoring fsck error.");
1273 static int fs_grow(const char *node_path
, const char *mount_path
) {
1274 _cleanup_close_
int mount_fd
= -1, node_fd
= -1;
1275 uint64_t size
, newsize
;
1278 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1280 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1282 if (ioctl(node_fd
, BLKGETSIZE64
, &size
) != 0)
1283 return log_debug_errno(errno
, "Failed to get block device size of %s: %m", node_path
);
1285 mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1287 return log_debug_errno(errno
, "Failed to open mountd file system %s: %m", mount_path
);
1289 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", mount_path
, size
);
1290 r
= resize_fs(mount_fd
, size
, &newsize
);
1292 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", mount_path
, size
);
1294 if (newsize
== size
)
1295 log_debug("Successfully resized \"%s\" to %s bytes.",
1296 mount_path
, FORMAT_BYTES(newsize
));
1298 assert(newsize
< size
);
1299 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1300 mount_path
, FORMAT_BYTES(newsize
), size
- newsize
);
1306 static int mount_partition(
1307 DissectedPartition
*m
,
1309 const char *directory
,
1312 DissectImageFlags flags
) {
1314 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1315 const char *p
, *node
, *fstype
;
1316 bool rw
, remap_uid_gid
= false;
1322 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1323 node
= m
->decrypted_node
?: m
->node
;
1324 fstype
= m
->decrypted_node
? m
->decrypted_fstype
: m
->fstype
;
1326 if (!m
->found
|| !node
)
1329 return -EAFNOSUPPORT
;
1331 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller
1332 * didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this
1334 if (streq(fstype
, "crypto_LUKS"))
1337 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
1339 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1340 r
= run_fsck(node
, fstype
);
1346 /* Automatically create missing mount points inside the image, if necessary. */
1347 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
1348 if (r
< 0 && r
!= -EROFS
)
1351 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1357 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1358 * image (as the branch above does) but the host hierarchy, and the created directory might
1359 * survive our mount in the host hierarchy hence. */
1360 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1361 r
= mkdir_p(where
, 0755);
1369 /* If requested, turn on discard support. */
1370 if (fstype_can_discard(fstype
) &&
1371 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1372 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
) > 0))) {
1373 options
= strdup("discard");
1378 if (uid_is_valid(uid_shift
) && uid_shift
!= 0) {
1380 if (fstype_can_uid_gid(fstype
)) {
1381 _cleanup_free_
char *uid_option
= NULL
;
1383 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1386 if (!strextend_with_separator(&options
, ",", uid_option
))
1388 } else if (FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
))
1389 remap_uid_gid
= true;
1392 if (!isempty(m
->mount_options
))
1393 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
1396 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1397 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1398 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1399 * from the upper file system still get propagated through to the underlying file system,
1400 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1401 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1402 * carry a per file system table here.
1404 * Note that this means that we might not be able to mount corrupted file systems as read-only
1405 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1406 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1407 * mount options for loopback devices this is the right choice, since otherwise using the same
1408 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The usecase of
1409 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1410 * access that actually modifies stuff work on such image files. Or to say this differently: if
1411 * people want their file systems to be fixed up they should just open them in writable mode, where
1412 * all these problems don't exist. */
1413 if (!rw
&& STRPTR_IN_SET(fstype
, "ext3", "ext4", "xfs", "btrfs"))
1414 if (!strextend_with_separator(&options
, ",", "norecovery"))
1417 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1421 if (rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
))
1422 (void) fs_grow(node
, p
);
1424 if (remap_uid_gid
) {
1425 r
= remount_idmap(p
, uid_shift
, uid_range
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
1433 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1434 _cleanup_free_
char *options
= NULL
;
1439 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
1441 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1442 r
= mkdir_p(where
, 0755);
1447 if (uid_is_valid(uid_shift
)) {
1448 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1452 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
1459 int dissected_image_mount(
1464 DissectImageFlags flags
) {
1466 int r
, xbootldr_mounted
;
1473 * -ENXIO → No root partition found
1474 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1475 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1476 * -EUCLEAN → fsck for file system failed
1477 * -EBUSY → File system already mounted/used elsewhere (kernel)
1478 * -EAFNOSUPPORT → File system type not supported or not known
1481 if (!(m
->partitions
[PARTITION_ROOT
].found
||
1482 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1483 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
1485 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1487 /* First mount the root fs. If there's none we use a tmpfs. */
1488 if (m
->partitions
[PARTITION_ROOT
].found
)
1489 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, flags
);
1491 r
= mount_root_tmpfs(where
, uid_shift
, flags
);
1495 /* For us mounting root always means mounting /usr as well */
1496 r
= mount_partition(m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, flags
);
1500 if ((flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
1501 /* If either one of the validation flags are set, ensure that the image qualifies
1502 * as one or the other (or both). */
1505 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
1506 r
= path_is_os_tree(where
);
1512 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
)) {
1513 r
= path_is_extension_tree(where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_SYSEXT_CHECK
));
1525 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1528 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, flags
);
1532 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, flags
);
1536 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, flags
);
1540 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, flags
);
1544 xbootldr_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, flags
);
1545 if (xbootldr_mounted
< 0)
1546 return xbootldr_mounted
;
1548 if (m
->partitions
[PARTITION_ESP
].found
) {
1549 int esp_done
= false;
1551 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1552 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1554 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1559 /* /efi doesn't exist. Let's see if /boot is suitable then */
1561 if (!xbootldr_mounted
) {
1562 _cleanup_free_
char *p
= NULL
;
1564 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1568 } else if (dir_is_empty(p
, /* ignore_hidden_or_backup= */ false) > 0) {
1569 /* It exists and is an empty directory. Let's mount the ESP there. */
1570 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, uid_range
, flags
);
1580 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1582 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, uid_range
, flags
);
1591 int dissected_image_mount_and_warn(
1596 DissectImageFlags flags
) {
1603 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, flags
);
1605 return log_error_errno(r
, "Not root file system found in image.");
1606 if (r
== -EMEDIUMTYPE
)
1607 return log_error_errno(r
, "No suitable os-release/extension-release file in image found.");
1609 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
1611 return log_error_errno(r
, "File system check on image failed.");
1613 return log_error_errno(r
, "File system already mounted elsewhere.");
1614 if (r
== -EAFNOSUPPORT
)
1615 return log_error_errno(r
, "File system type not supported or not known.");
1617 return log_error_errno(r
, "Failed to mount image: %m");
1622 #if HAVE_LIBCRYPTSETUP
1623 struct DecryptedPartition
{
1624 struct crypt_device
*device
;
1630 typedef struct DecryptedPartition DecryptedPartition
;
1632 struct DecryptedImage
{
1634 DecryptedPartition
*decrypted
;
1638 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
1639 #if HAVE_LIBCRYPTSETUP
1645 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
1646 DecryptedPartition
*p
= d
->decrypted
+ i
;
1648 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1649 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
1650 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1652 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1656 sym_crypt_free(p
->device
);
1666 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
1668 #if HAVE_LIBCRYPTSETUP
1669 static int decrypted_image_new(DecryptedImage
**ret
) {
1670 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1674 d
= new(DecryptedImage
, 1);
1678 *d
= (DecryptedImage
) {
1686 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1687 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1690 assert(original_node
);
1695 base
= strrchr(original_node
, '/');
1697 base
= original_node
;
1703 name
= strjoin(base
, suffix
);
1706 if (!filename_is_valid(name
))
1709 node
= path_join(sym_crypt_get_dir(), name
);
1713 *ret_name
= TAKE_PTR(name
);
1714 *ret_node
= TAKE_PTR(node
);
1719 static int decrypt_partition(
1720 DissectedPartition
*m
,
1721 const char *passphrase
,
1722 DissectImageFlags flags
,
1723 DecryptedImage
*d
) {
1725 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1726 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1732 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1735 if (!streq(m
->fstype
, "crypto_LUKS"))
1741 r
= dlopen_cryptsetup();
1745 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1749 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
1752 r
= sym_crypt_init(&cd
, m
->node
);
1754 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1756 cryptsetup_enable_logging(cd
);
1758 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
1760 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1762 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1763 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1764 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1766 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1767 return r
== -EPERM
? -EKEYREJECTED
: r
;
1770 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
1771 .name
= TAKE_PTR(name
),
1772 .device
= TAKE_PTR(cd
),
1775 m
->decrypted_node
= TAKE_PTR(node
);
1780 static int verity_can_reuse(
1781 const VeritySettings
*verity
,
1783 struct crypt_device
**ret_cd
) {
1785 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1786 _cleanup_free_
char *root_hash_existing
= NULL
;
1787 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1788 struct crypt_params_verity crypt_params
= {};
1789 size_t root_hash_existing_size
;
1796 r
= sym_crypt_init_by_name(&cd
, name
);
1798 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1800 cryptsetup_enable_logging(cd
);
1802 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
1804 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1806 root_hash_existing_size
= verity
->root_hash_size
;
1807 root_hash_existing
= malloc0(root_hash_existing_size
);
1808 if (!root_hash_existing
)
1811 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1813 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1814 if (verity
->root_hash_size
!= root_hash_existing_size
||
1815 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
1816 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1818 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1819 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1820 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1821 * signing for the new one, and vice versa. */
1822 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1823 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1826 *ret_cd
= TAKE_PTR(cd
);
1830 static inline char* dm_deferred_remove_clean(char *name
) {
1834 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1837 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1839 static int validate_signature_userspace(const VeritySettings
*verity
) {
1841 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
1842 _cleanup_strv_free_
char **certs
= NULL
;
1843 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
1844 _cleanup_free_
char *s
= NULL
;
1845 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
1846 * of declaration in place, please */
1847 const unsigned char *d
;
1851 assert(verity
->root_hash
);
1852 assert(verity
->root_hash_sig
);
1854 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
1855 * userspace validation. */
1857 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
1859 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
1860 if (strv_isempty(certs
)) {
1861 log_debug("No userspace dm-verity certificates found.");
1865 d
= verity
->root_hash_sig
;
1866 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
1868 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
1870 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
1872 return log_oom_debug();
1874 bio
= BIO_new_mem_buf(s
, strlen(s
));
1876 return log_oom_debug();
1878 sk
= sk_X509_new_null();
1880 return log_oom_debug();
1882 STRV_FOREACH(i
, certs
) {
1883 _cleanup_(X509_freep
) X509
*c
= NULL
;
1884 _cleanup_fclose_
FILE *f
= NULL
;
1886 f
= fopen(*i
, "re");
1888 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
1892 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
1894 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
1898 if (sk_X509_push(sk
, c
) == 0)
1899 return log_oom_debug();
1904 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
1906 log_debug("Userspace PKCS#7 validation succeeded.");
1908 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
1912 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
1917 static int do_crypt_activate_verity(
1918 struct crypt_device
*cd
,
1920 const VeritySettings
*verity
) {
1922 bool check_signature
;
1929 if (verity
->root_hash_sig
) {
1930 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIGNATURE");
1931 if (r
< 0 && r
!= -ENXIO
)
1932 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
1934 check_signature
= r
!= 0;
1936 check_signature
= false;
1938 if (check_signature
) {
1940 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1941 /* First, if we have support for signed keys in the kernel, then try that first. */
1942 r
= sym_crypt_activate_by_signed_key(
1946 verity
->root_hash_size
,
1947 verity
->root_hash_sig
,
1948 verity
->root_hash_sig_size
,
1949 CRYPT_ACTIVATE_READONLY
);
1953 log_debug("Validation of dm-verity signature failed via the kernel, trying userspace validation instead.");
1955 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.",
1956 program_invocation_short_name
);
1959 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
1960 * works we'll try to activate without telling the kernel the signature. */
1962 r
= validate_signature_userspace(verity
);
1966 return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY
),
1967 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
1970 return sym_crypt_activate_by_volume_key(
1974 verity
->root_hash_size
,
1975 CRYPT_ACTIVATE_READONLY
);
1978 static usec_t
verity_timeout(void) {
1979 usec_t t
= 100 * USEC_PER_MSEC
;
1983 /* On slower machines, like non-KVM vm, setting up device may take a long time.
1984 * Let's make the timeout configurable. */
1986 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
1990 r
= parse_sec(e
, &t
);
1993 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
1994 "using the default timeout (%s).",
1995 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
2000 static int verity_partition(
2001 PartitionDesignator designator
,
2002 DissectedPartition
*m
,
2003 DissectedPartition
*v
,
2004 const VeritySettings
*verity
,
2005 DissectImageFlags flags
,
2006 DecryptedImage
*d
) {
2008 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2009 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2010 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2014 assert(v
|| (verity
&& verity
->data_path
));
2016 if (!verity
|| !verity
->root_hash
)
2018 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2019 (verity
->designator
== designator
)))
2022 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2024 if (!verity
->data_path
) {
2025 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2028 if (!streq(v
->fstype
, "DM_verity_hash"))
2032 r
= dlopen_cryptsetup();
2036 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2037 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2038 _cleanup_free_
char *root_hash_encoded
= NULL
;
2040 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2041 if (!root_hash_encoded
)
2044 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2046 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2050 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2054 cryptsetup_enable_logging(cd
);
2056 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2060 r
= sym_crypt_set_data_device(cd
, m
->node
);
2064 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2067 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2068 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2069 * retry a few times before giving up. */
2070 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2071 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2072 _cleanup_close_
int fd
= -1;
2074 /* First, check if the device already exists. */
2075 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2076 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2077 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2079 goto check
; /* The device already exists. Let's check it. */
2081 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2082 r
= do_crypt_activate_verity(cd
, name
, verity
);
2084 goto success
; /* The device is activated. */
2085 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2086 * There's no way to distinguish this situation from a genuine error due to invalid
2087 * parameters, so immediately fall back to activating the device with a unique name.
2088 * Improvements in libcrypsetup can ensure this never happens:
2089 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2090 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2092 if (r
== -ENODEV
) /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */
2095 -EEXIST
, /* Volume has already been opened and ready to be used. */
2096 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2097 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2100 if (!restore_deferred_remove
){
2101 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2102 r
= dm_deferred_remove_cancel(name
);
2103 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2104 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2105 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2106 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2109 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2111 restore_deferred_remove
= strdup(name
);
2112 if (!restore_deferred_remove
)
2113 return log_oom_debug();
2116 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2117 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2118 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2121 -ENOENT
, /* Removed?? */
2122 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2123 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2126 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2129 /* devmapper might say that the device exists, but the devlink might not yet have been
2130 * created. Check and wait for the udev event in that case. */
2131 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2132 /* Fallback to activation with a unique device if it's taking too long */
2133 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2136 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2140 crypt_free_and_replace(cd
, existing_cd
);
2145 /* Device is being removed by another process. Let's wait for a while. */
2146 (void) usleep(2 * USEC_PER_MSEC
);
2149 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2150 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2151 /* Before trying to activate with unique name, we need to free crypt_device object.
2152 * Otherwise, we get error from libcryptsetup like the following:
2154 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2159 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2162 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2165 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2166 restore_deferred_remove
= mfree(restore_deferred_remove
);
2168 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2169 .name
= TAKE_PTR(name
),
2170 .device
= TAKE_PTR(cd
),
2173 m
->decrypted_node
= TAKE_PTR(node
);
2179 int dissected_image_decrypt(
2181 const char *passphrase
,
2182 const VeritySettings
*verity
,
2183 DissectImageFlags flags
) {
2185 #if HAVE_LIBCRYPTSETUP
2186 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2191 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
2195 * = 0 → There was nothing to decrypt
2196 * > 0 → Decrypted successfully
2197 * -ENOKEY → There's something to decrypt but no key was supplied
2198 * -EKEYREJECTED → Passed key was not correct
2201 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
2204 if (!m
->encrypted
&& !m
->verity_ready
)
2207 #if HAVE_LIBCRYPTSETUP
2208 r
= decrypted_image_new(&d
);
2212 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
2213 DissectedPartition
*p
= m
->partitions
+ i
;
2214 PartitionDesignator k
;
2219 r
= decrypt_partition(p
, passphrase
, flags
, d
);
2223 k
= PARTITION_VERITY_OF(i
);
2225 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
2230 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
2231 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
2232 if (r
< 0 && r
!= -EUCLEAN
)
2237 m
->decrypted_image
= TAKE_PTR(d
);
2245 int dissected_image_decrypt_interactively(
2247 const char *passphrase
,
2248 const VeritySettings
*verity
,
2249 DissectImageFlags flags
) {
2251 _cleanup_strv_free_erase_
char **z
= NULL
;
2258 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
2261 if (r
== -EKEYREJECTED
)
2262 log_error_errno(r
, "Incorrect passphrase, try again!");
2263 else if (r
!= -ENOKEY
)
2264 return log_error_errno(r
, "Failed to decrypt image: %m");
2267 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
2268 "Too many retries.");
2272 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", "dissect.passphrase", USEC_INFINITY
, 0, &z
);
2274 return log_error_errno(r
, "Failed to query for passphrase: %m");
2280 static int decrypted_image_relinquish(DecryptedImage
*d
) {
2283 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2284 * boolean so that we don't clean it up ourselves either anymore */
2286 #if HAVE_LIBCRYPTSETUP
2289 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2290 DecryptedPartition
*p
= d
->decrypted
+ i
;
2292 if (p
->relinquished
)
2295 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2297 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
2299 p
->relinquished
= true;
2306 int dissected_image_relinquish(DissectedImage
*m
) {
2311 if (m
->decrypted_image
) {
2312 r
= decrypted_image_relinquish(m
->decrypted_image
);
2318 loop_device_relinquish(m
->loop
);
2323 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
2330 e
= endswith(image
, ".raw");
2332 return strjoin(e
, suffix
);
2334 n
= new(char, e
- image
+ strlen(suffix
) + 1);
2338 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
2342 void verity_settings_done(VeritySettings
*v
) {
2345 v
->root_hash
= mfree(v
->root_hash
);
2346 v
->root_hash_size
= 0;
2348 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
2349 v
->root_hash_sig_size
= 0;
2351 v
->data_path
= mfree(v
->data_path
);
2354 int verity_settings_load(
2355 VeritySettings
*verity
,
2357 const char *root_hash_path
,
2358 const char *root_hash_sig_path
) {
2360 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2361 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
2362 _cleanup_free_
char *verity_data_path
= NULL
;
2363 PartitionDesignator designator
;
2368 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
2370 /* If we are asked to load the root hash for a device node, exit early */
2371 if (is_device_path(image
))
2374 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_SIDECAR");
2375 if (r
< 0 && r
!= -ENXIO
)
2376 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
2380 designator
= verity
->designator
;
2382 /* We only fill in what isn't already filled in */
2384 if (!verity
->root_hash
) {
2385 _cleanup_free_
char *text
= NULL
;
2387 if (root_hash_path
) {
2388 /* If explicitly specified it takes precedence */
2389 r
= read_one_line_file(root_hash_path
, &text
);
2394 designator
= PARTITION_ROOT
;
2396 /* Otherwise look for xattr and separate file, and first for the data for root and if
2397 * that doesn't exist for /usr */
2399 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2400 r
= getxattr_malloc(image
, "user.verity.roothash", &text
);
2402 _cleanup_free_
char *p
= NULL
;
2404 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2407 p
= build_auxiliary_path(image
, ".roothash");
2411 r
= read_one_line_file(p
, &text
);
2412 if (r
< 0 && r
!= -ENOENT
)
2417 designator
= PARTITION_ROOT
;
2420 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2421 /* So in the "roothash" xattr/file name above the "root" of course primarily
2422 * refers to the root of the Verity Merkle tree. But coincidentally it also
2423 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2424 * two distinct concepts called "root". Taking benefit of this happy
2425 * coincidence we call the file with the root hash for the /usr/ file system
2426 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2427 * confusing. We thus drop the reference to the root of the Merkle tree, and
2428 * just indicate which file system it's about. */
2429 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
);
2431 _cleanup_free_
char *p
= NULL
;
2433 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
2436 p
= build_auxiliary_path(image
, ".usrhash");
2440 r
= read_one_line_file(p
, &text
);
2441 if (r
< 0 && r
!= -ENOENT
)
2446 designator
= PARTITION_USR
;
2451 r
= unhexmem(text
, strlen(text
), &root_hash
, &root_hash_size
);
2454 if (root_hash_size
< sizeof(sd_id128_t
))
2459 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
2460 if (root_hash_sig_path
) {
2461 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2462 if (r
< 0 && r
!= -ENOENT
)
2466 designator
= PARTITION_ROOT
;
2468 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2469 _cleanup_free_
char *p
= NULL
;
2471 /* Follow naming convention recommended by the relevant RFC:
2472 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2473 p
= build_auxiliary_path(image
, ".roothash.p7s");
2477 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2478 if (r
< 0 && r
!= -ENOENT
)
2481 designator
= PARTITION_ROOT
;
2484 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2485 _cleanup_free_
char *p
= NULL
;
2487 p
= build_auxiliary_path(image
, ".usrhash.p7s");
2491 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2492 if (r
< 0 && r
!= -ENOENT
)
2495 designator
= PARTITION_USR
;
2499 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
2503 if (!verity
->data_path
) {
2504 _cleanup_free_
char *p
= NULL
;
2506 p
= build_auxiliary_path(image
, ".verity");
2510 if (access(p
, F_OK
) < 0) {
2511 if (errno
!= ENOENT
)
2514 verity_data_path
= TAKE_PTR(p
);
2518 verity
->root_hash
= TAKE_PTR(root_hash
);
2519 verity
->root_hash_size
= root_hash_size
;
2522 if (root_hash_sig
) {
2523 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
2524 verity
->root_hash_sig_size
= root_hash_sig_size
;
2527 if (verity_data_path
)
2528 verity
->data_path
= TAKE_PTR(verity_data_path
);
2530 if (verity
->designator
< 0)
2531 verity
->designator
= designator
;
2536 int dissected_image_load_verity_sig_partition(
2539 VeritySettings
*verity
) {
2541 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2542 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
2543 size_t root_hash_size
, root_hash_sig_size
;
2544 _cleanup_free_
char *buf
= NULL
;
2545 PartitionDesignator d
;
2546 DissectedPartition
*p
;
2547 JsonVariant
*rh
, *sig
;
2556 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
2559 r
= getenv_bool_secure("SYSTEMD_DISSECT_VERITY_EMBEDDED");
2560 if (r
< 0 && r
!= -ENXIO
)
2561 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
2565 d
= PARTITION_VERITY_SIG_OF(verity
->designator
< 0 ? PARTITION_ROOT
: verity
->designator
);
2568 p
= m
->partitions
+ d
;
2571 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
2574 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
2577 buf
= new(char, p
->size
+1);
2581 n
= pread(fd
, buf
, p
->size
, p
->offset
);
2584 if ((uint64_t) n
!= p
->size
)
2587 e
= memchr(buf
, 0, p
->size
);
2589 /* If we found a NUL byte then the rest of the data must be NUL too */
2590 if (!memeqzero(e
, p
->size
- (e
- buf
)))
2591 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
2595 r
= json_parse(buf
, 0, &v
, NULL
, NULL
);
2597 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
2599 rh
= json_variant_by_key(v
, "rootHash");
2601 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
2602 if (!json_variant_is_string(rh
))
2603 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'rootHash' field of signature JSON object is not a string.");
2605 r
= unhexmem(json_variant_string(rh
), SIZE_MAX
, &root_hash
, &root_hash_size
);
2607 return log_debug_errno(r
, "Failed to parse root hash field: %m");
2609 /* Check if specified root hash matches if it is specified */
2610 if (verity
->root_hash
&&
2611 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
2612 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
2614 a
= hexmem(root_hash
, root_hash_size
);
2615 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2617 return log_debug_errno(r
, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
2620 sig
= json_variant_by_key(v
, "signature");
2622 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
2623 if (!json_variant_is_string(sig
))
2624 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'signature' field of signature JSON object is not a string.");
2626 r
= unbase64mem(json_variant_string(sig
), SIZE_MAX
, &root_hash_sig
, &root_hash_sig_size
);
2628 return log_debug_errno(r
, "Failed to parse signature field: %m");
2630 free_and_replace(verity
->root_hash
, root_hash
);
2631 verity
->root_hash_size
= root_hash_size
;
2633 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
2634 verity
->root_hash_sig_size
= root_hash_sig_size
;
2639 int dissected_image_acquire_metadata(DissectedImage
*m
, DissectImageFlags extra_flags
) {
2646 META_EXTENSION_RELEASE
,
2647 META_HAS_INIT_SYSTEM
,
2651 static const char *const paths
[_META_MAX
] = {
2652 [META_HOSTNAME
] = "/etc/hostname\0",
2653 [META_MACHINE_ID
] = "/etc/machine-id\0",
2654 [META_MACHINE_INFO
] = "/etc/machine-info\0",
2655 [META_OS_RELEASE
] = ("/etc/os-release\0"
2656 "/usr/lib/os-release\0"),
2657 [META_EXTENSION_RELEASE
] = "extension-release\0", /* Used only for logging. */
2658 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
2661 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **extension_release
= NULL
;
2662 _cleanup_close_pair_
int error_pipe
[2] = { -1, -1 };
2663 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
2664 _cleanup_(sigkill_waitp
) pid_t child
= 0;
2665 sd_id128_t machine_id
= SD_ID128_NULL
;
2666 _cleanup_free_
char *hostname
= NULL
;
2667 unsigned n_meta_initialized
= 0;
2668 int fds
[2 * _META_MAX
], r
, v
;
2669 int has_init_system
= -1;
2672 BLOCK_SIGNALS(SIGCHLD
);
2676 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
2677 if (!paths
[n_meta_initialized
]) {
2678 fds
[2*n_meta_initialized
] = fds
[2*n_meta_initialized
+1] = -1;
2682 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
2688 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
2692 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
2697 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
2701 /* Child in a new mount namespace */
2702 error_pipe
[0] = safe_close(error_pipe
[0]);
2704 r
= dissected_image_mount(
2710 DISSECT_IMAGE_READ_ONLY
|
2711 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
2712 DISSECT_IMAGE_USR_NO_ROOT
);
2714 log_debug_errno(r
, "Failed to mount dissected image: %m");
2718 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2719 _cleanup_close_
int fd
= -ENOENT
;
2725 fds
[2*k
] = safe_close(fds
[2*k
]);
2729 case META_EXTENSION_RELEASE
:
2730 /* As per the os-release spec, if the image is an extension it will have a file
2731 * named after the image name in extension-release.d/ - we use the image name
2732 * and try to resolve it with the extension-release helpers, as sometimes
2733 * the image names are mangled on deployment and do not match anymore.
2734 * Unlike other paths this is not fixed, and the image name
2735 * can be mangled on deployment, so by calling into the helper
2736 * we allow a fallback that matches on the first extension-release
2737 * file found in the directory, if one named after the image cannot
2738 * be found first. */
2739 r
= open_extension_release(t
, m
->image_name
, /* relax_extension_release_check= */ false, NULL
, &fd
);
2741 fd
= r
; /* Propagate the error. */
2744 case META_HAS_INIT_SYSTEM
: {
2747 FOREACH_STRING(init
,
2748 "/usr/lib/systemd/systemd", /* systemd on /usr merged system */
2749 "/lib/systemd/systemd", /* systemd on /usr non-merged systems */
2750 "/sbin/init") { /* traditional path the Linux kernel invokes */
2752 r
= chase_symlinks(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
2755 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
2762 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
), false);
2770 NULSTR_FOREACH(p
, paths
[k
]) {
2771 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
2778 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
2779 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2783 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
2787 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2790 _exit(EXIT_SUCCESS
);
2793 /* Let parent know the error */
2794 (void) write(error_pipe
[1], &r
, sizeof(r
));
2795 _exit(EXIT_FAILURE
);
2798 error_pipe
[1] = safe_close(error_pipe
[1]);
2800 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2801 _cleanup_fclose_
FILE *f
= NULL
;
2806 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2808 f
= take_fdopen(&fds
[2*k
], "r");
2817 r
= read_etc_hostname_stream(f
, &hostname
);
2819 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
2823 case META_MACHINE_ID
: {
2824 _cleanup_free_
char *line
= NULL
;
2826 r
= read_line(f
, LONG_LINE_MAX
, &line
);
2828 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
2830 r
= sd_id128_from_string(line
, &machine_id
);
2832 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
2834 log_debug("/etc/machine-id file of image is empty.");
2835 else if (streq(line
, "uninitialized"))
2836 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
2838 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
2843 case META_MACHINE_INFO
:
2844 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
2846 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
2850 case META_OS_RELEASE
:
2851 r
= load_env_file_pairs(f
, "os-release", &os_release
);
2853 log_debug_errno(r
, "Failed to read OS release file of image: %m");
2857 case META_EXTENSION_RELEASE
:
2858 r
= load_env_file_pairs(f
, "extension-release", &extension_release
);
2860 log_debug_errno(r
, "Failed to read extension release file of image: %m");
2864 case META_HAS_INIT_SYSTEM
: {
2869 nr
= fread(&b
, 1, sizeof(b
), f
);
2870 if (nr
!= sizeof(b
))
2871 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
2873 has_init_system
= b
;
2879 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
2884 n
= read(error_pipe
[0], &v
, sizeof(v
));
2888 return v
; /* propagate error sent to us from child */
2892 if (r
!= EXIT_SUCCESS
)
2895 free_and_replace(m
->hostname
, hostname
);
2896 m
->machine_id
= machine_id
;
2897 strv_free_and_replace(m
->machine_info
, machine_info
);
2898 strv_free_and_replace(m
->os_release
, os_release
);
2899 strv_free_and_replace(m
->extension_release
, extension_release
);
2900 m
->has_init_system
= has_init_system
;
2903 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
2904 safe_close_pair(fds
+ 2*k
);
2909 int dissect_loop_device(
2911 const VeritySettings
*verity
,
2912 const MountOptions
*mount_options
,
2913 DissectImageFlags flags
,
2914 DissectedImage
**ret
) {
2917 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
2923 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
2927 m
->loop
= loop_device_ref(loop
);
2929 r
= dissect_image(m
, loop
->fd
, loop
->node
, verity
, mount_options
, flags
| DISSECT_IMAGE_BLOCK_DEVICE
);
2933 r
= dissected_image_probe_filesystem(m
);
2944 int dissect_loop_device_and_warn(
2946 const VeritySettings
*verity
,
2947 const MountOptions
*mount_options
,
2948 DissectImageFlags flags
,
2949 DissectedImage
**ret
) {
2955 assert(loop
->fd
>= 0);
2957 name
= ASSERT_PTR(loop
->backing_file
?: loop
->node
);
2959 r
= dissect_loop_device(loop
, verity
, mount_options
, flags
, ret
);
2963 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
2966 return log_error_errno(r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
2969 return log_error_errno(r
, "%s: The image does not pass validation.", name
);
2971 case -EADDRNOTAVAIL
:
2972 return log_error_errno(r
, "%s: No root partition for specified root hash found.", name
);
2975 return log_error_errno(r
, "%s: Multiple suitable root partitions found in image.", name
);
2978 return log_error_errno(r
, "%s: No suitable root partition found in image.", name
);
2980 case -EPROTONOSUPPORT
:
2981 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
2984 return log_error_errno(r
, "%s: Image is not a block device.", name
);
2987 return log_error_errno(r
,
2988 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
2989 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
2990 name
, strna(verity
? verity
->data_path
: NULL
));
2994 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
3000 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3003 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3004 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3005 * images we only check the partition type.
3007 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3010 if (image
->single_file_system
)
3011 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
3013 return PARTITION_VERITY_OF(partition_designator
) >= 0;
3016 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3017 PartitionDesignator k
;
3021 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3022 * works for the root partition, for others only if the associated verity partition was found. */
3024 if (!image
->verity_ready
)
3027 if (image
->single_file_system
)
3028 return partition_designator
== PARTITION_ROOT
;
3030 k
= PARTITION_VERITY_OF(partition_designator
);
3031 return k
>= 0 && image
->partitions
[k
].found
;
3034 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3035 PartitionDesignator k
;
3039 /* Checks if this partition has verity signature data available that we can use. */
3041 if (!image
->verity_sig_ready
)
3044 if (image
->single_file_system
)
3045 return partition_designator
== PARTITION_ROOT
;
3047 k
= PARTITION_VERITY_SIG_OF(partition_designator
);
3048 return k
>= 0 && image
->partitions
[k
].found
;
3051 MountOptions
* mount_options_free_all(MountOptions
*options
) {
3054 while ((m
= options
)) {
3055 LIST_REMOVE(mount_options
, options
, m
);
3063 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
3064 LIST_FOREACH(mount_options
, m
, options
)
3065 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
3071 int mount_image_privately_interactively(
3073 DissectImageFlags flags
,
3074 char **ret_directory
,
3075 LoopDevice
**ret_loop_device
) {
3077 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3078 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3079 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3080 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
3081 _cleanup_free_
char *temp
= NULL
;
3084 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3085 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3089 assert(ret_directory
);
3090 assert(ret_loop_device
);
3092 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
3094 return log_error_errno(r
, "Failed to load root hash data: %m");
3096 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
3098 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
3100 r
= loop_device_make_by_path(
3102 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
3103 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
3107 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
3109 r
= dissect_loop_device_and_warn(d
, &verity
, NULL
, flags
, &dissected_image
);
3113 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
3117 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
3121 r
= detach_mount_namespace();
3123 return log_error_errno(r
, "Failed to detach mount namespace: %m");
3125 r
= mkdir_p(temp
, 0700);
3127 return log_error_errno(r
, "Failed to create mount point: %m");
3129 created_dir
= TAKE_PTR(temp
);
3131 r
= dissected_image_mount_and_warn(dissected_image
, created_dir
, UID_INVALID
, UID_INVALID
, flags
);
3135 r
= loop_device_flock(d
, LOCK_UN
);
3139 r
= dissected_image_relinquish(dissected_image
);
3141 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
3143 *ret_directory
= TAKE_PTR(created_dir
);
3144 *ret_loop_device
= TAKE_PTR(d
);
3149 static const char *const partition_designator_table
[] = {
3150 [PARTITION_ROOT
] = "root",
3151 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
3152 [PARTITION_ROOT_OTHER
] = "root-other",
3153 [PARTITION_USR
] = "usr",
3154 [PARTITION_USR_SECONDARY
] = "usr-secondary",
3155 [PARTITION_USR_OTHER
] = "usr-other",
3156 [PARTITION_HOME
] = "home",
3157 [PARTITION_SRV
] = "srv",
3158 [PARTITION_ESP
] = "esp",
3159 [PARTITION_XBOOTLDR
] = "xbootldr",
3160 [PARTITION_SWAP
] = "swap",
3161 [PARTITION_ROOT_VERITY
] = "root-verity",
3162 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
3163 [PARTITION_ROOT_OTHER_VERITY
] = "root-other-verity",
3164 [PARTITION_USR_VERITY
] = "usr-verity",
3165 [PARTITION_USR_SECONDARY_VERITY
] = "usr-secondary-verity",
3166 [PARTITION_USR_OTHER_VERITY
] = "usr-other-verity",
3167 [PARTITION_ROOT_VERITY_SIG
] = "root-verity-sig",
3168 [PARTITION_ROOT_SECONDARY_VERITY_SIG
] = "root-secondary-verity-sig",
3169 [PARTITION_ROOT_OTHER_VERITY_SIG
] = "root-other-verity-sig",
3170 [PARTITION_USR_VERITY_SIG
] = "usr-verity-sig",
3171 [PARTITION_USR_SECONDARY_VERITY_SIG
] = "usr-secondary-verity-sig",
3172 [PARTITION_USR_OTHER_VERITY_SIG
] = "usr-other-verity-sig",
3173 [PARTITION_TMP
] = "tmp",
3174 [PARTITION_VAR
] = "var",
3177 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
3181 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
3182 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
3183 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
3186 int verity_dissect_and_mount(
3190 const MountOptions
*options
,
3191 const char *required_host_os_release_id
,
3192 const char *required_host_os_release_version_id
,
3193 const char *required_host_os_release_sysext_level
,
3194 const char *required_sysext_scope
) {
3196 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
3197 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3198 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3199 DissectImageFlags dissect_image_flags
;
3200 bool relax_extension_release_check
;
3206 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
3208 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3209 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
3211 return log_debug_errno(r
, "Failed to load root hash: %m");
3213 dissect_image_flags
= (verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
3214 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_SYSEXT_CHECK
: 0);
3216 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
3217 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
3218 r
= loop_device_make_by_path(
3219 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
3221 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
3225 return log_debug_errno(r
, "Failed to create loop device for image: %m");
3227 r
= dissect_loop_device(
3231 dissect_image_flags
,
3233 /* No partition table? Might be a single-filesystem image, try again */
3234 if (!verity
.data_path
&& r
== -ENOPKG
)
3235 r
= dissect_loop_device(
3239 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
3242 return log_debug_errno(r
, "Failed to dissect image: %m");
3244 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, &verity
);
3248 r
= dissected_image_decrypt(
3252 dissect_image_flags
);
3254 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
3256 r
= mkdir_p_label(dest
, 0755);
3258 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
3259 r
= umount_recursive(dest
, 0);
3261 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
3263 r
= dissected_image_mount(dissected_image
, dest
, UID_INVALID
, UID_INVALID
, dissect_image_flags
);
3265 return log_debug_errno(r
, "Failed to mount image: %m");
3267 r
= loop_device_flock(loop_device
, LOCK_UN
);
3269 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
3271 /* If we got os-release values from the caller, then we need to match them with the image's
3272 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
3273 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
3274 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
3275 * then a simple match on the ID will be performed. */
3276 if (required_host_os_release_id
) {
3277 _cleanup_strv_free_
char **extension_release
= NULL
;
3279 assert(!isempty(required_host_os_release_id
));
3281 r
= load_extension_release_pairs(dest
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
3283 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
3285 r
= extension_release_validate(
3286 dissected_image
->image_name
,
3287 required_host_os_release_id
,
3288 required_host_os_release_version_id
,
3289 required_host_os_release_sysext_level
,
3290 required_sysext_scope
,
3293 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
3295 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
3298 r
= dissected_image_relinquish(dissected_image
);
3300 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
3305 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, PartitionDesignator
);