1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
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 "discover-image.h"
27 #include "dissect-image.h"
30 #include "extension-release.h"
34 #include "fsck-util.h"
36 #include "hexdecoct.h"
37 #include "hostname-setup.h"
38 #include "id128-util.h"
39 #include "import-util.h"
41 #include "mount-util.h"
42 #include "mountpoint-util.h"
43 #include "namespace-util.h"
44 #include "nulstr-util.h"
46 #include "path-util.h"
47 #include "process-util.h"
48 #include "raw-clone.h"
49 #include "signal-util.h"
50 #include "stat-util.h"
51 #include "stdio-util.h"
52 #include "string-table.h"
53 #include "string-util.h"
55 #include "tmpfile-util.h"
56 #include "udev-util.h"
57 #include "user-util.h"
58 #include "xattr-util.h"
60 /* how many times to wait for the device nodes to appear */
61 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
63 int probe_filesystem(const char *node
, char **ret_fstype
) {
64 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
65 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and an
66 * different error otherwise. */
69 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
74 b
= blkid_new_probe_from_filename(node
);
76 return errno_or_else(ENOMEM
);
78 blkid_probe_enable_superblocks(b
, 1);
79 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
82 r
= blkid_do_safeprobe(b
);
84 log_debug("No type detected on partition %s", node
);
88 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
89 "Results ambiguous for partition %s", node
);
91 return errno_or_else(EIO
);
93 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
115 static int enumerator_for_parent(sd_device
*d
, sd_device_enumerator
**ret
) {
116 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
122 r
= sd_device_enumerator_new(&e
);
126 r
= sd_device_enumerator_allow_uninitialized(e
);
130 r
= sd_device_enumerator_add_match_parent(e
, d
);
138 static int device_is_partition(sd_device
*d
, blkid_partition pp
) {
139 blkid_loff_t bsize
, bstart
;
140 uint64_t size
, start
;
141 int partno
, bpartno
, r
;
147 r
= sd_device_get_subsystem(d
, &ss
);
150 if (!streq(ss
, "block"))
153 r
= sd_device_get_sysattr_value(d
, "partition", &v
);
154 if (r
== -ENOENT
|| /* Not a partition device */
155 ERRNO_IS_PRIVILEGE(r
)) /* Not ready to access? */
159 r
= safe_atoi(v
, &partno
);
164 bpartno
= blkid_partition_get_partno(pp
);
166 return errno_or_else(EIO
);
168 if (partno
!= bpartno
)
171 r
= sd_device_get_sysattr_value(d
, "start", &v
);
174 r
= safe_atou64(v
, &start
);
179 bstart
= blkid_partition_get_start(pp
);
181 return errno_or_else(EIO
);
183 if (start
!= (uint64_t) bstart
)
186 r
= sd_device_get_sysattr_value(d
, "size", &v
);
189 r
= safe_atou64(v
, &size
);
194 bsize
= blkid_partition_get_size(pp
);
196 return errno_or_else(EIO
);
198 if (size
!= (uint64_t) bsize
)
204 static int find_partition(
209 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
217 r
= enumerator_for_parent(parent
, &e
);
221 FOREACH_DEVICE(e
, q
) {
222 r
= device_is_partition(q
, pp
);
226 *ret
= sd_device_ref(q
);
235 sd_device
*parent_device
;
236 blkid_partition blkidp
;
240 static inline void wait_data_done(struct wait_data
*d
) {
241 sd_device_unref(d
->found
);
244 static int device_monitor_handler(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
245 const char *parent1_path
, *parent2_path
;
246 struct wait_data
*w
= userdata
;
252 if (device_for_action(device
, SD_DEVICE_REMOVE
))
255 r
= sd_device_get_parent(device
, &pp
);
257 return 0; /* Doesn't have a parent? No relevant to us */
259 r
= sd_device_get_syspath(pp
, &parent1_path
); /* Check parent of device of this action */
263 r
= sd_device_get_syspath(w
->parent_device
, &parent2_path
); /* Check parent of device we are looking for */
267 if (!path_equal(parent1_path
, parent2_path
))
268 return 0; /* Has a different parent than what we need, not interesting to us */
270 r
= device_is_partition(device
, w
->blkidp
);
273 if (r
== 0) /* Not the one we need */
276 /* It's the one we need! Yay! */
278 w
->found
= sd_device_ref(device
);
282 return sd_event_exit(sd_device_monitor_get_event(monitor
), r
);
285 static int wait_for_partition_device(
291 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timeout_source
= NULL
;
292 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
293 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
300 r
= find_partition(parent
, pp
, ret
);
304 r
= sd_event_new(&event
);
308 r
= sd_device_monitor_new(&monitor
);
312 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, "block", "partition");
316 r
= sd_device_monitor_attach_event(monitor
, event
);
320 _cleanup_(wait_data_done
) struct wait_data w
= {
321 .parent_device
= parent
,
325 r
= sd_device_monitor_start(monitor
, device_monitor_handler
, &w
);
329 /* Check again, the partition might have appeared in the meantime */
330 r
= find_partition(parent
, pp
, ret
);
334 if (deadline
!= USEC_INFINITY
) {
335 r
= sd_event_add_time(
336 event
, &timeout_source
,
337 CLOCK_MONOTONIC
, deadline
, 0,
338 NULL
, INT_TO_PTR(-ETIMEDOUT
));
343 r
= sd_event_loop(event
);
348 *ret
= TAKE_PTR(w
.found
);
352 static void check_partition_flags(
354 unsigned long long pflags
,
355 unsigned long long supported
) {
359 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
360 pflags
&= ~(supported
| GPT_FLAG_REQUIRED_PARTITION
| GPT_FLAG_NO_BLOCK_IO_PROTOCOL
| GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
365 /* If there are other bits set, then log about it, to make things discoverable */
366 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
367 unsigned long long bit
= 1ULL << i
;
368 if (!FLAGS_SET(pflags
, bit
))
371 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
375 static int device_wait_for_initialization_harder(
377 const char *subsystem
,
381 _cleanup_free_
char *uevent
= NULL
;
382 usec_t start
, left
, retrigger_timeout
;
385 start
= now(CLOCK_MONOTONIC
);
386 left
= usec_sub_unsigned(deadline
, start
);
389 char buf
[FORMAT_TIMESPAN_MAX
];
390 const char *sn
= NULL
;
392 (void) sd_device_get_sysname(device
, &sn
);
393 log_debug("Waiting for device '%s' to initialize for %s.", strna(sn
), format_timespan(buf
, sizeof(buf
), left
, 0));
396 if (left
!= USEC_INFINITY
)
397 retrigger_timeout
= CLAMP(left
/ 4, 1 * USEC_PER_SEC
, 5 * USEC_PER_SEC
); /* A fourth of the total timeout, but let's clamp to 1s…5s range */
399 retrigger_timeout
= 2 * USEC_PER_SEC
;
402 usec_t local_deadline
, n
;
405 n
= now(CLOCK_MONOTONIC
);
408 /* Find next deadline, when we'll retrigger */
409 local_deadline
= start
+
410 DIV_ROUND_UP(n
- start
, retrigger_timeout
) * retrigger_timeout
;
412 if (deadline
!= USEC_INFINITY
&& deadline
<= local_deadline
) {
413 local_deadline
= deadline
;
418 r
= device_wait_for_initialization(device
, subsystem
, local_deadline
, ret
);
419 if (r
>= 0 && DEBUG_LOGGING
) {
420 char buf
[FORMAT_TIMESPAN_MAX
];
421 const char *sn
= NULL
;
423 (void) sd_device_get_sysname(device
, &sn
);
424 log_debug("Successfully waited for device '%s' to initialize for %s.", strna(sn
), format_timespan(buf
, sizeof(buf
), usec_sub_unsigned(now(CLOCK_MONOTONIC
), start
), 0));
427 if (r
!= -ETIMEDOUT
|| last_try
)
433 r
= sd_device_get_syspath(device
, &syspath
);
437 uevent
= path_join(syspath
, "uevent");
443 char buf
[FORMAT_TIMESPAN_MAX
];
445 log_debug("Device didn't initialize within %s, assuming lost event. Retriggering device through %s.",
446 format_timespan(buf
, sizeof(buf
), usec_sub_unsigned(now(CLOCK_MONOTONIC
), start
), 0),
450 r
= write_string_file(uevent
, "change", WRITE_STRING_FILE_DISABLE_BUFFER
);
457 #define DEVICE_TIMEOUT_USEC (45 * USEC_PER_SEC)
461 const VeritySettings
*verity
,
462 const MountOptions
*mount_options
,
463 DissectImageFlags flags
,
464 DissectedImage
**ret
) {
467 #ifdef GPT_ROOT_NATIVE
468 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
470 #ifdef GPT_USR_NATIVE
471 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
473 bool is_gpt
, is_mbr
, generic_rw
, multiple_generic
= false;
474 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
475 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
476 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
477 _cleanup_free_
char *generic_node
= NULL
;
478 sd_id128_t generic_uuid
= SD_ID128_NULL
;
479 const char *pttype
= NULL
, *sysname
= NULL
;
481 int r
, generic_nr
, n_partitions
;
487 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
488 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
490 /* Probes a disk image, and returns information about what it found in *ret.
492 * Returns -ENOPKG if no suitable partition table or file system could be found.
493 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found. */
495 if (verity
&& verity
->root_hash
) {
496 sd_id128_t fsuuid
, vuuid
;
498 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
499 * first 128bit of the root hash. And we use the verity partition that has a UUID that match
500 * the final 128bit. */
502 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
505 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
506 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
508 if (sd_id128_is_null(fsuuid
))
510 if (sd_id128_is_null(vuuid
))
513 /* If the verity data declares it's for the /usr partition, then search for that, in all
514 * other cases assume it's for the root partition. */
515 #ifdef GPT_USR_NATIVE
516 if (verity
->designator
== PARTITION_USR
) {
518 usr_verity_uuid
= vuuid
;
521 #ifdef GPT_ROOT_NATIVE
523 root_verity_uuid
= vuuid
;
525 #ifdef GPT_USR_NATIVE
530 if (fstat(fd
, &st
) < 0)
533 if (!S_ISBLK(st
.st_mode
))
536 r
= sd_device_new_from_stat_rdev(&d
, &st
);
540 if (!FLAGS_SET(flags
, DISSECT_IMAGE_NO_UDEV
)) {
541 _cleanup_(sd_device_unrefp
) sd_device
*initialized
= NULL
;
543 /* If udev support is enabled, then let's wait for the device to be initialized before we doing anything. */
545 r
= device_wait_for_initialization_harder(
548 usec_add(now(CLOCK_MONOTONIC
), DEVICE_TIMEOUT_USEC
),
554 d
= TAKE_PTR(initialized
);
557 b
= blkid_new_probe();
562 r
= blkid_probe_set_device(b
, fd
, 0, 0);
564 return errno_or_else(ENOMEM
);
566 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
567 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
568 blkid_probe_enable_superblocks(b
, 1);
569 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
);
572 blkid_probe_enable_partitions(b
, 1);
573 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
576 r
= blkid_do_safeprobe(b
);
577 if (IN_SET(r
, -2, 1))
578 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
580 return errno_or_else(EIO
);
582 m
= new0(DissectedImage
, 1);
586 r
= sd_device_get_sysname(d
, &sysname
);
588 return log_debug_errno(r
, "Failed to get device sysname: %m");
589 if (startswith(sysname
, "loop")) {
590 _cleanup_free_
char *name_stripped
= NULL
;
591 const char *full_path
;
593 r
= sd_device_get_sysattr_value(d
, "loop/backing_file", &full_path
);
595 log_debug_errno(r
, "Failed to lookup image name via loop device backing file sysattr, ignoring: %m");
597 r
= raw_strip_suffixes(basename(full_path
), &name_stripped
);
602 free_and_replace(m
->image_name
, name_stripped
);
604 r
= free_and_strdup(&m
->image_name
, sysname
);
609 if (!image_name_is_valid(m
->image_name
)) {
610 log_debug("Image name %s is not valid, ignoring", strempty(m
->image_name
));
611 m
->image_name
= mfree(m
->image_name
);
614 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
615 (flags
& DISSECT_IMAGE_REQUIRE_ROOT
)) ||
616 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
617 const char *usage
= NULL
;
619 /* If flags permit this, also allow using non-partitioned single-filesystem images */
621 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
622 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
623 const char *fstype
= NULL
, *options
= NULL
, *devname
= NULL
;
624 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
626 /* OK, we have found a file system, that's our root partition then. */
627 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
635 r
= sd_device_get_devname(d
, &devname
);
643 m
->single_file_system
= true;
644 m
->verity
= verity
&& verity
->root_hash
&& verity
->data_path
&& (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
);
645 m
->can_verity
= verity
&& verity
->data_path
;
647 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
654 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
658 .architecture
= _ARCHITECTURE_INVALID
,
659 .fstype
= TAKE_PTR(t
),
661 .mount_options
= TAKE_PTR(o
),
664 m
->encrypted
= streq_ptr(fstype
, "crypto_LUKS");
671 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
675 is_gpt
= streq_ptr(pttype
, "gpt");
676 is_mbr
= streq_ptr(pttype
, "dos");
678 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
681 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
682 * do partition scanning. */
683 r
= blockdev_partscan_enabled(fd
);
687 return -EPROTONOSUPPORT
;
690 pl
= blkid_probe_get_partitions(b
);
692 return errno_or_else(ENOMEM
);
695 n_partitions
= blkid_partlist_numof_partitions(pl
);
696 if (n_partitions
< 0)
697 return errno_or_else(EIO
);
699 deadline
= usec_add(now(CLOCK_MONOTONIC
), DEVICE_TIMEOUT_USEC
);
700 for (int i
= 0; i
< n_partitions
; i
++) {
701 _cleanup_(sd_device_unrefp
) sd_device
*q
= NULL
;
702 unsigned long long pflags
;
708 pp
= blkid_partlist_get_partition(pl
, i
);
710 return errno_or_else(EIO
);
712 r
= wait_for_partition_device(d
, pp
, deadline
, &q
);
716 r
= sd_device_get_devname(q
, &node
);
720 pflags
= blkid_partition_get_flags(pp
);
723 nr
= blkid_partition_get_partno(pp
);
725 return errno_or_else(EIO
);
728 PartitionDesignator designator
= _PARTITION_DESIGNATOR_INVALID
;
729 int architecture
= _ARCHITECTURE_INVALID
;
730 const char *stype
, *sid
, *fstype
= NULL
;
731 sd_id128_t type_id
, id
;
734 sid
= blkid_partition_get_uuid(pp
);
737 if (sd_id128_from_string(sid
, &id
) < 0)
740 stype
= blkid_partition_get_type_string(pp
);
743 if (sd_id128_from_string(stype
, &type_id
) < 0)
746 if (sd_id128_equal(type_id
, GPT_HOME
)) {
748 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
750 if (pflags
& GPT_FLAG_NO_AUTO
)
753 designator
= PARTITION_HOME
;
754 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
756 } else if (sd_id128_equal(type_id
, GPT_SRV
)) {
758 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
760 if (pflags
& GPT_FLAG_NO_AUTO
)
763 designator
= PARTITION_SRV
;
764 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
766 } else if (sd_id128_equal(type_id
, GPT_ESP
)) {
768 /* Note that we don't check the GPT_FLAG_NO_AUTO flag for the ESP, as it is
769 * not defined there. We instead check the GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
770 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
773 if (pflags
& GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
776 designator
= PARTITION_ESP
;
779 } else if (sd_id128_equal(type_id
, GPT_XBOOTLDR
)) {
781 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
783 if (pflags
& GPT_FLAG_NO_AUTO
)
786 designator
= PARTITION_XBOOTLDR
;
787 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
789 #ifdef GPT_ROOT_NATIVE
790 else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE
)) {
792 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
794 if (pflags
& GPT_FLAG_NO_AUTO
)
797 /* If a root ID is specified, ignore everything but the root id */
798 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
801 designator
= PARTITION_ROOT
;
802 architecture
= native_architecture();
803 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
805 } else if (sd_id128_equal(type_id
, GPT_ROOT_NATIVE_VERITY
)) {
807 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
809 if (pflags
& GPT_FLAG_NO_AUTO
)
812 m
->can_verity
= true;
814 /* Ignore verity unless a root hash is specified */
815 if (sd_id128_is_null(root_verity_uuid
) || !sd_id128_equal(root_verity_uuid
, id
))
818 designator
= PARTITION_ROOT_VERITY
;
819 fstype
= "DM_verity_hash";
820 architecture
= native_architecture();
824 #ifdef GPT_ROOT_SECONDARY
825 else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY
)) {
827 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
829 if (pflags
& GPT_FLAG_NO_AUTO
)
832 /* If a root ID is specified, ignore everything but the root id */
833 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
836 designator
= PARTITION_ROOT_SECONDARY
;
837 architecture
= SECONDARY_ARCHITECTURE
;
838 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
840 } else if (sd_id128_equal(type_id
, GPT_ROOT_SECONDARY_VERITY
)) {
842 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
844 if (pflags
& GPT_FLAG_NO_AUTO
)
847 m
->can_verity
= true;
849 /* Ignore verity unless root has is specified */
850 if (sd_id128_is_null(root_verity_uuid
) || !sd_id128_equal(root_verity_uuid
, id
))
853 designator
= PARTITION_ROOT_SECONDARY_VERITY
;
854 fstype
= "DM_verity_hash";
855 architecture
= SECONDARY_ARCHITECTURE
;
859 #ifdef GPT_USR_NATIVE
860 else if (sd_id128_equal(type_id
, GPT_USR_NATIVE
)) {
862 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
864 if (pflags
& GPT_FLAG_NO_AUTO
)
867 /* If a usr ID is specified, ignore everything but the usr id */
868 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
871 designator
= PARTITION_USR
;
872 architecture
= native_architecture();
873 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
875 } else if (sd_id128_equal(type_id
, GPT_USR_NATIVE_VERITY
)) {
877 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
879 if (pflags
& GPT_FLAG_NO_AUTO
)
882 m
->can_verity
= true;
884 /* Ignore verity unless a usr hash is specified */
885 if (sd_id128_is_null(usr_verity_uuid
) || !sd_id128_equal(usr_verity_uuid
, id
))
888 designator
= PARTITION_USR_VERITY
;
889 fstype
= "DM_verity_hash";
890 architecture
= native_architecture();
894 #ifdef GPT_USR_SECONDARY
895 else if (sd_id128_equal(type_id
, GPT_USR_SECONDARY
)) {
897 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
899 if (pflags
& GPT_FLAG_NO_AUTO
)
902 /* If a usr ID is specified, ignore everything but the usr id */
903 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
906 designator
= PARTITION_USR_SECONDARY
;
907 architecture
= SECONDARY_ARCHITECTURE
;
908 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
910 } else if (sd_id128_equal(type_id
, GPT_USR_SECONDARY_VERITY
)) {
912 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
914 if (pflags
& GPT_FLAG_NO_AUTO
)
917 m
->can_verity
= true;
919 /* Ignore verity unless usr has is specified */
920 if (sd_id128_is_null(usr_verity_uuid
) || !sd_id128_equal(usr_verity_uuid
, id
))
923 designator
= PARTITION_USR_SECONDARY_VERITY
;
924 fstype
= "DM_verity_hash";
925 architecture
= SECONDARY_ARCHITECTURE
;
929 else if (sd_id128_equal(type_id
, GPT_SWAP
)) {
931 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
);
933 if (pflags
& GPT_FLAG_NO_AUTO
)
936 designator
= PARTITION_SWAP
;
939 } else if (sd_id128_equal(type_id
, GPT_LINUX_GENERIC
)) {
941 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
943 if (pflags
& GPT_FLAG_NO_AUTO
)
947 multiple_generic
= true;
950 generic_rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
952 generic_node
= strdup(node
);
957 } else if (sd_id128_equal(type_id
, GPT_TMP
)) {
959 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
961 if (pflags
& GPT_FLAG_NO_AUTO
)
964 designator
= PARTITION_TMP
;
965 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
967 } else if (sd_id128_equal(type_id
, GPT_VAR
)) {
969 check_partition_flags(node
, pflags
, GPT_FLAG_NO_AUTO
|GPT_FLAG_READ_ONLY
);
971 if (pflags
& GPT_FLAG_NO_AUTO
)
974 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
977 /* For /var we insist that the uuid of the partition matches the
978 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
979 * ID. Why? Unlike the other partitions /var is inherently
980 * installation specific, hence we need to be careful not to mount it
981 * in the wrong installation. By hashing the partition UUID from
982 * /etc/machine-id we can securely bind the partition to the
985 r
= sd_id128_get_machine_app_specific(GPT_VAR
, &var_uuid
);
989 if (!sd_id128_equal(var_uuid
, id
)) {
990 log_debug("Found a /var/ partition, but its UUID didn't match our expectations, ignoring.");
995 designator
= PARTITION_VAR
;
996 rw
= !(pflags
& GPT_FLAG_READ_ONLY
);
999 if (designator
!= _PARTITION_DESIGNATOR_INVALID
) {
1000 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
1001 const char *options
= NULL
;
1003 /* First one wins */
1004 if (m
->partitions
[designator
].found
)
1017 options
= mount_options_from_designator(mount_options
, designator
);
1019 o
= strdup(options
);
1024 m
->partitions
[designator
] = (DissectedPartition
) {
1028 .architecture
= architecture
,
1029 .node
= TAKE_PTR(n
),
1030 .fstype
= TAKE_PTR(t
),
1032 .mount_options
= TAKE_PTR(o
),
1036 } else if (is_mbr
) {
1038 switch (blkid_partition_get_type(pp
)) {
1040 case 0x83: /* Linux partition */
1042 if (pflags
!= 0x80) /* Bootable flag */
1046 multiple_generic
= true;
1050 generic_node
= strdup(node
);
1057 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1058 _cleanup_free_
char *n
= NULL
, *o
= NULL
;
1059 sd_id128_t id
= SD_ID128_NULL
;
1060 const char *sid
, *options
= NULL
;
1062 /* First one wins */
1063 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
1066 sid
= blkid_partition_get_uuid(pp
);
1068 (void) sd_id128_from_string(sid
, &id
);
1074 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
1076 o
= strdup(options
);
1081 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
1085 .architecture
= _ARCHITECTURE_INVALID
,
1086 .node
= TAKE_PTR(n
),
1088 .mount_options
= TAKE_PTR(o
),
1096 if (m
->partitions
[PARTITION_ROOT
].found
) {
1097 /* If we found the primary arch, then invalidate the secondary arch to avoid any ambiguities,
1098 * since we never want to mount the secondary arch in this case. */
1099 m
->partitions
[PARTITION_ROOT_SECONDARY
].found
= false;
1100 m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
].found
= false;
1101 m
->partitions
[PARTITION_USR_SECONDARY
].found
= false;
1102 m
->partitions
[PARTITION_USR_SECONDARY_VERITY
].found
= false;
1104 /* No root partition found? Then let's see if ther's one for the secondary architecture. And if not
1105 * either, then check if there's a single generic one, and use that. */
1107 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
1108 return -EADDRNOTAVAIL
;
1110 /* We didn't find a primary architecture root, but we found a primary architecture /usr? Refuse that for now. */
1111 if (m
->partitions
[PARTITION_USR
].found
|| m
->partitions
[PARTITION_USR_VERITY
].found
)
1112 return -EADDRNOTAVAIL
;
1114 if (m
->partitions
[PARTITION_ROOT_SECONDARY
].found
) {
1115 /* Upgrade secondary arch to first */
1116 m
->partitions
[PARTITION_ROOT
] = m
->partitions
[PARTITION_ROOT_SECONDARY
];
1117 zero(m
->partitions
[PARTITION_ROOT_SECONDARY
]);
1118 m
->partitions
[PARTITION_ROOT_VERITY
] = m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
];
1119 zero(m
->partitions
[PARTITION_ROOT_SECONDARY_VERITY
]);
1121 m
->partitions
[PARTITION_USR
] = m
->partitions
[PARTITION_USR_SECONDARY
];
1122 zero(m
->partitions
[PARTITION_USR_SECONDARY
]);
1123 m
->partitions
[PARTITION_USR_VERITY
] = m
->partitions
[PARTITION_USR_SECONDARY_VERITY
];
1124 zero(m
->partitions
[PARTITION_USR_SECONDARY_VERITY
]);
1126 } else if (flags
& DISSECT_IMAGE_REQUIRE_ROOT
) {
1127 _cleanup_free_
char *o
= NULL
;
1128 const char *options
= NULL
;
1130 /* If the root hash was set, then we won't fall back to a generic node, because the
1131 * root hash decides. */
1132 if (verity
&& verity
->root_hash
)
1133 return -EADDRNOTAVAIL
;
1135 /* If we didn't find a generic node, then we can't fix this up either */
1139 /* If we didn't find a properly marked root partition, but we did find a single suitable
1140 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1141 if (multiple_generic
)
1144 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1146 o
= strdup(options
);
1151 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1154 .partno
= generic_nr
,
1155 .architecture
= _ARCHITECTURE_INVALID
,
1156 .node
= TAKE_PTR(generic_node
),
1157 .uuid
= generic_uuid
,
1158 .mount_options
= TAKE_PTR(o
),
1163 /* Refuse if we found a verity partition for /usr but no matching file system partition */
1164 if (!m
->partitions
[PARTITION_USR
].found
&& m
->partitions
[PARTITION_USR_VERITY
].found
)
1165 return -EADDRNOTAVAIL
;
1167 /* Combinations of verity /usr with verity-less root is OK, but the reverse is not */
1168 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
&& m
->partitions
[PARTITION_USR
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1169 return -EADDRNOTAVAIL
;
1171 if (verity
&& verity
->root_hash
) {
1172 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1173 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1174 return -EADDRNOTAVAIL
;
1176 /* If we found a verity setup, then the root partition is necessarily read-only. */
1177 m
->partitions
[PARTITION_ROOT
].rw
= false;
1181 if (verity
->designator
== PARTITION_USR
) {
1182 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1183 return -EADDRNOTAVAIL
;
1185 m
->partitions
[PARTITION_USR
].rw
= false;
1190 blkid_free_probe(b
);
1193 /* Fill in file system types if we don't know them yet. */
1194 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1195 DissectedPartition
*p
= m
->partitions
+ i
;
1200 if (!p
->fstype
&& p
->node
) {
1201 r
= probe_filesystem(p
->node
, &p
->fstype
);
1202 if (r
< 0 && r
!= -EUCLEAN
)
1206 if (streq_ptr(p
->fstype
, "crypto_LUKS"))
1207 m
->encrypted
= true;
1209 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
1220 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1224 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1225 free(m
->partitions
[i
].fstype
);
1226 free(m
->partitions
[i
].node
);
1227 free(m
->partitions
[i
].decrypted_fstype
);
1228 free(m
->partitions
[i
].decrypted_node
);
1229 free(m
->partitions
[i
].mount_options
);
1232 free(m
->image_name
);
1234 strv_free(m
->machine_info
);
1235 strv_free(m
->os_release
);
1236 strv_free(m
->extension_release
);
1241 static int is_loop_device(const char *path
) {
1242 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1247 if (stat(path
, &st
) < 0)
1250 if (!S_ISBLK(st
.st_mode
))
1253 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1254 if (access(s
, F_OK
) < 0) {
1255 if (errno
!= ENOENT
)
1258 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1259 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1260 if (access(s
, F_OK
) < 0)
1261 return errno
== ENOENT
? false : -errno
;
1267 static int run_fsck(const char *node
, const char *fstype
) {
1274 r
= fsck_exists(fstype
);
1276 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1280 log_debug("Not checking partition %s, as fsck for %s does not exist.", node
, fstype
);
1284 r
= safe_fork("(fsck)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG
|FORK_NULL_STDIO
, &pid
);
1286 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1289 execl("/sbin/fsck", "/sbin/fsck", "-aT", node
, NULL
);
1290 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1291 _exit(FSCK_OPERATIONAL_ERROR
);
1294 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1295 if (exit_status
< 0)
1296 return log_debug_errno(exit_status
, "Failed to fork off /sbin/fsck: %m");
1298 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1299 log_debug("fsck failed with exit status %i.", exit_status
);
1301 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1302 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1304 log_debug("Ignoring fsck error.");
1310 static int mount_partition(
1311 DissectedPartition
*m
,
1313 const char *directory
,
1315 DissectImageFlags flags
) {
1317 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1318 const char *p
, *node
, *fstype
;
1325 /* Use decrypted node and matching fstype if available, otherwise use the original device */
1326 node
= m
->decrypted_node
?: m
->node
;
1327 fstype
= m
->decrypted_node
? m
->decrypted_fstype
: m
->fstype
;
1329 if (!m
->found
|| !node
)
1332 return -EAFNOSUPPORT
;
1334 /* 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. */
1335 if (streq(fstype
, "crypto_LUKS"))
1338 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_READ_ONLY
);
1340 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
) {
1341 r
= run_fsck(node
, fstype
);
1347 if (!FLAGS_SET(flags
, DISSECT_IMAGE_READ_ONLY
)) {
1348 /* Automatically create missing mount points, if necessary. */
1349 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
1354 r
= chase_symlinks(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1362 /* If requested, turn on discard support. */
1363 if (fstype_can_discard(fstype
) &&
1364 ((flags
& DISSECT_IMAGE_DISCARD
) ||
1365 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && is_loop_device(m
->node
) > 0))) {
1366 options
= strdup("discard");
1371 if (uid_is_valid(uid_shift
) && uid_shift
!= 0 && fstype_can_uid_gid(fstype
)) {
1372 _cleanup_free_
char *uid_option
= NULL
;
1374 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
1377 if (!strextend_with_separator(&options
, ",", uid_option
))
1381 if (!isempty(m
->mount_options
))
1382 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
1385 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1386 r
= mkdir_p(p
, 0755);
1391 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, MS_NODEV
|(rw
? 0 : MS_RDONLY
), options
);
1398 int dissected_image_mount(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1399 int r
, xbootldr_mounted
;
1406 * -ENXIO → No root partition found
1407 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
1408 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
1409 * -EUCLEAN → fsck for file system failed
1410 * -EBUSY → File system already mounted/used elsewhere (kernel)
1411 * -EAFNOSUPPORT → File system type not supported or not known
1414 if (!m
->partitions
[PARTITION_ROOT
].found
)
1417 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1418 r
= mount_partition(m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, flags
);
1423 /* Mask DISSECT_IMAGE_MKDIR for all subdirs: the idea is that only the top-level mount point is
1424 * created if needed, but the image itself not modified. */
1425 flags
&= ~DISSECT_IMAGE_MKDIR
;
1427 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
1428 /* For us mounting root always means mounting /usr as well */
1429 r
= mount_partition(m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, flags
);
1433 if (flags
& DISSECT_IMAGE_VALIDATE_OS
) {
1434 r
= path_is_os_tree(where
);
1438 r
= path_is_extension_tree(where
, m
->image_name
);
1442 return -EMEDIUMTYPE
;
1447 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
1450 r
= mount_partition(m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, flags
);
1454 r
= mount_partition(m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, flags
);
1458 r
= mount_partition(m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, flags
);
1462 r
= mount_partition(m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, flags
);
1466 xbootldr_mounted
= mount_partition(m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, flags
);
1467 if (xbootldr_mounted
< 0)
1468 return xbootldr_mounted
;
1470 if (m
->partitions
[PARTITION_ESP
].found
) {
1471 int esp_done
= false;
1473 /* Mount the ESP to /efi if it exists. If it doesn't exist, use /boot instead, but only if it
1474 * exists and is empty, and we didn't already mount the XBOOTLDR partition into it. */
1476 r
= chase_symlinks("/efi", where
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1481 /* /efi doesn't exist. Let's see if /boot is suitable then */
1483 if (!xbootldr_mounted
) {
1484 _cleanup_free_
char *p
= NULL
;
1486 r
= chase_symlinks("/boot", where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
1490 } else if (dir_is_empty(p
) > 0) {
1491 /* It exists and is an empty directory. Let's mount the ESP there. */
1492 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/boot", uid_shift
, flags
);
1502 /* OK, let's mount the ESP now to /efi (possibly creating the dir if missing) */
1504 r
= mount_partition(m
->partitions
+ PARTITION_ESP
, where
, "/efi", uid_shift
, flags
);
1513 int dissected_image_mount_and_warn(DissectedImage
*m
, const char *where
, uid_t uid_shift
, DissectImageFlags flags
) {
1519 r
= dissected_image_mount(m
, where
, uid_shift
, flags
);
1521 return log_error_errno(r
, "Not root file system found in image.");
1522 if (r
== -EMEDIUMTYPE
)
1523 return log_error_errno(r
, "No suitable os-release/extension-release file in image found.");
1525 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
1527 return log_error_errno(r
, "File system check on image failed.");
1529 return log_error_errno(r
, "File system already mounted elsewhere.");
1530 if (r
== -EAFNOSUPPORT
)
1531 return log_error_errno(r
, "File system type not supported or not known.");
1533 return log_error_errno(r
, "Failed to mount image: %m");
1538 #if HAVE_LIBCRYPTSETUP
1539 typedef struct DecryptedPartition
{
1540 struct crypt_device
*device
;
1543 } DecryptedPartition
;
1545 struct DecryptedImage
{
1546 DecryptedPartition
*decrypted
;
1552 DecryptedImage
* decrypted_image_unref(DecryptedImage
* d
) {
1553 #if HAVE_LIBCRYPTSETUP
1559 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
1560 DecryptedPartition
*p
= d
->decrypted
+ i
;
1562 if (p
->device
&& p
->name
&& !p
->relinquished
) {
1563 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, 0);
1565 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
1569 sym_crypt_free(p
->device
);
1578 #if HAVE_LIBCRYPTSETUP
1580 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
1581 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
1584 assert(original_node
);
1589 base
= strrchr(original_node
, '/');
1591 base
= original_node
;
1597 name
= strjoin(base
, suffix
);
1600 if (!filename_is_valid(name
))
1603 node
= path_join(sym_crypt_get_dir(), name
);
1607 *ret_name
= TAKE_PTR(name
);
1608 *ret_node
= TAKE_PTR(node
);
1613 static int decrypt_partition(
1614 DissectedPartition
*m
,
1615 const char *passphrase
,
1616 DissectImageFlags flags
,
1617 DecryptedImage
*d
) {
1619 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1620 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1626 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1629 if (!streq(m
->fstype
, "crypto_LUKS"))
1635 r
= dlopen_cryptsetup();
1639 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
1643 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1646 r
= sym_crypt_init(&cd
, m
->node
);
1648 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
1650 cryptsetup_enable_logging(cd
);
1652 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
1654 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
1656 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
1657 ((flags
& DISSECT_IMAGE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
1658 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
1660 log_debug_errno(r
, "Failed to activate LUKS device: %m");
1661 return r
== -EPERM
? -EKEYREJECTED
: r
;
1664 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
1665 .name
= TAKE_PTR(name
),
1666 .device
= TAKE_PTR(cd
),
1669 m
->decrypted_node
= TAKE_PTR(node
);
1674 static int verity_can_reuse(
1675 const VeritySettings
*verity
,
1677 struct crypt_device
**ret_cd
) {
1679 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
1680 _cleanup_free_
char *root_hash_existing
= NULL
;
1681 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1682 struct crypt_params_verity crypt_params
= {};
1683 size_t root_hash_existing_size
;
1690 r
= sym_crypt_init_by_name(&cd
, name
);
1692 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
1694 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
1696 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
1698 root_hash_existing_size
= verity
->root_hash_size
;
1699 root_hash_existing
= malloc0(root_hash_existing_size
);
1700 if (!root_hash_existing
)
1703 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
1705 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
1706 if (verity
->root_hash_size
!= root_hash_existing_size
||
1707 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
1708 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
1710 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1711 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
1712 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
1713 * signing for the new one, and vice versa. */
1714 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
1715 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
1718 *ret_cd
= TAKE_PTR(cd
);
1722 static inline char* dm_deferred_remove_clean(char *name
) {
1726 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
1729 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
1731 static int verity_partition(
1732 PartitionDesignator designator
,
1733 DissectedPartition
*m
,
1734 DissectedPartition
*v
,
1735 const VeritySettings
*verity
,
1736 DissectImageFlags flags
,
1737 DecryptedImage
*d
) {
1739 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
1740 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
1741 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
1745 assert(v
|| (verity
&& verity
->data_path
));
1747 if (!verity
|| !verity
->root_hash
)
1749 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
1750 (verity
->designator
== designator
)))
1753 if (!m
->found
|| !m
->node
|| !m
->fstype
)
1755 if (!verity
->data_path
) {
1756 if (!v
->found
|| !v
->node
|| !v
->fstype
)
1759 if (!streq(v
->fstype
, "DM_verity_hash"))
1763 r
= dlopen_cryptsetup();
1767 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
1768 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
1769 _cleanup_free_
char *root_hash_encoded
= NULL
;
1771 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
1772 if (!root_hash_encoded
)
1775 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
1777 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
1781 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
1785 cryptsetup_enable_logging(cd
);
1787 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
1791 r
= sym_crypt_set_data_device(cd
, m
->node
);
1795 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_allocated
, d
->n_decrypted
+ 1))
1798 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
1799 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
1800 * retry a few times before giving up. */
1801 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
1802 if (verity
->root_hash_sig
) {
1803 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
1804 r
= sym_crypt_activate_by_signed_key(
1808 verity
->root_hash_size
,
1809 verity
->root_hash_sig
,
1810 verity
->root_hash_sig_size
,
1811 CRYPT_ACTIVATE_READONLY
);
1813 r
= log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1814 "Activation of verity device with signature requested, but not supported by %s due to missing crypt_activate_by_signed_key().", program_invocation_short_name
);
1817 r
= sym_crypt_activate_by_volume_key(
1821 verity
->root_hash_size
,
1822 CRYPT_ACTIVATE_READONLY
);
1823 /* libdevmapper can return EINVAL when the device is already in the activation stage.
1824 * There's no way to distinguish this situation from a genuine error due to invalid
1825 * parameters, so immediately fall back to activating the device with a unique name.
1826 * Improvements in libcrypsetup can ensure this never happens:
1827 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
1828 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1829 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1832 -EEXIST
, /* Volume is already open and ready to be used */
1833 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name can fetch details */
1834 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again */))
1836 if (IN_SET(r
, -EEXIST
, -EBUSY
)) {
1837 struct crypt_device
*existing_cd
= NULL
;
1839 if (!restore_deferred_remove
){
1840 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
1841 r
= dm_deferred_remove_cancel(name
);
1842 /* If activation returns EBUSY there might be no deferred removal to cancel, that's fine */
1843 if (r
< 0 && r
!= -ENXIO
)
1844 return log_debug_errno(r
, "Disabling automated deferred removal for verity device %s failed: %m", node
);
1846 restore_deferred_remove
= strdup(name
);
1847 if (!restore_deferred_remove
)
1852 r
= verity_can_reuse(verity
, name
, &existing_cd
);
1853 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
1854 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1855 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1856 if (!IN_SET(r
, 0, -ENODEV
, -ENOENT
, -EBUSY
))
1857 return log_debug_errno(r
, "Checking whether existing verity device %s can be reused failed: %m", node
);
1859 /* devmapper might say that the device exists, but the devlink might not yet have been
1860 * created. Check and wait for the udev event in that case. */
1861 r
= device_wait_for_devlink(node
, "block", usec_add(now(CLOCK_MONOTONIC
), 100 * USEC_PER_MSEC
), NULL
);
1862 /* Fallback to activation with a unique device if it's taking too long */
1863 if (r
== -ETIMEDOUT
)
1876 /* Device is being opened by another process, but it has not finished yet, yield for 2ms */
1877 (void) usleep(2 * USEC_PER_MSEC
);
1880 /* An existing verity device was reported by libcryptsetup/libdevmapper, but we can't use it at this time.
1881 * Fall back to activating it with a unique device name. */
1882 if (r
!= 0 && FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
1883 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
1885 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
1886 restore_deferred_remove
= mfree(restore_deferred_remove
);
1888 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
1889 .name
= TAKE_PTR(name
),
1890 .device
= TAKE_PTR(cd
),
1893 m
->decrypted_node
= TAKE_PTR(node
);
1899 int dissected_image_decrypt(
1901 const char *passphrase
,
1902 const VeritySettings
*verity
,
1903 DissectImageFlags flags
,
1904 DecryptedImage
**ret
) {
1906 #if HAVE_LIBCRYPTSETUP
1907 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
1912 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
1916 * = 0 → There was nothing to decrypt
1917 * > 0 → Decrypted successfully
1918 * -ENOKEY → There's something to decrypt but no key was supplied
1919 * -EKEYREJECTED → Passed key was not correct
1922 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
1925 if (!m
->encrypted
&& !m
->verity
) {
1930 #if HAVE_LIBCRYPTSETUP
1931 d
= new0(DecryptedImage
, 1);
1935 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
1936 DissectedPartition
*p
= m
->partitions
+ i
;
1937 PartitionDesignator k
;
1942 r
= decrypt_partition(p
, passphrase
, flags
, d
);
1946 k
= PARTITION_VERITY_OF(i
);
1948 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
| DISSECT_IMAGE_VERITY_SHARE
, d
);
1953 if (!p
->decrypted_fstype
&& p
->decrypted_node
) {
1954 r
= probe_filesystem(p
->decrypted_node
, &p
->decrypted_fstype
);
1955 if (r
< 0 && r
!= -EUCLEAN
)
1968 int dissected_image_decrypt_interactively(
1970 const char *passphrase
,
1971 const VeritySettings
*verity
,
1972 DissectImageFlags flags
,
1973 DecryptedImage
**ret
) {
1975 _cleanup_strv_free_erase_
char **z
= NULL
;
1982 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
, ret
);
1985 if (r
== -EKEYREJECTED
)
1986 log_error_errno(r
, "Incorrect passphrase, try again!");
1987 else if (r
!= -ENOKEY
)
1988 return log_error_errno(r
, "Failed to decrypt image: %m");
1991 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
1992 "Too many retries.");
1996 r
= ask_password_auto("Please enter image passphrase:", NULL
, "dissect", "dissect", USEC_INFINITY
, 0, &z
);
1998 return log_error_errno(r
, "Failed to query for passphrase: %m");
2004 int decrypted_image_relinquish(DecryptedImage
*d
) {
2007 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
2008 * boolean so that we don't clean it up ourselves either anymore */
2010 #if HAVE_LIBCRYPTSETUP
2013 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2014 DecryptedPartition
*p
= d
->decrypted
+ i
;
2016 if (p
->relinquished
)
2019 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2021 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
2023 p
->relinquished
= true;
2030 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
2037 e
= endswith(image
, ".raw");
2039 return strjoin(e
, suffix
);
2041 n
= new(char, e
- image
+ strlen(suffix
) + 1);
2045 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
2049 void verity_settings_done(VeritySettings
*v
) {
2052 v
->root_hash
= mfree(v
->root_hash
);
2053 v
->root_hash_size
= 0;
2055 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
2056 v
->root_hash_sig_size
= 0;
2058 v
->data_path
= mfree(v
->data_path
);
2061 int verity_settings_load(
2062 VeritySettings
*verity
,
2064 const char *root_hash_path
,
2065 const char *root_hash_sig_path
) {
2067 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
2068 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
2069 _cleanup_free_
char *verity_data_path
= NULL
;
2070 PartitionDesignator designator
;
2075 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
2077 /* If we are asked to load the root hash for a device node, exit early */
2078 if (is_device_path(image
))
2081 designator
= verity
->designator
;
2083 /* We only fill in what isn't already filled in */
2085 if (!verity
->root_hash
) {
2086 _cleanup_free_
char *text
= NULL
;
2088 if (root_hash_path
) {
2089 /* If explicitly specified it takes precedence */
2090 r
= read_one_line_file(root_hash_path
, &text
);
2095 designator
= PARTITION_ROOT
;
2097 /* Otherwise look for xattr and separate file, and first for the data for root and if
2098 * that doesn't exist for /usr */
2100 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2101 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, true);
2103 _cleanup_free_
char *p
= NULL
;
2105 if (!IN_SET(r
, -ENODATA
, -ENOENT
) && !ERRNO_IS_NOT_SUPPORTED(r
))
2108 p
= build_auxiliary_path(image
, ".roothash");
2112 r
= read_one_line_file(p
, &text
);
2113 if (r
< 0 && r
!= -ENOENT
)
2118 designator
= PARTITION_ROOT
;
2121 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2122 /* So in the "roothash" xattr/file name above the "root" of course primarily
2123 * refers to the root of the Verity Merkle tree. But coincidentally it also
2124 * is the hash for the *root* file system, i.e. the "root" neatly refers to
2125 * two distinct concepts called "root". Taking benefit of this happy
2126 * coincidence we call the file with the root hash for the /usr/ file system
2127 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
2128 * confusing. We thus drop the reference to the root of the Merkle tree, and
2129 * just indicate which file system it's about. */
2130 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
, true);
2132 _cleanup_free_
char *p
= NULL
;
2134 if (!IN_SET(r
, -ENODATA
, -ENOENT
) && !ERRNO_IS_NOT_SUPPORTED(r
))
2137 p
= build_auxiliary_path(image
, ".usrhash");
2141 r
= read_one_line_file(p
, &text
);
2142 if (r
< 0 && r
!= -ENOENT
)
2147 designator
= PARTITION_USR
;
2152 r
= unhexmem(text
, strlen(text
), &root_hash
, &root_hash_size
);
2155 if (root_hash_size
< sizeof(sd_id128_t
))
2160 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
2161 if (root_hash_sig_path
) {
2162 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2163 if (r
< 0 && r
!= -ENOENT
)
2167 designator
= PARTITION_ROOT
;
2169 if (designator
< 0 || designator
== PARTITION_ROOT
) {
2170 _cleanup_free_
char *p
= NULL
;
2172 /* Follow naming convention recommended by the relevant RFC:
2173 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
2174 p
= build_auxiliary_path(image
, ".roothash.p7s");
2178 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2179 if (r
< 0 && r
!= -ENOENT
)
2182 designator
= PARTITION_ROOT
;
2185 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
2186 _cleanup_free_
char *p
= NULL
;
2188 p
= build_auxiliary_path(image
, ".usrhash.p7s");
2192 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
2193 if (r
< 0 && r
!= -ENOENT
)
2196 designator
= PARTITION_USR
;
2200 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
2204 if (!verity
->data_path
) {
2205 _cleanup_free_
char *p
= NULL
;
2207 p
= build_auxiliary_path(image
, ".verity");
2211 if (access(p
, F_OK
) < 0) {
2212 if (errno
!= ENOENT
)
2215 verity_data_path
= TAKE_PTR(p
);
2219 verity
->root_hash
= TAKE_PTR(root_hash
);
2220 verity
->root_hash_size
= root_hash_size
;
2223 if (root_hash_sig
) {
2224 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
2225 verity
->root_hash_sig_size
= root_hash_sig_size
;
2228 if (verity_data_path
)
2229 verity
->data_path
= TAKE_PTR(verity_data_path
);
2231 if (verity
->designator
< 0)
2232 verity
->designator
= designator
;
2237 int dissected_image_acquire_metadata(DissectedImage
*m
) {
2244 META_EXTENSION_RELEASE
,
2248 static const char *paths
[_META_MAX
] = {
2249 [META_HOSTNAME
] = "/etc/hostname\0",
2250 [META_MACHINE_ID
] = "/etc/machine-id\0",
2251 [META_MACHINE_INFO
] = "/etc/machine-info\0",
2252 [META_OS_RELEASE
] = ("/etc/os-release\0"
2253 "/usr/lib/os-release\0"),
2254 [META_EXTENSION_RELEASE
] = NULL
,
2257 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **extension_release
= NULL
;
2258 _cleanup_close_pair_
int error_pipe
[2] = { -1, -1 };
2259 _cleanup_(rmdir_and_freep
) char *t
= NULL
;
2260 _cleanup_(sigkill_waitp
) pid_t child
= 0;
2261 sd_id128_t machine_id
= SD_ID128_NULL
;
2262 _cleanup_free_
char *hostname
= NULL
;
2263 unsigned n_meta_initialized
= 0;
2264 int fds
[2 * _META_MAX
], r
, v
;
2267 BLOCK_SIGNALS(SIGCHLD
);
2271 /* As per the os-release spec, if the image is an extension it will have a file
2272 * named after the image name in extension-release.d/ */
2274 paths
[META_EXTENSION_RELEASE
] = strjoina("/usr/lib/extension-release.d/extension-release.", m
->image_name
);
2276 log_debug("No image name available, will skip extension-release metadata");
2278 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
2279 if (!paths
[n_meta_initialized
]) {
2280 fds
[2*n_meta_initialized
] = fds
[2*n_meta_initialized
+1] = -1;
2284 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
2290 r
= mkdtemp_malloc("/tmp/dissect-XXXXXX", &t
);
2294 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
2299 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
2303 error_pipe
[0] = safe_close(error_pipe
[0]);
2305 r
= dissected_image_mount(m
, t
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_MOUNT_ROOT_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
2307 /* Let parent know the error */
2308 (void) write(error_pipe
[1], &r
, sizeof(r
));
2310 log_debug_errno(r
, "Failed to mount dissected image: %m");
2311 _exit(EXIT_FAILURE
);
2314 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2315 _cleanup_close_
int fd
= -ENOENT
;
2321 fds
[2*k
] = safe_close(fds
[2*k
]);
2323 NULSTR_FOREACH(p
, paths
[k
]) {
2324 fd
= chase_symlinks_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
2329 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
2330 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2334 r
= copy_bytes(fd
, fds
[2*k
+1], (uint64_t) -1, 0);
2336 (void) write(error_pipe
[1], &r
, sizeof(r
));
2337 _exit(EXIT_FAILURE
);
2340 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2343 _exit(EXIT_SUCCESS
);
2346 error_pipe
[1] = safe_close(error_pipe
[1]);
2348 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
2349 _cleanup_fclose_
FILE *f
= NULL
;
2354 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
2356 f
= take_fdopen(&fds
[2*k
], "r");
2365 r
= read_etc_hostname_stream(f
, &hostname
);
2367 log_debug_errno(r
, "Failed to read /etc/hostname: %m");
2371 case META_MACHINE_ID
: {
2372 _cleanup_free_
char *line
= NULL
;
2374 r
= read_line(f
, LONG_LINE_MAX
, &line
);
2376 log_debug_errno(r
, "Failed to read /etc/machine-id: %m");
2378 r
= sd_id128_from_string(line
, &machine_id
);
2380 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
2382 log_debug("/etc/machine-id file is empty.");
2383 else if (streq(line
, "uninitialized"))
2384 log_debug("/etc/machine-id file is uninitialized (likely aborted first boot).");
2386 log_debug("/etc/machine-id has unexpected length %i.", r
);
2391 case META_MACHINE_INFO
:
2392 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
2394 log_debug_errno(r
, "Failed to read /etc/machine-info: %m");
2398 case META_OS_RELEASE
:
2399 r
= load_env_file_pairs(f
, "os-release", &os_release
);
2401 log_debug_errno(r
, "Failed to read OS release file: %m");
2405 case META_EXTENSION_RELEASE
:
2406 r
= load_env_file_pairs(f
, "extension-release", &extension_release
);
2408 log_debug_errno(r
, "Failed to read extension release file: %m");
2414 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
2419 n
= read(error_pipe
[0], &v
, sizeof(v
));
2423 return v
; /* propagate error sent to us from child */
2427 if (r
!= EXIT_SUCCESS
)
2430 free_and_replace(m
->hostname
, hostname
);
2431 m
->machine_id
= machine_id
;
2432 strv_free_and_replace(m
->machine_info
, machine_info
);
2433 strv_free_and_replace(m
->os_release
, os_release
);
2434 strv_free_and_replace(m
->extension_release
, extension_release
);
2437 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
2438 safe_close_pair(fds
+ 2*k
);
2443 int dissect_image_and_warn(
2446 const VeritySettings
*verity
,
2447 const MountOptions
*mount_options
,
2448 DissectImageFlags flags
,
2449 DissectedImage
**ret
) {
2451 _cleanup_free_
char *buffer
= NULL
;
2455 r
= fd_get_path(fd
, &buffer
);
2462 r
= dissect_image(fd
, verity
, mount_options
, flags
, ret
);
2466 return log_error_errno(r
, "Dissecting images is not supported, compiled without blkid support.");
2469 return log_error_errno(r
, "Couldn't identify a suitable partition table or file system in '%s'.", name
);
2471 case -EADDRNOTAVAIL
:
2472 return log_error_errno(r
, "No root partition for specified root hash found in '%s'.", name
);
2475 return log_error_errno(r
, "Multiple suitable root partitions found in image '%s'.", name
);
2478 return log_error_errno(r
, "No suitable root partition found in image '%s'.", name
);
2480 case -EPROTONOSUPPORT
:
2481 return log_error_errno(r
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", name
);
2485 return log_error_errno(r
, "Failed to dissect image '%s': %m", name
);
2491 bool dissected_image_can_do_verity(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
2492 if (image
->single_file_system
)
2493 return partition_designator
== PARTITION_ROOT
&& image
->can_verity
;
2495 return PARTITION_VERITY_OF(partition_designator
) >= 0;
2498 bool dissected_image_has_verity(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
2501 if (image
->single_file_system
)
2502 return partition_designator
== PARTITION_ROOT
&& image
->verity
;
2504 k
= PARTITION_VERITY_OF(partition_designator
);
2505 return k
>= 0 && image
->partitions
[k
].found
;
2508 MountOptions
* mount_options_free_all(MountOptions
*options
) {
2511 while ((m
= options
)) {
2512 LIST_REMOVE(mount_options
, options
, m
);
2520 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
2521 const MountOptions
*m
;
2523 LIST_FOREACH(mount_options
, m
, options
)
2524 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
2530 int mount_image_privately_interactively(
2532 DissectImageFlags flags
,
2533 char **ret_directory
,
2534 LoopDevice
**ret_loop_device
,
2535 DecryptedImage
**ret_decrypted_image
) {
2537 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
2538 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
2539 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2540 _cleanup_(rmdir_and_freep
) char *created_dir
= NULL
;
2541 _cleanup_free_
char *temp
= NULL
;
2544 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
2545 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
2549 assert(ret_directory
);
2550 assert(ret_loop_device
);
2551 assert(ret_decrypted_image
);
2553 r
= tempfn_random_child(NULL
, program_invocation_short_name
, &temp
);
2555 return log_error_errno(r
, "Failed to generate temporary mount directory: %m");
2557 r
= loop_device_make_by_path(
2559 FLAGS_SET(flags
, DISSECT_IMAGE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
2560 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
2563 return log_error_errno(r
, "Failed to set up loopback device: %m");
2565 r
= dissect_image_and_warn(d
->fd
, image
, NULL
, NULL
, flags
, &dissected_image
);
2569 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, NULL
, flags
, &decrypted_image
);
2573 r
= detach_mount_namespace();
2575 return log_error_errno(r
, "Failed to detach mount namespace: %m");
2577 r
= mkdir_p(temp
, 0700);
2579 return log_error_errno(r
, "Failed to create mount point: %m");
2581 created_dir
= TAKE_PTR(temp
);
2583 r
= dissected_image_mount_and_warn(dissected_image
, created_dir
, UID_INVALID
, flags
);
2587 if (decrypted_image
) {
2588 r
= decrypted_image_relinquish(decrypted_image
);
2590 return log_error_errno(r
, "Failed to relinquish DM devices: %m");
2593 loop_device_relinquish(d
);
2595 *ret_directory
= TAKE_PTR(created_dir
);
2596 *ret_loop_device
= TAKE_PTR(d
);
2597 *ret_decrypted_image
= TAKE_PTR(decrypted_image
);
2602 static const char *const partition_designator_table
[] = {
2603 [PARTITION_ROOT
] = "root",
2604 [PARTITION_ROOT_SECONDARY
] = "root-secondary",
2605 [PARTITION_USR
] = "usr",
2606 [PARTITION_USR_SECONDARY
] = "usr-secondary",
2607 [PARTITION_HOME
] = "home",
2608 [PARTITION_SRV
] = "srv",
2609 [PARTITION_ESP
] = "esp",
2610 [PARTITION_XBOOTLDR
] = "xbootldr",
2611 [PARTITION_SWAP
] = "swap",
2612 [PARTITION_ROOT_VERITY
] = "root-verity",
2613 [PARTITION_ROOT_SECONDARY_VERITY
] = "root-secondary-verity",
2614 [PARTITION_USR_VERITY
] = "usr-verity",
2615 [PARTITION_USR_SECONDARY_VERITY
] = "usr-secondary-verity",
2616 [PARTITION_TMP
] = "tmp",
2617 [PARTITION_VAR
] = "var",
2620 int verity_dissect_and_mount(
2623 const MountOptions
*options
,
2624 const char *required_host_os_release_id
,
2625 const char *required_host_os_release_version_id
,
2626 const char *required_host_os_release_sysext_level
) {
2628 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2629 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
2630 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
2631 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
2632 DissectImageFlags dissect_image_flags
;
2638 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
2640 return log_debug_errno(r
, "Failed to load root hash: %m");
2642 dissect_image_flags
= verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0;
2644 r
= loop_device_make_by_path(
2647 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
2650 return log_debug_errno(r
, "Failed to create loop device for image: %m");
2656 dissect_image_flags
,
2658 /* No partition table? Might be a single-filesystem image, try again */
2659 if (!verity
.data_path
&& r
== -ENOPKG
)
2664 dissect_image_flags
|DISSECT_IMAGE_NO_PARTITION_TABLE
,
2667 return log_debug_errno(r
, "Failed to dissect image: %m");
2669 r
= dissected_image_decrypt(
2673 dissect_image_flags
,
2676 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
2678 r
= mkdir_p_label(dest
, 0755);
2680 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
2681 r
= umount_recursive(dest
, 0);
2683 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
2685 r
= dissected_image_mount(dissected_image
, dest
, UID_INVALID
, dissect_image_flags
);
2687 return log_debug_errno(r
, "Failed to mount image: %m");
2689 /* If we got os-release values from the caller, then we need to match them with the image's
2690 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
2691 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
2692 * available, or else fallback to VERSION_ID. */
2693 if (required_host_os_release_id
&&
2694 (required_host_os_release_version_id
|| required_host_os_release_sysext_level
)) {
2695 _cleanup_strv_free_
char **extension_release
= NULL
;
2697 r
= load_extension_release_pairs(dest
, dissected_image
->image_name
, &extension_release
);
2699 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
2701 r
= extension_release_validate(
2702 dissected_image
->image_name
,
2703 required_host_os_release_id
,
2704 required_host_os_release_version_id
,
2705 required_host_os_release_sysext_level
,
2708 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
2710 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
2713 if (decrypted_image
) {
2714 r
= decrypted_image_relinquish(decrypted_image
);
2716 return log_debug_errno(r
, "Failed to relinquish decrypted image: %m");
2719 loop_device_relinquish(loop_device
);
2724 DEFINE_STRING_TABLE_LOOKUP(partition_designator
, PartitionDesignator
);