1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "architecture.h"
10 #include "ask-password-api.h"
11 #include "blkid-util.h"
12 #include "blockdev-util.h"
14 #include "crypt-util.h"
16 #include "device-nodes.h"
17 #include "dissect-image.h"
22 #include "hexdecoct.h"
23 #include "hostname-util.h"
24 #include "id128-util.h"
25 #include "linux-3.13/dm-ioctl.h"
27 #include "mount-util.h"
29 #include "path-util.h"
30 #include "process-util.h"
31 #include "raw-clone.h"
32 #include "signal-util.h"
33 #include "stat-util.h"
34 #include "stdio-util.h"
35 #include "string-table.h"
36 #include "string-util.h"
38 #include "udev-util.h"
39 #include "user-util.h"
40 #include "xattr-util.h"
42 int probe_filesystem(const char *node
, char **ret_fstype
) {
43 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
44 * 0/NULL will be returned. -EUCLEAN will be returned for ambigous results, and an
45 * different error otherwise. */
48 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
53 b
= blkid_new_probe_from_filename(node
);
55 return -errno
?: -ENOMEM
;
57 blkid_probe_enable_superblocks(b
, 1);
58 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
61 r
= blkid_do_safeprobe(b
);
63 log_debug("No type detected on partition %s", node
);
67 log_debug("Results ambiguous for partition %s", node
);
71 return -errno
?: -EIO
;
73 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
95 /* Detect RPMB and Boot partitions, which are not listed by blkid.
96 * See https://github.com/systemd/systemd/issues/5806. */
97 static bool device_is_mmc_special_partition(struct udev_device
*d
) {
100 sysname
= udev_device_get_sysname(d
);
101 return sysname
&& startswith(sysname
, "mmcblk") &&
102 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
105 static bool device_is_block(struct udev_device
*d
) {
108 ss
= udev_device_get_subsystem(d
);
112 return streq(ss
, "block");
118 const void *root_hash
,
119 size_t root_hash_size
,
120 DissectImageFlags flags
,
121 DissectedImage
**ret
) {
124 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
125 _cleanup_(udev_enumerate_unrefp
) struct udev_enumerate
*e
= NULL
;
126 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
127 _cleanup_(udev_device_unrefp
) struct udev_device
*d
= NULL
;
128 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
129 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
130 _cleanup_(udev_unrefp
) struct udev
*udev
= NULL
;
131 _cleanup_free_
char *generic_node
= NULL
;
132 sd_id128_t generic_uuid
= SD_ID128_NULL
;
133 const char *pttype
= NULL
;
134 struct udev_list_entry
*first
, *item
;
142 assert(root_hash
|| root_hash_size
== 0);
144 /* Probes a disk image, and returns information about what it found in *ret.
146 * Returns -ENOPKG if no suitable partition table or file system could be found.
147 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
150 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
151 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
154 if (root_hash_size
< sizeof(sd_id128_t
))
157 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
158 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
160 if (sd_id128_is_null(root_uuid
))
162 if (sd_id128_is_null(verity_uuid
))
166 if (fstat(fd
, &st
) < 0)
169 if (!S_ISBLK(st
.st_mode
))
172 b
= blkid_new_probe();
177 r
= blkid_probe_set_device(b
, fd
, 0, 0);
179 return -errno
?: -ENOMEM
;
181 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
182 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
183 blkid_probe_enable_superblocks(b
, 1);
184 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
187 blkid_probe_enable_partitions(b
, 1);
188 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
191 r
= blkid_do_safeprobe(b
);
192 if (IN_SET(r
, -2, 1)) {
193 log_debug("Failed to identify any partition table.");
197 return -errno
?: -EIO
;
199 m
= new0(DissectedImage
, 1);
203 if (!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
204 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) {
205 const char *usage
= NULL
;
207 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
208 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
209 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
210 const char *fstype
= NULL
;
212 /* OK, we have found a file system, that's our root partition then. */
213 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
221 if (asprintf(&n
, "/dev/block/%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
224 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
228 .architecture
= _ARCHITECTURE_INVALID
,
229 .fstype
= TAKE_PTR(t
),
233 m
->encrypted
= streq(fstype
, "crypto_LUKS");
241 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
245 is_gpt
= streq_ptr(pttype
, "gpt");
246 is_mbr
= streq_ptr(pttype
, "dos");
248 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
252 pl
= blkid_probe_get_partitions(b
);
254 return -errno
?: -ENOMEM
;
260 d
= udev_device_new_from_devnum(udev
, 'b', st
.st_rdev
);
268 log_debug("Kernel partitions never appeared.");
272 e
= udev_enumerate_new(udev
);
276 r
= udev_enumerate_add_match_parent(e
, d
);
280 r
= udev_enumerate_scan_devices(e
);
284 /* Count the partitions enumerated by the kernel */
286 first
= udev_enumerate_get_list_entry(e
);
287 udev_list_entry_foreach(item
, first
) {
288 _cleanup_(udev_device_unrefp
) struct udev_device
*q
;
291 q
= udev_device_new_from_syspath(udev
, udev_list_entry_get_name(item
));
295 qn
= udev_device_get_devnum(q
);
299 if (!device_is_block(q
))
302 if (device_is_mmc_special_partition(q
))
307 /* Count the partitions enumerated by blkid */
308 z
= blkid_partlist_numof_partitions(pl
);
312 log_debug("blkid and kernel partition list do not match.");
318 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running
319 * or it got EBUSY because udev already opened the device. Let's reprobe the device, which is a
320 * synchronous call that waits until probing is complete. */
326 if (ioctl(fd
, BLKRRPART
, 0) < 0) {
330 struct loop_info64 info
;
332 /* If we are running on a loop device that has partition scanning off,
333 * return an explicit recognizable error about this, so that callers
334 * can generate a proper message explaining the situation. */
336 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0 && (info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0) {
337 log_debug("Device is loop device and partition scanning is off!");
338 return -EPROTONOSUPPORT
;
346 /* If something else has the device open, such as an udev rule, the ioctl will return
347 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a
348 * bit, and try again.
350 * This is really something they should fix in the kernel! */
352 (void) usleep(50 * USEC_PER_MSEC
);
356 e
= udev_enumerate_unref(e
);
359 first
= udev_enumerate_get_list_entry(e
);
360 udev_list_entry_foreach(item
, first
) {
361 _cleanup_(udev_device_unrefp
) struct udev_device
*q
;
362 unsigned long long pflags
;
368 q
= udev_device_new_from_syspath(udev
, udev_list_entry_get_name(item
));
372 qn
= udev_device_get_devnum(q
);
376 if (st
.st_rdev
== qn
)
379 if (!device_is_block(q
))
382 if (device_is_mmc_special_partition(q
))
385 node
= udev_device_get_devnode(q
);
389 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
393 pflags
= blkid_partition_get_flags(pp
);
395 nr
= blkid_partition_get_partno(pp
);
400 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
401 const char *stype
, *sid
, *fstype
= NULL
;
402 sd_id128_t type_id
, id
;
405 sid
= blkid_partition_get_uuid(pp
);
408 if (sd_id128_from_string(sid
, &id
) < 0)
411 stype
= blkid_partition_get_type_string(pp
);
414 if (sd_id128_from_string(stype
, &type_id
) < 0)
417 if (sd_id128_equal(type_id
, GPT_HOME
)) {
419 if (pflags
& GPT_FLAG_NO_AUTO
)
422 designator
= PARTITION_HOME
;
423 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
424 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
426 if (pflags
& GPT_FLAG_NO_AUTO
)
429 designator
= PARTITION_SRV
;
430 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
431 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
433 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
434 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
435 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
437 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
440 designator
= PARTITION_ESP
;
443 #ifdef GPT_ROOT_NATIVE
444 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
446 if (pflags
& GPT_FLAG_NO_AUTO
)
449 /* If a root ID is specified, ignore everything but the root id */
450 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
453 designator
= PARTITION_ROOT
;
454 architecture
= native_architecture();
455 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
456 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
458 if (pflags
& GPT_FLAG_NO_AUTO
)
461 m
->can_verity
= true;
463 /* Ignore verity unless a root hash is specified */
464 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
467 designator
= PARTITION_ROOT_VERITY
;
468 fstype
= "DM_verity_hash";
469 architecture
= native_architecture();
473 #ifdef GPT_ROOT_SECONDARY
474 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
476 if (pflags
& GPT_FLAG_NO_AUTO
)
479 /* If a root ID is specified, ignore everything but the root id */
480 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
483 designator
= PARTITION_ROOT_SECONDARY
;
484 architecture
= SECONDARY_ARCHITECTURE
;
485 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
486 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
488 if (pflags
& GPT_FLAG_NO_AUTO
)
491 m
->can_verity
= true;
493 /* Ignore verity unless root has is specified */
494 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
497 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
498 fstype
= "DM_verity_hash";
499 architecture
= SECONDARY_ARCHITECTURE
;
503 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
505 if (pflags
& GPT_FLAG_NO_AUTO
)
508 designator
= PARTITION_SWAP
;
510 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
512 if (pflags
& GPT_FLAG_NO_AUTO
)
516 multiple_generic
= true;
519 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
521 generic_node
= strdup(node
);
527 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
528 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
531 if (m
->partitions
[designator
].found
)
544 m
->partitions
[designator
] = (DissectedPartition
) {
548 .architecture
= architecture
,
550 .fstype
= TAKE_PTR(t
),
557 if (pflags
!= 0x80) /* Bootable flag */
560 if (blkid_partition_get_type(pp
) != 0x83) /* Linux partition */
564 multiple_generic
= true;
568 generic_node
= strdup(node
);
575 if (!m
->partitions
[PARTITION_ROOT
].found
) {
576 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
577 * either, then check if there's a single generic one, and use that. */
579 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
580 return -EADDRNOTAVAIL
;
582 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
583 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
584 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
586 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
587 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
589 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
591 /* If the root has was set, then we won't fallback to a generic node, because the root hash
594 return -EADDRNOTAVAIL
;
596 /* If we didn't find a generic node, then we can't fix this up either */
600 /* If we didn't find a properly marked root partition, but we did find a single suitable
601 * generic Linux partition, then use this as root partition, if the caller asked for it. */
602 if (multiple_generic
)
605 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
608 .partno
= generic_nr
,
609 .architecture
= _ARCHITECTURE_INVALID
,
610 .node
= TAKE_PTR(generic_node
),
611 .uuid
= generic_uuid
,
617 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
618 return -EADDRNOTAVAIL
;
620 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
621 * (which would be weird, after all the root hash should only be assigned to one pair of
623 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
624 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
626 /* If we found a verity setup, then the root partition is necessarily read-only. */
627 m
->partitions
[PARTITION_ROOT
].rw
= false;
635 /* Fill in file system types if we don't know them yet. */
636 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
637 DissectedPartition
*p
= m
->partitions
+ i
;
642 if (!p
->fstype
&& p
->node
) {
643 r
= probe_filesystem(p
->node
, &p
->fstype
);
644 if (r
< 0 && r
!= -EUCLEAN
)
648 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
651 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
663 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
669 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
670 free(m
->partitions
[i
].fstype
);
671 free(m
->partitions
[i
].node
);
672 free(m
->partitions
[i
].decrypted_fstype
);
673 free(m
->partitions
[i
].decrypted_node
);
677 strv_free(m
->machine_info
);
678 strv_free(m
->os_release
);
683 static int is_loop_device(const char *path
) {
684 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
689 if (stat(path
, &st
) < 0)
692 if (!S_ISBLK(st
.st_mode
))
695 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
696 if (access(s
, F_OK
) < 0) {
700 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
701 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
702 if (access(s
, F_OK
) < 0)
703 return errno
== ENOENT
? false : -errno
;
709 static int mount_partition(
710 DissectedPartition
*m
,
712 const char *directory
,
714 DissectImageFlags flags
) {
716 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
717 const char *p
, *node
, *fstype
;
724 node
= m
->decrypted_node
?: m
->node
;
725 fstype
= m
->decrypted_fstype
?: m
->fstype
;
727 if (!m
->found
|| !node
|| !fstype
)
730 /* Stacked encryption? Yuck */
731 if (streq_ptr(fstype
, "crypto_LUKS"))
734 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
737 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
);
745 /* If requested, turn on discard support. */
746 if (fstype_can_discard(fstype
) &&
747 ((flags
& DISSECT_IMAGE_DISCARD
) ||
748 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
749 options
= strdup("discard");
754 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
755 _cleanup_free_
char *uid_option
= NULL
;
757 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
760 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
764 return mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
767 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
773 if (!m
->partitions
[PARTITION_ROOT
].found
)
776 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
777 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
781 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
782 r
= path_is_os_tree(where
);
790 if ((flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
))
793 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
797 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
801 if (m
->partitions
[PARTITION_ESP
].found
) {
804 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
806 FOREACH_STRING(mp
, "/efi", "/boot") {
807 _cleanup_free_
char *p
= NULL
;
809 r
= chase_symlinks(mp
, where
, CHASE_PREFIX_ROOT
, &p
);
815 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, mp
, uid_shift
, flags
);
825 #if HAVE_LIBCRYPTSETUP
826 typedef struct DecryptedPartition
{
827 struct crypt_device
*device
;
830 } DecryptedPartition
;
832 struct DecryptedImage
{
833 DecryptedPartition
*decrypted
;
839 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
840 #if HAVE_LIBCRYPTSETUP
847 for (i
= 0; i
< d
->n_decrypted
; i
++) {
848 DecryptedPartition
*p
= d
->decrypted
+ i
;
850 if (p
->device
&& p
->name
&& !p
->relinquished
) {
851 r
= crypt_deactivate(p
->device
, p
->name
);
853 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
857 crypt_free(p
->device
);
866 #if HAVE_LIBCRYPTSETUP
868 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
869 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
872 assert(original_node
);
877 base
= strrchr(original_node
, '/');
884 name
= strjoin(base
, suffix
);
887 if (!filename_is_valid(name
))
890 node
= strjoin(crypt_get_dir(), "/", name
);
894 *ret_name
= TAKE_PTR(name
);
895 *ret_node
= TAKE_PTR(node
);
900 static int decrypt_partition(
901 DissectedPartition
*m
,
902 const char *passphrase
,
903 DissectImageFlags flags
,
906 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
907 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
913 if (!m
->found
|| !m
->node
|| !m
->fstype
)
916 if (!streq(m
->fstype
, "crypto_LUKS"))
922 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
926 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
929 r
= crypt_init(&cd
, m
->node
);
931 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
933 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
935 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
937 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
938 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
939 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
941 log_debug_errno(r
, "Failed to activate LUKS device: %m");
942 return r
== -EPERM
? -EKEYREJECTED
: r
;
945 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
946 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
949 m
->decrypted_node
= TAKE_PTR(node
);
954 static int verity_partition(
955 DissectedPartition
*m
,
956 DissectedPartition
*v
,
957 const void *root_hash
,
958 size_t root_hash_size
,
959 DissectImageFlags flags
,
962 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
963 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
972 if (!m
->found
|| !m
->node
|| !m
->fstype
)
974 if (!v
->found
|| !v
->node
|| !v
->fstype
)
977 if (!streq(v
->fstype
, "DM_verity_hash"))
980 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
984 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
987 r
= crypt_init(&cd
, v
->node
);
991 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
995 r
= crypt_set_data_device(cd
, m
->node
);
999 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1003 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1004 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1007 m
->decrypted_node
= TAKE_PTR(node
);
1013 int dissected_image_decrypt(
1015 const char *passphrase
,
1016 const void *root_hash
,
1017 size_t root_hash_size
,
1018 DissectImageFlags flags
,
1019 DecryptedImage
**ret
) {
1021 #if HAVE_LIBCRYPTSETUP
1022 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1028 assert(root_hash
|| root_hash_size
== 0);
1032 * = 0 → There was nothing to decrypt
1033 * > 0 → Decrypted successfully
1034 * -ENOKEY → There's something to decrypt but no key was supplied
1035 * -EKEYREJECTED → Passed key was not correct
1038 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1041 if (!m
->encrypted
&& !m
->verity
) {
1046 #if HAVE_LIBCRYPTSETUP
1047 d
= new0(DecryptedImage
, 1);
1051 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1052 DissectedPartition
*p
= m
->partitions
+ i
;
1058 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1062 k
= PARTITION_VERITY_OF(i
);
1064 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, flags
, d
);
1069 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1070 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1071 if (r
< 0 && r
!= -EUCLEAN
)
1084 int dissected_image_decrypt_interactively(
1086 const char *passphrase
,
1087 const void *root_hash
,
1088 size_t root_hash_size
,
1089 DissectImageFlags flags
,
1090 DecryptedImage
**ret
) {
1092 _cleanup_strv_free_erase_
char **z
= NULL
;
1099 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, flags
, ret
);
1102 if (r
== -EKEYREJECTED
)
1103 log_error_errno(r
, "Incorrect passphrase, try again!");
1104 else if (r
!= -ENOKEY
)
1105 return log_error_errno(r
, "Failed to decrypt image: %m");
1108 log_error("Too many retries.");
1109 return -EKEYREJECTED
;
1114 r
= ask_password_auto("Please enter image passphrase!", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1116 return log_error_errno(r
, "Failed to query for passphrase: %m");
1122 #if HAVE_LIBCRYPTSETUP
1123 static int deferred_remove(DecryptedPartition
*p
) {
1125 struct dm_ioctl dm
= {
1129 DM_VERSION_PATCHLEVEL
1131 .data_size
= sizeof(dm
),
1132 .flags
= DM_DEFERRED_REMOVE
,
1135 _cleanup_close_
int fd
= -1;
1139 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1141 fd
= open("/dev/mapper/control", O_RDWR
|O_CLOEXEC
);
1145 strncpy(dm
.name
, p
->name
, sizeof(dm
.name
));
1147 if (ioctl(fd
, DM_DEV_REMOVE
, &dm
))
1154 int decrypted_image_relinquish(DecryptedImage
*d
) {
1156 #if HAVE_LIBCRYPTSETUP
1163 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1164 * that we don't clean it up ourselves either anymore */
1166 #if HAVE_LIBCRYPTSETUP
1167 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1168 DecryptedPartition
*p
= d
->decrypted
+ i
;
1170 if (p
->relinquished
)
1173 r
= deferred_remove(p
);
1175 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1177 p
->relinquished
= true;
1184 int root_hash_load(const char *image
, void **ret
, size_t *ret_size
) {
1185 _cleanup_free_
char *text
= NULL
;
1186 _cleanup_free_
void *k
= NULL
;
1194 if (is_device_path(image
)) {
1195 /* If we are asked to load the root hash for a device node, exit early */
1201 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1205 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1208 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1209 n
= stpcpy(fn
, image
);
1210 e
= endswith(fn
, ".raw");
1214 strcpy(n
, ".roothash");
1216 r
= read_one_line_file(fn
, &text
);
1226 r
= unhexmem(text
, strlen(text
), &k
, &l
);
1229 if (l
< sizeof(sd_id128_t
))
1238 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1248 static const char *const paths
[_META_MAX
] = {
1249 [META_HOSTNAME
] = "/etc/hostname\0",
1250 [META_MACHINE_ID
] = "/etc/machine-id\0",
1251 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1252 [META_OS_RELEASE
] = "/etc/os-release\0/usr/lib/os-release\0",
1255 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1256 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1257 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1258 sd_id128_t machine_id
= SD_ID128_NULL
;
1259 _cleanup_free_
char *hostname
= NULL
;
1260 unsigned n_meta_initialized
= 0, k
;
1261 int fds
[2 * _META_MAX
], r
;
1263 BLOCK_SIGNALS(SIGCHLD
);
1267 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1268 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1273 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1277 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1281 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1283 log_debug_errno(r
, "Failed to mount dissected image: %m");
1284 _exit(EXIT_FAILURE
);
1287 for (k
= 0; k
< _META_MAX
; k
++) {
1288 _cleanup_close_
int fd
= -1;
1291 fds
[2*k
] = safe_close(fds
[2*k
]);
1293 NULSTR_FOREACH(p
, paths
[k
]) {
1294 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1299 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1303 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1305 _exit(EXIT_FAILURE
);
1307 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1310 _exit(EXIT_SUCCESS
);
1313 for (k
= 0; k
< _META_MAX
; k
++) {
1314 _cleanup_fclose_
FILE *f
= NULL
;
1316 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1318 f
= fdopen(fds
[2*k
], "re");
1329 r
= read_etc_hostname_stream(f
, &hostname
);
1331 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1335 case META_MACHINE_ID
: {
1336 _cleanup_free_
char *line
= NULL
;
1338 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1340 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1342 r
= sd_id128_from_string(line
, &machine_id
);
1344 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1346 log_debug("/etc/machine-id file is empty.");
1348 log_debug("/etc/machine-id has unexpected length %i.", r
);
1353 case META_MACHINE_INFO
:
1354 r
= load_env_file_pairs(f
, "machine-info", NULL
, &machine_info
);
1356 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1360 case META_OS_RELEASE
:
1361 r
= load_env_file_pairs(f
, "os-release", NULL
, &os_release
);
1363 log_debug_errno(r
, "Failed to read OS release file: %m");
1369 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1373 if (r
!= EXIT_SUCCESS
)
1376 free_and_replace(m
->hostname
, hostname
);
1377 m
->machine_id
= machine_id
;
1378 strv_free_and_replace(m
->machine_info
, machine_info
);
1379 strv_free_and_replace(m
->os_release
, os_release
);
1382 for (k
= 0; k
< n_meta_initialized
; k
++)
1383 safe_close_pair(fds
+ 2*k
);
1388 int dissect_image_and_warn(
1391 const void *root_hash
,
1392 size_t root_hash_size
,
1393 DissectImageFlags flags
,
1394 DissectedImage
**ret
) {
1396 _cleanup_free_
char *buffer
= NULL
;
1400 r
= fd_get_path(fd
, &buffer
);
1407 r
= dissect_image(fd
, root_hash
, root_hash_size
, flags
, ret
);
1412 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1415 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1417 case -EADDRNOTAVAIL
:
1418 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1421 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1424 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1426 case -EPROTONOSUPPORT
:
1427 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1431 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1437 static const char *const partition_designator_table
[] = {
1438 [PARTITION_ROOT
] = "root",
1439 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1440 [PARTITION_HOME
] = "home",
1441 [PARTITION_SRV
] = "srv",
1442 [PARTITION_ESP
] = "esp",
1443 [PARTITION_SWAP
] = "swap",
1444 [PARTITION_ROOT_VERITY
] = "root-verity",
1445 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1448 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);