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 DissectImageFlags flags
,
311 DissectedImage
**ret
) {
314 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
315 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
316 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
317 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
318 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
319 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
320 _cleanup_free_
char *generic_node
= NULL
;
321 sd_id128_t generic_uuid
= SD_ID128_NULL
;
322 const char *pttype
= NULL
;
331 assert(root_hash
|| root_hash_size
== 0);
333 /* Probes a disk image, and returns information about what it found in *ret.
335 * Returns -ENOPKG if no suitable partition table or file system could be found.
336 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
339 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
340 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
343 if (root_hash_size
< sizeof(sd_id128_t
))
346 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
347 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
349 if (sd_id128_is_null(root_uuid
))
351 if (sd_id128_is_null(verity_uuid
))
355 if (fstat(fd
, &st
) < 0)
358 if (!S_ISBLK(st
.st_mode
))
361 b
= blkid_new_probe();
366 r
= blkid_probe_set_device(b
, fd
, 0, 0);
368 return errno_or_else(ENOMEM
);
370 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
371 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
372 blkid_probe_enable_superblocks(b
, 1);
373 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
376 blkid_probe_enable_partitions(b
, 1);
377 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
380 r
= blkid_do_safeprobe(b
);
381 if (IN_SET(r
, -2, 1))
382 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
384 return errno_or_else(EIO
);
386 m
= new0(DissectedImage
, 1);
390 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
394 if (!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
395 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) {
396 const char *usage
= NULL
;
398 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
399 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
400 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
401 const char *fstype
= NULL
;
403 /* OK, we have found a file system, that's our root partition then. */
404 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
412 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
416 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
420 .architecture
= _ARCHITECTURE_INVALID
,
421 .fstype
= TAKE_PTR(t
),
425 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
427 if (!streq(usage
, "filesystem")) {
428 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
438 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
442 is_gpt
= streq_ptr(pttype
, "gpt");
443 is_mbr
= streq_ptr(pttype
, "dos");
445 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
449 pl
= blkid_probe_get_partitions(b
);
451 return errno_or_else(ENOMEM
);
453 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
457 FOREACH_DEVICE(e
, q
) {
458 unsigned long long pflags
;
464 r
= sd_device_get_devnum(q
, &qn
);
468 if (st
.st_rdev
== qn
)
471 if (!device_is_block(q
))
474 if (device_is_mmc_special_partition(q
))
477 r
= sd_device_get_devname(q
, &node
);
481 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
485 pflags
= blkid_partition_get_flags(pp
);
487 nr
= blkid_partition_get_partno(pp
);
492 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
493 const char *stype
, *sid
, *fstype
= NULL
;
494 sd_id128_t type_id
, id
;
497 sid
= blkid_partition_get_uuid(pp
);
500 if (sd_id128_from_string(sid
, &id
) < 0)
503 stype
= blkid_partition_get_type_string(pp
);
506 if (sd_id128_from_string(stype
, &type_id
) < 0)
509 if (sd_id128_equal(type_id
, GPT_HOME
)) {
511 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
513 if (pflags
& GPT_FLAG_NO_AUTO
)
516 designator
= PARTITION_HOME
;
517 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
518 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
520 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
522 if (pflags
& GPT_FLAG_NO_AUTO
)
525 designator
= PARTITION_SRV
;
526 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
527 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
529 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
530 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
531 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
533 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
536 designator
= PARTITION_ESP
;
539 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
541 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
543 if (pflags
& GPT_FLAG_NO_AUTO
)
546 designator
= PARTITION_XBOOTLDR
;
547 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
549 #ifdef GPT_ROOT_NATIVE
550 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
552 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
554 if (pflags
& GPT_FLAG_NO_AUTO
)
557 /* If a root ID is specified, ignore everything but the root id */
558 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
561 designator
= PARTITION_ROOT
;
562 architecture
= native_architecture();
563 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
564 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
566 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
568 if (pflags
& GPT_FLAG_NO_AUTO
)
571 m
->can_verity
= true;
573 /* Ignore verity unless a root hash is specified */
574 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
577 designator
= PARTITION_ROOT_VERITY
;
578 fstype
= "DM_verity_hash";
579 architecture
= native_architecture();
583 #ifdef GPT_ROOT_SECONDARY
584 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
586 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
588 if (pflags
& GPT_FLAG_NO_AUTO
)
591 /* If a root ID is specified, ignore everything but the root id */
592 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
595 designator
= PARTITION_ROOT_SECONDARY
;
596 architecture
= SECONDARY_ARCHITECTURE
;
597 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
598 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
600 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
602 if (pflags
& GPT_FLAG_NO_AUTO
)
605 m
->can_verity
= true;
607 /* Ignore verity unless root has is specified */
608 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
611 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
612 fstype
= "DM_verity_hash";
613 architecture
= SECONDARY_ARCHITECTURE
;
617 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
619 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
621 if (pflags
& GPT_FLAG_NO_AUTO
)
624 designator
= PARTITION_SWAP
;
626 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
628 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
630 if (pflags
& GPT_FLAG_NO_AUTO
)
634 multiple_generic
= true;
637 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
639 generic_node
= strdup(node
);
644 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
646 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
648 if (pflags
& GPT_FLAG_NO_AUTO
)
651 designator
= PARTITION_TMP
;
652 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
654 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
656 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
658 if (pflags
& GPT_FLAG_NO_AUTO
)
661 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
664 /* For /var we insist that the uuid of the partition matches the
665 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
666 * ID. Why? Unlike the other partitions /var is inherently
667 * installation specific, hence we need to be careful not to mount it
668 * in the wrong installation. By hashing the partition UUID from
669 * /etc/machine-id we can securely bind the partition to the
672 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
676 if (!sd_id128_equal(var_uuid
, id
)) {
677 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
682 designator
= PARTITION_VAR
;
683 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
686 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
687 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
690 if (m
->partitions
[designator
].found
)
703 m
->partitions
[designator
] = (DissectedPartition
) {
707 .architecture
= architecture
,
709 .fstype
= TAKE_PTR(t
),
716 switch (blkid_partition_get_type(pp
)) {
718 case 0x83: /* Linux partition */
720 if (pflags
!= 0x80) /* Bootable flag */
724 multiple_generic
= true;
728 generic_node
= strdup(node
);
735 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
736 _cleanup_free_
char *n
= NULL
;
737 sd_id128_t id
= SD_ID128_NULL
;
741 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
744 sid
= blkid_partition_get_uuid(pp
);
746 (void) sd_id128_from_string(sid
, &id
);
752 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
756 .architecture
= _ARCHITECTURE_INVALID
,
766 if (!m
->partitions
[PARTITION_ROOT
].found
) {
767 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
768 * either, then check if there's a single generic one, and use that. */
770 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
771 return -EADDRNOTAVAIL
;
773 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
774 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
775 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
777 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
778 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
780 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
782 /* If the root has was set, then we won't fallback to a generic node, because the root hash
785 return -EADDRNOTAVAIL
;
787 /* If we didn't find a generic node, then we can't fix this up either */
791 /* If we didn't find a properly marked root partition, but we did find a single suitable
792 * generic Linux partition, then use this as root partition, if the caller asked for it. */
793 if (multiple_generic
)
796 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
799 .partno
= generic_nr
,
800 .architecture
= _ARCHITECTURE_INVALID
,
801 .node
= TAKE_PTR(generic_node
),
802 .uuid
= generic_uuid
,
808 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
809 return -EADDRNOTAVAIL
;
811 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
812 * (which would be weird, after all the root hash should only be assigned to one pair of
814 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
815 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
817 /* If we found a verity setup, then the root partition is necessarily read-only. */
818 m
->partitions
[PARTITION_ROOT
].rw
= false;
826 /* Fill in file system types if we don't know them yet. */
827 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
828 DissectedPartition
*p
= m
->partitions
+ i
;
833 if (!p
->fstype
&& p
->node
) {
834 r
= probe_filesystem(p
->node
, &p
->fstype
);
835 if (r
< 0 && r
!= -EUCLEAN
)
839 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
842 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
854 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
860 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
861 free(m
->partitions
[i
].fstype
);
862 free(m
->partitions
[i
].node
);
863 free(m
->partitions
[i
].decrypted_fstype
);
864 free(m
->partitions
[i
].decrypted_node
);
868 strv_free(m
->machine_info
);
869 strv_free(m
->os_release
);
874 static int is_loop_device(const char *path
) {
875 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
880 if (stat(path
, &st
) < 0)
883 if (!S_ISBLK(st
.st_mode
))
886 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
887 if (access(s
, F_OK
) < 0) {
891 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
892 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
893 if (access(s
, F_OK
) < 0)
894 return errno
== ENOENT
? false : -errno
;
900 static int run_fsck(const char *node
, const char *fstype
) {
907 r
= fsck_exists(fstype
);
909 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
913 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
917 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
919 return log_debug_errno(r
, "Failed to fork off fsck: %m");
922 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
923 log_debug_errno(errno
, "Failed to execl() fsck: %m");
924 _exit(FSCK_OPERATIONAL_ERROR
);
927 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
929 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
931 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
932 log_debug("fsck failed with exit status %i.", exit_status
);
934 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
935 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
937 log_debug("Ignoring fsck error.");
943 static int mount_partition(
944 DissectedPartition
*m
,
946 const char *directory
,
948 DissectImageFlags flags
) {
950 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
951 const char *p
, *node
, *fstype
;
958 node
= m
->decrypted_node
?: m
->node
;
959 fstype
= m
->decrypted_fstype
?: m
->fstype
;
961 if (!m
->found
|| !node
|| !fstype
)
964 /* Stacked encryption? Yuck */
965 if (streq_ptr(fstype
, "crypto_LUKS"))
968 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
970 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
971 r
= run_fsck(node
, fstype
);
977 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
985 /* If requested, turn on discard support. */
986 if (fstype_can_discard(fstype
) &&
987 ((flags
& DISSECT_IMAGE_DISCARD
) ||
988 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
989 options
= strdup("discard");
994 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
995 _cleanup_free_
char *uid_option
= NULL
;
997 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1000 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
1004 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1011 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1012 int r
, boot_mounted
;
1017 if (!m
->partitions
[PARTITION_ROOT
].found
)
1020 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1021 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1025 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1026 r
= path_is_os_tree(where
);
1030 return -EMEDIUMTYPE
;
1034 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1037 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1041 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1045 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1049 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1053 boot_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1054 if (boot_mounted
< 0)
1055 return boot_mounted
;
1057 if (m
->partitions
[PARTITION_ESP
].found
) {
1058 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1059 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1061 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1063 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1067 } else if (boot_mounted
<= 0) {
1068 _cleanup_free_
char *p
= NULL
;
1070 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1071 if (r
>= 0 && dir_is_empty(p
) > 0) {
1072 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1082 #if HAVE_LIBCRYPTSETUP
1083 typedef struct DecryptedPartition
{
1084 struct crypt_device
*device
;
1087 } DecryptedPartition
;
1089 struct DecryptedImage
{
1090 DecryptedPartition
*decrypted
;
1096 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1097 #if HAVE_LIBCRYPTSETUP
1104 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1105 DecryptedPartition
*p
= d
->decrypted
+ i
;
1107 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1108 r
= crypt_deactivate(p
->device
, p
->name
);
1110 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1114 crypt_free(p
->device
);
1123 #if HAVE_LIBCRYPTSETUP
1125 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1126 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1129 assert(original_node
);
1134 base
= strrchr(original_node
, '/');
1141 name
= strjoin(base
, suffix
);
1144 if (!filename_is_valid(name
))
1147 node
= path_join(crypt_get_dir(), name
);
1151 *ret_name
= TAKE_PTR(name
);
1152 *ret_node
= TAKE_PTR(node
);
1157 static int decrypt_partition(
1158 DissectedPartition
*m
,
1159 const char *passphrase
,
1160 DissectImageFlags flags
,
1161 DecryptedImage
*d
) {
1163 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1164 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1170 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1173 if (!streq(m
->fstype
, "crypto_LUKS"))
1179 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1183 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1186 r
= crypt_init(&cd
, m
->node
);
1188 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1190 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1192 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
1194 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1196 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1197 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1198 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1200 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1201 return r
== -EPERM
? -EKEYREJECTED
: r
;
1204 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1205 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1208 m
->decrypted_node
= TAKE_PTR(node
);
1213 static int verity_partition(
1214 DissectedPartition
*m
,
1215 DissectedPartition
*v
,
1216 const void *root_hash
,
1217 size_t root_hash_size
,
1218 DissectImageFlags flags
,
1219 DecryptedImage
*d
) {
1221 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1222 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1231 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1233 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1236 if (!streq(v
->fstype
, "DM_verity_hash"))
1239 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1243 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1246 r
= crypt_init(&cd
, v
->node
);
1250 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1252 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1256 r
= crypt_set_data_device(cd
, m
->node
);
1260 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1264 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1265 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1268 m
->decrypted_node
= TAKE_PTR(node
);
1274 int dissected_image_decrypt(
1276 const char *passphrase
,
1277 const void *root_hash
,
1278 size_t root_hash_size
,
1279 DissectImageFlags flags
,
1280 DecryptedImage
**ret
) {
1282 #if HAVE_LIBCRYPTSETUP
1283 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1289 assert(root_hash
|| root_hash_size
== 0);
1293 * = 0 → There was nothing to decrypt
1294 * > 0 → Decrypted successfully
1295 * -ENOKEY → There's something to decrypt but no key was supplied
1296 * -EKEYREJECTED → Passed key was not correct
1299 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1302 if (!m
->encrypted
&& !m
->verity
) {
1307 #if HAVE_LIBCRYPTSETUP
1308 d
= new0(DecryptedImage
, 1);
1312 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1313 DissectedPartition
*p
= m
->partitions
+ i
;
1319 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1323 k
= PARTITION_VERITY_OF(i
);
1325 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, flags
, d
);
1330 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1331 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1332 if (r
< 0 && r
!= -EUCLEAN
)
1345 int dissected_image_decrypt_interactively(
1347 const char *passphrase
,
1348 const void *root_hash
,
1349 size_t root_hash_size
,
1350 DissectImageFlags flags
,
1351 DecryptedImage
**ret
) {
1353 _cleanup_strv_free_erase_
char **z
= NULL
;
1360 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, flags
, ret
);
1363 if (r
== -EKEYREJECTED
)
1364 log_error_errno(r
, "Incorrect passphrase, try again!");
1365 else if (r
!= -ENOKEY
)
1366 return log_error_errno(r
, "Failed to decrypt image: %m");
1369 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1370 "Too many retries.");
1374 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1376 return log_error_errno(r
, "Failed to query for passphrase: %m");
1382 int decrypted_image_relinquish(DecryptedImage
*d
) {
1384 #if HAVE_LIBCRYPTSETUP
1391 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1392 * that we don't clean it up ourselves either anymore */
1394 #if HAVE_LIBCRYPTSETUP
1395 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1396 DecryptedPartition
*p
= d
->decrypted
+ i
;
1398 if (p
->relinquished
)
1401 r
= dm_deferred_remove(p
->name
);
1403 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1405 p
->relinquished
= true;
1412 int root_hash_load(const char *image
, void **ret
, size_t *ret_size
) {
1413 _cleanup_free_
char *text
= NULL
;
1414 _cleanup_free_
void *k
= NULL
;
1422 if (is_device_path(image
)) {
1423 /* If we are asked to load the root hash for a device node, exit early */
1429 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1433 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1436 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1437 n
= stpcpy(fn
, image
);
1438 e
= endswith(fn
, ".raw");
1442 strcpy(n
, ".roothash");
1444 r
= read_one_line_file(fn
, &text
);
1454 r
= unhexmem(text
, strlen(text
), &k
, &l
);
1457 if (l
< sizeof(sd_id128_t
))
1466 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1476 static const char *const paths
[_META_MAX
] = {
1477 [META_HOSTNAME
] = "/etc/hostname\0",
1478 [META_MACHINE_ID
] = "/etc/machine-id\0",
1479 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1480 [META_OS_RELEASE
] = "/etc/os-release\0"
1481 "/usr/lib/os-release\0",
1484 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1485 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1486 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1487 sd_id128_t machine_id
= SD_ID128_NULL
;
1488 _cleanup_free_
char *hostname
= NULL
;
1489 unsigned n_meta_initialized
= 0, k
;
1490 int fds
[2 * _META_MAX
], r
;
1492 BLOCK_SIGNALS(SIGCHLD
);
1496 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1497 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1502 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1506 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1510 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1512 log_debug_errno(r
, "Failed to mount dissected image: %m");
1513 _exit(EXIT_FAILURE
);
1516 for (k
= 0; k
< _META_MAX
; k
++) {
1517 _cleanup_close_
int fd
= -1;
1520 fds
[2*k
] = safe_close(fds
[2*k
]);
1522 NULSTR_FOREACH(p
, paths
[k
]) {
1523 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1528 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1532 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1534 _exit(EXIT_FAILURE
);
1536 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1539 _exit(EXIT_SUCCESS
);
1542 for (k
= 0; k
< _META_MAX
; k
++) {
1543 _cleanup_fclose_
FILE *f
= NULL
;
1545 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1547 f
= take_fdopen(&fds
[2*k
], "r");
1556 r
= read_etc_hostname_stream(f
, &hostname
);
1558 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1562 case META_MACHINE_ID
: {
1563 _cleanup_free_
char *line
= NULL
;
1565 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1567 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1569 r
= sd_id128_from_string(line
, &machine_id
);
1571 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1573 log_debug("/etc/machine-id file is empty.");
1575 log_debug("/etc/machine-id has unexpected length %i.", r
);
1580 case META_MACHINE_INFO
:
1581 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1583 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1587 case META_OS_RELEASE
:
1588 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1590 log_debug_errno(r
, "Failed to read OS release file: %m");
1596 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1600 if (r
!= EXIT_SUCCESS
)
1603 free_and_replace(m
->hostname
, hostname
);
1604 m
->machine_id
= machine_id
;
1605 strv_free_and_replace(m
->machine_info
, machine_info
);
1606 strv_free_and_replace(m
->os_release
, os_release
);
1609 for (k
= 0; k
< n_meta_initialized
; k
++)
1610 safe_close_pair(fds
+ 2*k
);
1615 int dissect_image_and_warn(
1618 const void *root_hash
,
1619 size_t root_hash_size
,
1620 DissectImageFlags flags
,
1621 DissectedImage
**ret
) {
1623 _cleanup_free_
char *buffer
= NULL
;
1627 r
= fd_get_path(fd
, &buffer
);
1634 r
= dissect_image(fd
, root_hash
, root_hash_size
, flags
, ret
);
1639 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1642 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1644 case -EADDRNOTAVAIL
:
1645 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1648 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1651 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1653 case -EPROTONOSUPPORT
:
1654 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1658 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1664 static const char *const partition_designator_table
[] = {
1665 [PARTITION_ROOT
] = "root",
1666 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1667 [PARTITION_HOME
] = "home",
1668 [PARTITION_SRV
] = "srv",
1669 [PARTITION_ESP
] = "esp",
1670 [PARTITION_XBOOTLDR
] = "xbootldr",
1671 [PARTITION_SWAP
] = "swap",
1672 [PARTITION_ROOT_VERITY
] = "root-verity",
1673 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1674 [PARTITION_TMP
] = "tmp",
1675 [PARTITION_VAR
] = "var",
1678 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);