1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2016 Lennart Poettering
12 #include "architecture.h"
13 #include "ask-password-api.h"
14 #include "blkid-util.h"
15 #include "blockdev-util.h"
17 #include "crypt-util.h"
19 #include "device-nodes.h"
20 #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"
32 #include "path-util.h"
33 #include "process-util.h"
34 #include "raw-clone.h"
35 #include "signal-util.h"
36 #include "stat-util.h"
37 #include "stdio-util.h"
38 #include "string-table.h"
39 #include "string-util.h"
41 #include "udev-util.h"
42 #include "user-util.h"
43 #include "xattr-util.h"
45 int probe_filesystem(const char *node
, char **ret_fstype
) {
46 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
47 * 0/NULL will be returned. -EUCLEAN will be returned for ambigous results, and an
48 * different error otherwise. */
51 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
56 b
= blkid_new_probe_from_filename(node
);
58 return -errno
?: -ENOMEM
;
60 blkid_probe_enable_superblocks(b
, 1);
61 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
64 r
= blkid_do_safeprobe(b
);
66 log_debug("No type detected on partition %s", node
);
70 log_debug("Results ambiguous for partition %s", node
);
74 return -errno
?: -EIO
;
76 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
98 /* Detect RPMB and Boot partitions, which are not listed by blkid.
99 * See https://github.com/systemd/systemd/issues/5806. */
100 static bool device_is_mmc_special_partition(struct udev_device
*d
) {
103 sysname
= udev_device_get_sysname(d
);
104 return sysname
&& startswith(sysname
, "mmcblk") &&
105 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
108 static bool device_is_block(struct udev_device
*d
) {
111 ss
= udev_device_get_subsystem(d
);
115 return streq(ss
, "block");
121 const void *root_hash
,
122 size_t root_hash_size
,
123 DissectImageFlags flags
,
124 DissectedImage
**ret
) {
127 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
128 _cleanup_(udev_enumerate_unrefp
) struct udev_enumerate
*e
= NULL
;
129 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
130 _cleanup_(udev_device_unrefp
) struct udev_device
*d
= NULL
;
131 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
132 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
133 _cleanup_(udev_unrefp
) struct udev
*udev
= NULL
;
134 _cleanup_free_
char *generic_node
= NULL
;
135 sd_id128_t generic_uuid
= SD_ID128_NULL
;
136 const char *pttype
= NULL
;
137 struct udev_list_entry
*first
, *item
;
145 assert(root_hash
|| root_hash_size
== 0);
147 /* Probes a disk image, and returns information about what it found in *ret.
149 * Returns -ENOPKG if no suitable partition table or file system could be found.
150 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
153 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
154 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
157 if (root_hash_size
< sizeof(sd_id128_t
))
160 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
161 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
163 if (sd_id128_is_null(root_uuid
))
165 if (sd_id128_is_null(verity_uuid
))
169 if (fstat(fd
, &st
) < 0)
172 if (!S_ISBLK(st
.st_mode
))
175 b
= blkid_new_probe();
180 r
= blkid_probe_set_device(b
, fd
, 0, 0);
182 return -errno
?: -ENOMEM
;
184 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
185 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
186 blkid_probe_enable_superblocks(b
, 1);
187 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
190 blkid_probe_enable_partitions(b
, 1);
191 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
194 r
= blkid_do_safeprobe(b
);
195 if (IN_SET(r
, -2, 1)) {
196 log_debug("Failed to identify any partition table.");
200 return -errno
?: -EIO
;
202 m
= new0(DissectedImage
, 1);
206 if (!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
207 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) {
208 const char *usage
= NULL
;
210 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
211 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
212 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
213 const char *fstype
= NULL
;
215 /* OK, we have found a file system, that's our root partition then. */
216 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
224 if (asprintf(&n
, "/dev/block/%u:%u", major(st
.st_rdev
), minor(st
.st_rdev
)) < 0)
227 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
231 .architecture
= _ARCHITECTURE_INVALID
,
232 .fstype
= TAKE_PTR(t
),
236 m
->encrypted
= streq(fstype
, "crypto_LUKS");
244 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
248 is_gpt
= streq_ptr(pttype
, "gpt");
249 is_mbr
= streq_ptr(pttype
, "dos");
251 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
255 pl
= blkid_probe_get_partitions(b
);
257 return -errno
?: -ENOMEM
;
263 d
= udev_device_new_from_devnum(udev
, 'b', st
.st_rdev
);
271 log_debug("Kernel partitions never appeared.");
275 e
= udev_enumerate_new(udev
);
279 r
= udev_enumerate_add_match_parent(e
, d
);
283 r
= udev_enumerate_scan_devices(e
);
287 /* Count the partitions enumerated by the kernel */
289 first
= udev_enumerate_get_list_entry(e
);
290 udev_list_entry_foreach(item
, first
) {
291 _cleanup_(udev_device_unrefp
) struct udev_device
*q
;
294 q
= udev_device_new_from_syspath(udev
, udev_list_entry_get_name(item
));
298 qn
= udev_device_get_devnum(q
);
302 if (!device_is_block(q
))
305 if (device_is_mmc_special_partition(q
))
310 /* Count the partitions enumerated by blkid */
311 z
= blkid_partlist_numof_partitions(pl
);
315 log_debug("blkid and kernel partition list do not match.");
321 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running
322 * or it got EBUSY because udev already opened the device. Let's reprobe the device, which is a
323 * synchronous call that waits until probing is complete. */
329 if (ioctl(fd
, BLKRRPART
, 0) < 0) {
333 struct loop_info64 info
;
335 /* If we are running on a loop device that has partition scanning off,
336 * return an explicit recognizable error about this, so that callers
337 * can generate a proper message explaining the situation. */
339 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0 && (info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0) {
340 log_debug("Device is loop device and partition scanning is off!");
341 return -EPROTONOSUPPORT
;
349 /* If something else has the device open, such as an udev rule, the ioctl will return
350 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a
351 * bit, and try again.
353 * This is really something they should fix in the kernel! */
355 (void) usleep(50 * USEC_PER_MSEC
);
359 e
= udev_enumerate_unref(e
);
362 first
= udev_enumerate_get_list_entry(e
);
363 udev_list_entry_foreach(item
, first
) {
364 _cleanup_(udev_device_unrefp
) struct udev_device
*q
;
365 unsigned long long pflags
;
371 q
= udev_device_new_from_syspath(udev
, udev_list_entry_get_name(item
));
375 qn
= udev_device_get_devnum(q
);
379 if (st
.st_rdev
== qn
)
382 if (!device_is_block(q
))
385 if (device_is_mmc_special_partition(q
))
388 node
= udev_device_get_devnode(q
);
392 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
396 pflags
= blkid_partition_get_flags(pp
);
398 nr
= blkid_partition_get_partno(pp
);
403 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
404 const char *stype
, *sid
, *fstype
= NULL
;
405 sd_id128_t type_id
, id
;
408 sid
= blkid_partition_get_uuid(pp
);
411 if (sd_id128_from_string(sid
, &id
) < 0)
414 stype
= blkid_partition_get_type_string(pp
);
417 if (sd_id128_from_string(stype
, &type_id
) < 0)
420 if (sd_id128_equal(type_id
, GPT_HOME
)) {
422 if (pflags
& GPT_FLAG_NO_AUTO
)
425 designator
= PARTITION_HOME
;
426 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
427 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
429 if (pflags
& GPT_FLAG_NO_AUTO
)
432 designator
= PARTITION_SRV
;
433 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
434 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
436 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
437 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
438 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
440 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
443 designator
= PARTITION_ESP
;
446 #ifdef GPT_ROOT_NATIVE
447 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
449 if (pflags
& GPT_FLAG_NO_AUTO
)
452 /* If a root ID is specified, ignore everything but the root id */
453 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
456 designator
= PARTITION_ROOT
;
457 architecture
= native_architecture();
458 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
459 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
461 if (pflags
& GPT_FLAG_NO_AUTO
)
464 m
->can_verity
= true;
466 /* Ignore verity unless a root hash is specified */
467 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
470 designator
= PARTITION_ROOT_VERITY
;
471 fstype
= "DM_verity_hash";
472 architecture
= native_architecture();
476 #ifdef GPT_ROOT_SECONDARY
477 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
479 if (pflags
& GPT_FLAG_NO_AUTO
)
482 /* If a root ID is specified, ignore everything but the root id */
483 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
486 designator
= PARTITION_ROOT_SECONDARY
;
487 architecture
= SECONDARY_ARCHITECTURE
;
488 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
489 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
491 if (pflags
& GPT_FLAG_NO_AUTO
)
494 m
->can_verity
= true;
496 /* Ignore verity unless root has is specified */
497 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
500 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
501 fstype
= "DM_verity_hash";
502 architecture
= SECONDARY_ARCHITECTURE
;
506 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
508 if (pflags
& GPT_FLAG_NO_AUTO
)
511 designator
= PARTITION_SWAP
;
513 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
515 if (pflags
& GPT_FLAG_NO_AUTO
)
519 multiple_generic
= true;
522 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
524 generic_node
= strdup(node
);
530 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
531 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
534 if (m
->partitions
[designator
].found
)
547 m
->partitions
[designator
] = (DissectedPartition
) {
551 .architecture
= architecture
,
553 .fstype
= TAKE_PTR(t
),
560 if (pflags
!= 0x80) /* Bootable flag */
563 if (blkid_partition_get_type(pp
) != 0x83) /* Linux partition */
567 multiple_generic
= true;
571 generic_node
= strdup(node
);
578 if (!m
->partitions
[PARTITION_ROOT
].found
) {
579 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
580 * either, then check if there's a single generic one, and use that. */
582 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
583 return -EADDRNOTAVAIL
;
585 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
586 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
587 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
589 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
590 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
592 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
594 /* If the root has was set, then we won't fallback to a generic node, because the root hash
597 return -EADDRNOTAVAIL
;
599 /* If we didn't find a generic node, then we can't fix this up either */
603 /* If we didn't find a properly marked root partition, but we did find a single suitable
604 * generic Linux partition, then use this as root partition, if the caller asked for it. */
605 if (multiple_generic
)
608 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
611 .partno
= generic_nr
,
612 .architecture
= _ARCHITECTURE_INVALID
,
613 .node
= TAKE_PTR(generic_node
),
614 .uuid
= generic_uuid
,
620 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
621 return -EADDRNOTAVAIL
;
623 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
624 * (which would be weird, after all the root hash should only be assigned to one pair of
626 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
627 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
629 /* If we found a verity setup, then the root partition is necessarily read-only. */
630 m
->partitions
[PARTITION_ROOT
].rw
= false;
638 /* Fill in file system types if we don't know them yet. */
639 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
640 DissectedPartition
*p
= m
->partitions
+ i
;
645 if (!p
->fstype
&& p
->node
) {
646 r
= probe_filesystem(p
->node
, &p
->fstype
);
647 if (r
< 0 && r
!= -EUCLEAN
)
651 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
654 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
666 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
672 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
673 free(m
->partitions
[i
].fstype
);
674 free(m
->partitions
[i
].node
);
675 free(m
->partitions
[i
].decrypted_fstype
);
676 free(m
->partitions
[i
].decrypted_node
);
680 strv_free(m
->machine_info
);
681 strv_free(m
->os_release
);
686 static int is_loop_device(const char *path
) {
687 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
692 if (stat(path
, &st
) < 0)
695 if (!S_ISBLK(st
.st_mode
))
698 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
699 if (access(s
, F_OK
) < 0) {
703 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
704 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
705 if (access(s
, F_OK
) < 0)
706 return errno
== ENOENT
? false : -errno
;
712 static int mount_partition(
713 DissectedPartition
*m
,
715 const char *directory
,
717 DissectImageFlags flags
) {
719 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
720 const char *p
, *node
, *fstype
;
727 node
= m
->decrypted_node
?: m
->node
;
728 fstype
= m
->decrypted_fstype
?: m
->fstype
;
730 if (!m
->found
|| !node
|| !fstype
)
733 /* Stacked encryption? Yuck */
734 if (streq_ptr(fstype
, "crypto_LUKS"))
737 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
740 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
);
748 /* If requested, turn on discard support. */
749 if (fstype_can_discard(fstype
) &&
750 ((flags
& DISSECT_IMAGE_DISCARD
) ||
751 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
752 options
= strdup("discard");
757 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
758 _cleanup_free_
char *uid_option
= NULL
;
760 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
763 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
767 return mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
770 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
776 if (!m
->partitions
[PARTITION_ROOT
].found
)
779 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
780 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
784 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
785 r
= path_is_os_tree(where
);
793 if ((flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
))
796 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
800 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
804 if (m
->partitions
[PARTITION_ESP
].found
) {
807 /* Mount the ESP to /efi if it exists and is empty. If it doesn't exist, use /boot instead. */
809 FOREACH_STRING(mp
, "/efi", "/boot") {
810 _cleanup_free_
char *p
= NULL
;
812 r
= chase_symlinks(mp
, where
, CHASE_PREFIX_ROOT
, &p
);
818 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, mp
, uid_shift
, flags
);
828 #if HAVE_LIBCRYPTSETUP
829 typedef struct DecryptedPartition
{
830 struct crypt_device
*device
;
833 } DecryptedPartition
;
835 struct DecryptedImage
{
836 DecryptedPartition
*decrypted
;
842 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
843 #if HAVE_LIBCRYPTSETUP
850 for (i
= 0; i
< d
->n_decrypted
; i
++) {
851 DecryptedPartition
*p
= d
->decrypted
+ i
;
853 if (p
->device
&& p
->name
&& !p
->relinquished
) {
854 r
= crypt_deactivate(p
->device
, p
->name
);
856 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
860 crypt_free(p
->device
);
869 #if HAVE_LIBCRYPTSETUP
871 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
872 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
875 assert(original_node
);
880 base
= strrchr(original_node
, '/');
887 name
= strjoin(base
, suffix
);
890 if (!filename_is_valid(name
))
893 node
= strjoin(crypt_get_dir(), "/", name
);
897 *ret_name
= TAKE_PTR(name
);
898 *ret_node
= TAKE_PTR(node
);
903 static int decrypt_partition(
904 DissectedPartition
*m
,
905 const char *passphrase
,
906 DissectImageFlags flags
,
909 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
910 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
916 if (!m
->found
|| !m
->node
|| !m
->fstype
)
919 if (!streq(m
->fstype
, "crypto_LUKS"))
925 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
929 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
932 r
= crypt_init(&cd
, m
->node
);
934 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
936 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
938 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
940 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
941 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
942 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
944 log_debug_errno(r
, "Failed to activate LUKS device: %m");
945 return r
== -EPERM
? -EKEYREJECTED
: r
;
948 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
949 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
952 m
->decrypted_node
= TAKE_PTR(node
);
957 static int verity_partition(
958 DissectedPartition
*m
,
959 DissectedPartition
*v
,
960 const void *root_hash
,
961 size_t root_hash_size
,
962 DissectImageFlags flags
,
965 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
966 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
975 if (!m
->found
|| !m
->node
|| !m
->fstype
)
977 if (!v
->found
|| !v
->node
|| !v
->fstype
)
980 if (!streq(v
->fstype
, "DM_verity_hash"))
983 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
987 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
990 r
= crypt_init(&cd
, v
->node
);
994 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
998 r
= crypt_set_data_device(cd
, m
->node
);
1002 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1006 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1007 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1010 m
->decrypted_node
= TAKE_PTR(node
);
1016 int dissected_image_decrypt(
1018 const char *passphrase
,
1019 const void *root_hash
,
1020 size_t root_hash_size
,
1021 DissectImageFlags flags
,
1022 DecryptedImage
**ret
) {
1024 #if HAVE_LIBCRYPTSETUP
1025 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1031 assert(root_hash
|| root_hash_size
== 0);
1035 * = 0 → There was nothing to decrypt
1036 * > 0 → Decrypted successfully
1037 * -ENOKEY → There's something to decrypt but no key was supplied
1038 * -EKEYREJECTED → Passed key was not correct
1041 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1044 if (!m
->encrypted
&& !m
->verity
) {
1049 #if HAVE_LIBCRYPTSETUP
1050 d
= new0(DecryptedImage
, 1);
1054 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1055 DissectedPartition
*p
= m
->partitions
+ i
;
1061 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1065 k
= PARTITION_VERITY_OF(i
);
1067 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, flags
, d
);
1072 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1073 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1074 if (r
< 0 && r
!= -EUCLEAN
)
1087 int dissected_image_decrypt_interactively(
1089 const char *passphrase
,
1090 const void *root_hash
,
1091 size_t root_hash_size
,
1092 DissectImageFlags flags
,
1093 DecryptedImage
**ret
) {
1095 _cleanup_strv_free_erase_
char **z
= NULL
;
1102 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, flags
, ret
);
1105 if (r
== -EKEYREJECTED
)
1106 log_error_errno(r
, "Incorrect passphrase, try again!");
1107 else if (r
!= -ENOKEY
) {
1108 log_error_errno(r
, "Failed to decrypt image: %m");
1113 log_error("Too many retries.");
1114 return -EKEYREJECTED
;
1119 r
= ask_password_auto("Please enter image passphrase!", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1121 return log_error_errno(r
, "Failed to query for passphrase: %m");
1127 #if HAVE_LIBCRYPTSETUP
1128 static int deferred_remove(DecryptedPartition
*p
) {
1130 struct dm_ioctl dm
= {
1134 DM_VERSION_PATCHLEVEL
1136 .data_size
= sizeof(dm
),
1137 .flags
= DM_DEFERRED_REMOVE
,
1140 _cleanup_close_
int fd
= -1;
1144 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1146 fd
= open("/dev/mapper/control", O_RDWR
|O_CLOEXEC
);
1150 strncpy(dm
.name
, p
->name
, sizeof(dm
.name
));
1152 if (ioctl(fd
, DM_DEV_REMOVE
, &dm
))
1159 int decrypted_image_relinquish(DecryptedImage
*d
) {
1161 #if HAVE_LIBCRYPTSETUP
1168 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1169 * that we don't clean it up ourselves either anymore */
1171 #if HAVE_LIBCRYPTSETUP
1172 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1173 DecryptedPartition
*p
= d
->decrypted
+ i
;
1175 if (p
->relinquished
)
1178 r
= deferred_remove(p
);
1180 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1182 p
->relinquished
= true;
1189 int root_hash_load(const char *image
, void **ret
, size_t *ret_size
) {
1190 _cleanup_free_
char *text
= NULL
;
1191 _cleanup_free_
void *k
= NULL
;
1199 if (is_device_path(image
)) {
1200 /* If we are asked to load the root hash for a device node, exit early */
1206 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1210 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1213 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1214 n
= stpcpy(fn
, image
);
1215 e
= endswith(fn
, ".raw");
1219 strcpy(n
, ".roothash");
1221 r
= read_one_line_file(fn
, &text
);
1231 r
= unhexmem(text
, strlen(text
), &k
, &l
);
1234 if (l
< sizeof(sd_id128_t
))
1243 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1253 static const char *const paths
[_META_MAX
] = {
1254 [META_HOSTNAME
] = "/etc/hostname\0",
1255 [META_MACHINE_ID
] = "/etc/machine-id\0",
1256 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1257 [META_OS_RELEASE
] = "/etc/os-release\0/usr/lib/os-release\0",
1260 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1261 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1262 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1263 sd_id128_t machine_id
= SD_ID128_NULL
;
1264 _cleanup_free_
char *hostname
= NULL
;
1265 unsigned n_meta_initialized
= 0, k
;
1266 int fds
[2 * _META_MAX
], r
;
1268 BLOCK_SIGNALS(SIGCHLD
);
1272 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1273 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1278 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1282 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1286 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1288 log_debug_errno(r
, "Failed to mount dissected image: %m");
1289 _exit(EXIT_FAILURE
);
1292 for (k
= 0; k
< _META_MAX
; k
++) {
1293 _cleanup_close_
int fd
= -1;
1296 fds
[2*k
] = safe_close(fds
[2*k
]);
1298 NULSTR_FOREACH(p
, paths
[k
]) {
1299 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1304 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1308 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1310 _exit(EXIT_FAILURE
);
1312 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1315 _exit(EXIT_SUCCESS
);
1318 for (k
= 0; k
< _META_MAX
; k
++) {
1319 _cleanup_fclose_
FILE *f
= NULL
;
1321 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1323 f
= fdopen(fds
[2*k
], "re");
1334 r
= read_etc_hostname_stream(f
, &hostname
);
1336 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1340 case META_MACHINE_ID
: {
1341 _cleanup_free_
char *line
= NULL
;
1343 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1345 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1347 r
= sd_id128_from_string(line
, &machine_id
);
1349 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1351 log_debug("/etc/machine-id file is empty.");
1353 log_debug("/etc/machine-id has unexpected length %i.", r
);
1358 case META_MACHINE_INFO
:
1359 r
= load_env_file_pairs(f
, "machine-info", NULL
, &machine_info
);
1361 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1365 case META_OS_RELEASE
:
1366 r
= load_env_file_pairs(f
, "os-release", NULL
, &os_release
);
1368 log_debug_errno(r
, "Failed to read OS release file: %m");
1374 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1378 if (r
!= EXIT_SUCCESS
)
1381 free_and_replace(m
->hostname
, hostname
);
1382 m
->machine_id
= machine_id
;
1383 strv_free_and_replace(m
->machine_info
, machine_info
);
1384 strv_free_and_replace(m
->os_release
, os_release
);
1387 for (k
= 0; k
< n_meta_initialized
; k
++)
1388 safe_close_pair(fds
+ 2*k
);
1393 int dissect_image_and_warn(
1396 const void *root_hash
,
1397 size_t root_hash_size
,
1398 DissectImageFlags flags
,
1399 DissectedImage
**ret
) {
1401 _cleanup_free_
char *buffer
= NULL
;
1405 r
= fd_get_path(fd
, &buffer
);
1412 r
= dissect_image(fd
, root_hash
, root_hash_size
, flags
, ret
);
1417 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1420 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1422 case -EADDRNOTAVAIL
:
1423 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1426 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1429 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1431 case -EPROTONOSUPPORT
:
1432 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1436 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1442 static const char *const partition_designator_table
[] = {
1443 [PARTITION_ROOT
] = "root",
1444 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1445 [PARTITION_HOME
] = "home",
1446 [PARTITION_SRV
] = "srv",
1447 [PARTITION_ESP
] = "esp",
1448 [PARTITION_SWAP
] = "swap",
1449 [PARTITION_ROOT_VERITY
] = "root-verity",
1450 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1453 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);