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 log_debug("Results ambiguous for partition %s", node
);
83 return errno_or_else(EIO
);
85 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
107 /* Detect RPMB and Boot partitions, which are not listed by blkid.
108 * See https://github.com/systemd/systemd/issues/5806. */
109 static bool device_is_mmc_special_partition(sd_device
*d
) {
114 if (sd_device_get_sysname(d
, &sysname
) < 0)
117 return startswith(sysname
, "mmcblk") &&
118 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
121 static bool device_is_block(sd_device
*d
) {
126 if (sd_device_get_subsystem(d
, &ss
) < 0)
129 return streq(ss
, "block");
132 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
133 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
139 r
= sd_device_enumerator_new(&e
);
143 r
= sd_device_enumerator_allow_uninitialized(e
);
147 r
= sd_device_enumerator_add_match_parent(e
, d
);
155 /* how many times to wait for the device nodes to appear */
156 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
158 static int wait_for_partitions_to_appear(
161 unsigned num_partitions
,
162 DissectImageFlags flags
,
163 sd_device_enumerator
**ret_enumerator
) {
165 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
172 assert(ret_enumerator
);
174 r
= enumerator_for_parent(d
, &e
);
178 /* Count the partitions enumerated by the kernel */
180 FOREACH_DEVICE(e
, q
) {
181 if (sd_device_get_devnum(q
, NULL
) < 0)
183 if (!device_is_block(q
))
185 if (device_is_mmc_special_partition(q
))
188 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
189 r
= device_wait_for_initialization(q
, "block", USEC_INFINITY
, NULL
);
197 if (n
== num_partitions
+ 1) {
198 *ret_enumerator
= TAKE_PTR(e
);
199 return 0; /* success! */
201 if (n
> num_partitions
+ 1)
202 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
203 "blkid and kernel partition lists do not match.");
205 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
206 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
207 * call that waits until probing is complete. */
209 for (unsigned j
= 0; ; j
++) {
213 if (ioctl(fd
, BLKRRPART
, 0) >= 0)
217 struct loop_info64 info
;
219 /* If we are running on a loop device that has partition scanning off, return
220 * an explicit recognizable error about this, so that callers can generate a
221 * proper message explaining the situation. */
223 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0) {
224 #if HAVE_VALGRIND_MEMCHECK_H
225 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
226 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
229 if ((info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0)
230 return log_debug_errno(EPROTONOSUPPORT
,
231 "Device is a loop device and partition scanning is off!");
237 /* If something else has the device open, such as an udev rule, the ioctl will return
238 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
241 * This is really something they should fix in the kernel! */
242 (void) usleep(50 * USEC_PER_MSEC
);
246 return -EAGAIN
; /* no success yet, try again */
249 static int loop_wait_for_partitions_to_appear(
252 unsigned num_partitions
,
253 DissectImageFlags flags
,
254 sd_device_enumerator
**ret_enumerator
) {
255 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
260 assert(ret_enumerator
);
262 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions
);
264 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
265 r
= device_wait_for_initialization(d
, "block", USEC_INFINITY
, &device
);
269 device
= sd_device_ref(d
);
271 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
272 r
= wait_for_partitions_to_appear(fd
, device
, num_partitions
, flags
, ret_enumerator
);
277 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
278 "Kernel partitions dit not appear within %d attempts",
279 N_DEVICE_NODE_LIST_ATTEMPTS
);
282 static void check_partition_flags(
284 unsigned long long pflags
,
285 unsigned long long supported
) {
289 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
290 pflags
&= ~(supported
| GPT_FLAG_REQUIRED_PARTITION
| GPT_FLAG_NO_BLOCK_IO_PROTOCOL
| GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
295 /* If there are other bits set, then log about it, to make things discoverable */
296 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
297 unsigned long long bit
= 1ULL << i
;
298 if (!FLAGS_SET(pflags
, bit
))
301 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
309 const void *root_hash
,
310 size_t root_hash_size
,
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);
334 /* Probes a disk image, and returns information about what it found in *ret.
336 * Returns -ENOPKG if no suitable partition table or file system could be found.
337 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
340 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
341 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
344 if (root_hash_size
< sizeof(sd_id128_t
))
347 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
348 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
350 if (sd_id128_is_null(root_uuid
))
352 if (sd_id128_is_null(verity_uuid
))
356 if (fstat(fd
, &st
) < 0)
359 if (!S_ISBLK(st
.st_mode
))
362 b
= blkid_new_probe();
367 r
= blkid_probe_set_device(b
, fd
, 0, 0);
369 return errno_or_else(ENOMEM
);
371 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
372 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
373 blkid_probe_enable_superblocks(b
, 1);
374 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
377 blkid_probe_enable_partitions(b
, 1);
378 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
381 r
= blkid_do_safeprobe(b
);
382 if (IN_SET(r
, -2, 1))
383 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
385 return errno_or_else(EIO
);
387 m
= new0(DissectedImage
, 1);
391 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
395 if (!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
396 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) {
397 const char *usage
= NULL
;
399 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
400 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
401 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
402 const char *fstype
= NULL
;
404 /* OK, we have found a file system, that's our root partition then. */
405 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
413 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
417 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
421 .architecture
= _ARCHITECTURE_INVALID
,
422 .fstype
= TAKE_PTR(t
),
426 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
428 if (!streq(usage
, "filesystem")) {
429 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
439 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
443 is_gpt
= streq_ptr(pttype
, "gpt");
444 is_mbr
= streq_ptr(pttype
, "dos");
446 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
450 pl
= blkid_probe_get_partitions(b
);
452 return errno_or_else(ENOMEM
);
454 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
458 FOREACH_DEVICE(e
, q
) {
459 unsigned long long pflags
;
465 r
= sd_device_get_devnum(q
, &qn
);
469 if (st
.st_rdev
== qn
)
472 if (!device_is_block(q
))
475 if (device_is_mmc_special_partition(q
))
478 r
= sd_device_get_devname(q
, &node
);
482 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
486 pflags
= blkid_partition_get_flags(pp
);
488 nr
= blkid_partition_get_partno(pp
);
493 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
494 const char *stype
, *sid
, *fstype
= NULL
;
495 sd_id128_t type_id
, id
;
498 sid
= blkid_partition_get_uuid(pp
);
501 if (sd_id128_from_string(sid
, &id
) < 0)
504 stype
= blkid_partition_get_type_string(pp
);
507 if (sd_id128_from_string(stype
, &type_id
) < 0)
510 if (sd_id128_equal(type_id
, GPT_HOME
)) {
512 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
514 if (pflags
& GPT_FLAG_NO_AUTO
)
517 designator
= PARTITION_HOME
;
518 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
519 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
521 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
523 if (pflags
& GPT_FLAG_NO_AUTO
)
526 designator
= PARTITION_SRV
;
527 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
528 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
530 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
531 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
532 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
534 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
537 designator
= PARTITION_ESP
;
540 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
542 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
544 if (pflags
& GPT_FLAG_NO_AUTO
)
547 designator
= PARTITION_XBOOTLDR
;
548 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
550 #ifdef GPT_ROOT_NATIVE
551 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
553 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
555 if (pflags
& GPT_FLAG_NO_AUTO
)
558 /* If a root ID is specified, ignore everything but the root id */
559 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
562 designator
= PARTITION_ROOT
;
563 architecture
= native_architecture();
564 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
565 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
567 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
569 if (pflags
& GPT_FLAG_NO_AUTO
)
572 m
->can_verity
= true;
574 /* Ignore verity unless a root hash is specified */
575 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
578 designator
= PARTITION_ROOT_VERITY
;
579 fstype
= "DM_verity_hash";
580 architecture
= native_architecture();
584 #ifdef GPT_ROOT_SECONDARY
585 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
587 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
589 if (pflags
& GPT_FLAG_NO_AUTO
)
592 /* If a root ID is specified, ignore everything but the root id */
593 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
596 designator
= PARTITION_ROOT_SECONDARY
;
597 architecture
= SECONDARY_ARCHITECTURE
;
598 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
599 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
601 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
603 if (pflags
& GPT_FLAG_NO_AUTO
)
606 m
->can_verity
= true;
608 /* Ignore verity unless root has is specified */
609 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
612 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
613 fstype
= "DM_verity_hash";
614 architecture
= SECONDARY_ARCHITECTURE
;
618 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
620 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
622 if (pflags
& GPT_FLAG_NO_AUTO
)
625 designator
= PARTITION_SWAP
;
627 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
629 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
631 if (pflags
& GPT_FLAG_NO_AUTO
)
635 multiple_generic
= true;
638 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
640 generic_node
= strdup(node
);
645 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
647 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
649 if (pflags
& GPT_FLAG_NO_AUTO
)
652 designator
= PARTITION_TMP
;
653 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
655 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
657 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
659 if (pflags
& GPT_FLAG_NO_AUTO
)
662 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
665 /* For /var we insist that the uuid of the partition matches the
666 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
667 * ID. Why? Unlike the other partitions /var is inherently
668 * installation specific, hence we need to be careful not to mount it
669 * in the wrong installation. By hashing the partition UUID from
670 * /etc/machine-id we can securely bind the partition to the
673 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
677 if (!sd_id128_equal(var_uuid
, id
)) {
678 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
683 designator
= PARTITION_VAR
;
684 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
687 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
688 _cleanup_free_
char *t
= NULL
, *n
= NULL
;
691 if (m
->partitions
[designator
].found
)
704 m
->partitions
[designator
] = (DissectedPartition
) {
708 .architecture
= architecture
,
710 .fstype
= TAKE_PTR(t
),
717 switch (blkid_partition_get_type(pp
)) {
719 case 0x83: /* Linux partition */
721 if (pflags
!= 0x80) /* Bootable flag */
725 multiple_generic
= true;
729 generic_node
= strdup(node
);
736 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
737 _cleanup_free_
char *n
= NULL
;
738 sd_id128_t id
= SD_ID128_NULL
;
742 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
745 sid
= blkid_partition_get_uuid(pp
);
747 (void) sd_id128_from_string(sid
, &id
);
753 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
757 .architecture
= _ARCHITECTURE_INVALID
,
767 if (!m
->partitions
[PARTITION_ROOT
].found
) {
768 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
769 * either, then check if there's a single generic one, and use that. */
771 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
772 return -EADDRNOTAVAIL
;
774 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
775 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
776 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
778 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
779 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
781 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
783 /* If the root has was set, then we won't fallback to a generic node, because the root hash
786 return -EADDRNOTAVAIL
;
788 /* If we didn't find a generic node, then we can't fix this up either */
792 /* If we didn't find a properly marked root partition, but we did find a single suitable
793 * generic Linux partition, then use this as root partition, if the caller asked for it. */
794 if (multiple_generic
)
797 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
800 .partno
= generic_nr
,
801 .architecture
= _ARCHITECTURE_INVALID
,
802 .node
= TAKE_PTR(generic_node
),
803 .uuid
= generic_uuid
,
809 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
810 return -EADDRNOTAVAIL
;
812 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
813 * (which would be weird, after all the root hash should only be assigned to one pair of
815 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
816 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
818 /* If we found a verity setup, then the root partition is necessarily read-only. */
819 m
->partitions
[PARTITION_ROOT
].rw
= false;
827 /* Fill in file system types if we don't know them yet. */
828 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
829 DissectedPartition
*p
= m
->partitions
+ i
;
834 if (!p
->fstype
&& p
->node
) {
835 r
= probe_filesystem(p
->node
, &p
->fstype
);
836 if (r
< 0 && r
!= -EUCLEAN
)
840 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
843 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
855 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
861 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
862 free(m
->partitions
[i
].fstype
);
863 free(m
->partitions
[i
].node
);
864 free(m
->partitions
[i
].decrypted_fstype
);
865 free(m
->partitions
[i
].decrypted_node
);
869 strv_free(m
->machine_info
);
870 strv_free(m
->os_release
);
875 static int is_loop_device(const char *path
) {
876 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
881 if (stat(path
, &st
) < 0)
884 if (!S_ISBLK(st
.st_mode
))
887 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
888 if (access(s
, F_OK
) < 0) {
892 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
893 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
894 if (access(s
, F_OK
) < 0)
895 return errno
== ENOENT
? false : -errno
;
901 static int run_fsck(const char *node
, const char *fstype
) {
908 r
= fsck_exists(fstype
);
910 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
914 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
918 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
920 return log_debug_errno(r
, "Failed to fork off fsck: %m");
923 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
924 log_debug_errno(errno
, "Failed to execl() fsck: %m");
925 _exit(FSCK_OPERATIONAL_ERROR
);
928 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
930 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
932 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
933 log_debug("fsck failed with exit status %i.", exit_status
);
935 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
936 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
938 log_debug("Ignoring fsck error.");
944 static int mount_partition(
945 DissectedPartition
*m
,
947 const char *directory
,
949 DissectImageFlags flags
) {
951 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
952 const char *p
, *node
, *fstype
;
959 node
= m
->decrypted_node
?: m
->node
;
960 fstype
= m
->decrypted_fstype
?: m
->fstype
;
962 if (!m
->found
|| !node
|| !fstype
)
965 /* Stacked encryption? Yuck */
966 if (streq_ptr(fstype
, "crypto_LUKS"))
969 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
971 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
972 r
= run_fsck(node
, fstype
);
978 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
986 /* If requested, turn on discard support. */
987 if (fstype_can_discard(fstype
) &&
988 ((flags
& DISSECT_IMAGE_DISCARD
) ||
989 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
990 options
= strdup("discard");
995 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
996 _cleanup_free_
char *uid_option
= NULL
;
998 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1001 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
1005 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1012 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1013 int r
, boot_mounted
;
1018 if (!m
->partitions
[PARTITION_ROOT
].found
)
1021 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1022 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1026 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1027 r
= path_is_os_tree(where
);
1031 return -EMEDIUMTYPE
;
1035 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1038 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1042 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1046 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1050 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1054 boot_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1055 if (boot_mounted
< 0)
1056 return boot_mounted
;
1058 if (m
->partitions
[PARTITION_ESP
].found
) {
1059 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1060 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1062 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1064 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1068 } else if (boot_mounted
<= 0) {
1069 _cleanup_free_
char *p
= NULL
;
1071 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1072 if (r
>= 0 && dir_is_empty(p
) > 0) {
1073 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1083 #if HAVE_LIBCRYPTSETUP
1084 typedef struct DecryptedPartition
{
1085 struct crypt_device
*device
;
1088 } DecryptedPartition
;
1090 struct DecryptedImage
{
1091 DecryptedPartition
*decrypted
;
1097 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1098 #if HAVE_LIBCRYPTSETUP
1105 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1106 DecryptedPartition
*p
= d
->decrypted
+ i
;
1108 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1109 r
= crypt_deactivate(p
->device
, p
->name
);
1111 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1115 crypt_free(p
->device
);
1124 #if HAVE_LIBCRYPTSETUP
1126 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1127 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1130 assert(original_node
);
1135 base
= strrchr(original_node
, '/');
1142 name
= strjoin(base
, suffix
);
1145 if (!filename_is_valid(name
))
1148 node
= path_join(crypt_get_dir(), name
);
1152 *ret_name
= TAKE_PTR(name
);
1153 *ret_node
= TAKE_PTR(node
);
1158 static int decrypt_partition(
1159 DissectedPartition
*m
,
1160 const char *passphrase
,
1161 DissectImageFlags flags
,
1162 DecryptedImage
*d
) {
1164 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1165 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1171 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1174 if (!streq(m
->fstype
, "crypto_LUKS"))
1180 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1184 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1187 r
= crypt_init(&cd
, m
->node
);
1189 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1191 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
1193 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1195 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1196 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1197 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1199 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1200 return r
== -EPERM
? -EKEYREJECTED
: r
;
1203 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1204 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1207 m
->decrypted_node
= TAKE_PTR(node
);
1212 static int verity_partition(
1213 DissectedPartition
*m
,
1214 DissectedPartition
*v
,
1215 const void *root_hash
,
1216 size_t root_hash_size
,
1217 DissectImageFlags flags
,
1218 DecryptedImage
*d
) {
1220 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1221 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1230 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1232 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1235 if (!streq(v
->fstype
, "DM_verity_hash"))
1238 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1242 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1245 r
= crypt_init(&cd
, v
->node
);
1249 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1253 r
= crypt_set_data_device(cd
, m
->node
);
1257 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1261 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1262 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1265 m
->decrypted_node
= TAKE_PTR(node
);
1271 int dissected_image_decrypt(
1273 const char *passphrase
,
1274 const void *root_hash
,
1275 size_t root_hash_size
,
1276 DissectImageFlags flags
,
1277 DecryptedImage
**ret
) {
1279 #if HAVE_LIBCRYPTSETUP
1280 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1286 assert(root_hash
|| root_hash_size
== 0);
1290 * = 0 → There was nothing to decrypt
1291 * > 0 → Decrypted successfully
1292 * -ENOKEY → There's something to decrypt but no key was supplied
1293 * -EKEYREJECTED → Passed key was not correct
1296 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1299 if (!m
->encrypted
&& !m
->verity
) {
1304 #if HAVE_LIBCRYPTSETUP
1305 d
= new0(DecryptedImage
, 1);
1309 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1310 DissectedPartition
*p
= m
->partitions
+ i
;
1316 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1320 k
= PARTITION_VERITY_OF(i
);
1322 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, flags
, d
);
1327 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1328 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1329 if (r
< 0 && r
!= -EUCLEAN
)
1342 int dissected_image_decrypt_interactively(
1344 const char *passphrase
,
1345 const void *root_hash
,
1346 size_t root_hash_size
,
1347 DissectImageFlags flags
,
1348 DecryptedImage
**ret
) {
1350 _cleanup_strv_free_erase_
char **z
= NULL
;
1357 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, flags
, ret
);
1360 if (r
== -EKEYREJECTED
)
1361 log_error_errno(r
, "Incorrect passphrase, try again!");
1362 else if (r
!= -ENOKEY
)
1363 return log_error_errno(r
, "Failed to decrypt image: %m");
1366 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1367 "Too many retries.");
1371 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1373 return log_error_errno(r
, "Failed to query for passphrase: %m");
1379 int decrypted_image_relinquish(DecryptedImage
*d
) {
1381 #if HAVE_LIBCRYPTSETUP
1388 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1389 * that we don't clean it up ourselves either anymore */
1391 #if HAVE_LIBCRYPTSETUP
1392 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1393 DecryptedPartition
*p
= d
->decrypted
+ i
;
1395 if (p
->relinquished
)
1398 r
= dm_deferred_remove(p
->name
);
1400 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1402 p
->relinquished
= true;
1409 int root_hash_load(const char *image
, void **ret
, size_t *ret_size
) {
1410 _cleanup_free_
char *text
= NULL
;
1411 _cleanup_free_
void *k
= NULL
;
1419 if (is_device_path(image
)) {
1420 /* If we are asked to load the root hash for a device node, exit early */
1426 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1430 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1433 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1434 n
= stpcpy(fn
, image
);
1435 e
= endswith(fn
, ".raw");
1439 strcpy(n
, ".roothash");
1441 r
= read_one_line_file(fn
, &text
);
1451 r
= unhexmem(text
, strlen(text
), &k
, &l
);
1454 if (l
< sizeof(sd_id128_t
))
1463 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1473 static const char *const paths
[_META_MAX
] = {
1474 [META_HOSTNAME
] = "/etc/hostname\0",
1475 [META_MACHINE_ID
] = "/etc/machine-id\0",
1476 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1477 [META_OS_RELEASE
] = "/etc/os-release\0"
1478 "/usr/lib/os-release\0",
1481 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1482 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1483 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1484 sd_id128_t machine_id
= SD_ID128_NULL
;
1485 _cleanup_free_
char *hostname
= NULL
;
1486 unsigned n_meta_initialized
= 0, k
;
1487 int fds
[2 * _META_MAX
], r
;
1489 BLOCK_SIGNALS(SIGCHLD
);
1493 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1494 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1499 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1503 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1507 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1509 log_debug_errno(r
, "Failed to mount dissected image: %m");
1510 _exit(EXIT_FAILURE
);
1513 for (k
= 0; k
< _META_MAX
; k
++) {
1514 _cleanup_close_
int fd
= -1;
1517 fds
[2*k
] = safe_close(fds
[2*k
]);
1519 NULSTR_FOREACH(p
, paths
[k
]) {
1520 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1525 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1529 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1531 _exit(EXIT_FAILURE
);
1533 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1536 _exit(EXIT_SUCCESS
);
1539 for (k
= 0; k
< _META_MAX
; k
++) {
1540 _cleanup_fclose_
FILE *f
= NULL
;
1542 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1544 f
= fdopen(fds
[2*k
], "r");
1555 r
= read_etc_hostname_stream(f
, &hostname
);
1557 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1561 case META_MACHINE_ID
: {
1562 _cleanup_free_
char *line
= NULL
;
1564 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1566 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1568 r
= sd_id128_from_string(line
, &machine_id
);
1570 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1572 log_debug("/etc/machine-id file is empty.");
1574 log_debug("/etc/machine-id has unexpected length %i.", r
);
1579 case META_MACHINE_INFO
:
1580 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1582 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1586 case META_OS_RELEASE
:
1587 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1589 log_debug_errno(r
, "Failed to read OS release file: %m");
1595 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1599 if (r
!= EXIT_SUCCESS
)
1602 free_and_replace(m
->hostname
, hostname
);
1603 m
->machine_id
= machine_id
;
1604 strv_free_and_replace(m
->machine_info
, machine_info
);
1605 strv_free_and_replace(m
->os_release
, os_release
);
1608 for (k
= 0; k
< n_meta_initialized
; k
++)
1609 safe_close_pair(fds
+ 2*k
);
1614 int dissect_image_and_warn(
1617 const void *root_hash
,
1618 size_t root_hash_size
,
1619 DissectImageFlags flags
,
1620 DissectedImage
**ret
) {
1622 _cleanup_free_
char *buffer
= NULL
;
1626 r
= fd_get_path(fd
, &buffer
);
1633 r
= dissect_image(fd
, root_hash
, root_hash_size
, flags
, ret
);
1638 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1641 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1643 case -EADDRNOTAVAIL
:
1644 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1647 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1650 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1652 case -EPROTONOSUPPORT
:
1653 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1657 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1663 static const char *const partition_designator_table
[] = {
1664 [PARTITION_ROOT
] = "root",
1665 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1666 [PARTITION_HOME
] = "home",
1667 [PARTITION_SRV
] = "srv",
1668 [PARTITION_ESP
] = "esp",
1669 [PARTITION_XBOOTLDR
] = "xbootldr",
1670 [PARTITION_SWAP
] = "swap",
1671 [PARTITION_ROOT_VERITY
] = "root-verity",
1672 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1673 [PARTITION_TMP
] = "tmp",
1674 [PARTITION_VAR
] = "var",
1677 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);