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>
14 #include "sd-device.h"
17 #include "architecture.h"
18 #include "ask-password-api.h"
19 #include "blkid-util.h"
20 #include "blockdev-util.h"
22 #include "cryptsetup-util.h"
24 #include "device-nodes.h"
25 #include "device-util.h"
26 #include "dissect-image.h"
32 #include "fsck-util.h"
34 #include "hexdecoct.h"
35 #include "hostname-util.h"
36 #include "id128-util.h"
38 #include "mount-util.h"
39 #include "mountpoint-util.h"
40 #include "namespace-util.h"
41 #include "nulstr-util.h"
43 #include "path-util.h"
44 #include "process-util.h"
45 #include "raw-clone.h"
46 #include "signal-util.h"
47 #include "stat-util.h"
48 #include "stdio-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
52 #include "tmpfile-util.h"
53 #include "udev-util.h"
54 #include "user-util.h"
55 #include "xattr-util.h"
57 /* how many times to wait for the device nodes to appear */
58 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
60 int probe_filesystem(const char *node
, char **ret_fstype
) {
61 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
62 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
63 * different error otherwise. */
66 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
71 b
= blkid_new_probe_from_filename(node
);
73 return errno_or_else(ENOMEM
);
75 blkid_probe_enable_superblocks(b
, 1);
76 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
79 r
= blkid_do_safeprobe(b
);
81 log_debug("No type detected on partition %s", node
);
85 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
86 "Results ambiguous for partition %s", node
);
88 return errno_or_else(EIO
);
90 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
112 /* Detect RPMB and Boot partitions, which are not listed by blkid.
113 * See https://github.com/systemd/systemd/issues/5806. */
114 static bool device_is_mmc_special_partition(sd_device
*d
) {
119 if (sd_device_get_sysname(d
, &sysname
) < 0)
122 return startswith(sysname
, "mmcblk") &&
123 (endswith(sysname
, "rpmb") || endswith(sysname
, "boot0") || endswith(sysname
, "boot1"));
126 static bool device_is_block(sd_device
*d
) {
131 if (sd_device_get_subsystem(d
, &ss
) < 0)
134 return streq(ss
, "block");
137 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
138 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
144 r
= sd_device_enumerator_new(&e
);
148 r
= sd_device_enumerator_allow_uninitialized(e
);
152 r
= sd_device_enumerator_add_match_parent(e
, d
);
160 static int wait_for_partitions_to_appear(
163 unsigned num_partitions
,
164 DissectImageFlags flags
,
165 sd_device_enumerator
**ret_enumerator
) {
167 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
174 assert(ret_enumerator
);
176 r
= enumerator_for_parent(d
, &e
);
180 /* Count the partitions enumerated by the kernel */
182 FOREACH_DEVICE(e
, q
) {
183 if (sd_device_get_devnum(q
, NULL
) < 0)
185 if (!device_is_block(q
))
187 if (device_is_mmc_special_partition(q
))
190 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
191 r
= device_wait_for_initialization(q
, "block", USEC_INFINITY
, NULL
);
199 if (n
== num_partitions
+ 1) {
200 *ret_enumerator
= TAKE_PTR(e
);
201 return 0; /* success! */
203 if (n
> num_partitions
+ 1)
204 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
205 "blkid and kernel partition lists do not match.");
207 /* The kernel has probed fewer partitions than blkid? Maybe the kernel prober is still running or it
208 * got EBUSY because udev already opened the device. Let's reprobe the device, which is a synchronous
209 * call that waits until probing is complete. */
211 for (unsigned j
= 0; ; j
++) {
215 if (ioctl(fd
, BLKRRPART
, 0) >= 0)
219 /* If we are running on a block device that has partition scanning off, return an
220 * explicit recognizable error about this, so that callers can generate a proper
221 * message explaining the situation. */
223 r
= blockdev_partscan_enabled(fd
);
227 return log_debug_errno(EPROTONOSUPPORT
,
228 "Device is a loop device and partition scanning is off!");
230 return -EINVAL
; /* original error */
235 /* If something else has the device open, such as an udev rule, the ioctl will return
236 * EBUSY. Since there's no way to wait until it isn't busy anymore, let's just wait a bit,
239 * This is really something they should fix in the kernel! */
240 (void) usleep(50 * USEC_PER_MSEC
);
244 return -EAGAIN
; /* no success yet, try again */
247 static int loop_wait_for_partitions_to_appear(
250 unsigned num_partitions
,
251 DissectImageFlags flags
,
252 sd_device_enumerator
**ret_enumerator
) {
253 _cleanup_(sd_device_unrefp
) sd_device
*device
= NULL
;
258 assert(ret_enumerator
);
260 log_debug("Waiting for device (parent + %d partitions) to appear...", num_partitions
);
262 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
263 r
= device_wait_for_initialization(d
, "block", USEC_INFINITY
, &device
);
267 device
= sd_device_ref(d
);
269 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
270 r
= wait_for_partitions_to_appear(fd
, device
, num_partitions
, flags
, ret_enumerator
);
275 return log_debug_errno(SYNTHETIC_ERRNO(ENXIO
),
276 "Kernel partitions dit not appear within %d attempts",
277 N_DEVICE_NODE_LIST_ATTEMPTS
);
280 static void check_partition_flags(
282 unsigned long long pflags
,
283 unsigned long long supported
) {
287 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
288 pflags
&= ~(supported
| GPT_FLAG_REQUIRED_PARTITION
| GPT_FLAG_NO_BLOCK_IO_PROTOCOL
| GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
293 /* If there are other bits set, then log about it, to make things discoverable */
294 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
295 unsigned long long bit
= 1ULL << i
;
296 if (!FLAGS_SET(pflags
, bit
))
299 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
307 const VeritySettings
*verity
,
308 const MountOptions
*mount_options
,
309 DissectImageFlags flags
,
310 DissectedImage
**ret
) {
313 sd_id128_t root_uuid
= SD_ID128_NULL
, verity_uuid
= SD_ID128_NULL
;
314 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
315 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
316 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
317 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
318 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
319 _cleanup_free_
char *generic_node
= NULL
;
320 sd_id128_t generic_uuid
= SD_ID128_NULL
;
321 const char *pttype
= NULL
;
329 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
330 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
332 /* Probes a disk image, and returns information about what it found in *ret.
334 * Returns -ENOPKG if no suitable partition table or file system could be found.
335 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
337 if (verity
&& verity
->root_hash
) {
338 /* If a root hash is supplied, then we use the root partition that has a UUID that match the first
339 * 128bit of the root hash. And we use the verity partition that has a UUID that match the final
342 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
345 memcpy(&root_uuid
, verity
->root_hash
, sizeof(sd_id128_t
));
346 memcpy(&verity_uuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
348 if (sd_id128_is_null(root_uuid
))
350 if (sd_id128_is_null(verity_uuid
))
354 if (fstat(fd
, &st
) < 0)
357 if (!S_ISBLK(st
.st_mode
))
360 b
= blkid_new_probe();
365 r
= blkid_probe_set_device(b
, fd
, 0, 0);
367 return errno_or_else(ENOMEM
);
369 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
370 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
371 blkid_probe_enable_superblocks(b
, 1);
372 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
375 blkid_probe_enable_partitions(b
, 1);
376 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
379 r
= blkid_do_safeprobe(b
);
380 if (IN_SET(r
, -2, 1))
381 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
383 return errno_or_else(EIO
);
385 m
= new0(DissectedImage
, 1);
389 r
= sd_device_new_from_devnum(&d
, 'b', st
.st_rdev
);
393 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
394 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) ||
395 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
396 const char *usage
= NULL
;
398 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
399 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
400 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
401 const char *fstype
= NULL
, *options
= NULL
;
403 /* OK, we have found a file system, that's our root partition then. */
404 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
412 r
= device_path_make_major_minor(st
.st_mode
, st
.st_rdev
, &n
);
416 m
->single_file_system
= true;
417 m
->verity
= verity
&& verity
->root_hash
&& verity
->data_path
;
418 m
->can_verity
= verity
&& verity
->data_path
;
420 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
427 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
431 .architecture
= _ARCHITECTURE_INVALID
,
432 .fstype
= TAKE_PTR(t
),
434 .mount_options
= TAKE_PTR(o
),
437 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
439 /* Even on a single partition we need to wait for udev to create the
440 * /dev/block/X:Y symlink to /dev/loopZ */
441 r
= loop_wait_for_partitions_to_appear(fd
, d
, 0, flags
, &e
);
450 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
454 is_gpt
= streq_ptr(pttype
, "gpt");
455 is_mbr
= streq_ptr(pttype
, "dos");
457 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
461 pl
= blkid_probe_get_partitions(b
);
463 return errno_or_else(ENOMEM
);
465 r
= loop_wait_for_partitions_to_appear(fd
, d
, blkid_partlist_numof_partitions(pl
), flags
, &e
);
469 FOREACH_DEVICE(e
, q
) {
470 unsigned long long pflags
;
476 r
= sd_device_get_devnum(q
, &qn
);
480 if (st
.st_rdev
== qn
)
483 if (!device_is_block(q
))
486 if (device_is_mmc_special_partition(q
))
489 r
= sd_device_get_devname(q
, &node
);
493 pp
= blkid_partlist_devno_to_partition(pl
, qn
);
497 pflags
= blkid_partition_get_flags(pp
);
499 nr
= blkid_partition_get_partno(pp
);
504 PartitionDesignator designator
= _PARTITION_DESIGNATOR_INVALID
;
505 int architecture
= _ARCHITECTURE_INVALID
;
506 const char *stype
, *sid
, *fstype
= NULL
;
507 sd_id128_t type_id
, id
;
510 sid
= blkid_partition_get_uuid(pp
);
513 if (sd_id128_from_string(sid
, &id
) < 0)
516 stype
= blkid_partition_get_type_string(pp
);
519 if (sd_id128_from_string(stype
, &type_id
) < 0)
522 if (sd_id128_equal(type_id
, GPT_HOME
)) {
524 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
526 if (pflags
& GPT_FLAG_NO_AUTO
)
529 designator
= PARTITION_HOME
;
530 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
531 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
533 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
535 if (pflags
& GPT_FLAG_NO_AUTO
)
538 designator
= PARTITION_SRV
;
539 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
540 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
542 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is not defined
543 * there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as recommended by the
544 * UEFI spec (See "12.3.3 Number and Location of System Partitions"). */
546 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
549 designator
= PARTITION_ESP
;
552 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
554 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
556 if (pflags
& GPT_FLAG_NO_AUTO
)
559 designator
= PARTITION_XBOOTLDR
;
560 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
562 #ifdef GPT_ROOT_NATIVE
563 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
565 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
567 if (pflags
& GPT_FLAG_NO_AUTO
)
570 /* If a root ID is specified, ignore everything but the root id */
571 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
574 designator
= PARTITION_ROOT
;
575 architecture
= native_architecture();
576 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
577 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
579 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
581 if (pflags
& GPT_FLAG_NO_AUTO
)
584 m
->can_verity
= true;
586 /* Ignore verity unless a root hash is specified */
587 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
590 designator
= PARTITION_ROOT_VERITY
;
591 fstype
= "DM_verity_hash";
592 architecture
= native_architecture();
596 #ifdef GPT_ROOT_SECONDARY
597 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
599 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
601 if (pflags
& GPT_FLAG_NO_AUTO
)
604 /* If a root ID is specified, ignore everything but the root id */
605 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
608 designator
= PARTITION_ROOT_SECONDARY
;
609 architecture
= SECONDARY_ARCHITECTURE
;
610 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
611 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
613 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
615 if (pflags
& GPT_FLAG_NO_AUTO
)
618 m
->can_verity
= true;
620 /* Ignore verity unless root has is specified */
621 if (sd_id128_is_null(verity_uuid
) || !sd_id128_equal(verity_uuid
, id
))
624 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
625 fstype
= "DM_verity_hash";
626 architecture
= SECONDARY_ARCHITECTURE
;
630 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
632 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
634 if (pflags
& GPT_FLAG_NO_AUTO
)
637 designator
= PARTITION_SWAP
;
639 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
641 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
643 if (pflags
& GPT_FLAG_NO_AUTO
)
647 multiple_generic
= true;
650 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
652 generic_node
= strdup(node
);
657 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
659 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
661 if (pflags
& GPT_FLAG_NO_AUTO
)
664 designator
= PARTITION_TMP
;
665 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
667 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
669 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
671 if (pflags
& GPT_FLAG_NO_AUTO
)
674 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
677 /* For /var we insist that the uuid of the partition matches the
678 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
679 * ID. Why? Unlike the other partitions /var is inherently
680 * installation specific, hence we need to be careful not to mount it
681 * in the wrong installation. By hashing the partition UUID from
682 * /etc/machine-id we can securely bind the partition to the
685 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
689 if (!sd_id128_equal(var_uuid
, id
)) {
690 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
695 designator
= PARTITION_VAR
;
696 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
699 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
700 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
701 const char *options
= NULL
;
704 if (m
->partitions
[designator
].found
)
717 options
= mount_options_from_designator(mount_options
, designator
);
724 m
->partitions
[designator
] = (DissectedPartition
) {
728 .architecture
= architecture
,
730 .fstype
= TAKE_PTR(t
),
732 .mount_options
= TAKE_PTR(o
),
738 switch (blkid_partition_get_type(pp
)) {
740 case 0x83: /* Linux partition */
742 if (pflags
!= 0x80) /* Bootable flag */
746 multiple_generic
= true;
750 generic_node
= strdup(node
);
757 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
758 _cleanup_free_
char *n
= NULL
, *o
= NULL
;
759 sd_id128_t id
= SD_ID128_NULL
;
760 const char *sid
, *options
= NULL
;
763 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
766 sid
= blkid_partition_get_uuid(pp
);
768 (void) sd_id128_from_string(sid
, &id
);
774 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
781 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
785 .architecture
= _ARCHITECTURE_INVALID
,
788 .mount_options
= TAKE_PTR(o
),
796 if (!m
->partitions
[PARTITION_ROOT
].found
) {
797 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
798 * either, then check if there's a single generic one, and use that. */
800 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
801 return -EADDRNOTAVAIL
;
803 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
804 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
805 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
807 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
808 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
810 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
811 _cleanup_free_
char *o
= NULL
;
812 const char *options
= NULL
;
814 /* If the root hash was set, then we won't fall back to a generic node, because the
815 * root hash decides. */
816 if (verity
&& verity
->root_hash
)
817 return -EADDRNOTAVAIL
;
819 /* If we didn't find a generic node, then we can't fix this up either */
823 /* If we didn't find a properly marked root partition, but we did find a single suitable
824 * generic Linux partition, then use this as root partition, if the caller asked for it. */
825 if (multiple_generic
)
828 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
835 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
838 .partno
= generic_nr
,
839 .architecture
= _ARCHITECTURE_INVALID
,
840 .node
= TAKE_PTR(generic_node
),
841 .uuid
= generic_uuid
,
842 .mount_options
= TAKE_PTR(o
),
847 if (verity
&& verity
->root_hash
) {
848 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
849 return -EADDRNOTAVAIL
;
851 /* If we found the primary root with the hash, then we definitely want to suppress any secondary root
852 * (which would be weird, after all the root hash should only be assigned to one pair of
854 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
855 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
857 /* If we found a verity setup, then the root partition is necessarily read-only. */
858 m
->partitions
[PARTITION_ROOT
].rw
= false;
866 /* Fill in file system types if we don't know them yet. */
867 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
868 DissectedPartition
*p
= m
->partitions
+ i
;
873 if (!p
->fstype
&& p
->node
) {
874 r
= probe_filesystem(p
->node
, &p
->fstype
);
875 if (r
< 0 && r
!= -EUCLEAN
)
879 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
882 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
894 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
898 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
899 free(m
->partitions
[i
].fstype
);
900 free(m
->partitions
[i
].node
);
901 free(m
->partitions
[i
].decrypted_fstype
);
902 free(m
->partitions
[i
].decrypted_node
);
903 free(m
->partitions
[i
].mount_options
);
907 strv_free(m
->machine_info
);
908 strv_free(m
->os_release
);
913 static int is_loop_device(const char *path
) {
914 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
919 if (stat(path
, &st
) < 0)
922 if (!S_ISBLK(st
.st_mode
))
925 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
926 if (access(s
, F_OK
) < 0) {
930 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
931 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
932 if (access(s
, F_OK
) < 0)
933 return errno
== ENOENT
? false : -errno
;
939 static int run_fsck(const char *node
, const char *fstype
) {
946 r
= fsck_exists(fstype
);
948 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
952 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
956 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
958 return log_debug_errno(r
, "Failed to fork off fsck: %m");
961 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
962 log_debug_errno(errno
, "Failed to execl() fsck: %m");
963 _exit(FSCK_OPERATIONAL_ERROR
);
966 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
968 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
970 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
971 log_debug("fsck failed with exit status %i.", exit_status
);
973 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
974 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
976 log_debug("Ignoring fsck error.");
982 static int mount_partition(
983 DissectedPartition
*m
,
985 const char *directory
,
987 DissectImageFlags flags
) {
989 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
990 const char *p
, *node
, *fstype
;
997 /* Use decrypted node and matching fstype if available, otherwise use the original device */
998 node
= m
->decrypted_node
?: m
->node
;
999 fstype
= m
->decrypted_node
? m
->decrypted_fstype
: m
->fstype
;
1001 if (!m
->found
|| !node
)
1004 return -EAFNOSUPPORT
;
1006 /* We are looking at an encrypted partition? This either means stacked encryption, or the caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error for this case. */
1007 if (streq(fstype
, "crypto_LUKS"))
1010 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
1012 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1013 r
= run_fsck(node
, fstype
);
1019 if (!FLAGS_SET(flags
, DISSECT_IMAGE_READ_ONLY
)) {
1020 /* Automatically create missing mount points, if necessary. */
1021 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
1026 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1034 /* If requested, turn on discard support. */
1035 if (fstype_can_discard(fstype
) &&
1036 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1037 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
)))) {
1038 options
= strdup("discard");
1043 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
1044 _cleanup_free_
char *uid_option
= NULL
;
1046 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1049 if (!strextend_with_separator(&options
, ",", uid_option
, NULL
))
1053 if (!isempty(m
->mount_options
))
1054 if (!strextend_with_separator(&options
, ",", m
->mount_options
, NULL
))
1057 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1058 r
= mkdir_p(p
, 0755);
1063 r
= mount_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1070 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1071 int r
, xbootldr_mounted
;
1078 * -ENXIO → No root partition found
1079 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release file found
1080 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1081 * -EUCLEAN → fsck for file system failed
1082 * -EBUSY → File system already mounted/used elsewhere (kernel)
1083 * -EAFNOSUPPORT → File system type not supported or not known
1086 if (!m
->partitions
[PARTITION_ROOT
].found
)
1089 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1090 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1094 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1095 r
= path_is_os_tree(where
);
1099 return -EMEDIUMTYPE
;
1103 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1106 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1107 * created if needed, but the image itself not modified. */
1108 flags
&= ~DISSECT_IMAGE_MKDIR
;
1110 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1114 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1118 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1122 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1126 xbootldr_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1127 if (xbootldr_mounted
< 0)
1128 return xbootldr_mounted
;
1130 if (m
->partitions
[PARTITION_ESP
].found
) {
1131 int esp_done
= false;
1133 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1134 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1136 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1141 /* /efi doesn't exist. Let's see if /boot is suitable then */
1143 if (!xbootldr_mounted
) {
1144 _cleanup_free_
char *p
= NULL
;
1146 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1150 } else if (dir_is_empty(p
) > 0) {
1151 /* It exists and is an empty directory. Let's mount the ESP there. */
1152 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1162 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1164 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1173 int dissected_image_mount_and_warn(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1179 r
= dissected_image_mount(m
, where
, uid_shift
, flags
);
1181 return log_error_errno(r
, "Not root file system found in image.");
1182 if (r
== -EMEDIUMTYPE
)
1183 return log_error_errno(r
, "No suitable os-release file in image found.");
1185 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
1187 return log_error_errno(r
, "File system check on image failed.");
1189 return log_error_errno(r
, "File system already mounted elsewhere.");
1190 if (r
== -EAFNOSUPPORT
)
1191 return log_error_errno(r
, "File system type not supported or not known.");
1193 return log_error_errno(r
, "Failed to mount image: %m");
1198 #if HAVE_LIBCRYPTSETUP
1199 typedef struct DecryptedPartition
{
1200 struct crypt_device
*device
;
1203 } DecryptedPartition
;
1205 struct DecryptedImage
{
1206 DecryptedPartition
*decrypted
;
1212 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1213 #if HAVE_LIBCRYPTSETUP
1220 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1221 DecryptedPartition
*p
= d
->decrypted
+ i
;
1223 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1224 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, 0);
1226 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1230 sym_crypt_free(p
->device
);
1239 #if HAVE_LIBCRYPTSETUP
1241 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1242 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1245 assert(original_node
);
1250 base
= strrchr(original_node
, '/');
1252 base
= original_node
;
1258 name
= strjoin(base
, suffix
);
1261 if (!filename_is_valid(name
))
1264 node
= path_join(sym_crypt_get_dir(), name
);
1268 *ret_name
= TAKE_PTR(name
);
1269 *ret_node
= TAKE_PTR(node
);
1274 static int decrypt_partition(
1275 DissectedPartition
*m
,
1276 const char *passphrase
,
1277 DissectImageFlags flags
,
1278 DecryptedImage
*d
) {
1280 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1281 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1287 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1290 if (!streq(m
->fstype
, "crypto_LUKS"))
1296 r
= dlopen_cryptsetup();
1300 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1304 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1307 r
= sym_crypt_init(&cd
, m
->node
);
1309 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1311 cryptsetup_enable_logging(cd
);
1313 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
1315 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1317 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1318 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1319 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1321 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1322 return r
== -EPERM
? -EKEYREJECTED
: r
;
1325 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1326 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1329 m
->decrypted_node
= TAKE_PTR(node
);
1334 static int verity_can_reuse(
1335 const VeritySettings
*verity
,
1337 struct crypt_device
**ret_cd
) {
1339 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1340 _cleanup_free_
char *root_hash_existing
= NULL
;
1341 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1342 struct crypt_params_verity crypt_params
= {};
1343 size_t root_hash_existing_size
;
1350 r
= sym_crypt_init_by_name(&cd
, name
);
1352 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1354 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
1356 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1358 root_hash_existing_size
= verity
->root_hash_size
;
1359 root_hash_existing
= malloc0(root_hash_existing_size
);
1360 if (!root_hash_existing
)
1363 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1365 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1366 if (verity
->root_hash_size
!= root_hash_existing_size
||
1367 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
1368 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1370 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1371 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1372 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1373 * signing for the new one, and viceversa. */
1374 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1375 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1378 *ret_cd
= TAKE_PTR(cd
);
1382 static inline void dm_deferred_remove_clean(char *name
) {
1386 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1389 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1391 static int verity_partition(
1392 DissectedPartition
*m
,
1393 DissectedPartition
*v
,
1394 const VeritySettings
*verity
,
1395 DissectImageFlags flags
,
1396 DecryptedImage
*d
) {
1398 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1399 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
1400 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1404 assert(v
|| (verity
&& verity
->data_path
));
1406 if (!verity
|| !verity
->root_hash
)
1409 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1411 if (!verity
->data_path
) {
1412 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1415 if (!streq(v
->fstype
, "DM_verity_hash"))
1419 r
= dlopen_cryptsetup();
1423 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
1424 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1425 _cleanup_free_
char *root_hash_encoded
= NULL
;
1427 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
1428 if (!root_hash_encoded
)
1431 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
1433 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1437 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
1441 cryptsetup_enable_logging(cd
);
1443 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
1447 r
= sym_crypt_set_data_device(cd
, m
->node
);
1451 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1454 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1455 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1456 * retry a few times before giving up. */
1457 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
1458 if (verity
->root_hash_sig
) {
1459 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1460 r
= sym_crypt_activate_by_signed_key(
1464 verity
->root_hash_size
,
1465 verity
->root_hash_sig
,
1466 verity
->root_hash_sig_size
,
1467 CRYPT_ACTIVATE_READONLY
);
1469 r
= log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1470 "Activation of verity device with signature requested, but not supported by %s due to missing crypt_activate_by_signed_key().", program_invocation_short_name
);
1473 r
= sym_crypt_activate_by_volume_key(
1477 verity
->root_hash_size
,
1478 CRYPT_ACTIVATE_READONLY
);
1479 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1480 * There's no way to distinguish this situation from a genuine error due to invalid
1481 * parameters, so immediately fall back to activating the device with a unique name.
1482 * Improvements in libcrypsetup can ensure this never happens:
1483 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1484 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1485 return verity_partition(m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1488 -EEXIST
, /* Volume is already open and ready to be used */
1489 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1490 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
1492 if (IN_SET(r
, -EEXIST
, -EBUSY
)) {
1493 struct crypt_device
*existing_cd
= NULL
;
1495 if (!restore_deferred_remove
){
1496 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1497 r
= dm_deferred_remove_cancel(name
);
1498 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1499 if (r
< 0 && r
!= -ENXIO
)
1500 return log_debug_errno(r
, "Disabling automated deferred removal for verity device %s failed: %m", node
);
1502 restore_deferred_remove
= strdup(name
);
1503 if (!restore_deferred_remove
)
1508 r
= verity_can_reuse(verity
, name
, &existing_cd
);
1509 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1510 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1511 return verity_partition(m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1512 if (!IN_SET(r
, 0, -ENODEV
, -ENOENT
, -EBUSY
))
1513 return log_debug_errno(r
, "Checking whether existing verity device %s can be reused failed: %m", node
);
1515 /* devmapper might say that the device exists, but the devlink might not yet have been
1516 * created. Check and wait for the udev event in that case. */
1517 r
= device_wait_for_devlink(node
, "block", 100 * USEC_PER_MSEC
, NULL
);
1518 /* Fallback to activation with a unique device if it's taking too long */
1519 if (r
== -ETIMEDOUT
)
1532 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1533 (void) usleep(2 * USEC_PER_MSEC
);
1536 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1537 * Fall back to activating it with a unique device name. */
1538 if (r
!= 0 && FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1539 return verity_partition(m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1541 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1542 restore_deferred_remove
= mfree(restore_deferred_remove
);
1544 d
->decrypted
[d
->n_decrypted
].name
= TAKE_PTR(name
);
1545 d
->decrypted
[d
->n_decrypted
].device
= TAKE_PTR(cd
);
1548 m
->decrypted_node
= TAKE_PTR(node
);
1554 int dissected_image_decrypt(
1556 const char *passphrase
,
1557 const VeritySettings
*verity
,
1558 DissectImageFlags flags
,
1559 DecryptedImage
**ret
) {
1561 #if HAVE_LIBCRYPTSETUP
1562 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1567 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
1571 * = 0 → There was nothing to decrypt
1572 * > 0 → Decrypted successfully
1573 * -ENOKEY → There's something to decrypt but no key was supplied
1574 * -EKEYREJECTED → Passed key was not correct
1577 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
1580 if (!m
->encrypted
&& !m
->verity
) {
1585 #if HAVE_LIBCRYPTSETUP
1586 d
= new0(DecryptedImage
, 1);
1590 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1591 DissectedPartition
*p
= m
->partitions
+ i
;
1592 PartitionDesignator k
;
1597 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1601 k
= PARTITION_VERITY_OF(i
);
1603 r
= verity_partition(p
, m
->partitions
+ k
, verity
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
1608 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1609 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1610 if (r
< 0 && r
!= -EUCLEAN
)
1623 int dissected_image_decrypt_interactively(
1625 const char *passphrase
,
1626 const VeritySettings
*verity
,
1627 DissectImageFlags flags
,
1628 DecryptedImage
**ret
) {
1630 _cleanup_strv_free_erase_
char **z
= NULL
;
1637 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
, ret
);
1640 if (r
== -EKEYREJECTED
)
1641 log_error_errno(r
, "Incorrect passphrase, try again!");
1642 else if (r
!= -ENOKEY
)
1643 return log_error_errno(r
, "Failed to decrypt image: %m");
1646 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1647 "Too many retries.");
1651 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1653 return log_error_errno(r
, "Failed to query for passphrase: %m");
1659 int decrypted_image_relinquish(DecryptedImage
*d
) {
1661 #if HAVE_LIBCRYPTSETUP
1668 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a boolean so
1669 * that we don't clean it up ourselves either anymore */
1671 #if HAVE_LIBCRYPTSETUP
1672 for (i
= 0; i
< d
->n_decrypted
; i
++) {
1673 DecryptedPartition
*p
= d
->decrypted
+ i
;
1675 if (p
->relinquished
)
1678 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
1680 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
1682 p
->relinquished
= true;
1689 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
1696 e
= endswith(image
, ".raw");
1698 return strjoin(e
, suffix
);
1700 n
= new(char, e
- image
+ strlen(suffix
) + 1);
1704 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
1708 void verity_settings_done(VeritySettings
*v
) {
1711 v
->root_hash
= mfree(v
->root_hash
);
1712 v
->root_hash_size
= 0;
1714 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
1715 v
->root_hash_sig_size
= 0;
1717 v
->data_path
= mfree(v
->data_path
);
1720 int verity_settings_load(
1721 VeritySettings
*verity
,
1723 const char *root_hash_path
,
1724 const char *root_hash_sig_path
) {
1726 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
1727 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
1728 _cleanup_free_
char *verity_data_path
= NULL
;
1734 /* If we are asked to load the root hash for a device node, exit early */
1735 if (is_device_path(image
))
1738 /* We only fill in what isn't already filled in */
1740 if (!verity
->root_hash
) {
1741 _cleanup_free_
char *text
= NULL
;
1743 if (root_hash_path
) {
1744 r
= read_one_line_file(root_hash_path
, &text
);
1748 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
1750 _cleanup_free_
char *p
= NULL
;
1752 if (!IN_SET(r
, -ENODATA
, -ENOENT
) && !ERRNO_IS_NOT_SUPPORTED(r
))
1755 p
= build_auxiliary_path(image
, ".roothash");
1759 r
= read_one_line_file(p
, &text
);
1760 if (r
< 0 && r
!= -ENOENT
)
1766 r
= unhexmem(text
, strlen(text
), &root_hash
, &root_hash_size
);
1769 if (root_hash_size
< sizeof(sd_id128_t
))
1774 if (!verity
->root_hash_sig
) {
1775 _cleanup_free_
char *p
= NULL
;
1777 if (!root_hash_sig_path
) {
1778 /* Follow naming convention recommended by the relevant RFC:
1779 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
1780 p
= build_auxiliary_path(image
, ".roothash.p7s");
1784 root_hash_sig_path
= p
;
1787 r
= read_full_file_full(AT_FDCWD
, root_hash_sig_path
, 0, (char**) &root_hash_sig
, &root_hash_sig_size
);
1791 } else if (root_hash_sig_size
== 0) /* refuse empty size signatures */
1795 if (!verity
->data_path
) {
1796 _cleanup_free_
char *p
= NULL
;
1798 p
= build_auxiliary_path(image
, ".verity");
1802 if (access(p
, F_OK
) < 0) {
1803 if (errno
!= ENOENT
)
1806 verity_data_path
= TAKE_PTR(p
);
1810 verity
->root_hash
= TAKE_PTR(root_hash
);
1811 verity
->root_hash_size
= root_hash_size
;
1814 if (root_hash_sig
) {
1815 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
1816 verity
->root_hash_sig_size
= root_hash_sig_size
;
1819 if (verity_data_path
)
1820 verity
->data_path
= TAKE_PTR(verity_data_path
);
1825 int dissected_image_acquire_metadata(DissectedImage
*m
) {
1835 static const char *const paths
[_META_MAX
] = {
1836 [META_HOSTNAME
] = "/etc/hostname\0",
1837 [META_MACHINE_ID
] = "/etc/machine-id\0",
1838 [META_MACHINE_INFO
] = "/etc/machine-info\0",
1839 [META_OS_RELEASE
] = "/etc/os-release\0"
1840 "/usr/lib/os-release\0",
1843 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
;
1844 _cleanup_close_pair_
int error_pipe
[2] = { -1, -1 };
1845 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
1846 _cleanup_(sigkill_waitp
) pid_t child
= 0;
1847 sd_id128_t machine_id
= SD_ID128_NULL
;
1848 _cleanup_free_
char *hostname
= NULL
;
1849 unsigned n_meta_initialized
= 0, k
;
1850 int fds
[2 * _META_MAX
], r
, v
;
1853 BLOCK_SIGNALS(SIGCHLD
);
1857 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++)
1858 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
1863 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
1867 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
1872 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
1876 error_pipe
[0] = safe_close(error_pipe
[0]);
1878 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
1880 /* Let parent know the error */
1881 (void) write(error_pipe
[1], &r
, sizeof(r
));
1883 log_debug_errno(r
, "Failed to mount dissected image: %m");
1884 _exit(EXIT_FAILURE
);
1887 for (k
= 0; k
< _META_MAX
; k
++) {
1888 _cleanup_close_
int fd
= -ENOENT
;
1891 fds
[2*k
] = safe_close(fds
[2*k
]);
1893 NULSTR_FOREACH(p
, paths
[k
]) {
1894 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
1899 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
1900 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1904 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
1906 (void) write(error_pipe
[1], &r
, sizeof(r
));
1907 _exit(EXIT_FAILURE
);
1910 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1913 _exit(EXIT_SUCCESS
);
1916 error_pipe
[1] = safe_close(error_pipe
[1]);
1918 for (k
= 0; k
< _META_MAX
; k
++) {
1919 _cleanup_fclose_
FILE *f
= NULL
;
1921 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
1923 f
= take_fdopen(&fds
[2*k
], "r");
1932 r
= read_etc_hostname_stream(f
, &hostname
);
1934 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
1938 case META_MACHINE_ID
: {
1939 _cleanup_free_
char *line
= NULL
;
1941 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1943 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
1945 r
= sd_id128_from_string(line
, &machine_id
);
1947 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
1949 log_debug("/etc/machine-id file is empty.");
1951 log_debug("/etc/machine-id has unexpected length %i.", r
);
1956 case META_MACHINE_INFO
:
1957 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
1959 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
1963 case META_OS_RELEASE
:
1964 r
= load_env_file_pairs(f
, "os-release", &os_release
);
1966 log_debug_errno(r
, "Failed to read OS release file: %m");
1972 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
1977 n
= read(error_pipe
[0], &v
, sizeof(v
));
1981 return v
; /* propagate error sent to us from child */
1985 if (r
!= EXIT_SUCCESS
)
1988 free_and_replace(m
->hostname
, hostname
);
1989 m
->machine_id
= machine_id
;
1990 strv_free_and_replace(m
->machine_info
, machine_info
);
1991 strv_free_and_replace(m
->os_release
, os_release
);
1994 for (k
= 0; k
< n_meta_initialized
; k
++)
1995 safe_close_pair(fds
+ 2*k
);
2000 int dissect_image_and_warn(
2003 const VeritySettings
*verity
,
2004 const MountOptions
*mount_options
,
2005 DissectImageFlags flags
,
2006 DissectedImage
**ret
) {
2008 _cleanup_free_
char *buffer
= NULL
;
2012 r
= fd_get_path(fd
, &buffer
);
2019 r
= dissect_image(fd
, verity
, mount_options
, flags
, ret
);
2024 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
2027 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
2029 case -EADDRNOTAVAIL
:
2030 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
2033 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
2036 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
2038 case -EPROTONOSUPPORT
:
2039 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
2043 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
2049 bool dissected_image_can_do_verity(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
2050 if (image
->single_file_system
)
2051 return partition_designator
== PARTITION_ROOT
&& image
->can_verity
;
2053 return PARTITION_VERITY_OF(partition_designator
) >= 0;
2056 bool dissected_image_has_verity(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
2059 if (image
->single_file_system
)
2060 return partition_designator
== PARTITION_ROOT
&& image
->verity
;
2062 k
= PARTITION_VERITY_OF(partition_designator
);
2063 return k
>= 0 && image
->partitions
[k
].found
;
2066 MountOptions
* mount_options_free_all(MountOptions
*options
) {
2069 while ((m
= options
)) {
2070 LIST_REMOVE(mount_options
, options
, m
);
2078 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
2079 const MountOptions
*m
;
2081 LIST_FOREACH(mount_options
, m
, options
)
2082 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
2088 int mount_image_privately_interactively(
2090 DissectImageFlags flags
,
2091 char **ret_directory
,
2092 LoopDevice
**ret_loop_device
,
2093 DecryptedImage
**ret_decrypted_image
) {
2095 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
2096 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
2097 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2098 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
2099 _cleanup_free_
char *temp
= NULL
;
2102 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2103 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2107 assert(ret_directory
);
2108 assert(ret_loop_device
);
2109 assert(ret_decrypted_image
);
2111 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
2113 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
2115 r
= loop_device_make_by_path(
2117 FLAGS_SET(flags
, DISSECT_IMAGE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
2118 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
2121 return log_error_errno(r
, "Failed to set up loopback device: %m");
2123 r
= dissect_image_and_warn(d
->fd
, image
, NULL
, NULL
, flags
, &dissected_image
);
2127 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, NULL
, flags
, &decrypted_image
);
2131 r
= detach_mount_namespace();
2133 return log_error_errno(r
, "Failed to detach mount namespace: %m");
2135 r
= mkdir_p(temp
, 0700);
2137 return log_error_errno(r
, "Failed to create mount point: %m");
2139 created_dir
= TAKE_PTR(temp
);
2141 r
= dissected_image_mount_and_warn(dissected_image
, created_dir
, UID_INVALID
, flags
);
2145 if (decrypted_image
) {
2146 r
= decrypted_image_relinquish(decrypted_image
);
2148 return log_error_errno(r
, "Failed to relinquish DM devices: %m");
2151 loop_device_relinquish(d
);
2153 *ret_directory
= TAKE_PTR(created_dir
);
2154 *ret_loop_device
= TAKE_PTR(d
);
2155 *ret_decrypted_image
= TAKE_PTR(decrypted_image
);
2160 static const char *const partition_designator_table
[] = {
2161 [PARTITION_ROOT
] = "root",
2162 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
2163 [PARTITION_HOME
] = "home",
2164 [PARTITION_SRV
] = "srv",
2165 [PARTITION_ESP
] = "esp",
2166 [PARTITION_XBOOTLDR
] = "xbootldr",
2167 [PARTITION_SWAP
] = "swap",
2168 [PARTITION_ROOT_VERITY
] = "root-verity",
2169 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
2170 [PARTITION_TMP
] = "tmp",
2171 [PARTITION_VAR
] = "var",
2174 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, PartitionDesignator
);