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"
37 #include "mount-util.h"
38 #include "mountpoint-util.h"
39 #include "namespace-util.h"
40 #include "nulstr-util.h"
42 #include "path-util.h"
43 #include "process-util.h"
44 #include "raw-clone.h"
45 #include "signal-util.h"
46 #include "stat-util.h"
47 #include "stdio-util.h"
48 #include "string-table.h"
49 #include "string-util.h"
51 #include "tmpfile-util.h"
52 #include "udev-util.h"
53 #include "user-util.h"
54 #include "xattr-util.h"
56 int probe_filesystem(const char *node
, char **ret_fstype
) {
57 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
58 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
59 * different error otherwise. */
62 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
67 b
= blkid_new_probe_from_filename(node
);
69 return errno_or_else(ENOMEM
);
71 blkid_probe_enable_superblocks(b
, 1);
72 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
75 r
= blkid_do_safeprobe(b
);
77 log_debug("No type detected on partition %s", node
);
81 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
82 "Results ambiguous for partition %s", node
);
84 return errno_or_else(EIO
);
86 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
108 /* Detect RPMB and Boot partitions, which are not listed by blkid.
109 * See https://github.com/systemd/systemd/issues/5806. */
110 static bool device_is_mmc_special_partition(sd_device
*d
) {
115 if (sd_device_get_sysname(d
, &sysname
) < 0)
118 return startswith(sysname
, "mmcblk") &&
119 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
122 static bool device_is_block(sd_device
*d
) {
127 if (sd_device_get_subsystem(d
, &ss
) < 0)
130 return streq(ss
, "block");
133 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
134 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
140 r
= sd_device_enumerator_new(&e
);
144 r
= sd_device_enumerator_allow_uninitialized(e
);
148 r
= sd_device_enumerator_add_match_parent(e
, d
);
156 /* how many times to wait for the device nodes to appear */
157 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
159 static int wait_for_partitions_to_appear(
162 unsigned num_partitions
,
163 DissectImageFlags flags
,
164 sd_device_enumerator
**ret_enumerator
) {
166 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
173 assert(ret_enumerator
);
175 r
= enumerator_for_parent(d
, &e
);
179 /* Count the partitions enumerated by the kernel */
181 FOREACH_DEVICE(e
, q
) {
182 if (sd_device_get_devnum(q
, NULL
) < 0)
184 if (!device_is_block(q
))
186 if (device_is_mmc_special_partition(q
))
189 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
190 r
= device_wait_for_initialization(q
, "block", USEC_INFINITY
, NULL
);
198 if (n
== num_partitions
+ 1) {
199 *ret_enumerator
= TAKE_PTR(e
);
200 return 0; /* success! */
202 if (n
> num_partitions
+ 1)
203 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
204 "blkid and kernel partition lists do not match.");
206 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
207 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
208 * call that waits until probing is complete. */
210 for (unsigned j
= 0; ; j
++) {
214 if (ioctl(fd
, BLKRRPART
, 0) >= 0)
218 struct loop_info64 info
;
220 /* If we are running on a loop device that has partition scanning off, return
221 * an explicit recognizable error about this, so that callers can generate a
222 * proper message explaining the situation. */
224 if (ioctl(fd
, LOOP_GET_STATUS64
, &info
) >= 0) {
225 #if HAVE_VALGRIND_MEMCHECK_H
226 /* Valgrind currently doesn't know LOOP_GET_STATUS64. Remove this once it does */
227 VALGRIND_MAKE_MEM_DEFINED(&info
, sizeof(info
));
230 if ((info
.lo_flags
& LO_FLAGS_PARTSCAN
) == 0)
231 return log_debug_errno(EPROTONOSUPPORT
,
232 "Device is a loop device and partition scanning is off!");
238 /* If something else has the device open, such as an udev rule, the ioctl will return
239 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
242 * This is really something they should fix in the kernel! */
243 (void) usleep(50 * USEC_PER_MSEC
);
247 return -EAGAIN
; /* no success yet, try again */
250 static int loop_wait_for_partitions_to_appear(
253 unsigned num_partitions
,
254 DissectImageFlags flags
,
255 sd_device_enumerator
**ret_enumerator
) {
256 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
261 assert(ret_enumerator
);
263 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions
);
265 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
266 r
= device_wait_for_initialization(d
, "block", USEC_INFINITY
, &device
);
270 device
= sd_device_ref(d
);
272 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
273 r
= wait_for_partitions_to_appear(fd
, device
, num_partitions
, flags
, ret_enumerator
);
278 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
279 "Kernel partitions dit not appear within %d attempts",
280 N_DEVICE_NODE_LIST_ATTEMPTS
);
283 static void check_partition_flags(
285 unsigned long long pflags
,
286 unsigned long long supported
) {
290 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
291 pflags
&= ~(supported
| GPT_FLAG_REQUIRED_PARTITION
| GPT_FLAG_NO_BLOCK_IO_PROTOCOL
| GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
296 /* If there are other bits set, then log about it, to make things discoverable */
297 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
298 unsigned long long bit
= 1ULL << i
;
299 if (!FLAGS_SET(pflags
, bit
))
302 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
310 const void *root_hash
,
311 size_t root_hash_size
,
312 const char *verity_data
,
313 const MountOptions
*mount_options
,
314 DissectImageFlags flags
,
315 DissectedImage
**ret
) {
318 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
319 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
320 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
321 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
322 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
323 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
324 _cleanup_free_
char *generic_node
= NULL
;
325 sd_id128_t generic_uuid
= SD_ID128_NULL
;
326 const char *pttype
= NULL
;
335 assert(root_hash
|| root_hash_size
== 0);
336 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
338 /* Probes a disk image, and returns information about what it found in *ret.
340 * Returns -ENOPKG if no suitable partition table or file system could be found.
341 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
344 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
345 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
348 if (root_hash_size
< sizeof(sd_id128_t
))
351 memcpy(&root_uuid
, root_hash
, sizeof(sd_id128_t
));
352 memcpy(&verity_uuid
, (const uint8_t*) root_hash
+ root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
354 if (sd_id128_is_null(root_uuid
))
356 if (sd_id128_is_null(verity_uuid
))
360 if (fstat(fd
, &st
) < 0)
363 if (!S_ISBLK(st
.st_mode
))
366 b
= blkid_new_probe();
371 r
= blkid_probe_set_device(b
, fd
, 0, 0);
373 return errno_or_else(ENOMEM
);
375 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
376 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
377 blkid_probe_enable_superblocks(b
, 1);
378 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
381 blkid_probe_enable_partitions(b
, 1);
382 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
385 r
= blkid_do_safeprobe(b
);
386 if (IN_SET(r
, -2, 1))
387 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
389 return errno_or_else(EIO
);
391 m
= new0(DissectedImage
, 1);
395 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
399 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
400 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) ||
401 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
402 const char *usage
= NULL
;
404 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
405 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
406 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
407 const char *fstype
= NULL
, *options
= NULL
;
409 /* OK, we have found a file system, that's our root partition then. */
410 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
418 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
422 m
->single_file_system
= true;
423 m
->verity
= root_hash
&& verity_data
;
424 m
->can_verity
= !!verity_data
;
426 options
= mount_options_from_part(mount_options
, 0);
433 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
437 .architecture
= _ARCHITECTURE_INVALID
,
438 .fstype
= TAKE_PTR(t
),
440 .mount_options
= TAKE_PTR(o
),
443 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
445 /* Even on a single partition we need to wait for udev to create the
446 * /dev/block/X:Y symlink to /dev/loopZ */
447 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
456 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
460 is_gpt
= streq_ptr(pttype
, "gpt");
461 is_mbr
= streq_ptr(pttype
, "dos");
463 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
467 pl
= blkid_probe_get_partitions(b
);
469 return errno_or_else(ENOMEM
);
471 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
475 FOREACH_DEVICE(e
, q
) {
476 unsigned long long pflags
;
482 r
= sd_device_get_devnum(q
, &qn
);
486 if (st
.st_rdev
== qn
)
489 if (!device_is_block(q
))
492 if (device_is_mmc_special_partition(q
))
495 r
= sd_device_get_devname(q
, &node
);
499 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
503 pflags
= blkid_partition_get_flags(pp
);
505 nr
= blkid_partition_get_partno(pp
);
510 int designator
= _PARTITION_DESIGNATOR_INVALID
, architecture
= _ARCHITECTURE_INVALID
;
511 const char *stype
, *sid
, *fstype
= NULL
;
512 sd_id128_t type_id
, id
;
515 sid
= blkid_partition_get_uuid(pp
);
518 if (sd_id128_from_string(sid
, &id
) < 0)
521 stype
= blkid_partition_get_type_string(pp
);
524 if (sd_id128_from_string(stype
, &type_id
) < 0)
527 if (sd_id128_equal(type_id
, GPT_HOME
)) {
529 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
531 if (pflags
& GPT_FLAG_NO_AUTO
)
534 designator
= PARTITION_HOME
;
535 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
536 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
538 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
540 if (pflags
& GPT_FLAG_NO_AUTO
)
543 designator
= PARTITION_SRV
;
544 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
545 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
547 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
548 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
549 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
551 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
554 designator
= PARTITION_ESP
;
557 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
559 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
561 if (pflags
& GPT_FLAG_NO_AUTO
)
564 designator
= PARTITION_XBOOTLDR
;
565 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
567 #ifdef GPT_ROOT_NATIVE
568 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
570 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
572 if (pflags
& GPT_FLAG_NO_AUTO
)
575 /* If a root ID is specified, ignore everything but the root id */
576 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
579 designator
= PARTITION_ROOT
;
580 architecture
= native_architecture();
581 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
582 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
584 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
586 if (pflags
& GPT_FLAG_NO_AUTO
)
589 m
->can_verity
= true;
591 /* Ignore verity unless a root hash is specified */
592 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
595 designator
= PARTITION_ROOT_VERITY
;
596 fstype
= "DM_verity_hash";
597 architecture
= native_architecture();
601 #ifdef GPT_ROOT_SECONDARY
602 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
604 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
606 if (pflags
& GPT_FLAG_NO_AUTO
)
609 /* If a root ID is specified, ignore everything but the root id */
610 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
613 designator
= PARTITION_ROOT_SECONDARY
;
614 architecture
= SECONDARY_ARCHITECTURE
;
615 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
616 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
618 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
620 if (pflags
& GPT_FLAG_NO_AUTO
)
623 m
->can_verity
= true;
625 /* Ignore verity unless root has is specified */
626 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
629 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
630 fstype
= "DM_verity_hash";
631 architecture
= SECONDARY_ARCHITECTURE
;
635 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
637 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
639 if (pflags
& GPT_FLAG_NO_AUTO
)
642 designator
= PARTITION_SWAP
;
644 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
646 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
648 if (pflags
& GPT_FLAG_NO_AUTO
)
652 multiple_generic
= true;
655 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
657 generic_node
= strdup(node
);
662 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
664 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
666 if (pflags
& GPT_FLAG_NO_AUTO
)
669 designator
= PARTITION_TMP
;
670 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
672 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
674 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
676 if (pflags
& GPT_FLAG_NO_AUTO
)
679 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
682 /* For /var we insist that the uuid of the partition matches the
683 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
684 * ID. Why? Unlike the other partitions /var is inherently
685 * installation specific, hence we need to be careful not to mount it
686 * in the wrong installation. By hashing the partition UUID from
687 * /etc/machine-id we can securely bind the partition to the
690 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
694 if (!sd_id128_equal(var_uuid
, id
)) {
695 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
700 designator
= PARTITION_VAR
;
701 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
704 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
705 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
706 const char *options
= NULL
;
709 if (m
->partitions
[designator
].found
)
722 options
= mount_options_from_part(mount_options
, nr
);
729 m
->partitions
[designator
] = (DissectedPartition
) {
733 .architecture
= architecture
,
735 .fstype
= TAKE_PTR(t
),
737 .mount_options
= TAKE_PTR(o
),
743 switch (blkid_partition_get_type(pp
)) {
745 case 0x83: /* Linux partition */
747 if (pflags
!= 0x80) /* Bootable flag */
751 multiple_generic
= true;
755 generic_node
= strdup(node
);
762 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
763 _cleanup_free_
char *n
= NULL
, *o
= NULL
;
764 sd_id128_t id
= SD_ID128_NULL
;
765 const char *sid
, *options
= NULL
;
768 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
771 sid
= blkid_partition_get_uuid(pp
);
773 (void) sd_id128_from_string(sid
, &id
);
779 options
= mount_options_from_part(mount_options
, nr
);
786 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
790 .architecture
= _ARCHITECTURE_INVALID
,
793 .mount_options
= TAKE_PTR(o
),
801 if (!m
->partitions
[PARTITION_ROOT
].found
) {
802 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
803 * either, then check if there's a single generic one, and use that. */
805 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
806 return -EADDRNOTAVAIL
;
808 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
809 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
810 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
812 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
813 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
815 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
816 _cleanup_free_
char *o
= NULL
;
817 const char *options
= NULL
;
819 /* If the root has was set, then we won't fallback to a generic node, because the root hash
822 return -EADDRNOTAVAIL
;
824 /* If we didn't find a generic node, then we can't fix this up either */
828 /* If we didn't find a properly marked root partition, but we did find a single suitable
829 * generic Linux partition, then use this as root partition, if the caller asked for it. */
830 if (multiple_generic
)
833 options
= mount_options_from_part(mount_options
, generic_nr
);
840 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
843 .partno
= generic_nr
,
844 .architecture
= _ARCHITECTURE_INVALID
,
845 .node
= TAKE_PTR(generic_node
),
846 .uuid
= generic_uuid
,
847 .mount_options
= TAKE_PTR(o
),
853 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
854 return -EADDRNOTAVAIL
;
856 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
857 * (which would be weird, after all the root hash should only be assigned to one pair of
859 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
860 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
862 /* If we found a verity setup, then the root partition is necessarily read-only. */
863 m
->partitions
[PARTITION_ROOT
].rw
= false;
871 /* Fill in file system types if we don't know them yet. */
872 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
873 DissectedPartition
*p
= m
->partitions
+ i
;
878 if (!p
->fstype
&& p
->node
) {
879 r
= probe_filesystem(p
->node
, &p
->fstype
);
880 if (r
< 0 && r
!= -EUCLEAN
)
884 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
887 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
899 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
905 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
906 free(m
->partitions
[i
].fstype
);
907 free(m
->partitions
[i
].node
);
908 free(m
->partitions
[i
].decrypted_fstype
);
909 free(m
->partitions
[i
].decrypted_node
);
910 free(m
->partitions
[i
].mount_options
);
914 strv_free(m
->machine_info
);
915 strv_free(m
->os_release
);
920 static int is_loop_device(const char *path
) {
921 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
926 if (stat(path
, &st
) < 0)
929 if (!S_ISBLK(st
.st_mode
))
932 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
933 if (access(s
, F_OK
) < 0) {
937 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
938 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
939 if (access(s
, F_OK
) < 0)
940 return errno
== ENOENT
? false : -errno
;
946 static int run_fsck(const char *node
, const char *fstype
) {
953 r
= fsck_exists(fstype
);
955 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
959 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
963 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
965 return log_debug_errno(r
, "Failed to fork off fsck: %m");
968 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
969 log_debug_errno(errno
, "Failed to execl() fsck: %m");
970 _exit(FSCK_OPERATIONAL_ERROR
);
973 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
975 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
977 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
978 log_debug("fsck failed with exit status %i.", exit_status
);
980 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
981 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
983 log_debug("Ignoring fsck error.");
989 static int mount_partition(
990 DissectedPartition
*m
,
992 const char *directory
,
994 DissectImageFlags flags
) {
996 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
997 const char *p
, *node
, *fstype
;
1004 node
= m
->decrypted_node
?: m
->node
;
1005 fstype
= m
->decrypted_fstype
?: m
->fstype
;
1007 if (!m
->found
|| !node
|| !fstype
)
1010 /* Stacked encryption? Yuck */
1011 if (streq_ptr(fstype
, "crypto_LUKS"))
1014 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
1016 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1017 r
= run_fsck(node
, fstype
);
1023 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1031 /* If requested, turn on discard support. */
1032 if (fstype_can_discard(fstype
) &&
1033 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1034 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
1035 options
= strdup("discard");
1040 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
1041 _cleanup_free_
char *uid_option
= NULL
;
1043 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1046 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
1050 if (!isempty(m
->mount_options
))
1051 if (!strextend_with_separator(&options
, ",", m
->mount_options
, NULL
))
1054 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1061 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1062 int r
, boot_mounted
;
1067 if (!m
->partitions
[PARTITION_ROOT
].found
)
1070 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1071 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1075 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1076 r
= path_is_os_tree(where
);
1080 return -EMEDIUMTYPE
;
1084 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1087 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1091 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1095 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1099 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1103 boot_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1104 if (boot_mounted
< 0)
1105 return boot_mounted
;
1107 if (m
->partitions
[PARTITION_ESP
].found
) {
1108 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1109 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1111 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1113 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1117 } else if (boot_mounted
<= 0) {
1118 _cleanup_free_
char *p
= NULL
;
1120 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1121 if (r
>= 0 && dir_is_empty(p
) > 0) {
1122 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1132 #if HAVE_LIBCRYPTSETUP
1133 typedef struct DecryptedPartition
{
1134 struct crypt_device
*device
;
1137 } DecryptedPartition
;
1139 struct DecryptedImage
{
1140 DecryptedPartition
*decrypted
;
1146 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1147 #if HAVE_LIBCRYPTSETUP
1154 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1155 DecryptedPartition
*p
= d
->decrypted
+ i
;
1157 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1158 r
= crypt_deactivate(p
->device
, p
->name
);
1160 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1164 crypt_free(p
->device
);
1173 #if HAVE_LIBCRYPTSETUP
1175 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1176 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1179 assert(original_node
);
1184 base
= strrchr(original_node
, '/');
1186 base
= original_node
;
1192 name
= strjoin(base
, suffix
);
1195 if (!filename_is_valid(name
))
1198 node
= path_join(crypt_get_dir(), name
);
1202 *ret_name
= TAKE_PTR(name
);
1203 *ret_node
= TAKE_PTR(node
);
1208 static int decrypt_partition(
1209 DissectedPartition
*m
,
1210 const char *passphrase
,
1211 DissectImageFlags flags
,
1212 DecryptedImage
*d
) {
1214 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1215 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1221 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1224 if (!streq(m
->fstype
, "crypto_LUKS"))
1230 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1234 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1237 r
= crypt_init(&cd
, m
->node
);
1239 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1241 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1243 r
= crypt_load(cd
, CRYPT_LUKS
, NULL
);
1245 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1247 r
= crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1248 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1249 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1251 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1252 return r
== -EPERM
? -EKEYREJECTED
: r
;
1255 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1256 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1259 m
->decrypted_node
= TAKE_PTR(node
);
1264 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
) {
1265 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1266 _cleanup_free_
char *root_hash_existing
= NULL
;
1267 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1268 struct crypt_params_verity crypt_params
= {};
1269 size_t root_hash_existing_size
= root_hash_size
;
1274 r
= crypt_init_by_name(&cd
, name
);
1276 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1277 r
= crypt_get_verity_info(cd
, &crypt_params
);
1279 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1280 root_hash_existing
= malloc0(root_hash_size
);
1281 if (!root_hash_existing
)
1283 r
= crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1285 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1286 if (root_hash_size
!= root_hash_existing_size
|| memcmp(root_hash_existing
, root_hash
, root_hash_size
) != 0)
1287 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1288 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1289 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount
1290 * used the same settings, so that a previous unsigned mount will not be reused if the user
1291 * asks to use signing for the new one, and viceversa. */
1292 if (has_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1293 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1296 *ret_cd
= TAKE_PTR(cd
);
1300 static inline void dm_deferred_remove_clean(char *name
) {
1303 (void) crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1306 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1308 static int verity_partition(
1309 DissectedPartition
*m
,
1310 DissectedPartition
*v
,
1311 const void *root_hash
,
1312 size_t root_hash_size
,
1313 const char *verity_data
,
1314 const char *root_hash_sig_path
,
1315 const void *root_hash_sig
,
1316 size_t root_hash_sig_size
,
1317 DissectImageFlags flags
,
1318 DecryptedImage
*d
) {
1320 _cleanup_free_
char *node
= NULL
, *name
= NULL
, *hash_sig_from_file
= NULL
;
1321 _cleanup_(crypt_freep
) struct crypt_device
*cd
= NULL
;
1322 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
1326 assert(v
|| verity_data
);
1331 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1334 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1337 if (!streq(v
->fstype
, "DM_verity_hash"))
1341 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
1342 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1343 _cleanup_free_
char *root_hash_encoded
= NULL
;
1344 root_hash_encoded
= hexmem(root_hash
, root_hash_size
);
1345 if (!root_hash_encoded
)
1347 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
1349 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1353 if (!root_hash_sig
&& root_hash_sig_path
) {
1354 r
= read_full_file_full(AT_FDCWD
, root_hash_sig_path
, 0, &hash_sig_from_file
, &root_hash_sig_size
);
1359 r
= crypt_init(&cd
, verity_data
?: v
->node
);
1363 crypt_set_log_callback(cd
, cryptsetup_log_glue
, NULL
);
1365 r
= crypt_load(cd
, CRYPT_VERITY
, NULL
);
1369 r
= crypt_set_data_device(cd
, m
->node
);
1373 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1376 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1377 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1378 * retry a few times before giving up. */
1379 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
1380 if (root_hash_sig
|| hash_sig_from_file
) {
1381 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1382 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
);
1384 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()");
1387 r
= crypt_activate_by_volume_key(cd
, name
, root_hash
, root_hash_size
, CRYPT_ACTIVATE_READONLY
);
1388 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1389 * There's no way to distinguish this situation from a genuine error due to invalid
1390 * parameters, so immediately fallback to activating the device with a unique name.
1391 * Improvements in libcrypsetup can ensure this never happens: https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1392 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1393 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
);
1394 if (!IN_SET(r
, 0, -EEXIST
, -ENODEV
))
1397 struct crypt_device
*existing_cd
= NULL
;
1399 if (!restore_deferred_remove
){
1400 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1401 r
= dm_deferred_remove_cancel(name
);
1403 return log_debug_errno(r
, "Disabling automated deferred removal for verity device %s failed: %m", node
);
1404 restore_deferred_remove
= strdup(name
);
1405 if (!restore_deferred_remove
)
1409 r
= verity_can_reuse(root_hash
, root_hash_size
, !!root_hash_sig
|| !!hash_sig_from_file
, name
, &existing_cd
);
1410 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1411 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1412 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
);
1413 if (!IN_SET(r
, 0, -ENODEV
, -ENOENT
))
1414 return log_debug_errno(r
, "Checking whether existing verity device %s can be reused failed: %m", node
);
1425 /* Sanity check: libdevmapper is known to report that the device already exists and is active,
1426 * but it's actually not there, so the later filesystem probe or mount would fail. */
1428 r
= access(node
, F_OK
);
1429 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1430 * Fall back to activating it with a unique device name. */
1431 if (r
!= 0 && FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1432 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
);
1434 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1435 restore_deferred_remove
= mfree(restore_deferred_remove
);
1437 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1438 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1441 m
->decrypted_node
= TAKE_PTR(node
);
1447 int dissected_image_decrypt(
1449 const char *passphrase
,
1450 const void *root_hash
,
1451 size_t root_hash_size
,
1452 const char *verity_data
,
1453 const char *root_hash_sig_path
,
1454 const void *root_hash_sig
,
1455 size_t root_hash_sig_size
,
1456 DissectImageFlags flags
,
1457 DecryptedImage
**ret
) {
1459 #if HAVE_LIBCRYPTSETUP
1460 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1466 assert(root_hash
|| root_hash_size
== 0);
1470 * = 0 → There was nothing to decrypt
1471 * > 0 → Decrypted successfully
1472 * -ENOKEY → There's something to decrypt but no key was supplied
1473 * -EKEYREJECTED → Passed key was not correct
1476 if (root_hash
&& root_hash_size
< sizeof(sd_id128_t
))
1479 if (!m
->encrypted
&& !m
->verity
) {
1484 #if HAVE_LIBCRYPTSETUP
1485 d
= new0(DecryptedImage
, 1);
1489 for (i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1490 DissectedPartition
*p
= m
->partitions
+ i
;
1496 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1500 k
= PARTITION_VERITY_OF(i
);
1502 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
);
1507 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1508 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1509 if (r
< 0 && r
!= -EUCLEAN
)
1522 int dissected_image_decrypt_interactively(
1524 const char *passphrase
,
1525 const void *root_hash
,
1526 size_t root_hash_size
,
1527 const char *verity_data
,
1528 const char *root_hash_sig_path
,
1529 const void *root_hash_sig
,
1530 size_t root_hash_sig_size
,
1531 DissectImageFlags flags
,
1532 DecryptedImage
**ret
) {
1534 _cleanup_strv_free_erase_
char **z
= NULL
;
1541 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
);
1544 if (r
== -EKEYREJECTED
)
1545 log_error_errno(r
, "Incorrect passphrase, try again!");
1546 else if (r
!= -ENOKEY
)
1547 return log_error_errno(r
, "Failed to decrypt image: %m");
1550 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1551 "Too many retries.");
1555 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1557 return log_error_errno(r
, "Failed to query for passphrase: %m");
1563 int decrypted_image_relinquish(DecryptedImage
*d
) {
1565 #if HAVE_LIBCRYPTSETUP
1572 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1573 * that we don't clean it up ourselves either anymore */
1575 #if HAVE_LIBCRYPTSETUP
1576 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1577 DecryptedPartition
*p
= d
->decrypted
+ i
;
1579 if (p
->relinquished
)
1582 r
= crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1584 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1586 p
->relinquished
= true;
1593 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
) {
1594 _cleanup_free_
char *verity_filename
= NULL
, *roothashsig_filename
= NULL
;
1595 _cleanup_free_
void *roothash_decoded
= NULL
;
1596 size_t roothash_decoded_size
= 0;
1601 if (is_device_path(image
)) {
1602 /* If we are asked to load the root hash for a device node, exit early */
1604 *ret_roothash
= NULL
;
1605 if (ret_roothash_size
)
1606 *ret_roothash_size
= 0;
1607 if (ret_verity_data
)
1608 *ret_verity_data
= NULL
;
1609 if (ret_roothashsig
)
1610 *ret_roothashsig
= NULL
;
1614 if (ret_verity_data
) {
1617 verity_filename
= new(char, strlen(image
) + STRLEN(".verity") + 1);
1618 if (!verity_filename
)
1620 strcpy(verity_filename
, image
);
1621 e
= endswith(verity_filename
, ".raw");
1623 strcpy(e
, ".verity");
1625 strcat(verity_filename
, ".verity");
1627 r
= access(verity_filename
, F_OK
);
1629 if (errno
!= ENOENT
)
1631 verity_filename
= mfree(verity_filename
);
1635 if (ret_roothashsig
) {
1638 /* Follow naming convention recommended by the relevant RFC:
1639 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1640 roothashsig_filename
= new(char, strlen(image
) + STRLEN(".roothash.p7s") + 1);
1641 if (!roothashsig_filename
)
1643 strcpy(roothashsig_filename
, image
);
1644 e
= endswith(roothashsig_filename
, ".raw");
1646 strcpy(e
, ".roothash.p7s");
1648 strcat(roothashsig_filename
, ".roothash.p7s");
1650 r
= access(roothashsig_filename
, R_OK
);
1652 if (errno
!= ENOENT
)
1654 roothashsig_filename
= mfree(roothashsig_filename
);
1659 _cleanup_free_
char *text
= NULL
;
1660 assert(ret_roothash_size
);
1662 if (root_hash_path
) {
1663 /* We have the path to a roothash to load and decode, eg: RootHash=/foo/bar.roothash */
1664 r
= read_one_line_file(root_hash_path
, &text
);
1668 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1672 if (!IN_SET(r
, -ENODATA
, -EOPNOTSUPP
, -ENOENT
))
1675 fn
= newa(char, strlen(image
) + STRLEN(".roothash") + 1);
1676 n
= stpcpy(fn
, image
);
1677 e
= endswith(fn
, ".raw");
1681 strcpy(n
, ".roothash");
1683 r
= read_one_line_file(fn
, &text
);
1684 if (r
< 0 && r
!= -ENOENT
)
1690 r
= unhexmem(text
, strlen(text
), &roothash_decoded
, &roothash_decoded_size
);
1693 if (roothash_decoded_size
< sizeof(sd_id128_t
))
1699 *ret_roothash
= TAKE_PTR(roothash_decoded
);
1700 *ret_roothash_size
= roothash_decoded_size
;
1702 if (ret_verity_data
)
1703 *ret_verity_data
= TAKE_PTR(verity_filename
);
1704 if (roothashsig_filename
)
1705 *ret_roothashsig
= TAKE_PTR(roothashsig_filename
);
1710 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1720 static const char *const paths
[_META_MAX
] = {
1721 [META_HOSTNAME
] = "/etc/hostname\0",
1722 [META_MACHINE_ID
] = "/etc/machine-id\0",
1723 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1724 [META_OS_RELEASE
] = "/etc/os-release\0"
1725 "/usr/lib/os-release\0",
1728 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1729 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1730 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1731 sd_id128_t machine_id
= SD_ID128_NULL
;
1732 _cleanup_free_
char *hostname
= NULL
;
1733 unsigned n_meta_initialized
= 0, k
;
1734 int fds
[2 * _META_MAX
], r
;
1736 BLOCK_SIGNALS(SIGCHLD
);
1740 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1741 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1746 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1750 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1754 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1756 log_debug_errno(r
, "Failed to mount dissected image: %m");
1757 _exit(EXIT_FAILURE
);
1760 for (k
= 0; k
< _META_MAX
; k
++) {
1761 _cleanup_close_
int fd
= -1;
1764 fds
[2*k
] = safe_close(fds
[2*k
]);
1766 NULSTR_FOREACH(p
, paths
[k
]) {
1767 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1772 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1776 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1778 _exit(EXIT_FAILURE
);
1780 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1783 _exit(EXIT_SUCCESS
);
1786 for (k
= 0; k
< _META_MAX
; k
++) {
1787 _cleanup_fclose_
FILE *f
= NULL
;
1789 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1791 f
= take_fdopen(&fds
[2*k
], "r");
1800 r
= read_etc_hostname_stream(f
, &hostname
);
1802 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1806 case META_MACHINE_ID
: {
1807 _cleanup_free_
char *line
= NULL
;
1809 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1811 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1813 r
= sd_id128_from_string(line
, &machine_id
);
1815 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1817 log_debug("/etc/machine-id file is empty.");
1819 log_debug("/etc/machine-id has unexpected length %i.", r
);
1824 case META_MACHINE_INFO
:
1825 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1827 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1831 case META_OS_RELEASE
:
1832 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1834 log_debug_errno(r
, "Failed to read OS release file: %m");
1840 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1844 if (r
!= EXIT_SUCCESS
)
1847 free_and_replace(m
->hostname
, hostname
);
1848 m
->machine_id
= machine_id
;
1849 strv_free_and_replace(m
->machine_info
, machine_info
);
1850 strv_free_and_replace(m
->os_release
, os_release
);
1853 for (k
= 0; k
< n_meta_initialized
; k
++)
1854 safe_close_pair(fds
+ 2*k
);
1859 int dissect_image_and_warn(
1862 const void *root_hash
,
1863 size_t root_hash_size
,
1864 const char *verity_data
,
1865 const MountOptions
*mount_options
,
1866 DissectImageFlags flags
,
1867 DissectedImage
**ret
) {
1869 _cleanup_free_
char *buffer
= NULL
;
1873 r
= fd_get_path(fd
, &buffer
);
1880 r
= dissect_image(fd
, root_hash
, root_hash_size
, verity_data
, mount_options
, flags
, ret
);
1885 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
1888 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
1890 case -EADDRNOTAVAIL
:
1891 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
1894 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
1897 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
1899 case -EPROTONOSUPPORT
:
1900 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
1904 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
1910 bool dissected_image_can_do_verity(const DissectedImage
*image
, unsigned partition_designator
) {
1911 if (image
->single_file_system
)
1912 return partition_designator
== PARTITION_ROOT
&& image
->can_verity
;
1914 return PARTITION_VERITY_OF(partition_designator
) >= 0;
1917 bool dissected_image_has_verity(const DissectedImage
*image
, unsigned partition_designator
) {
1920 if (image
->single_file_system
)
1921 return partition_designator
== PARTITION_ROOT
&& image
->verity
;
1923 k
= PARTITION_VERITY_OF(partition_designator
);
1924 return k
>= 0 && image
->partitions
[k
].found
;
1927 MountOptions
* mount_options_free_all(MountOptions
*options
) {
1930 while ((m
= options
)) {
1931 LIST_REMOVE(mount_options
, options
, m
);
1939 const char* mount_options_from_part(const MountOptions
*options
, unsigned int partition_number
) {
1942 LIST_FOREACH(mount_options
, m
, (MountOptions
*)options
)
1943 if (partition_number
== m
->partition_number
&& !isempty(m
->options
))
1949 int mount_image_privately_interactively(
1951 DissectImageFlags flags
,
1952 char **ret_directory
,
1953 LoopDevice
**ret_loop_device
,
1954 DecryptedImage
**ret_decrypted_image
) {
1956 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
1957 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
1958 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
1959 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
1960 _cleanup_free_
char *temp
= NULL
;
1963 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
1964 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
1968 assert(ret_directory
);
1969 assert(ret_loop_device
);
1970 assert(ret_decrypted_image
);
1972 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
1974 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
1976 r
= loop_device_make_by_path(
1978 FLAGS_SET(flags
, DISSECT_IMAGE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
1979 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
1982 return log_error_errno(r
, "Failed to set up loopback device: %m");
1984 r
= dissect_image_and_warn(d
->fd
, image
, NULL
, 0, NULL
, NULL
, flags
, &dissected_image
);
1988 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, NULL
, 0, NULL
, NULL
, NULL
, 0, flags
, &decrypted_image
);
1992 r
= detach_mount_namespace();
1994 return log_error_errno(r
, "Failed to detach mount namespace: %m");
1996 r
= mkdir_p(temp
, 0700);
1998 return log_error_errno(r
, "Failed to create mount point: %m");
2000 created_dir
= TAKE_PTR(temp
);
2002 r
= dissected_image_mount(dissected_image
, created_dir
, UID_INVALID
, flags
);
2004 return log_error_errno(r
, "File system check on image failed: %m");
2006 return log_error_errno(r
, "Failed to mount image: %m");
2008 if (decrypted_image
) {
2009 r
= decrypted_image_relinquish(decrypted_image
);
2011 return log_error_errno(r
, "Failed to relinquish DM devices: %m");
2014 loop_device_relinquish(d
);
2016 *ret_directory
= TAKE_PTR(created_dir
);
2017 *ret_loop_device
= TAKE_PTR(d
);
2018 *ret_decrypted_image
= TAKE_PTR(decrypted_image
);
2023 static const char *const partition_designator_table
[] = {
2024 [PARTITION_ROOT
] = "root",
2025 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
2026 [PARTITION_HOME
] = "home",
2027 [PARTITION_SRV
] = "srv",
2028 [PARTITION_ESP
] = "esp",
2029 [PARTITION_XBOOTLDR
] = "xbootldr",
2030 [PARTITION_SWAP
] = "swap",
2031 [PARTITION_ROOT_VERITY
] = "root-verity",
2032 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
2033 [PARTITION_TMP
] = "tmp",
2034 [PARTITION_VAR
] = "var",
2037 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, int);