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 const MountOptions
*mount_options
,
312 DissectImageFlags flags
,
313 DissectedImage
**ret
) {
316 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
317 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
318 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
319 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
320 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
321 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
322 _cleanup_free_
char *generic_node
= NULL
;
323 sd_id128_t generic_uuid
= SD_ID128_NULL
;
324 const char *pttype
= NULL
;
333 assert(root_hash
|| root_hash_size
== 0);
334 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
336 /* Probes a disk image, and returns information about what it found in *ret.
338 * Returns -ENOPKG if no suitable partition table or file system could be found.
339 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
342 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
343 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
346 if (root_hash_size
< sizeof(sd_id128_t
))
349 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
350 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
352 if (sd_id128_is_null(root_uuid
))
354 if (sd_id128_is_null(verity_uuid
))
358 if (fstat(fd
, &st
) < 0)
361 if (!S_ISBLK(st
.st_mode
))
364 b
= blkid_new_probe();
369 r
= blkid_probe_set_device(b
, fd
, 0, 0);
371 return errno_or_else(ENOMEM
);
373 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
374 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
375 blkid_probe_enable_superblocks(b
, 1);
376 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
379 blkid_probe_enable_partitions(b
, 1);
380 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
383 r
= blkid_do_safeprobe(b
);
384 if (IN_SET(r
, -2, 1))
385 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
387 return errno_or_else(EIO
);
389 m
= new0(DissectedImage
, 1);
393 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
397 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
398 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) ||
399 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
400 const char *usage
= NULL
;
402 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
403 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
404 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
405 const char *fstype
= NULL
, *options
= NULL
;
407 /* OK, we have found a file system, that's our root partition then. */
408 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
416 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
420 m
->single_file_system
= true;
421 m
->verity
= root_hash
&& verity_data
;
422 m
->can_verity
= !!verity_data
;
424 options
= mount_options_from_part(mount_options
, 0);
431 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
435 .architecture
= _ARCHITECTURE_INVALID
,
436 .fstype
= TAKE_PTR(t
),
438 .mount_options
= TAKE_PTR(o
),
441 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
443 /* Even on a single partition we need to wait for udev to create the
444 * /dev/block/X:Y symlink to /dev/loopZ */
445 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
454 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
458 is_gpt
= streq_ptr(pttype
, "gpt");
459 is_mbr
= streq_ptr(pttype
, "dos");
461 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
465 pl
= blkid_probe_get_partitions(b
);
467 return errno_or_else(ENOMEM
);
469 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
473 FOREACH_DEVICE(e
, q
) {
474 unsigned long long pflags
;
480 r
= sd_device_get_devnum(q
, &qn
);
484 if (st
.st_rdev
== qn
)
487 if (!device_is_block(q
))
490 if (device_is_mmc_special_partition(q
))
493 r
= sd_device_get_devname(q
, &node
);
497 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
501 pflags
= blkid_partition_get_flags(pp
);
503 nr
= blkid_partition_get_partno(pp
);
508 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
509 const char *stype
, *sid
, *fstype
= NULL
;
510 sd_id128_t type_id
, id
;
513 sid
= blkid_partition_get_uuid(pp
);
516 if (sd_id128_from_string(sid
, &id
) < 0)
519 stype
= blkid_partition_get_type_string(pp
);
522 if (sd_id128_from_string(stype
, &type_id
) < 0)
525 if (sd_id128_equal(type_id
, GPT_HOME
)) {
527 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
529 if (pflags
& GPT_FLAG_NO_AUTO
)
532 designator
= PARTITION_HOME
;
533 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
534 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
536 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
538 if (pflags
& GPT_FLAG_NO_AUTO
)
541 designator
= PARTITION_SRV
;
542 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
543 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
545 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
546 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
547 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
549 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
552 designator
= PARTITION_ESP
;
555 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
557 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
559 if (pflags
& GPT_FLAG_NO_AUTO
)
562 designator
= PARTITION_XBOOTLDR
;
563 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
565 #ifdef GPT_ROOT_NATIVE
566 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
568 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
570 if (pflags
& GPT_FLAG_NO_AUTO
)
573 /* If a root ID is specified, ignore everything but the root id */
574 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
577 designator
= PARTITION_ROOT
;
578 architecture
= native_architecture();
579 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
580 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
582 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
584 if (pflags
& GPT_FLAG_NO_AUTO
)
587 m
->can_verity
= true;
589 /* Ignore verity unless a root hash is specified */
590 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
593 designator
= PARTITION_ROOT_VERITY
;
594 fstype
= "DM_verity_hash";
595 architecture
= native_architecture();
599 #ifdef GPT_ROOT_SECONDARY
600 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
602 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
604 if (pflags
& GPT_FLAG_NO_AUTO
)
607 /* If a root ID is specified, ignore everything but the root id */
608 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
611 designator
= PARTITION_ROOT_SECONDARY
;
612 architecture
= SECONDARY_ARCHITECTURE
;
613 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
614 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
616 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
618 if (pflags
& GPT_FLAG_NO_AUTO
)
621 m
->can_verity
= true;
623 /* Ignore verity unless root has is specified */
624 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
627 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
628 fstype
= "DM_verity_hash";
629 architecture
= SECONDARY_ARCHITECTURE
;
633 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
635 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
637 if (pflags
& GPT_FLAG_NO_AUTO
)
640 designator
= PARTITION_SWAP
;
642 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
644 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
646 if (pflags
& GPT_FLAG_NO_AUTO
)
650 multiple_generic
= true;
653 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
655 generic_node
= strdup(node
);
660 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
662 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
664 if (pflags
& GPT_FLAG_NO_AUTO
)
667 designator
= PARTITION_TMP
;
668 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
670 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
672 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
674 if (pflags
& GPT_FLAG_NO_AUTO
)
677 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
680 /* For /var we insist that the uuid of the partition matches the
681 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
682 * ID. Why? Unlike the other partitions /var is inherently
683 * installation specific, hence we need to be careful not to mount it
684 * in the wrong installation. By hashing the partition UUID from
685 * /etc/machine-id we can securely bind the partition to the
688 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
692 if (!sd_id128_equal(var_uuid
, id
)) {
693 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
698 designator
= PARTITION_VAR
;
699 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
702 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
703 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
704 const char *options
= NULL
;
707 if (m
->partitions
[designator
].found
)
720 options
= mount_options_from_part(mount_options
, nr
);
727 m
->partitions
[designator
] = (DissectedPartition
) {
731 .architecture
= architecture
,
733 .fstype
= TAKE_PTR(t
),
735 .mount_options
= TAKE_PTR(o
),
741 switch (blkid_partition_get_type(pp
)) {
743 case 0x83: /* Linux partition */
745 if (pflags
!= 0x80) /* Bootable flag */
749 multiple_generic
= true;
753 generic_node
= strdup(node
);
760 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
761 _cleanup_free_
char *n
= NULL
, *o
= NULL
;
762 sd_id128_t id
= SD_ID128_NULL
;
763 const char *sid
, *options
= NULL
;
766 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
769 sid
= blkid_partition_get_uuid(pp
);
771 (void) sd_id128_from_string(sid
, &id
);
777 options
= mount_options_from_part(mount_options
, nr
);
784 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
788 .architecture
= _ARCHITECTURE_INVALID
,
791 .mount_options
= TAKE_PTR(o
),
799 if (!m
->partitions
[PARTITION_ROOT
].found
) {
800 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
801 * either, then check if there's a single generic one, and use that. */
803 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
804 return -EADDRNOTAVAIL
;
806 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
807 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
808 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
810 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
811 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
813 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
814 _cleanup_free_
char *o
= NULL
;
815 const char *options
= NULL
;
817 /* If the root has was set, then we won't fallback to a generic node, because the root hash
820 return -EADDRNOTAVAIL
;
822 /* If we didn't find a generic node, then we can't fix this up either */
826 /* If we didn't find a properly marked root partition, but we did find a single suitable
827 * generic Linux partition, then use this as root partition, if the caller asked for it. */
828 if (multiple_generic
)
831 options
= mount_options_from_part(mount_options
, generic_nr
);
838 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
841 .partno
= generic_nr
,
842 .architecture
= _ARCHITECTURE_INVALID
,
843 .node
= TAKE_PTR(generic_node
),
844 .uuid
= generic_uuid
,
845 .mount_options
= TAKE_PTR(o
),
851 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
852 return -EADDRNOTAVAIL
;
854 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
855 * (which would be weird, after all the root hash should only be assigned to one pair of
857 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
858 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
860 /* If we found a verity setup, then the root partition is necessarily read-only. */
861 m
->partitions
[PARTITION_ROOT
].rw
= false;
869 /* Fill in file system types if we don't know them yet. */
870 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
871 DissectedPartition
*p
= m
->partitions
+ i
;
876 if (!p
->fstype
&& p
->node
) {
877 r
= probe_filesystem(p
->node
, &p
->fstype
);
878 if (r
< 0 && r
!= -EUCLEAN
)
882 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
885 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
897 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
903 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
904 free(m
->partitions
[i
].fstype
);
905 free(m
->partitions
[i
].node
);
906 free(m
->partitions
[i
].decrypted_fstype
);
907 free(m
->partitions
[i
].decrypted_node
);
908 free(m
->partitions
[i
].mount_options
);
912 strv_free(m
->machine_info
);
913 strv_free(m
->os_release
);
918 static int is_loop_device(const char *path
) {
919 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
924 if (stat(path
, &st
) < 0)
927 if (!S_ISBLK(st
.st_mode
))
930 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
931 if (access(s
, F_OK
) < 0) {
935 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
936 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
937 if (access(s
, F_OK
) < 0)
938 return errno
== ENOENT
? false : -errno
;
944 static int run_fsck(const char *node
, const char *fstype
) {
951 r
= fsck_exists(fstype
);
953 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
957 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
961 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
963 return log_debug_errno(r
, "Failed to fork off fsck: %m");
966 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
967 log_debug_errno(errno
, "Failed to execl() fsck: %m");
968 _exit(FSCK_OPERATIONAL_ERROR
);
971 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
973 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
975 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
976 log_debug("fsck failed with exit status %i.", exit_status
);
978 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
979 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
981 log_debug("Ignoring fsck error.");
987 static int mount_partition(
988 DissectedPartition
*m
,
990 const char *directory
,
992 DissectImageFlags flags
) {
994 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
995 const char *p
, *node
, *fstype
;
1002 node
= m
->decrypted_node
?: m
->node
;
1003 fstype
= m
->decrypted_fstype
?: m
->fstype
;
1005 if (!m
->found
|| !node
|| !fstype
)
1008 /* Stacked encryption? Yuck */
1009 if (streq_ptr(fstype
, "crypto_LUKS"))
1012 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
1014 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1015 r
= run_fsck(node
, fstype
);
1021 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1029 /* If requested, turn on discard support. */
1030 if (fstype_can_discard(fstype
) &&
1031 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1032 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
1033 options
= strdup("discard");
1038 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
1039 _cleanup_free_
char *uid_option
= NULL
;
1041 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1044 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
1048 if (!isempty(m
->mount_options
))
1049 if (!strextend_with_separator(&options
, ",", m
->mount_options
, NULL
))
1052 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1059 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1060 int r
, boot_mounted
;
1065 if (!m
->partitions
[PARTITION_ROOT
].found
)
1068 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1069 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1073 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1074 r
= path_is_os_tree(where
);
1078 return -EMEDIUMTYPE
;
1082 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1085 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1089 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1093 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1097 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1101 boot_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1102 if (boot_mounted
< 0)
1103 return boot_mounted
;
1105 if (m
->partitions
[PARTITION_ESP
].found
) {
1106 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1107 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1109 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1111 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1115 } else if (boot_mounted
<= 0) {
1116 _cleanup_free_
char *p
= NULL
;
1118 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1119 if (r
>= 0 && dir_is_empty(p
) > 0) {
1120 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1130 #if HAVE_LIBCRYPTSETUP
1131 typedef struct DecryptedPartition
{
1132 struct crypt_device
*device
;
1135 } DecryptedPartition
;
1137 struct DecryptedImage
{
1138 DecryptedPartition
*decrypted
;
1144 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1145 #if HAVE_LIBCRYPTSETUP
1152 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1153 DecryptedPartition
*p
= d
->decrypted
+ i
;
1155 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1156 r
= crypt_deactivate(p
->device
, p
->name
);
1158 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1162 crypt_free(p
->device
);
1171 #if HAVE_LIBCRYPTSETUP
1173 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1174 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1177 assert(original_node
);
1182 base
= strrchr(original_node
, '/');
1184 base
= original_node
;
1190 name
= strjoin(base
, suffix
);
1193 if (!filename_is_valid(name
))
1196 node
= path_join(crypt_get_dir(), name
);
1200 *ret_name
= TAKE_PTR(name
);
1201 *ret_node
= TAKE_PTR(node
);
1206 static int decrypt_partition(
1207 DissectedPartition
*m
,
1208 const char *passphrase
,
1209 DissectImageFlags flags
,
1210 DecryptedImage
*d
) {
1212 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1213 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1219 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1222 if (!streq(m
->fstype
, "crypto_LUKS"))
1228 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1232 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1235 r
= crypt_init(&cd
, m
->node
);
1237 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1239 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1241 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
1243 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1245 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1246 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1247 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1249 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1250 return r
== -EPERM
? -EKEYREJECTED
: r
;
1253 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1254 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1257 m
->decrypted_node
= TAKE_PTR(node
);
1262 static int verity_can_reuse(const void *root_hash
, size_t root_hash_size
, bool has_sig
, const char *name
, struct crypt_device
**ret_cd
) {
1263 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1264 _cleanup_free_
char *root_hash_existing
= NULL
;
1265 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1266 struct crypt_params_verity crypt_params
= {};
1267 size_t root_hash_existing_size
= root_hash_size
;
1272 r
= crypt_init_by_name(&cd
, name
);
1274 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1275 r
= crypt_get_verity_info(cd
, &crypt_params
);
1277 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1278 root_hash_existing
= malloc0(root_hash_size
);
1279 if (!root_hash_existing
)
1281 r
= crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1283 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1284 if (root_hash_size
!= root_hash_existing_size
|| memcmp(root_hash_existing
, root_hash
, root_hash_size
) != 0)
1285 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1286 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1287 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount
1288 * used the same settings, so that a previous unsigned mount will not be reused if the user
1289 * asks to use signing for the new one, and viceversa. */
1290 if (has_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1291 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1294 *ret_cd
= TAKE_PTR(cd
);
1298 static inline void dm_deferred_remove_clean(char *name
) {
1301 (void) crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1304 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1306 static int verity_partition(
1307 DissectedPartition
*m
,
1308 DissectedPartition
*v
,
1309 const void *root_hash
,
1310 size_t root_hash_size
,
1311 const char *verity_data
,
1312 const char *root_hash_sig_path
,
1313 const void *root_hash_sig
,
1314 size_t root_hash_sig_size
,
1315 DissectImageFlags flags
,
1316 DecryptedImage
*d
) {
1318 _cleanup_free_
char *node
= NULL
, *name
= NULL
, *hash_sig_from_file
= NULL
;
1319 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1320 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
1324 assert(v
|| verity_data
);
1329 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1332 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1335 if (!streq(v
->fstype
, "DM_verity_hash"))
1339 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
1340 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1341 _cleanup_free_
char *root_hash_encoded
= NULL
;
1342 root_hash_encoded
= hexmem(root_hash
, root_hash_size
);
1343 if (!root_hash_encoded
)
1345 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
1347 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1351 if (!root_hash_sig
&& root_hash_sig_path
) {
1352 r
= read_full_file_full(AT_FDCWD
, root_hash_sig_path
, 0, &hash_sig_from_file
, &root_hash_sig_size
);
1357 r
= crypt_init(&cd
, verity_data
?: v
->node
);
1361 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1363 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1367 r
= crypt_set_data_device(cd
, m
->node
);
1371 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1374 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1375 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1376 * retry a few times before giving up. */
1377 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
1378 if (root_hash_sig
|| hash_sig_from_file
) {
1379 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1380 r
= crypt_activate_by_signed_key(cd
, name
, root_hash
, root_hash_size
, root_hash_sig
?: hash_sig_from_file
, root_hash_sig_size
, CRYPT_ACTIVATE_READONLY
);
1382 r
= log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "activation of verity device with signature requested, but not supported by cryptsetup due to missing crypt_activate_by_signed_key()");
1385 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1386 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1387 * There's no way to distinguish this situation from a genuine error due to invalid
1388 * parameters, so immediately fallback to activating the device with a unique name.
1389 * Improvements in libcrypsetup can ensure this never happens: https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1390 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1391 return verity_partition(m
, v
, root_hash
, root_hash_size
, verity_data
, NULL
, root_hash_sig
?: hash_sig_from_file
, root_hash_sig_size
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1392 if (!IN_SET(r
, 0, -EEXIST
, -ENODEV
))
1395 struct crypt_device
*existing_cd
= NULL
;
1397 if (!restore_deferred_remove
){
1398 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1399 r
= dm_deferred_remove_cancel(name
);
1401 return log_debug_errno(r
, "Disabling automated deferred removal for verity device %s failed: %m", node
);
1402 restore_deferred_remove
= strdup(name
);
1403 if (!restore_deferred_remove
)
1407 r
= verity_can_reuse(root_hash
, root_hash_size
, !!root_hash_sig
|| !!hash_sig_from_file
, name
, &existing_cd
);
1408 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1409 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1410 return verity_partition(m
, v
, root_hash
, root_hash_size
, verity_data
, NULL
, root_hash_sig
?: hash_sig_from_file
, root_hash_sig_size
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1411 if (!IN_SET(r
, 0, -ENODEV
, -ENOENT
))
1412 return log_debug_errno(r
, "Checking whether existing verity device %s can be reused failed: %m", node
);
1423 /* Sanity check: libdevmapper is known to report that the device already exists and is active,
1424 * but it's actually not there, so the later filesystem probe or mount would fail. */
1426 r
= access(node
, F_OK
);
1427 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1428 * Fall back to activating it with a unique device name. */
1429 if (r
!= 0 && FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1430 return verity_partition(m
, v
, root_hash
, root_hash_size
, verity_data
, NULL
, root_hash_sig
?: hash_sig_from_file
, root_hash_sig_size
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1432 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1433 restore_deferred_remove
= mfree(restore_deferred_remove
);
1435 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1436 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1439 m
->decrypted_node
= TAKE_PTR(node
);
1445 int dissected_image_decrypt(
1447 const char *passphrase
,
1448 const void *root_hash
,
1449 size_t root_hash_size
,
1450 const char *verity_data
,
1451 const char *root_hash_sig_path
,
1452 const void *root_hash_sig
,
1453 size_t root_hash_sig_size
,
1454 DissectImageFlags flags
,
1455 DecryptedImage
**ret
) {
1457 #if HAVE_LIBCRYPTSETUP
1458 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1464 assert(root_hash
|| root_hash_size
== 0);
1468 * = 0 → There was nothing to decrypt
1469 * > 0 → Decrypted successfully
1470 * -ENOKEY → There's something to decrypt but no key was supplied
1471 * -EKEYREJECTED → Passed key was not correct
1474 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1477 if (!m
->encrypted
&& !m
->verity
) {
1482 #if HAVE_LIBCRYPTSETUP
1483 d
= new0(DecryptedImage
, 1);
1487 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1488 DissectedPartition
*p
= m
->partitions
+ i
;
1494 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1498 k
= PARTITION_VERITY_OF(i
);
1500 r
= verity_partition(p
, m
->partitions
+ k
, root_hash
, root_hash_size
, verity_data
, root_hash_sig_path
, root_hash_sig
, root_hash_sig_size
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
1505 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1506 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1507 if (r
< 0 && r
!= -EUCLEAN
)
1520 int dissected_image_decrypt_interactively(
1522 const char *passphrase
,
1523 const void *root_hash
,
1524 size_t root_hash_size
,
1525 const char *verity_data
,
1526 const char *root_hash_sig_path
,
1527 const void *root_hash_sig
,
1528 size_t root_hash_sig_size
,
1529 DissectImageFlags flags
,
1530 DecryptedImage
**ret
) {
1532 _cleanup_strv_free_erase_
char **z
= NULL
;
1539 r
= dissected_image_decrypt(m
, passphrase
, root_hash
, root_hash_size
, verity_data
, root_hash_sig_path
, root_hash_sig
, root_hash_sig_size
, flags
, ret
);
1542 if (r
== -EKEYREJECTED
)
1543 log_error_errno(r
, "Incorrect passphrase, try again!");
1544 else if (r
!= -ENOKEY
)
1545 return log_error_errno(r
, "Failed to decrypt image: %m");
1548 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1549 "Too many retries.");
1553 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1555 return log_error_errno(r
, "Failed to query for passphrase: %m");
1561 int decrypted_image_relinquish(DecryptedImage
*d
) {
1563 #if HAVE_LIBCRYPTSETUP
1570 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1571 * that we don't clean it up ourselves either anymore */
1573 #if HAVE_LIBCRYPTSETUP
1574 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1575 DecryptedPartition
*p
= d
->decrypted
+ i
;
1577 if (p
->relinquished
)
1580 r
= crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1582 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1584 p
->relinquished
= true;
1591 int verity_metadata_load(const char *image
, const char *root_hash_path
, void **ret_roothash
, size_t *ret_roothash_size
, char **ret_verity_data
, char **ret_roothashsig
) {
1592 _cleanup_free_
char *verity_filename
= NULL
, *roothashsig_filename
= NULL
;
1593 _cleanup_free_
void *roothash_decoded
= NULL
;
1594 size_t roothash_decoded_size
= 0;
1599 if (is_device_path(image
)) {
1600 /* If we are asked to load the root hash for a device node, exit early */
1602 *ret_roothash
= NULL
;
1603 if (ret_roothash_size
)
1604 *ret_roothash_size
= 0;
1605 if (ret_verity_data
)
1606 *ret_verity_data
= NULL
;
1607 if (ret_roothashsig
)
1608 *ret_roothashsig
= NULL
;
1612 if (ret_verity_data
) {
1615 verity_filename
= new(char, strlen(image
) + STRLEN(".verity") + 1);
1616 if (!verity_filename
)
1618 strcpy(verity_filename
, image
);
1619 e
= endswith(verity_filename
, ".raw");
1621 strcpy(e
, ".verity");
1623 strcat(verity_filename
, ".verity");
1625 r
= access(verity_filename
, F_OK
);
1627 if (errno
!= ENOENT
)
1629 verity_filename
= mfree(verity_filename
);
1633 if (ret_roothashsig
) {
1636 /* Follow naming convention recommended by the relevant RFC:
1637 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1638 roothashsig_filename
= new(char, strlen(image
) + STRLEN(".roothash.p7s") + 1);
1639 if (!roothashsig_filename
)
1641 strcpy(roothashsig_filename
, image
);
1642 e
= endswith(roothashsig_filename
, ".raw");
1644 strcpy(e
, ".roothash.p7s");
1646 strcat(roothashsig_filename
, ".roothash.p7s");
1648 r
= access(roothashsig_filename
, R_OK
);
1650 if (errno
!= ENOENT
)
1652 roothashsig_filename
= mfree(roothashsig_filename
);
1657 _cleanup_free_
char *text
= NULL
;
1658 assert(ret_roothash_size
);
1660 if (root_hash_path
) {
1661 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1662 r
= read_one_line_file(root_hash_path
, &text
);
1666 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1670 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1673 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1674 n
= stpcpy(fn
, image
);
1675 e
= endswith(fn
, ".raw");
1679 strcpy(n
, ".roothash");
1681 r
= read_one_line_file(fn
, &text
);
1682 if (r
< 0 && r
!= -ENOENT
)
1688 r
= unhexmem(text
, strlen(text
), &roothash_decoded
, &roothash_decoded_size
);
1691 if (roothash_decoded_size
< sizeof(sd_id128_t
))
1697 *ret_roothash
= TAKE_PTR(roothash_decoded
);
1698 *ret_roothash_size
= roothash_decoded_size
;
1700 if (ret_verity_data
)
1701 *ret_verity_data
= TAKE_PTR(verity_filename
);
1702 if (roothashsig_filename
)
1703 *ret_roothashsig
= TAKE_PTR(roothashsig_filename
);
1708 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1718 static const char *const paths
[_META_MAX
] = {
1719 [META_HOSTNAME
] = "/etc/hostname\0",
1720 [META_MACHINE_ID
] = "/etc/machine-id\0",
1721 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1722 [META_OS_RELEASE
] = "/etc/os-release\0"
1723 "/usr/lib/os-release\0",
1726 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1727 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1728 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1729 sd_id128_t machine_id
= SD_ID128_NULL
;
1730 _cleanup_free_
char *hostname
= NULL
;
1731 unsigned n_meta_initialized
= 0, k
;
1732 int fds
[2 * _META_MAX
], r
;
1734 BLOCK_SIGNALS(SIGCHLD
);
1738 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1739 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1744 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1748 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1752 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1754 log_debug_errno(r
, "Failed to mount dissected image: %m");
1755 _exit(EXIT_FAILURE
);
1758 for (k
= 0; k
< _META_MAX
; k
++) {
1759 _cleanup_close_
int fd
= -1;
1762 fds
[2*k
] = safe_close(fds
[2*k
]);
1764 NULSTR_FOREACH(p
, paths
[k
]) {
1765 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1770 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1774 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1776 _exit(EXIT_FAILURE
);
1778 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1781 _exit(EXIT_SUCCESS
);
1784 for (k
= 0; k
< _META_MAX
; k
++) {
1785 _cleanup_fclose_
FILE *f
= NULL
;
1787 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1789 f
= take_fdopen(&fds
[2*k
], "r");
1798 r
= read_etc_hostname_stream(f
, &hostname
);
1800 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1804 case META_MACHINE_ID
: {
1805 _cleanup_free_
char *line
= NULL
;
1807 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1809 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1811 r
= sd_id128_from_string(line
, &machine_id
);
1813 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1815 log_debug("/etc/machine-id file is empty.");
1817 log_debug("/etc/machine-id has unexpected length %i.", r
);
1822 case META_MACHINE_INFO
:
1823 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1825 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1829 case META_OS_RELEASE
:
1830 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1832 log_debug_errno(r
, "Failed to read OS release file: %m");
1838 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1842 if (r
!= EXIT_SUCCESS
)
1845 free_and_replace(m
->hostname
, hostname
);
1846 m
->machine_id
= machine_id
;
1847 strv_free_and_replace(m
->machine_info
, machine_info
);
1848 strv_free_and_replace(m
->os_release
, os_release
);
1851 for (k
= 0; k
< n_meta_initialized
; k
++)
1852 safe_close_pair(fds
+ 2*k
);
1857 int dissect_image_and_warn(
1860 const void *root_hash
,
1861 size_t root_hash_size
,
1862 const char *verity_data
,
1863 const MountOptions
*mount_options
,
1864 DissectImageFlags flags
,
1865 DissectedImage
**ret
) {
1867 _cleanup_free_
char *buffer
= NULL
;
1871 r
= fd_get_path(fd
, &buffer
);
1878 r
= dissect_image(fd
, root_hash
, root_hash_size
, verity_data
, mount_options
, flags
, ret
);
1883 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1886 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1888 case -EADDRNOTAVAIL
:
1889 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1892 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1895 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1897 case -EPROTONOSUPPORT
:
1898 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1902 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1908 bool dissected_image_can_do_verity(const DissectedImage
*image
, unsigned partition_designator
) {
1909 if (image
->single_file_system
)
1910 return partition_designator
== PARTITION_ROOT
&& image
->can_verity
;
1912 return PARTITION_VERITY_OF(partition_designator
) >= 0;
1915 bool dissected_image_has_verity(const DissectedImage
*image
, unsigned partition_designator
) {
1918 if (image
->single_file_system
)
1919 return partition_designator
== PARTITION_ROOT
&& image
->verity
;
1921 k
= PARTITION_VERITY_OF(partition_designator
);
1922 return k
>= 0 && image
->partitions
[k
].found
;
1925 MountOptions
* mount_options_free_all(MountOptions
*options
) {
1928 while ((m
= options
)) {
1929 LIST_REMOVE(mount_options
, options
, m
);
1937 const char* mount_options_from_part(const MountOptions
*options
, unsigned int partition_number
) {
1940 LIST_FOREACH(mount_options
, m
, (MountOptions
*)options
)
1941 if (partition_number
== m
->partition_number
&& !isempty(m
->options
))
1946 static const char *const partition_designator_table
[] = {
1947 [PARTITION_ROOT
] = "root",
1948 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
1949 [PARTITION_HOME
] = "home",
1950 [PARTITION_SRV
] = "srv",
1951 [PARTITION_ESP
] = "esp",
1952 [PARTITION_XBOOTLDR
] = "xbootldr",
1953 [PARTITION_SWAP
] = "swap",
1954 [PARTITION_ROOT_VERITY
] = "root-verity",
1955 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
1956 [PARTITION_TMP
] = "tmp",
1957 [PARTITION_VAR
] = "var",
1960 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);