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"
32 #include "nulstr-util.h"
34 #include "path-util.h"
35 #include "process-util.h"
36 #include "raw-clone.h"
37 #include "signal-util.h"
38 #include "stat-util.h"
39 #include "stdio-util.h"
40 #include "string-table.h"
41 #include "string-util.h"
43 #include "tmpfile-util.h"
44 #include "udev-util.h"
45 #include "user-util.h"
46 #include "xattr-util.h"
48 int probe_filesystem(const char *node
, char **ret_fstype
) {
49 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
50 * 0/NULL will be returned. -EUCLEAN will be returned for ambigous results, and an
51 * different error otherwise. */
54 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
59 b
= blkid_new_probe_from_filename(node
);
61 return -errno
?: -ENOMEM
;
63 blkid_probe_enable_superblocks(b
, 1);
64 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
67 r
= blkid_do_safeprobe(b
);
69 log_debug("No type detected on partition %s", node
);
73 log_debug("Results ambiguous for partition %s", node
);
77 return -errno
?: -EIO
;
79 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
101 /* Detect RPMB and Boot partitions, which are not listed by blkid.
102 * See https://github.com/systemd/systemd/issues/5806. */
103 static bool device_is_mmc_special_partition(sd_device
*d
) {
108 if (sd_device_get_sysname(d
, &sysname
) < 0)
111 return startswith(sysname
, "mmcblk") &&
112 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
115 static bool device_is_block(sd_device
*d
) {
120 if (sd_device_get_subsystem(d
, &ss
) < 0)
123 return streq(ss
, "block");
126 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
127 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
133 r
= sd_device_enumerator_new(&e
);
137 r
= sd_device_enumerator_allow_uninitialized(e
);
141 r
= sd_device_enumerator_add_match_parent(e
, d
);
149 /* how many times to wait for the device nodes to appear */
150 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
152 static int wait_for_partitions_to_appear(
155 unsigned num_partitions
,
156 DissectImageFlags flags
,
157 sd_device_enumerator
**ret_enumerator
) {
159 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
166 assert(ret_enumerator
);
168 r
= enumerator_for_parent(d
, &e
);
172 /* Count the partitions enumerated by the kernel */
174 FOREACH_DEVICE(e
, q
) {
175 if (sd_device_get_devnum(q
, NULL
) < 0)
177 if (!device_is_block(q
))
179 if (device_is_mmc_special_partition(q
))
182 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
183 r
= device_wait_for_initialization(q
, "block", NULL
);
191 if (n
== num_partitions
+ 1) {
192 *ret_enumerator
= TAKE_PTR(e
);
193 return 0; /* success! */
195 if (n
> num_partitions
+ 1)
196 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
197 "blkid and kernel partition lists do not match.");
199 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
200 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
201 * call that waits until probing is complete. */
203 for (unsigned j
= 0; ; j
++) {
207 if (ioctl(fd
, BLKRRPART
, 0) >= 0)
211 struct loop_info64 info
;
213 /* If we are running on a loop device that has partition scanning off, return
214 * an explicit recognizable error about this, so that callers can generate a
215 * proper message explaining the situation. */
217 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0 && (info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0) {
218 log_debug("Device is a loop device and partition scanning is off!");
219 return -EPROTONOSUPPORT
;
225 /* If something else has the device open, such as an udev rule, the ioctl will return
226 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
229 * This is really something they should fix in the kernel! */
230 (void) usleep(50 * USEC_PER_MSEC
);
234 return -EAGAIN
; /* no success yet, try again */
237 static int loop_wait_for_partitions_to_appear(
240 unsigned num_partitions
,
241 DissectImageFlags flags
,
242 sd_device_enumerator
**ret_enumerator
) {
243 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
248 assert(ret_enumerator
);
250 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions
);
252 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
253 r
= device_wait_for_initialization(d
, "block", &device
);
257 device
= sd_device_ref(d
);
259 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
260 r
= wait_for_partitions_to_appear(fd
, device
, num_partitions
, flags
, ret_enumerator
);
265 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
266 "Kernel partitions dit not appear within %d attempts",
267 N_DEVICE_NODE_LIST_ATTEMPTS
);
274 const void *root_hash
,
275 size_t root_hash_size
,
276 DissectImageFlags flags
,
277 DissectedImage
**ret
) {
280 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
281 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
282 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
283 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
284 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
285 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
286 _cleanup_free_
char *generic_node
= NULL
;
287 sd_id128_t generic_uuid
= SD_ID128_NULL
;
288 const char *pttype
= NULL
;
297 assert(root_hash
|| root_hash_size
== 0);
299 /* Probes a disk image, and returns information about what it found in *ret.
301 * Returns -ENOPKG if no suitable partition table or file system could be found.
302 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
305 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
306 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
309 if (root_hash_size
< sizeof(sd_id128_t
))
312 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
313 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
315 if (sd_id128_is_null(root_uuid
))
317 if (sd_id128_is_null(verity_uuid
))
321 if (fstat(fd
, &st
) < 0)
324 if (!S_ISBLK(st
.st_mode
))
327 b
= blkid_new_probe();
332 r
= blkid_probe_set_device(b
, fd
, 0, 0);
334 return -errno
?: -ENOMEM
;
336 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
337 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
338 blkid_probe_enable_superblocks(b
, 1);
339 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
342 blkid_probe_enable_partitions(b
, 1);
343 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
346 r
= blkid_do_safeprobe(b
);
347 if (IN_SET(r
, -2, 1))
348 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
350 return -errno
?: -EIO
;
352 m
= new0(DissectedImage
, 1);
356 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
360 if (!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
361 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) {
362 const char *usage
= NULL
;
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
;
367 const char *fstype
= 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
);
378 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
382 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
386 .architecture
= _ARCHITECTURE_INVALID
,
387 .fstype
= TAKE_PTR(t
),
391 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
393 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
403 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
407 is_gpt
= streq_ptr(pttype
, "gpt");
408 is_mbr
= streq_ptr(pttype
, "dos");
410 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
414 pl
= blkid_probe_get_partitions(b
);
416 return -errno
?: -ENOMEM
;
418 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
422 FOREACH_DEVICE(e
, q
) {
423 unsigned long long pflags
;
429 r
= sd_device_get_devnum(q
, &qn
);
433 if (st
.st_rdev
== qn
)
436 if (!device_is_block(q
))
439 if (device_is_mmc_special_partition(q
))
442 r
= sd_device_get_devname(q
, &node
);
446 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
450 pflags
= blkid_partition_get_flags(pp
);
452 nr
= blkid_partition_get_partno(pp
);
457 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
458 const char *stype
, *sid
, *fstype
= NULL
;
459 sd_id128_t type_id
, id
;
462 sid
= blkid_partition_get_uuid(pp
);
465 if (sd_id128_from_string(sid
, &id
) < 0)
468 stype
= blkid_partition_get_type_string(pp
);
471 if (sd_id128_from_string(stype
, &type_id
) < 0)
474 if (sd_id128_equal(type_id
, GPT_HOME
)) {
476 if (pflags
& GPT_FLAG_NO_AUTO
)
479 designator
= PARTITION_HOME
;
480 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
481 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
483 if (pflags
& GPT_FLAG_NO_AUTO
)
486 designator
= PARTITION_SRV
;
487 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
488 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
490 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
491 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
492 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
494 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
497 designator
= PARTITION_ESP
;
500 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
502 if (pflags
& GPT_FLAG_NO_AUTO
)
505 designator
= PARTITION_XBOOTLDR
;
506 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
508 #ifdef GPT_ROOT_NATIVE
509 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
511 if (pflags
& GPT_FLAG_NO_AUTO
)
514 /* If a root ID is specified, ignore everything but the root id */
515 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
518 designator
= PARTITION_ROOT
;
519 architecture
= native_architecture();
520 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
521 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
523 if (pflags
& GPT_FLAG_NO_AUTO
)
526 m
->can_verity
= true;
528 /* Ignore verity unless a root hash is specified */
529 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
532 designator
= PARTITION_ROOT_VERITY
;
533 fstype
= "DM_verity_hash";
534 architecture
= native_architecture();
538 #ifdef GPT_ROOT_SECONDARY
539 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
541 if (pflags
& GPT_FLAG_NO_AUTO
)
544 /* If a root ID is specified, ignore everything but the root id */
545 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
548 designator
= PARTITION_ROOT_SECONDARY
;
549 architecture
= SECONDARY_ARCHITECTURE
;
550 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
551 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
553 if (pflags
& GPT_FLAG_NO_AUTO
)
556 m
->can_verity
= true;
558 /* Ignore verity unless root has is specified */
559 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
562 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
563 fstype
= "DM_verity_hash";
564 architecture
= SECONDARY_ARCHITECTURE
;
568 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
570 if (pflags
& GPT_FLAG_NO_AUTO
)
573 designator
= PARTITION_SWAP
;
575 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
577 if (pflags
& GPT_FLAG_NO_AUTO
)
581 multiple_generic
= true;
584 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
586 generic_node
= strdup(node
);
592 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
593 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
596 if (m
->partitions
[designator
].found
)
609 m
->partitions
[designator
] = (DissectedPartition
) {
613 .architecture
= architecture
,
615 .fstype
= TAKE_PTR(t
),
622 switch (blkid_partition_get_type(pp
)) {
624 case 0x83: /* Linux partition */
626 if (pflags
!= 0x80) /* Bootable flag */
630 multiple_generic
= true;
634 generic_node
= strdup(node
);
641 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
642 _cleanup_free_
char *n
= NULL
;
643 sd_id128_t id
= SD_ID128_NULL
;
647 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
650 sid
= blkid_partition_get_uuid(pp
);
652 (void) sd_id128_from_string(sid
, &id
);
658 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
662 .architecture
= _ARCHITECTURE_INVALID
,
672 if (!m
->partitions
[PARTITION_ROOT
].found
) {
673 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
674 * either, then check if there's a single generic one, and use that. */
676 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
677 return -EADDRNOTAVAIL
;
679 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
680 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
681 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
683 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
684 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
686 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
688 /* If the root has was set, then we won't fallback to a generic node, because the root hash
691 return -EADDRNOTAVAIL
;
693 /* If we didn't find a generic node, then we can't fix this up either */
697 /* If we didn't find a properly marked root partition, but we did find a single suitable
698 * generic Linux partition, then use this as root partition, if the caller asked for it. */
699 if (multiple_generic
)
702 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
705 .partno
= generic_nr
,
706 .architecture
= _ARCHITECTURE_INVALID
,
707 .node
= TAKE_PTR(generic_node
),
708 .uuid
= generic_uuid
,
714 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
715 return -EADDRNOTAVAIL
;
717 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
718 * (which would be weird, after all the root hash should only be assigned to one pair of
720 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
721 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
723 /* If we found a verity setup, then the root partition is necessarily read-only. */
724 m
->partitions
[PARTITION_ROOT
].rw
= false;
732 /* Fill in file system types if we don't know them yet. */
733 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
734 DissectedPartition
*p
= m
->partitions
+ i
;
739 if (!p
->fstype
&& p
->node
) {
740 r
= probe_filesystem(p
->node
, &p
->fstype
);
741 if (r
< 0 && r
!= -EUCLEAN
)
745 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
748 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
760 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
766 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
767 free(m
->partitions
[i
].fstype
);
768 free(m
->partitions
[i
].node
);
769 free(m
->partitions
[i
].decrypted_fstype
);
770 free(m
->partitions
[i
].decrypted_node
);
774 strv_free(m
->machine_info
);
775 strv_free(m
->os_release
);
780 static int is_loop_device(const char *path
) {
781 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
786 if (stat(path
, &st
) < 0)
789 if (!S_ISBLK(st
.st_mode
))
792 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
793 if (access(s
, F_OK
) < 0) {
797 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
798 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
799 if (access(s
, F_OK
) < 0)
800 return errno
== ENOENT
? false : -errno
;
806 static int mount_partition(
807 DissectedPartition
*m
,
809 const char *directory
,
811 DissectImageFlags flags
) {
813 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
814 const char *p
, *node
, *fstype
;
821 node
= m
->decrypted_node
?: m
->node
;
822 fstype
= m
->decrypted_fstype
?: m
->fstype
;
824 if (!m
->found
|| !node
|| !fstype
)
827 /* Stacked encryption? Yuck */
828 if (streq_ptr(fstype
, "crypto_LUKS"))
831 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
834 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
);
842 /* If requested, turn on discard support. */
843 if (fstype_can_discard(fstype
) &&
844 ((flags
& DISSECT_IMAGE_DISCARD
) ||
845 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
846 options
= strdup("discard");
851 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
852 _cleanup_free_
char *uid_option
= NULL
;
854 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
857 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
861 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
868 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
874 if (!m
->partitions
[PARTITION_ROOT
].found
)
877 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
878 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
882 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
883 r
= path_is_os_tree(where
);
891 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
894 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
898 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
902 boot_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
903 if (boot_mounted
< 0)
906 if (m
->partitions
[PARTITION_ESP
].found
) {
907 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
908 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
910 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
);
912 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
916 } else if (boot_mounted
<= 0) {
917 _cleanup_free_
char *p
= NULL
;
919 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
);
920 if (r
>= 0 && dir_is_empty(p
) > 0) {
921 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
931 #if HAVE_LIBCRYPTSETUP
932 typedef struct DecryptedPartition
{
933 struct crypt_device
*device
;
936 } DecryptedPartition
;
938 struct DecryptedImage
{
939 DecryptedPartition
*decrypted
;
945 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
946 #if HAVE_LIBCRYPTSETUP
953 for (i
= 0; i
< d
->n_decrypted
; i
++) {
954 DecryptedPartition
*p
= d
->decrypted
+ i
;
956 if (p
->device
&& p
->name
&& !p
->relinquished
) {
957 r
= crypt_deactivate(p
->device
, p
->name
);
959 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
963 crypt_free(p
->device
);
972 #if HAVE_LIBCRYPTSETUP
974 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
975 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
978 assert(original_node
);
983 base
= strrchr(original_node
, '/');
990 name
= strjoin(base
, suffix
);
993 if (!filename_is_valid(name
))
996 node
= strjoin(crypt_get_dir(), "/", name
);
1000 *ret_name
= TAKE_PTR(name
);
1001 *ret_node
= TAKE_PTR(node
);
1006 static int decrypt_partition(
1007 DissectedPartition
*m
,
1008 const char *passphrase
,
1009 DissectImageFlags flags
,
1010 DecryptedImage
*d
) {
1012 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1013 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1019 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1022 if (!streq(m
->fstype
, "crypto_LUKS"))
1028 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1032 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1035 r
= crypt_init(&cd
, m
->node
);
1037 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1039 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
1041 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1043 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1044 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1045 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1047 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1048 return r
== -EPERM
? -EKEYREJECTED
: r
;
1051 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1052 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1055 m
->decrypted_node
= TAKE_PTR(node
);
1060 static int verity_partition(
1061 DissectedPartition
*m
,
1062 DissectedPartition
*v
,
1063 const void *root_hash
,
1064 size_t root_hash_size
,
1065 DissectImageFlags flags
,
1066 DecryptedImage
*d
) {
1068 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1069 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1078 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1080 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1083 if (!streq(v
->fstype
, "DM_verity_hash"))
1086 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1090 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1093 r
= crypt_init(&cd
, v
->node
);
1097 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1101 r
= crypt_set_data_device(cd
, m
->node
);
1105 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1109 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1110 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1113 m
->decrypted_node
= TAKE_PTR(node
);
1119 int dissected_image_decrypt(
1121 const char *passphrase
,
1122 const void *root_hash
,
1123 size_t root_hash_size
,
1124 DissectImageFlags flags
,
1125 DecryptedImage
**ret
) {
1127 #if HAVE_LIBCRYPTSETUP
1128 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1134 assert(root_hash
|| root_hash_size
== 0);
1138 * = 0 → There was nothing to decrypt
1139 * > 0 → Decrypted successfully
1140 * -ENOKEY → There's something to decrypt but no key was supplied
1141 * -EKEYREJECTED → Passed key was not correct
1144 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1147 if (!m
->encrypted
&& !m
->verity
) {
1152 #if HAVE_LIBCRYPTSETUP
1153 d
= new0(DecryptedImage
, 1);
1157 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1158 DissectedPartition
*p
= m
->partitions
+ i
;
1164 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1168 k
= PARTITION_VERITY_OF(i
);
1170 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, flags
, d
);
1175 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1176 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1177 if (r
< 0 && r
!= -EUCLEAN
)
1190 int dissected_image_decrypt_interactively(
1192 const char *passphrase
,
1193 const void *root_hash
,
1194 size_t root_hash_size
,
1195 DissectImageFlags flags
,
1196 DecryptedImage
**ret
) {
1198 _cleanup_strv_free_erase_
char **z
= NULL
;
1205 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, flags
, ret
);
1208 if (r
== -EKEYREJECTED
)
1209 log_error_errno(r
, "Incorrect passphrase, try again!");
1210 else if (r
!= -ENOKEY
)
1211 return log_error_errno(r
, "Failed to decrypt image: %m");
1214 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1215 "Too many retries.");
1219 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1221 return log_error_errno(r
, "Failed to query for passphrase: %m");
1227 #if HAVE_LIBCRYPTSETUP
1228 static int deferred_remove(DecryptedPartition
*p
) {
1229 struct dm_ioctl dm
= {
1233 DM_VERSION_PATCHLEVEL
1235 .data_size
= sizeof(dm
),
1236 .flags
= DM_DEFERRED_REMOVE
,
1239 _cleanup_close_
int fd
= -1;
1243 /* Unfortunately, libcryptsetup doesn't provide a proper API for this, hence call the ioctl() directly. */
1245 fd
= open("/dev/mapper/control", O_RDWR
|O_CLOEXEC
);
1249 if (strlen(p
->name
) > sizeof(dm
.name
))
1250 return -ENAMETOOLONG
;
1252 strncpy(dm
.name
, p
->name
, sizeof(dm
.name
));
1254 if (ioctl(fd
, DM_DEV_REMOVE
, &dm
))
1261 int decrypted_image_relinquish(DecryptedImage
*d
) {
1263 #if HAVE_LIBCRYPTSETUP
1270 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1271 * that we don't clean it up ourselves either anymore */
1273 #if HAVE_LIBCRYPTSETUP
1274 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1275 DecryptedPartition
*p
= d
->decrypted
+ i
;
1277 if (p
->relinquished
)
1280 r
= deferred_remove(p
);
1282 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1284 p
->relinquished
= true;
1291 int root_hash_load(const char *image
, void **ret
, size_t *ret_size
) {
1292 _cleanup_free_
char *text
= NULL
;
1293 _cleanup_free_
void *k
= NULL
;
1301 if (is_device_path(image
)) {
1302 /* If we are asked to load the root hash for a device node, exit early */
1308 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1312 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1315 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1316 n
= stpcpy(fn
, image
);
1317 e
= endswith(fn
, ".raw");
1321 strcpy(n
, ".roothash");
1323 r
= read_one_line_file(fn
, &text
);
1333 r
= unhexmem(text
, strlen(text
), &k
, &l
);
1336 if (l
< sizeof(sd_id128_t
))
1345 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1355 static const char *const paths
[_META_MAX
] = {
1356 [META_HOSTNAME
] = "/etc/hostname\0",
1357 [META_MACHINE_ID
] = "/etc/machine-id\0",
1358 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1359 [META_OS_RELEASE
] = "/etc/os-release\0/usr/lib/os-release\0",
1362 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1363 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1364 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1365 sd_id128_t machine_id
= SD_ID128_NULL
;
1366 _cleanup_free_
char *hostname
= NULL
;
1367 unsigned n_meta_initialized
= 0, k
;
1368 int fds
[2 * _META_MAX
], r
;
1370 BLOCK_SIGNALS(SIGCHLD
);
1374 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1375 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1380 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1384 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1388 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1390 log_debug_errno(r
, "Failed to mount dissected image: %m");
1391 _exit(EXIT_FAILURE
);
1394 for (k
= 0; k
< _META_MAX
; k
++) {
1395 _cleanup_close_
int fd
= -1;
1398 fds
[2*k
] = safe_close(fds
[2*k
]);
1400 NULSTR_FOREACH(p
, paths
[k
]) {
1401 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1406 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1410 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1412 _exit(EXIT_FAILURE
);
1414 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1417 _exit(EXIT_SUCCESS
);
1420 for (k
= 0; k
< _META_MAX
; k
++) {
1421 _cleanup_fclose_
FILE *f
= NULL
;
1423 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1425 f
= fdopen(fds
[2*k
], "r");
1436 r
= read_etc_hostname_stream(f
, &hostname
);
1438 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1442 case META_MACHINE_ID
: {
1443 _cleanup_free_
char *line
= NULL
;
1445 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1447 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1449 r
= sd_id128_from_string(line
, &machine_id
);
1451 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1453 log_debug("/etc/machine-id file is empty.");
1455 log_debug("/etc/machine-id has unexpected length %i.", r
);
1460 case META_MACHINE_INFO
:
1461 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1463 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1467 case META_OS_RELEASE
:
1468 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1470 log_debug_errno(r
, "Failed to read OS release file: %m");
1476 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1480 if (r
!= EXIT_SUCCESS
)
1483 free_and_replace(m
->hostname
, hostname
);
1484 m
->machine_id
= machine_id
;
1485 strv_free_and_replace(m
->machine_info
, machine_info
);
1486 strv_free_and_replace(m
->os_release
, os_release
);
1489 for (k
= 0; k
< n_meta_initialized
; k
++)
1490 safe_close_pair(fds
+ 2*k
);
1495 int dissect_image_and_warn(
1498 const void *root_hash
,
1499 size_t root_hash_size
,
1500 DissectImageFlags flags
,
1501 DissectedImage
**ret
) {
1503 _cleanup_free_
char *buffer
= NULL
;
1507 r
= fd_get_path(fd
, &buffer
);
1514 r
= dissect_image(fd
, root_hash
, root_hash_size
, flags
, ret
);
1519 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1522 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1524 case -EADDRNOTAVAIL
:
1525 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1528 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1531 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1533 case -EPROTONOSUPPORT
:
1534 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1538 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1544 static const char *const partition_designator_table
[] = {
1545 [PARTITION_ROOT
] = "root",
1546 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1547 [PARTITION_HOME
] = "home",
1548 [PARTITION_SRV
] = "srv",
1549 [PARTITION_ESP
] = "esp",
1550 [PARTITION_XBOOTLDR
] = "xbootldr",
1551 [PARTITION_SWAP
] = "swap",
1552 [PARTITION_ROOT_VERITY
] = "root-verity",
1553 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1556 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);