1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "architecture.h"
11 #include "ask-password-api.h"
12 #include "blkid-util.h"
13 #include "blockdev-util.h"
15 #include "crypt-util.h"
17 #include "device-nodes.h"
18 #include "device-util.h"
19 #include "dissect-image.h"
25 #include "hexdecoct.h"
26 #include "hostname-util.h"
27 #include "id128-util.h"
28 #include "linux-3.13/dm-ioctl.h"
30 #include "mount-util.h"
31 #include "mountpoint-util.h"
33 #include "path-util.h"
34 #include "process-util.h"
35 #include "raw-clone.h"
36 #include "signal-util.h"
37 #include "stat-util.h"
38 #include "stdio-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
42 #include "tmpfile-util.h"
43 #include "udev-util.h"
44 #include "user-util.h"
45 #include "xattr-util.h"
47 int probe_filesystem(const char *node
, char **ret_fstype
) {
48 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
49 * 0/NULL will be returned. -EUCLEAN will be returned for ambigous results, and an
50 * different error otherwise. */
53 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
58 b
= blkid_new_probe_from_filename(node
);
60 return -errno
?: -ENOMEM
;
62 blkid_probe_enable_superblocks(b
, 1);
63 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
66 r
= blkid_do_safeprobe(b
);
68 log_debug("No type detected on partition %s", node
);
72 log_debug("Results ambiguous for partition %s", node
);
76 return -errno
?: -EIO
;
78 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
100 /* Detect RPMB and Boot partitions, which are not listed by blkid.
101 * See https://github.com/systemd/systemd/issues/5806. */
102 static bool device_is_mmc_special_partition(sd_device
*d
) {
107 if (sd_device_get_sysname(d
, &sysname
) < 0)
110 return startswith(sysname
, "mmcblk") &&
111 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
114 static bool device_is_block(sd_device
*d
) {
119 if (sd_device_get_subsystem(d
, &ss
) < 0)
122 return streq(ss
, "block");
125 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
126 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
132 r
= sd_device_enumerator_new(&e
);
136 r
= sd_device_enumerator_allow_uninitialized(e
);
140 r
= sd_device_enumerator_add_match_parent(e
, d
);
148 /* how many times to wait for the device nodes to appear */
149 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
151 static int wait_for_partitions_to_appear(
154 unsigned num_partitions
,
155 DissectImageFlags flags
,
156 sd_device_enumerator
**ret_enumerator
) {
158 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
165 assert(ret_enumerator
);
167 r
= enumerator_for_parent(d
, &e
);
171 /* Count the partitions enumerated by the kernel */
173 FOREACH_DEVICE(e
, q
) {
174 if (sd_device_get_devnum(q
, NULL
) < 0)
176 if (!device_is_block(q
))
178 if (device_is_mmc_special_partition(q
))
181 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
182 r
= device_wait_for_initialization(q
, "block", NULL
);
190 if (n
== num_partitions
+ 1) {
191 *ret_enumerator
= TAKE_PTR(e
);
192 return 0; /* success! */
194 if (n
> num_partitions
+ 1)
195 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
196 "blkid and kernel partition lists do not match.");
198 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
199 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
200 * call that waits until probing is complete. */
202 for (unsigned j
= 0; ; j
++) {
206 if (ioctl(fd
, BLKRRPART
, 0) >= 0)
210 struct loop_info64 info
;
212 /* If we are running on a loop device that has partition scanning off, return
213 * an explicit recognizable error about this, so that callers can generate a
214 * proper message explaining the situation. */
216 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0 && (info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0) {
217 log_debug("Device is a loop device and partition scanning is off!");
218 return -EPROTONOSUPPORT
;
224 /* If something else has the device open, such as an udev rule, the ioctl will return
225 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
228 * This is really something they should fix in the kernel! */
229 (void) usleep(50 * USEC_PER_MSEC
);
233 return -EAGAIN
; /* no success yet, try again */
236 static int loop_wait_for_partitions_to_appear(
239 unsigned num_partitions
,
240 DissectImageFlags flags
,
241 sd_device_enumerator
**ret_enumerator
) {
242 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
247 assert(ret_enumerator
);
249 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions
);
251 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
252 r
= device_wait_for_initialization(d
, "block", &device
);
256 device
= sd_device_ref(d
);
258 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
259 r
= wait_for_partitions_to_appear(fd
, device
, num_partitions
, flags
, ret_enumerator
);
264 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
265 "Kernel partitions dit not appear within %d attempts",
266 N_DEVICE_NODE_LIST_ATTEMPTS
);
273 const void *root_hash
,
274 size_t root_hash_size
,
275 DissectImageFlags flags
,
276 DissectedImage
**ret
) {
279 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
280 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
281 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
282 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
283 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
284 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
285 _cleanup_free_
char *generic_node
= NULL
;
286 sd_id128_t generic_uuid
= SD_ID128_NULL
;
287 const char *pttype
= NULL
;
296 assert(root_hash
|| root_hash_size
== 0);
298 /* Probes a disk image, and returns information about what it found in *ret.
300 * Returns -ENOPKG if no suitable partition table or file system could be found.
301 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
304 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
305 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
308 if (root_hash_size
< sizeof(sd_id128_t
))
311 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
312 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
314 if (sd_id128_is_null(root_uuid
))
316 if (sd_id128_is_null(verity_uuid
))
320 if (fstat(fd
, &st
) < 0)
323 if (!S_ISBLK(st
.st_mode
))
326 b
= blkid_new_probe();
331 r
= blkid_probe_set_device(b
, fd
, 0, 0);
333 return -errno
?: -ENOMEM
;
335 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
336 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
337 blkid_probe_enable_superblocks(b
, 1);
338 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
341 blkid_probe_enable_partitions(b
, 1);
342 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
345 r
= blkid_do_safeprobe(b
);
346 if (IN_SET(r
, -2, 1)) {
347 log_debug("Failed to identify any partition table.");
351 return -errno
?: -EIO
;
353 m
= new0(DissectedImage
, 1);
357 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
361 if (!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
362 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) {
363 const char *usage
= NULL
;
365 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
366 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
367 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
368 const char *fstype
= NULL
;
370 /* OK, we have found a file system, that's our root partition then. */
371 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
379 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
383 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
387 .architecture
= _ARCHITECTURE_INVALID
,
388 .fstype
= TAKE_PTR(t
),
392 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
394 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
404 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
408 is_gpt
= streq_ptr(pttype
, "gpt");
409 is_mbr
= streq_ptr(pttype
, "dos");
411 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
415 pl
= blkid_probe_get_partitions(b
);
417 return -errno
?: -ENOMEM
;
419 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
423 FOREACH_DEVICE(e
, q
) {
424 unsigned long long pflags
;
430 r
= sd_device_get_devnum(q
, &qn
);
434 if (st
.st_rdev
== qn
)
437 if (!device_is_block(q
))
440 if (device_is_mmc_special_partition(q
))
443 r
= sd_device_get_devname(q
, &node
);
447 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
451 pflags
= blkid_partition_get_flags(pp
);
453 nr
= blkid_partition_get_partno(pp
);
458 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
459 const char *stype
, *sid
, *fstype
= NULL
;
460 sd_id128_t type_id
, id
;
463 sid
= blkid_partition_get_uuid(pp
);
466 if (sd_id128_from_string(sid
, &id
) < 0)
469 stype
= blkid_partition_get_type_string(pp
);
472 if (sd_id128_from_string(stype
, &type_id
) < 0)
475 if (sd_id128_equal(type_id
, GPT_HOME
)) {
477 if (pflags
& GPT_FLAG_NO_AUTO
)
480 designator
= PARTITION_HOME
;
481 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
482 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
484 if (pflags
& GPT_FLAG_NO_AUTO
)
487 designator
= PARTITION_SRV
;
488 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
489 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
491 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
492 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
493 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
495 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
498 designator
= PARTITION_ESP
;
501 #ifdef GPT_ROOT_NATIVE
502 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
504 if (pflags
& GPT_FLAG_NO_AUTO
)
507 /* If a root ID is specified, ignore everything but the root id */
508 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
511 designator
= PARTITION_ROOT
;
512 architecture
= native_architecture();
513 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
514 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
516 if (pflags
& GPT_FLAG_NO_AUTO
)
519 m
->can_verity
= true;
521 /* Ignore verity unless a root hash is specified */
522 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
525 designator
= PARTITION_ROOT_VERITY
;
526 fstype
= "DM_verity_hash";
527 architecture
= native_architecture();
531 #ifdef GPT_ROOT_SECONDARY
532 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
534 if (pflags
& GPT_FLAG_NO_AUTO
)
537 /* If a root ID is specified, ignore everything but the root id */
538 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
541 designator
= PARTITION_ROOT_SECONDARY
;
542 architecture
= SECONDARY_ARCHITECTURE
;
543 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
544 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
546 if (pflags
& GPT_FLAG_NO_AUTO
)
549 m
->can_verity
= true;
551 /* Ignore verity unless root has is specified */
552 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
555 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
556 fstype
= "DM_verity_hash";
557 architecture
= SECONDARY_ARCHITECTURE
;
561 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
563 if (pflags
& GPT_FLAG_NO_AUTO
)
566 designator
= PARTITION_SWAP
;
568 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
570 if (pflags
& GPT_FLAG_NO_AUTO
)
574 multiple_generic
= true;
577 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
579 generic_node
= strdup(node
);
585 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
586 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
589 if (m
->partitions
[designator
].found
)
602 m
->partitions
[designator
] = (DissectedPartition
) {
606 .architecture
= architecture
,
608 .fstype
= TAKE_PTR(t
),
615 if (pflags
!= 0x80) /* Bootable flag */
618 if (blkid_partition_get_type(pp
) != 0x83) /* Linux partition */
622 multiple_generic
= true;
626 generic_node
= strdup(node
);
633 if (!m
->partitions
[PARTITION_ROOT
].found
) {
634 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
635 * either, then check if there's a single generic one, and use that. */
637 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
638 return -EADDRNOTAVAIL
;
640 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
641 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
642 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
644 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
645 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
647 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
649 /* If the root has was set, then we won't fallback to a generic node, because the root hash
652 return -EADDRNOTAVAIL
;
654 /* If we didn't find a generic node, then we can't fix this up either */
658 /* If we didn't find a properly marked root partition, but we did find a single suitable
659 * generic Linux partition, then use this as root partition, if the caller asked for it. */
660 if (multiple_generic
)
663 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
666 .partno
= generic_nr
,
667 .architecture
= _ARCHITECTURE_INVALID
,
668 .node
= TAKE_PTR(generic_node
),
669 .uuid
= generic_uuid
,
675 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
676 return -EADDRNOTAVAIL
;
678 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
679 * (which would be weird, after all the root hash should only be assigned to one pair of
681 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
682 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
684 /* If we found a verity setup, then the root partition is necessarily read-only. */
685 m
->partitions
[PARTITION_ROOT
].rw
= false;
693 /* Fill in file system types if we don't know them yet. */
694 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
695 DissectedPartition
*p
= m
->partitions
+ i
;
700 if (!p
->fstype
&& p
->node
) {
701 r
= probe_filesystem(p
->node
, &p
->fstype
);
702 if (r
< 0 && r
!= -EUCLEAN
)
706 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
709 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
721 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
727 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
728 free(m
->partitions
[i
].fstype
);
729 free(m
->partitions
[i
].node
);
730 free(m
->partitions
[i
].decrypted_fstype
);
731 free(m
->partitions
[i
].decrypted_node
);
735 strv_free(m
->machine_info
);
736 strv_free(m
->os_release
);
741 static int is_loop_device(const char *path
) {
742 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
747 if (stat(path
, &st
) < 0)
750 if (!S_ISBLK(st
.st_mode
))
753 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
754 if (access(s
, F_OK
) < 0) {
758 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
759 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
760 if (access(s
, F_OK
) < 0)
761 return errno
== ENOENT
? false : -errno
;
767 static int mount_partition(
768 DissectedPartition
*m
,
770 const char *directory
,
772 DissectImageFlags flags
) {
774 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
775 const char *p
, *node
, *fstype
;
782 node
= m
->decrypted_node
?: m
->node
;
783 fstype
= m
->decrypted_fstype
?: m
->fstype
;
785 if (!m
->found
|| !node
|| !fstype
)
788 /* Stacked encryption? Yuck */
789 if (streq_ptr(fstype
, "crypto_LUKS"))
792 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
795 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
);
803 /* If requested, turn on discard support. */
804 if (fstype_can_discard(fstype
) &&
805 ((flags
& DISSECT_IMAGE_DISCARD
) ||
806 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
807 options
= strdup("discard");
812 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
813 _cleanup_free_
char *uid_option
= NULL
;
815 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
818 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
822 return mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
825 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
831 if (!m
->partitions
[PARTITION_ROOT
].found
)
834 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
835 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
839 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
840 r
= path_is_os_tree(where
);
848 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
851 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
855 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
859 if (m
->partitions
[PARTITION_ESP
].found
) {
862 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
864 FOREACH_STRING(mp
, "/efi", "/boot") {
865 _cleanup_free_
char *p
= NULL
;
867 r
= chase_symlinks(mp
, where
, CHASE_PREFIX_ROOT
, &p
);
873 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, mp
, uid_shift
, flags
);
883 #if HAVE_LIBCRYPTSETUP
884 typedef struct DecryptedPartition
{
885 struct crypt_device
*device
;
888 } DecryptedPartition
;
890 struct DecryptedImage
{
891 DecryptedPartition
*decrypted
;
897 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
898 #if HAVE_LIBCRYPTSETUP
905 for (i
= 0; i
< d
->n_decrypted
; i
++) {
906 DecryptedPartition
*p
= d
->decrypted
+ i
;
908 if (p
->device
&& p
->name
&& !p
->relinquished
) {
909 r
= crypt_deactivate(p
->device
, p
->name
);
911 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
915 crypt_free(p
->device
);
924 #if HAVE_LIBCRYPTSETUP
926 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
927 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
930 assert(original_node
);
935 base
= strrchr(original_node
, '/');
942 name
= strjoin(base
, suffix
);
945 if (!filename_is_valid(name
))
948 node
= strjoin(crypt_get_dir(), "/", name
);
952 *ret_name
= TAKE_PTR(name
);
953 *ret_node
= TAKE_PTR(node
);
958 static int decrypt_partition(
959 DissectedPartition
*m
,
960 const char *passphrase
,
961 DissectImageFlags flags
,
964 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
965 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
971 if (!m
->found
|| !m
->node
|| !m
->fstype
)
974 if (!streq(m
->fstype
, "crypto_LUKS"))
980 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
984 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
987 r
= crypt_init(&cd
, m
->node
);
989 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
991 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
993 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
995 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
996 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
997 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
999 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1000 return r
== -EPERM
? -EKEYREJECTED
: r
;
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
);
1012 static int verity_partition(
1013 DissectedPartition
*m
,
1014 DissectedPartition
*v
,
1015 const void *root_hash
,
1016 size_t root_hash_size
,
1017 DissectImageFlags flags
,
1018 DecryptedImage
*d
) {
1020 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1021 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1030 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1032 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1035 if (!streq(v
->fstype
, "DM_verity_hash"))
1038 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1042 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1045 r
= crypt_init(&cd
, v
->node
);
1049 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1053 r
= crypt_set_data_device(cd
, m
->node
);
1057 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1061 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1062 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1065 m
->decrypted_node
= TAKE_PTR(node
);
1071 int dissected_image_decrypt(
1073 const char *passphrase
,
1074 const void *root_hash
,
1075 size_t root_hash_size
,
1076 DissectImageFlags flags
,
1077 DecryptedImage
**ret
) {
1079 #if HAVE_LIBCRYPTSETUP
1080 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1086 assert(root_hash
|| root_hash_size
== 0);
1090 * = 0 → There was nothing to decrypt
1091 * > 0 → Decrypted successfully
1092 * -ENOKEY → There's something to decrypt but no key was supplied
1093 * -EKEYREJECTED → Passed key was not correct
1096 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1099 if (!m
->encrypted
&& !m
->verity
) {
1104 #if HAVE_LIBCRYPTSETUP
1105 d
= new0(DecryptedImage
, 1);
1109 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1110 DissectedPartition
*p
= m
->partitions
+ i
;
1116 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1120 k
= PARTITION_VERITY_OF(i
);
1122 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, flags
, d
);
1127 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1128 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1129 if (r
< 0 && r
!= -EUCLEAN
)
1142 int dissected_image_decrypt_interactively(
1144 const char *passphrase
,
1145 const void *root_hash
,
1146 size_t root_hash_size
,
1147 DissectImageFlags flags
,
1148 DecryptedImage
**ret
) {
1150 _cleanup_strv_free_erase_
char **z
= NULL
;
1157 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, flags
, ret
);
1160 if (r
== -EKEYREJECTED
)
1161 log_error_errno(r
, "Incorrect passphrase, try again!");
1162 else if (r
!= -ENOKEY
)
1163 return log_error_errno(r
, "Failed to decrypt image: %m");
1166 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1167 "Too many retries.");
1171 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1173 return log_error_errno(r
, "Failed to query for passphrase: %m");
1179 #if HAVE_LIBCRYPTSETUP
1180 static int deferred_remove(DecryptedPartition
*p
) {
1182 struct dm_ioctl dm
= {
1186 DM_VERSION_PATCHLEVEL
1188 .data_size
= sizeof(dm
),
1189 .flags
= DM_DEFERRED_REMOVE
,
1192 _cleanup_close_
int fd
= -1;
1196 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1198 fd
= open("/dev/mapper/control", O_RDWR
|O_CLOEXEC
);
1202 strncpy(dm
.name
, p
->name
, sizeof(dm
.name
));
1204 if (ioctl(fd
, DM_DEV_REMOVE
, &dm
))
1211 int decrypted_image_relinquish(DecryptedImage
*d
) {
1213 #if HAVE_LIBCRYPTSETUP
1220 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1221 * that we don't clean it up ourselves either anymore */
1223 #if HAVE_LIBCRYPTSETUP
1224 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1225 DecryptedPartition
*p
= d
->decrypted
+ i
;
1227 if (p
->relinquished
)
1230 r
= deferred_remove(p
);
1232 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1234 p
->relinquished
= true;
1241 int root_hash_load(const char *image
, void **ret
, size_t *ret_size
) {
1242 _cleanup_free_
char *text
= NULL
;
1243 _cleanup_free_
void *k
= NULL
;
1251 if (is_device_path(image
)) {
1252 /* If we are asked to load the root hash for a device node, exit early */
1258 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1262 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1265 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1266 n
= stpcpy(fn
, image
);
1267 e
= endswith(fn
, ".raw");
1271 strcpy(n
, ".roothash");
1273 r
= read_one_line_file(fn
, &text
);
1283 r
= unhexmem(text
, strlen(text
), &k
, &l
);
1286 if (l
< sizeof(sd_id128_t
))
1295 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1305 static const char *const paths
[_META_MAX
] = {
1306 [META_HOSTNAME
] = "/etc/hostname\0",
1307 [META_MACHINE_ID
] = "/etc/machine-id\0",
1308 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1309 [META_OS_RELEASE
] = "/etc/os-release\0/usr/lib/os-release\0",
1312 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1313 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1314 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1315 sd_id128_t machine_id
= SD_ID128_NULL
;
1316 _cleanup_free_
char *hostname
= NULL
;
1317 unsigned n_meta_initialized
= 0, k
;
1318 int fds
[2 * _META_MAX
], r
;
1320 BLOCK_SIGNALS(SIGCHLD
);
1324 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1325 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1330 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1334 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1338 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1340 log_debug_errno(r
, "Failed to mount dissected image: %m");
1341 _exit(EXIT_FAILURE
);
1344 for (k
= 0; k
< _META_MAX
; k
++) {
1345 _cleanup_close_
int fd
= -1;
1348 fds
[2*k
] = safe_close(fds
[2*k
]);
1350 NULSTR_FOREACH(p
, paths
[k
]) {
1351 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1356 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1360 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1362 _exit(EXIT_FAILURE
);
1364 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1367 _exit(EXIT_SUCCESS
);
1370 for (k
= 0; k
< _META_MAX
; k
++) {
1371 _cleanup_fclose_
FILE *f
= NULL
;
1373 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1375 f
= fdopen(fds
[2*k
], "r");
1386 r
= read_etc_hostname_stream(f
, &hostname
);
1388 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1392 case META_MACHINE_ID
: {
1393 _cleanup_free_
char *line
= NULL
;
1395 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1397 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1399 r
= sd_id128_from_string(line
, &machine_id
);
1401 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1403 log_debug("/etc/machine-id file is empty.");
1405 log_debug("/etc/machine-id has unexpected length %i.", r
);
1410 case META_MACHINE_INFO
:
1411 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1413 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1417 case META_OS_RELEASE
:
1418 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1420 log_debug_errno(r
, "Failed to read OS release file: %m");
1426 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1430 if (r
!= EXIT_SUCCESS
)
1433 free_and_replace(m
->hostname
, hostname
);
1434 m
->machine_id
= machine_id
;
1435 strv_free_and_replace(m
->machine_info
, machine_info
);
1436 strv_free_and_replace(m
->os_release
, os_release
);
1439 for (k
= 0; k
< n_meta_initialized
; k
++)
1440 safe_close_pair(fds
+ 2*k
);
1445 int dissect_image_and_warn(
1448 const void *root_hash
,
1449 size_t root_hash_size
,
1450 DissectImageFlags flags
,
1451 DissectedImage
**ret
) {
1453 _cleanup_free_
char *buffer
= NULL
;
1457 r
= fd_get_path(fd
, &buffer
);
1464 r
= dissect_image(fd
, root_hash
, root_hash_size
, flags
, ret
);
1469 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1472 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1474 case -EADDRNOTAVAIL
:
1475 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1478 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1481 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1483 case -EPROTONOSUPPORT
:
1484 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1488 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1494 static const char *const partition_designator_table
[] = {
1495 [PARTITION_ROOT
] = "root",
1496 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1497 [PARTITION_HOME
] = "home",
1498 [PARTITION_SRV
] = "srv",
1499 [PARTITION_ESP
] = "esp",
1500 [PARTITION_SWAP
] = "swap",
1501 [PARTITION_ROOT_VERITY
] = "root-verity",
1502 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1505 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);