1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 #if HAVE_VALGRIND_MEMCHECK_H
4 #include <valgrind/memcheck.h>
7 #include <linux/dm-ioctl.h>
8 #include <linux/loop.h>
10 #include <sys/prctl.h>
13 #include "sd-device.h"
16 #include "architecture.h"
17 #include "ask-password-api.h"
18 #include "blkid-util.h"
19 #include "blockdev-util.h"
21 #include "crypt-util.h"
23 #include "device-nodes.h"
24 #include "device-util.h"
25 #include "dissect-image.h"
31 #include "fsck-util.h"
33 #include "hexdecoct.h"
34 #include "hostname-util.h"
35 #include "id128-util.h"
36 #include "mount-util.h"
37 #include "mountpoint-util.h"
38 #include "nulstr-util.h"
40 #include "path-util.h"
41 #include "process-util.h"
42 #include "raw-clone.h"
43 #include "signal-util.h"
44 #include "stat-util.h"
45 #include "stdio-util.h"
46 #include "string-table.h"
47 #include "string-util.h"
49 #include "tmpfile-util.h"
50 #include "udev-util.h"
51 #include "user-util.h"
52 #include "xattr-util.h"
54 int probe_filesystem(const char *node
, char **ret_fstype
) {
55 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
56 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
57 * different error otherwise. */
60 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
65 b
= blkid_new_probe_from_filename(node
);
67 return errno_or_else(ENOMEM
);
69 blkid_probe_enable_superblocks(b
, 1);
70 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
73 r
= blkid_do_safeprobe(b
);
75 log_debug("No type detected on partition %s", node
);
79 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
80 "Results ambiguous for partition %s", node
);
82 return errno_or_else(EIO
);
84 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
106 /* Detect RPMB and Boot partitions, which are not listed by blkid.
107 * See https://github.com/systemd/systemd/issues/5806. */
108 static bool device_is_mmc_special_partition(sd_device
*d
) {
113 if (sd_device_get_sysname(d
, &sysname
) < 0)
116 return startswith(sysname
, "mmcblk") &&
117 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
120 static bool device_is_block(sd_device
*d
) {
125 if (sd_device_get_subsystem(d
, &ss
) < 0)
128 return streq(ss
, "block");
131 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
132 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
138 r
= sd_device_enumerator_new(&e
);
142 r
= sd_device_enumerator_allow_uninitialized(e
);
146 r
= sd_device_enumerator_add_match_parent(e
, d
);
154 /* how many times to wait for the device nodes to appear */
155 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
157 static int wait_for_partitions_to_appear(
160 unsigned num_partitions
,
161 DissectImageFlags flags
,
162 sd_device_enumerator
**ret_enumerator
) {
164 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
171 assert(ret_enumerator
);
173 r
= enumerator_for_parent(d
, &e
);
177 /* Count the partitions enumerated by the kernel */
179 FOREACH_DEVICE(e
, q
) {
180 if (sd_device_get_devnum(q
, NULL
) < 0)
182 if (!device_is_block(q
))
184 if (device_is_mmc_special_partition(q
))
187 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
188 r
= device_wait_for_initialization(q
, "block", USEC_INFINITY
, NULL
);
196 if (n
== num_partitions
+ 1) {
197 *ret_enumerator
= TAKE_PTR(e
);
198 return 0; /* success! */
200 if (n
> num_partitions
+ 1)
201 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
202 "blkid and kernel partition lists do not match.");
204 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
205 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
206 * call that waits until probing is complete. */
208 for (unsigned j
= 0; ; j
++) {
212 if (ioctl(fd
, BLKRRPART
, 0) >= 0)
216 struct loop_info64 info
;
218 /* If we are running on a loop device that has partition scanning off, return
219 * an explicit recognizable error about this, so that callers can generate a
220 * proper message explaining the situation. */
222 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0) {
223 #if HAVE_VALGRIND_MEMCHECK_H
224 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
225 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
228 if ((info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0)
229 return log_debug_errno(EPROTONOSUPPORT
,
230 "Device is a loop device and partition scanning is off!");
236 /* If something else has the device open, such as an udev rule, the ioctl will return
237 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
240 * This is really something they should fix in the kernel! */
241 (void) usleep(50 * USEC_PER_MSEC
);
245 return -EAGAIN
; /* no success yet, try again */
248 static int loop_wait_for_partitions_to_appear(
251 unsigned num_partitions
,
252 DissectImageFlags flags
,
253 sd_device_enumerator
**ret_enumerator
) {
254 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
259 assert(ret_enumerator
);
261 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions
);
263 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
264 r
= device_wait_for_initialization(d
, "block", USEC_INFINITY
, &device
);
268 device
= sd_device_ref(d
);
270 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
271 r
= wait_for_partitions_to_appear(fd
, device
, num_partitions
, flags
, ret_enumerator
);
276 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
277 "Kernel partitions dit not appear within %d attempts",
278 N_DEVICE_NODE_LIST_ATTEMPTS
);
281 static void check_partition_flags(
283 unsigned long long pflags
,
284 unsigned long long supported
) {
288 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
289 pflags
&= ~(supported
| GPT_FLAG_REQUIRED_PARTITION
| GPT_FLAG_NO_BLOCK_IO_PROTOCOL
| GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
294 /* If there are other bits set, then log about it, to make things discoverable */
295 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
296 unsigned long long bit
= 1ULL << i
;
297 if (!FLAGS_SET(pflags
, bit
))
300 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
308 const void *root_hash
,
309 size_t root_hash_size
,
310 const char *verity_data
,
311 DissectImageFlags flags
,
312 DissectedImage
**ret
) {
315 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
316 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
317 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
318 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
319 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
320 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
321 _cleanup_free_
char *generic_node
= NULL
;
322 sd_id128_t generic_uuid
= SD_ID128_NULL
;
323 const char *pttype
= NULL
;
332 assert(root_hash
|| root_hash_size
== 0);
333 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
335 /* Probes a disk image, and returns information about what it found in *ret.
337 * Returns -ENOPKG if no suitable partition table or file system could be found.
338 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
341 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
342 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
345 if (root_hash_size
< sizeof(sd_id128_t
))
348 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
349 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
351 if (sd_id128_is_null(root_uuid
))
353 if (sd_id128_is_null(verity_uuid
))
357 if (fstat(fd
, &st
) < 0)
360 if (!S_ISBLK(st
.st_mode
))
363 b
= blkid_new_probe();
368 r
= blkid_probe_set_device(b
, fd
, 0, 0);
370 return errno_or_else(ENOMEM
);
372 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
373 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
374 blkid_probe_enable_superblocks(b
, 1);
375 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
378 blkid_probe_enable_partitions(b
, 1);
379 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
382 r
= blkid_do_safeprobe(b
);
383 if (IN_SET(r
, -2, 1))
384 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
386 return errno_or_else(EIO
);
388 m
= new0(DissectedImage
, 1);
392 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
396 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
397 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) ||
398 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
399 const char *usage
= NULL
;
401 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
402 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
403 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
404 const char *fstype
= NULL
;
406 /* OK, we have found a file system, that's our root partition then. */
407 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
415 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
419 m
->single_file_system
= true;
420 m
->verity
= root_hash
&& verity_data
;
421 m
->can_verity
= !!verity_data
;
423 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
427 .architecture
= _ARCHITECTURE_INVALID
,
428 .fstype
= TAKE_PTR(t
),
432 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
434 /* Even on a single partition we need to wait for udev to create the
435 * /dev/block/X:Y symlink to /dev/loopZ */
436 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
445 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
449 is_gpt
= streq_ptr(pttype
, "gpt");
450 is_mbr
= streq_ptr(pttype
, "dos");
452 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
456 pl
= blkid_probe_get_partitions(b
);
458 return errno_or_else(ENOMEM
);
460 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
464 FOREACH_DEVICE(e
, q
) {
465 unsigned long long pflags
;
471 r
= sd_device_get_devnum(q
, &qn
);
475 if (st
.st_rdev
== qn
)
478 if (!device_is_block(q
))
481 if (device_is_mmc_special_partition(q
))
484 r
= sd_device_get_devname(q
, &node
);
488 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
492 pflags
= blkid_partition_get_flags(pp
);
494 nr
= blkid_partition_get_partno(pp
);
499 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
500 const char *stype
, *sid
, *fstype
= NULL
;
501 sd_id128_t type_id
, id
;
504 sid
= blkid_partition_get_uuid(pp
);
507 if (sd_id128_from_string(sid
, &id
) < 0)
510 stype
= blkid_partition_get_type_string(pp
);
513 if (sd_id128_from_string(stype
, &type_id
) < 0)
516 if (sd_id128_equal(type_id
, GPT_HOME
)) {
518 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
520 if (pflags
& GPT_FLAG_NO_AUTO
)
523 designator
= PARTITION_HOME
;
524 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
525 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
527 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
529 if (pflags
& GPT_FLAG_NO_AUTO
)
532 designator
= PARTITION_SRV
;
533 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
534 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
536 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
537 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
538 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
540 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
543 designator
= PARTITION_ESP
;
546 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
548 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
550 if (pflags
& GPT_FLAG_NO_AUTO
)
553 designator
= PARTITION_XBOOTLDR
;
554 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
556 #ifdef GPT_ROOT_NATIVE
557 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
559 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
561 if (pflags
& GPT_FLAG_NO_AUTO
)
564 /* If a root ID is specified, ignore everything but the root id */
565 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
568 designator
= PARTITION_ROOT
;
569 architecture
= native_architecture();
570 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
571 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
573 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
575 if (pflags
& GPT_FLAG_NO_AUTO
)
578 m
->can_verity
= true;
580 /* Ignore verity unless a root hash is specified */
581 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
584 designator
= PARTITION_ROOT_VERITY
;
585 fstype
= "DM_verity_hash";
586 architecture
= native_architecture();
590 #ifdef GPT_ROOT_SECONDARY
591 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
593 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
595 if (pflags
& GPT_FLAG_NO_AUTO
)
598 /* If a root ID is specified, ignore everything but the root id */
599 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
602 designator
= PARTITION_ROOT_SECONDARY
;
603 architecture
= SECONDARY_ARCHITECTURE
;
604 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
605 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
607 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
609 if (pflags
& GPT_FLAG_NO_AUTO
)
612 m
->can_verity
= true;
614 /* Ignore verity unless root has is specified */
615 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
618 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
619 fstype
= "DM_verity_hash";
620 architecture
= SECONDARY_ARCHITECTURE
;
624 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
626 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
628 if (pflags
& GPT_FLAG_NO_AUTO
)
631 designator
= PARTITION_SWAP
;
633 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
635 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
637 if (pflags
& GPT_FLAG_NO_AUTO
)
641 multiple_generic
= true;
644 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
646 generic_node
= strdup(node
);
651 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
653 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
655 if (pflags
& GPT_FLAG_NO_AUTO
)
658 designator
= PARTITION_TMP
;
659 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
661 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
663 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
665 if (pflags
& GPT_FLAG_NO_AUTO
)
668 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
671 /* For /var we insist that the uuid of the partition matches the
672 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
673 * ID. Why? Unlike the other partitions /var is inherently
674 * installation specific, hence we need to be careful not to mount it
675 * in the wrong installation. By hashing the partition UUID from
676 * /etc/machine-id we can securely bind the partition to the
679 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
683 if (!sd_id128_equal(var_uuid
, id
)) {
684 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
689 designator
= PARTITION_VAR
;
690 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
693 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
694 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
697 if (m
->partitions
[designator
].found
)
710 m
->partitions
[designator
] = (DissectedPartition
) {
714 .architecture
= architecture
,
716 .fstype
= TAKE_PTR(t
),
723 switch (blkid_partition_get_type(pp
)) {
725 case 0x83: /* Linux partition */
727 if (pflags
!= 0x80) /* Bootable flag */
731 multiple_generic
= true;
735 generic_node
= strdup(node
);
742 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
743 _cleanup_free_
char *n
= NULL
;
744 sd_id128_t id
= SD_ID128_NULL
;
748 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
751 sid
= blkid_partition_get_uuid(pp
);
753 (void) sd_id128_from_string(sid
, &id
);
759 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
763 .architecture
= _ARCHITECTURE_INVALID
,
773 if (!m
->partitions
[PARTITION_ROOT
].found
) {
774 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
775 * either, then check if there's a single generic one, and use that. */
777 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
778 return -EADDRNOTAVAIL
;
780 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
781 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
782 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
784 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
785 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
787 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
789 /* If the root has was set, then we won't fallback to a generic node, because the root hash
792 return -EADDRNOTAVAIL
;
794 /* If we didn't find a generic node, then we can't fix this up either */
798 /* If we didn't find a properly marked root partition, but we did find a single suitable
799 * generic Linux partition, then use this as root partition, if the caller asked for it. */
800 if (multiple_generic
)
803 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
806 .partno
= generic_nr
,
807 .architecture
= _ARCHITECTURE_INVALID
,
808 .node
= TAKE_PTR(generic_node
),
809 .uuid
= generic_uuid
,
815 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
816 return -EADDRNOTAVAIL
;
818 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
819 * (which would be weird, after all the root hash should only be assigned to one pair of
821 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
822 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
824 /* If we found a verity setup, then the root partition is necessarily read-only. */
825 m
->partitions
[PARTITION_ROOT
].rw
= false;
833 /* Fill in file system types if we don't know them yet. */
834 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
835 DissectedPartition
*p
= m
->partitions
+ i
;
840 if (!p
->fstype
&& p
->node
) {
841 r
= probe_filesystem(p
->node
, &p
->fstype
);
842 if (r
< 0 && r
!= -EUCLEAN
)
846 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
849 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
861 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
867 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
868 free(m
->partitions
[i
].fstype
);
869 free(m
->partitions
[i
].node
);
870 free(m
->partitions
[i
].decrypted_fstype
);
871 free(m
->partitions
[i
].decrypted_node
);
875 strv_free(m
->machine_info
);
876 strv_free(m
->os_release
);
881 static int is_loop_device(const char *path
) {
882 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
887 if (stat(path
, &st
) < 0)
890 if (!S_ISBLK(st
.st_mode
))
893 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
894 if (access(s
, F_OK
) < 0) {
898 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
899 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
900 if (access(s
, F_OK
) < 0)
901 return errno
== ENOENT
? false : -errno
;
907 static int run_fsck(const char *node
, const char *fstype
) {
914 r
= fsck_exists(fstype
);
916 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
920 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
924 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
926 return log_debug_errno(r
, "Failed to fork off fsck: %m");
929 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
930 log_debug_errno(errno
, "Failed to execl() fsck: %m");
931 _exit(FSCK_OPERATIONAL_ERROR
);
934 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
936 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
938 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
939 log_debug("fsck failed with exit status %i.", exit_status
);
941 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
942 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
944 log_debug("Ignoring fsck error.");
950 static int mount_partition(
951 DissectedPartition
*m
,
953 const char *directory
,
955 DissectImageFlags flags
) {
957 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
958 const char *p
, *node
, *fstype
;
965 node
= m
->decrypted_node
?: m
->node
;
966 fstype
= m
->decrypted_fstype
?: m
->fstype
;
968 if (!m
->found
|| !node
|| !fstype
)
971 /* Stacked encryption? Yuck */
972 if (streq_ptr(fstype
, "crypto_LUKS"))
975 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
977 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
978 r
= run_fsck(node
, fstype
);
984 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
992 /* If requested, turn on discard support. */
993 if (fstype_can_discard(fstype
) &&
994 ((flags
& DISSECT_IMAGE_DISCARD
) ||
995 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
996 options
= strdup("discard");
1001 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
1002 _cleanup_free_
char *uid_option
= NULL
;
1004 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1007 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
1011 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1018 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1019 int r
, boot_mounted
;
1024 if (!m
->partitions
[PARTITION_ROOT
].found
)
1027 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1028 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1032 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1033 r
= path_is_os_tree(where
);
1037 return -EMEDIUMTYPE
;
1041 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1044 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1048 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1052 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1056 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1060 boot_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1061 if (boot_mounted
< 0)
1062 return boot_mounted
;
1064 if (m
->partitions
[PARTITION_ESP
].found
) {
1065 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1066 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1068 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1070 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1074 } else if (boot_mounted
<= 0) {
1075 _cleanup_free_
char *p
= NULL
;
1077 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1078 if (r
>= 0 && dir_is_empty(p
) > 0) {
1079 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1089 #if HAVE_LIBCRYPTSETUP
1090 typedef struct DecryptedPartition
{
1091 struct crypt_device
*device
;
1094 } DecryptedPartition
;
1096 struct DecryptedImage
{
1097 DecryptedPartition
*decrypted
;
1103 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1104 #if HAVE_LIBCRYPTSETUP
1111 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1112 DecryptedPartition
*p
= d
->decrypted
+ i
;
1114 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1115 r
= crypt_deactivate(p
->device
, p
->name
);
1117 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1121 crypt_free(p
->device
);
1130 #if HAVE_LIBCRYPTSETUP
1132 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1133 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1136 assert(original_node
);
1141 base
= strrchr(original_node
, '/');
1148 name
= strjoin(base
, suffix
);
1151 if (!filename_is_valid(name
))
1154 node
= path_join(crypt_get_dir(), name
);
1158 *ret_name
= TAKE_PTR(name
);
1159 *ret_node
= TAKE_PTR(node
);
1164 static int decrypt_partition(
1165 DissectedPartition
*m
,
1166 const char *passphrase
,
1167 DissectImageFlags flags
,
1168 DecryptedImage
*d
) {
1170 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1171 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1177 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1180 if (!streq(m
->fstype
, "crypto_LUKS"))
1186 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1190 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1193 r
= crypt_init(&cd
, m
->node
);
1195 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1197 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1199 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
1201 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1203 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1204 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1205 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1207 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1208 return r
== -EPERM
? -EKEYREJECTED
: r
;
1211 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1212 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1215 m
->decrypted_node
= TAKE_PTR(node
);
1220 static int verity_partition(
1221 DissectedPartition
*m
,
1222 DissectedPartition
*v
,
1223 const void *root_hash
,
1224 size_t root_hash_size
,
1225 const char *verity_data
,
1226 DissectImageFlags flags
,
1227 DecryptedImage
*d
) {
1229 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1230 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1234 assert(v
|| verity_data
);
1239 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1242 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1245 if (!streq(v
->fstype
, "DM_verity_hash"))
1249 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1253 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1256 r
= crypt_init(&cd
, verity_data
?: v
->node
);
1260 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1262 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1266 r
= crypt_set_data_device(cd
, m
->node
);
1270 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1274 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1275 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1278 m
->decrypted_node
= TAKE_PTR(node
);
1284 int dissected_image_decrypt(
1286 const char *passphrase
,
1287 const void *root_hash
,
1288 size_t root_hash_size
,
1289 const char *verity_data
,
1290 DissectImageFlags flags
,
1291 DecryptedImage
**ret
) {
1293 #if HAVE_LIBCRYPTSETUP
1294 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1300 assert(root_hash
|| root_hash_size
== 0);
1304 * = 0 → There was nothing to decrypt
1305 * > 0 → Decrypted successfully
1306 * -ENOKEY → There's something to decrypt but no key was supplied
1307 * -EKEYREJECTED → Passed key was not correct
1310 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1313 if (!m
->encrypted
&& !m
->verity
) {
1318 #if HAVE_LIBCRYPTSETUP
1319 d
= new0(DecryptedImage
, 1);
1323 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1324 DissectedPartition
*p
= m
->partitions
+ i
;
1330 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1334 k
= PARTITION_VERITY_OF(i
);
1336 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, verity_data
, flags
, d
);
1341 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1342 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1343 if (r
< 0 && r
!= -EUCLEAN
)
1356 int dissected_image_decrypt_interactively(
1358 const char *passphrase
,
1359 const void *root_hash
,
1360 size_t root_hash_size
,
1361 const char *verity_data
,
1362 DissectImageFlags flags
,
1363 DecryptedImage
**ret
) {
1365 _cleanup_strv_free_erase_
char **z
= NULL
;
1372 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, verity_data
, flags
, ret
);
1375 if (r
== -EKEYREJECTED
)
1376 log_error_errno(r
, "Incorrect passphrase, try again!");
1377 else if (r
!= -ENOKEY
)
1378 return log_error_errno(r
, "Failed to decrypt image: %m");
1381 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1382 "Too many retries.");
1386 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1388 return log_error_errno(r
, "Failed to query for passphrase: %m");
1394 int decrypted_image_relinquish(DecryptedImage
*d
) {
1396 #if HAVE_LIBCRYPTSETUP
1403 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1404 * that we don't clean it up ourselves either anymore */
1406 #if HAVE_LIBCRYPTSETUP
1407 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1408 DecryptedPartition
*p
= d
->decrypted
+ i
;
1410 if (p
->relinquished
)
1413 r
= dm_deferred_remove(p
->name
);
1415 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1417 p
->relinquished
= true;
1424 int verity_metadata_load(const char *image
, const char *root_hash_path
, void **ret_roothash
, size_t *ret_roothash_size
, char **ret_verity_data
) {
1425 _cleanup_free_
char *verity_filename
= NULL
;
1426 _cleanup_free_
void *roothash_decoded
= NULL
;
1427 size_t roothash_decoded_size
= 0;
1432 if (is_device_path(image
)) {
1433 /* If we are asked to load the root hash for a device node, exit early */
1435 *ret_roothash
= NULL
;
1436 if (ret_roothash_size
)
1437 *ret_roothash_size
= 0;
1438 if (ret_verity_data
)
1439 *ret_verity_data
= NULL
;
1443 if (ret_verity_data
) {
1446 verity_filename
= new(char, strlen(image
) + STRLEN(".verity") + 1);
1447 if (!verity_filename
)
1449 strcpy(verity_filename
, image
);
1450 e
= endswith(verity_filename
, ".raw");
1452 strcpy(e
, ".verity");
1454 strcat(verity_filename
, ".verity");
1456 r
= access(verity_filename
, F_OK
);
1458 if (errno
!= ENOENT
)
1460 verity_filename
= mfree(verity_filename
);
1465 _cleanup_free_
char *text
= NULL
;
1466 assert(ret_roothash_size
);
1468 if (root_hash_path
) {
1469 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1470 r
= read_one_line_file(root_hash_path
, &text
);
1474 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1478 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1481 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1482 n
= stpcpy(fn
, image
);
1483 e
= endswith(fn
, ".raw");
1487 strcpy(n
, ".roothash");
1489 r
= read_one_line_file(fn
, &text
);
1490 if (r
< 0 && r
!= -ENOENT
)
1496 r
= unhexmem(text
, strlen(text
), &roothash_decoded
, &roothash_decoded_size
);
1499 if (roothash_decoded_size
< sizeof(sd_id128_t
))
1505 *ret_roothash
= TAKE_PTR(roothash_decoded
);
1506 *ret_roothash_size
= roothash_decoded_size
;
1508 if (ret_verity_data
)
1509 *ret_verity_data
= TAKE_PTR(verity_filename
);
1514 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1524 static const char *const paths
[_META_MAX
] = {
1525 [META_HOSTNAME
] = "/etc/hostname\0",
1526 [META_MACHINE_ID
] = "/etc/machine-id\0",
1527 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1528 [META_OS_RELEASE
] = "/etc/os-release\0"
1529 "/usr/lib/os-release\0",
1532 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1533 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1534 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1535 sd_id128_t machine_id
= SD_ID128_NULL
;
1536 _cleanup_free_
char *hostname
= NULL
;
1537 unsigned n_meta_initialized
= 0, k
;
1538 int fds
[2 * _META_MAX
], r
;
1540 BLOCK_SIGNALS(SIGCHLD
);
1544 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1545 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1550 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1554 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1558 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1560 log_debug_errno(r
, "Failed to mount dissected image: %m");
1561 _exit(EXIT_FAILURE
);
1564 for (k
= 0; k
< _META_MAX
; k
++) {
1565 _cleanup_close_
int fd
= -1;
1568 fds
[2*k
] = safe_close(fds
[2*k
]);
1570 NULSTR_FOREACH(p
, paths
[k
]) {
1571 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1576 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1580 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1582 _exit(EXIT_FAILURE
);
1584 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1587 _exit(EXIT_SUCCESS
);
1590 for (k
= 0; k
< _META_MAX
; k
++) {
1591 _cleanup_fclose_
FILE *f
= NULL
;
1593 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1595 f
= take_fdopen(&fds
[2*k
], "r");
1604 r
= read_etc_hostname_stream(f
, &hostname
);
1606 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1610 case META_MACHINE_ID
: {
1611 _cleanup_free_
char *line
= NULL
;
1613 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1615 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1617 r
= sd_id128_from_string(line
, &machine_id
);
1619 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1621 log_debug("/etc/machine-id file is empty.");
1623 log_debug("/etc/machine-id has unexpected length %i.", r
);
1628 case META_MACHINE_INFO
:
1629 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1631 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1635 case META_OS_RELEASE
:
1636 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1638 log_debug_errno(r
, "Failed to read OS release file: %m");
1644 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1648 if (r
!= EXIT_SUCCESS
)
1651 free_and_replace(m
->hostname
, hostname
);
1652 m
->machine_id
= machine_id
;
1653 strv_free_and_replace(m
->machine_info
, machine_info
);
1654 strv_free_and_replace(m
->os_release
, os_release
);
1657 for (k
= 0; k
< n_meta_initialized
; k
++)
1658 safe_close_pair(fds
+ 2*k
);
1663 int dissect_image_and_warn(
1666 const void *root_hash
,
1667 size_t root_hash_size
,
1668 const char *verity_data
,
1669 DissectImageFlags flags
,
1670 DissectedImage
**ret
) {
1672 _cleanup_free_
char *buffer
= NULL
;
1676 r
= fd_get_path(fd
, &buffer
);
1683 r
= dissect_image(fd
, root_hash
, root_hash_size
, verity_data
, flags
, ret
);
1688 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1691 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1693 case -EADDRNOTAVAIL
:
1694 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1697 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1700 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1702 case -EPROTONOSUPPORT
:
1703 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1707 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1713 bool dissected_image_can_do_verity(const DissectedImage
*image
, unsigned partition_designator
) {
1714 if (image
->single_file_system
)
1715 return partition_designator
== PARTITION_ROOT
&& image
->can_verity
;
1717 return PARTITION_VERITY_OF(partition_designator
) >= 0;
1720 bool dissected_image_has_verity(const DissectedImage
*image
, unsigned partition_designator
) {
1723 if (image
->single_file_system
)
1724 return partition_designator
== PARTITION_ROOT
&& image
->verity
;
1726 k
= PARTITION_VERITY_OF(partition_designator
);
1727 return k
>= 0 && image
->partitions
[k
].found
;
1730 static const char *const partition_designator_table
[] = {
1731 [PARTITION_ROOT
] = "root",
1732 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1733 [PARTITION_HOME
] = "home",
1734 [PARTITION_SRV
] = "srv",
1735 [PARTITION_ESP
] = "esp",
1736 [PARTITION_XBOOTLDR
] = "xbootldr",
1737 [PARTITION_SWAP
] = "swap",
1738 [PARTITION_ROOT_VERITY
] = "root-verity",
1739 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1740 [PARTITION_TMP
] = "tmp",
1741 [PARTITION_VAR
] = "var",
1744 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);