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/mount.h>
11 #include <sys/prctl.h>
16 #include <openssl/err.h>
17 #include <openssl/pem.h>
18 #include <openssl/x509.h>
21 #include "sd-device.h"
24 #include "architecture.h"
25 #include "ask-password-api.h"
26 #include "blkid-util.h"
27 #include "blockdev-util.h"
28 #include "btrfs-util.h"
30 #include "conf-files.h"
31 #include "constants.h"
33 #include "cryptsetup-util.h"
34 #include "device-nodes.h"
35 #include "device-util.h"
36 #include "devnum-util.h"
37 #include "discover-image.h"
38 #include "dissect-image.h"
42 #include "extension-util.h"
46 #include "fsck-util.h"
48 #include "hexdecoct.h"
49 #include "hostname-setup.h"
50 #include "id128-util.h"
51 #include "import-util.h"
53 #include "missing_mount.h"
54 #include "missing_syscall.h"
55 #include "mkdir-label.h"
56 #include "mount-util.h"
57 #include "mountpoint-util.h"
58 #include "namespace-util.h"
59 #include "nulstr-util.h"
60 #include "openssl-util.h"
62 #include "path-util.h"
63 #include "proc-cmdline.h"
64 #include "process-util.h"
65 #include "raw-clone.h"
66 #include "resize-fs.h"
67 #include "signal-util.h"
68 #include "sparse-endian.h"
69 #include "stat-util.h"
70 #include "stdio-util.h"
71 #include "string-table.h"
72 #include "string-util.h"
74 #include "tmpfile-util.h"
75 #include "udev-util.h"
76 #include "user-util.h"
77 #include "xattr-util.h"
79 /* how many times to wait for the device nodes to appear */
80 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
82 int dissect_fstype_ok(const char *fstype
) {
86 /* When we automatically mount file systems, be a bit conservative by default what we are willing to
87 * mount, just as an extra safety net to not mount with badly maintained legacy file system
90 e
= secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
92 _cleanup_strv_free_
char **l
= NULL
;
94 l
= strv_split(e
, ":");
98 b
= strv_contains(l
, fstype
);
100 b
= STR_IN_SET(fstype
,
111 log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype
);
115 int probe_sector_size(int fd
, uint32_t *ret
) {
117 /* Disk images might be for 512B or for 4096 sector sizes, let's try to auto-detect that by searching
118 * for the GPT headers at the relevant byte offsets */
120 assert_cc(sizeof(GptHeader
) == 92);
122 /* We expect a sector size in the range 512…4096. The GPT header is located in the second
123 * sector. Hence it could be at byte 512 at the earliest, and at byte 4096 at the latest. And we must
124 * read with granularity of the largest sector size we care about. Which means 8K. */
125 uint8_t sectors
[2 * 4096];
132 n
= pread(fd
, sectors
, sizeof(sectors
), 0);
135 if (n
!= sizeof(sectors
)) /* too short? */
138 /* Let's see if we find the GPT partition header with various expected sector sizes */
139 for (uint32_t sz
= 512; sz
<= 4096; sz
<<= 1) {
142 assert(sizeof(sectors
) >= sz
* 2);
143 p
= (const GptHeader
*) (sectors
+ sz
);
145 if (!gpt_header_has_signature(p
))
149 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
150 "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
156 log_debug("Determined sector size %" PRIu32
" based on discovered partition table.", found
);
158 return 1; /* indicate we *did* find it */
162 log_debug("Couldn't find any partition table to derive sector size of.");
163 *ret
= 512; /* pick the traditional default */
164 return 0; /* indicate we didn't find it */
167 int probe_sector_size_prefer_ioctl(int fd
, uint32_t *ret
) {
173 /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
174 * configured sector size rather than probing by contents */
176 if (fstat(fd
, &st
) < 0)
179 if (S_ISBLK(st
.st_mode
))
180 return blockdev_get_sector_size(fd
, ret
);
182 return probe_sector_size(fd
, ret
);
185 int probe_filesystem_full(
192 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
193 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
194 * different error otherwise. */
197 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
198 _cleanup_free_
char *path_by_fd
= NULL
;
199 _cleanup_close_
int fd_close
= -EBADF
;
203 assert(fd
>= 0 || path
);
207 fd_close
= open(path
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
215 r
= fd_get_path(fd
, &path_by_fd
);
222 if (size
== 0) /* empty size? nothing found! */
225 b
= blkid_new_probe();
229 /* The Linux kernel maintains separate block device caches for main ("whole") and partition block
230 * devices, which means making a change to one might not be reflected immediately when reading via
231 * the other. That's massively confusing when mixing accesses to such devices. Let's address this in
232 * a limited way: when probing a file system that is not at the beginning of the block device we
233 * apparently probe a partition via the main block device, and in that case let's first flush the
234 * main block device cache, so that we get the data that the per-partition block device last
237 * This only works under the assumption that any tools that write to the partition block devices
238 * issue an syncfs()/fsync() on the device after making changes. Typically file system formatting
239 * tools that write a superblock onto a partition block device do that, however. */
241 if (ioctl(fd
, BLKFLSBUF
, 0) < 0)
242 log_debug_errno(errno
, "Failed to flush block device cache, ignoring: %m");
245 r
= blkid_probe_set_device(
249 size
== UINT64_MAX
? 0 : size
); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
251 return errno_or_else(ENOMEM
);
253 blkid_probe_enable_superblocks(b
, 1);
254 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
257 r
= blkid_do_safeprobe(b
);
258 if (r
== _BLKID_SAFEPROBE_NOT_FOUND
)
260 if (r
== _BLKID_SAFEPROBE_AMBIGUOUS
)
261 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
262 "Results ambiguous for partition %s", path
);
263 if (r
== _BLKID_SAFEPROBE_ERROR
)
264 return log_debug_errno(errno_or_else(EIO
), "Failed to probe partition %s: %m", path
);
266 assert(r
== _BLKID_SAFEPROBE_FOUND
);
268 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
273 log_debug("Probed fstype '%s' on partition %s.", fstype
, path
);
284 log_debug("No type detected on partition %s", path
);
293 static int image_policy_may_use(
294 const ImagePolicy
*policy
,
295 PartitionDesignator designator
) {
297 PartitionPolicyFlags f
;
299 /* For each partition we find in the partition table do a first check if it may exist at all given
300 * the policy, or if it shall be ignored. */
302 f
= image_policy_get_exhaustively(policy
, designator
);
306 if ((f
& _PARTITION_POLICY_USE_MASK
) == PARTITION_POLICY_ABSENT
)
307 /* only flag set in policy is "absent"? then this partition may not exist at all */
308 return log_debug_errno(
309 SYNTHETIC_ERRNO(ERFKILL
),
310 "Partition of designator '%s' exists, but not allowed by policy, refusing.",
311 partition_designator_to_string(designator
));
312 if ((f
& _PARTITION_POLICY_USE_MASK
& ~PARTITION_POLICY_ABSENT
) == PARTITION_POLICY_UNUSED
) {
313 /* only "unused" or "unused" + "absent" are set? then don't use it */
314 log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
315 partition_designator_to_string(designator
));
316 return false; /* ignore! */
319 return true; /* use! */
322 static int image_policy_check_protection(
323 const ImagePolicy
*policy
,
324 PartitionDesignator designator
,
325 PartitionPolicyFlags found_flags
) {
327 PartitionPolicyFlags policy_flags
;
329 /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
334 policy_flags
= image_policy_get_exhaustively(policy
, designator
);
335 if (policy_flags
< 0)
338 if ((found_flags
& policy_flags
) == 0) {
339 _cleanup_free_
char *found_flags_string
= NULL
, *policy_flags_string
= NULL
;
341 (void) partition_policy_flags_to_string(found_flags
, /* simplify= */ true, &found_flags_string
);
342 (void) partition_policy_flags_to_string(policy_flags
, /* simplify= */ true, &policy_flags_string
);
344 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
345 partition_designator_to_string(designator
),
346 strnull(found_flags_string
), strnull(policy_flags_string
));
352 static int image_policy_check_partition_flags(
353 const ImagePolicy
*policy
,
354 PartitionDesignator designator
,
355 uint64_t gpt_flags
) {
357 PartitionPolicyFlags policy_flags
;
360 /* Checks if the partition flags in the policy match reality */
362 policy_flags
= image_policy_get_exhaustively(policy
, designator
);
363 if (policy_flags
< 0)
366 b
= FLAGS_SET(gpt_flags
, SD_GPT_FLAG_READ_ONLY
);
367 if ((policy_flags
& _PARTITION_POLICY_READ_ONLY_MASK
) == (b
? PARTITION_POLICY_READ_ONLY_OFF
: PARTITION_POLICY_READ_ONLY_ON
))
368 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
369 partition_designator_to_string(designator
),
370 one_zero(!b
), one_zero(b
));
372 b
= FLAGS_SET(gpt_flags
, SD_GPT_FLAG_GROWFS
);
373 if ((policy_flags
& _PARTITION_POLICY_GROWFS_MASK
) == (b
? PARTITION_POLICY_GROWFS_OFF
: PARTITION_POLICY_GROWFS_ON
))
374 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
375 partition_designator_to_string(designator
),
376 one_zero(!b
), one_zero(b
));
381 static int dissected_image_probe_filesystems(
384 const ImagePolicy
*policy
) {
390 /* Fill in file system types if we don't know them yet. */
392 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
393 DissectedPartition
*p
= m
->partitions
+ i
;
394 PartitionPolicyFlags found_flags
;
400 /* If we have an fd referring to the partition block device, use that. Otherwise go
401 * via the whole block device or backing regular file, and read via offset. */
402 if (p
->mount_node_fd
>= 0)
403 r
= probe_filesystem_full(p
->mount_node_fd
, p
->node
, 0, UINT64_MAX
, &p
->fstype
);
405 r
= probe_filesystem_full(fd
, p
->node
, p
->offset
, p
->size
, &p
->fstype
);
410 if (streq_ptr(p
->fstype
, "crypto_LUKS")) {
412 found_flags
= PARTITION_POLICY_ENCRYPTED
; /* found this one, and its definitely encrypted */
414 /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
415 * set all other ways that indicate "present". */
416 found_flags
= PARTITION_POLICY_UNPROTECTED
|PARTITION_POLICY_VERITY
|PARTITION_POLICY_SIGNED
;
418 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
424 /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
425 * hence we need to validate this against policy again, to see if the policy still matches
426 * with this new information. Note that image_policy_check_protection() will check for
427 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
428 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
429 * OR verity OR signed), but that's fine since the earlier policy check already checked more
430 * specific which of those three cases where OK. Keep in mind that this function here only
431 * looks at specific partitions (and thus can only deduce encryption or not) but not the
432 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
433 * checks already did the relevant checks that look at the whole partition table, and
434 * enforced policy there as needed. */
435 r
= image_policy_check_protection(policy
, i
, found_flags
);
443 static void check_partition_flags(
445 unsigned long long pflags
,
446 unsigned long long supported
) {
450 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
451 pflags
&= ~(supported
|
452 SD_GPT_FLAG_REQUIRED_PARTITION
|
453 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
|
454 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
459 /* If there are other bits set, then log about it, to make things discoverable */
460 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
461 unsigned long long bit
= 1ULL << i
;
462 if (!FLAGS_SET(pflags
, bit
))
465 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
469 static int dissected_image_new(const char *path
, DissectedImage
**ret
) {
470 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
471 _cleanup_free_
char *name
= NULL
;
477 _cleanup_free_
char *filename
= NULL
;
479 r
= path_extract_filename(path
, &filename
);
483 r
= raw_strip_suffixes(filename
, &name
);
487 if (!image_name_is_valid(name
)) {
488 log_debug("Image name %s is not valid, ignoring.", strna(name
));
493 m
= new(DissectedImage
, 1);
497 *m
= (DissectedImage
) {
498 .has_init_system
= -1,
499 .image_name
= TAKE_PTR(name
),
502 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
503 m
->partitions
[i
] = DISSECTED_PARTITION_NULL
;
510 static void dissected_partition_done(DissectedPartition
*p
) {
516 free(p
->decrypted_fstype
);
517 free(p
->decrypted_node
);
518 free(p
->mount_options
);
519 safe_close(p
->mount_node_fd
);
520 safe_close(p
->fsmount_fd
);
522 *p
= DISSECTED_PARTITION_NULL
;
526 static int make_partition_devname(
527 const char *whole_devname
,
530 DissectImageFlags flags
,
533 _cleanup_free_
char *s
= NULL
;
536 assert(whole_devname
);
537 assert(nr
!= 0); /* zero is not a valid partition nr */
540 if (!FLAGS_SET(flags
, DISSECT_IMAGE_DISKSEQ_DEVNODE
) || diskseq
== 0) {
542 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
543 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
544 * block device node name ends in a digit, then suffix a 'p', followed by the partition
545 * number. Otherwise, just suffix the partition number without any 'p'. */
547 if (nr
< 0) { /* whole disk? */
548 s
= strdup(whole_devname
);
552 size_t l
= strlen(whole_devname
);
553 if (l
< 1) /* underflow check for the subtraction below */
556 bool need_p
= ascii_isdigit(whole_devname
[l
-1]); /* Last char a digit? */
558 if (asprintf(&s
, "%s%s%i", whole_devname
, need_p
? "p" : "", nr
) < 0)
562 if (nr
< 0) /* whole disk? */
563 r
= asprintf(&s
, "/dev/disk/by-diskseq/%" PRIu64
, diskseq
);
565 r
= asprintf(&s
, "/dev/disk/by-diskseq/%" PRIu64
"-part%i", diskseq
, nr
);
574 static int open_partition(
577 const LoopDevice
*loop
) {
579 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
580 _cleanup_close_
int fd
= -EBADF
;
587 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
591 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
592 r
= block_device_new_from_fd(fd
, is_partition
? BLOCK_DEVICE_LOOKUP_WHOLE_DISK
: 0, &dev
);
596 r
= sd_device_get_devnum(dev
, &devnum
);
600 if (loop
->devno
!= devnum
)
603 /* Also check diskseq. */
604 if (loop
->diskseq
!= 0) {
607 r
= fd_get_diskseq(fd
, &diskseq
);
611 if (loop
->diskseq
!= diskseq
)
615 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR
", diskseq=%" PRIu64
").",
616 node
, fd
, DEVNUM_FORMAT_VAL(loop
->devno
), loop
->diskseq
);
620 static int compare_arch(Architecture a
, Architecture b
) {
624 if (a
== native_architecture())
627 if (b
== native_architecture())
630 #ifdef ARCHITECTURE_SECONDARY
631 if (a
== ARCHITECTURE_SECONDARY
)
634 if (b
== ARCHITECTURE_SECONDARY
)
641 static int dissect_image(
645 const VeritySettings
*verity
,
646 const MountOptions
*mount_options
,
647 const ImagePolicy
*policy
,
648 DissectImageFlags flags
) {
650 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
651 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
652 bool is_gpt
, is_mbr
, multiple_generic
= false,
653 generic_rw
= false, /* initialize to appease gcc */
654 generic_growfs
= false;
655 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
656 _cleanup_free_
char *generic_node
= NULL
;
657 sd_id128_t generic_uuid
= SD_ID128_NULL
;
658 const char *pttype
= NULL
, *sptuuid
= NULL
;
660 int r
, generic_nr
= -1, n_partitions
;
665 assert(!verity
|| verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
666 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
667 assert(!verity
|| verity
->root_hash_sig
|| verity
->root_hash_sig_size
== 0);
668 assert(!verity
|| (verity
->root_hash
|| !verity
->root_hash_sig
));
669 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
670 assert(m
->sector_size
> 0);
672 /* Probes a disk image, and returns information about what it found in *ret.
674 * Returns -ENOPKG if no suitable partition table or file system could be found.
675 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
676 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
677 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that
678 * Returns -ERFKILL if image doesn't match image policy
679 * Returns -EBADR if verity data was provided externally for an image that has a GPT partition table (i.e. is not just a naked fs)
680 * Returns -EPROTONOSUPPORT if DISSECT_IMAGE_ADD_PARTITION_DEVICES is set but the block device does not have partition logic enabled
681 * Returns -ENOMSG if we didn't find a single usable partition (and DISSECT_IMAGE_REFUSE_EMPTY is set) */
683 uint64_t diskseq
= m
->loop
? m
->loop
->diskseq
: 0;
685 if (verity
&& verity
->root_hash
) {
686 sd_id128_t fsuuid
, vuuid
;
688 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
689 * first 128-bit of the root hash. And we use the verity partition that has a UUID that match
690 * the final 128-bit. */
692 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
695 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
696 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
698 if (sd_id128_is_null(fsuuid
))
700 if (sd_id128_is_null(vuuid
))
703 /* If the verity data declares it's for the /usr partition, then search for that, in all
704 * other cases assume it's for the root partition. */
705 if (verity
->designator
== PARTITION_USR
) {
707 usr_verity_uuid
= vuuid
;
710 root_verity_uuid
= vuuid
;
714 b
= blkid_new_probe();
719 r
= blkid_probe_set_device(b
, fd
, 0, 0);
721 return errno_or_else(ENOMEM
);
724 r
= blkid_probe_set_sectorsize(b
, m
->sector_size
);
726 return errno_or_else(EIO
);
728 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
729 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
730 blkid_probe_enable_superblocks(b
, 1);
731 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
|BLKID_SUBLKS_UUID
);
734 blkid_probe_enable_partitions(b
, 1);
735 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
738 r
= blkid_do_safeprobe(b
);
739 if (r
== _BLKID_SAFEPROBE_ERROR
)
740 return errno_or_else(EIO
);
741 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
))
742 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
744 assert(r
== _BLKID_SAFEPROBE_FOUND
);
746 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
747 (flags
& DISSECT_IMAGE_GENERIC_ROOT
)) ||
748 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
749 const char *usage
= NULL
;
751 /* If flags permit this, also allow using non-partitioned single-filesystem images */
753 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
754 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
755 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
756 const char *fstype
= NULL
, *options
= NULL
, *suuid
= NULL
;
757 _cleanup_close_
int mount_node_fd
= -EBADF
;
758 sd_id128_t uuid
= SD_ID128_NULL
;
759 PartitionPolicyFlags found_flags
;
762 /* OK, we have found a file system, that's our root partition then. */
764 r
= image_policy_may_use(policy
, PARTITION_ROOT
);
767 if (r
== 0) /* policy says ignore this, so we ignore it */
770 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
771 (void) blkid_probe_lookup_value(b
, "UUID", &suuid
, NULL
);
773 encrypted
= streq_ptr(fstype
, "crypto_LUKS");
775 if (verity_settings_data_covers(verity
, PARTITION_ROOT
))
776 found_flags
= verity
->root_hash_sig
? PARTITION_POLICY_SIGNED
: PARTITION_POLICY_VERITY
;
778 found_flags
= encrypted
? PARTITION_POLICY_ENCRYPTED
: PARTITION_POLICY_UNPROTECTED
;
780 r
= image_policy_check_protection(policy
, PARTITION_ROOT
, found_flags
);
784 r
= image_policy_check_partition_flags(policy
, PARTITION_ROOT
, 0); /* we have no gpt partition flags, hence check against all bits off */
788 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
789 mount_node_fd
= open_partition(devname
, /* is_partition = */ false, m
->loop
);
790 if (mount_node_fd
< 0)
791 return mount_node_fd
;
801 /* blkid will return FAT's serial number as UUID, hence it is quite possible
802 * that parsing this will fail. We'll ignore the ID, since it's just too
803 * short to be useful as true identifier. */
804 r
= sd_id128_from_string(suuid
, &uuid
);
806 log_debug_errno(r
, "Failed to parse file system UUID '%s', ignoring: %m", suuid
);
809 r
= make_partition_devname(devname
, diskseq
, -1, flags
, &n
);
813 m
->single_file_system
= true;
814 m
->encrypted
= encrypted
;
816 m
->has_verity
= verity
&& verity
->data_path
;
817 m
->verity_ready
= verity_settings_data_covers(verity
, PARTITION_ROOT
);
819 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
820 m
->verity_sig_ready
= m
->verity_ready
&& verity
->root_hash_sig
;
822 m
->image_uuid
= uuid
;
824 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
831 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
833 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
835 .architecture
= _ARCHITECTURE_INVALID
,
836 .fstype
= TAKE_PTR(t
),
838 .mount_options
= TAKE_PTR(o
),
839 .mount_node_fd
= TAKE_FD(mount_node_fd
),
842 .fsmount_fd
= -EBADF
,
849 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
853 is_gpt
= streq_ptr(pttype
, "gpt");
854 is_mbr
= streq_ptr(pttype
, "dos");
856 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
859 /* We support external verity data partitions only if the image has no partition table */
860 if (verity
&& verity
->data_path
)
863 if (FLAGS_SET(flags
, DISSECT_IMAGE_ADD_PARTITION_DEVICES
)) {
864 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
865 * do partition scanning. */
866 r
= blockdev_partscan_enabled(fd
);
870 return -EPROTONOSUPPORT
;
873 (void) blkid_probe_lookup_value(b
, "PTUUID", &sptuuid
, NULL
);
875 r
= sd_id128_from_string(sptuuid
, &m
->image_uuid
);
877 log_debug_errno(r
, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid
);
881 pl
= blkid_probe_get_partitions(b
);
883 return errno_or_else(ENOMEM
);
886 n_partitions
= blkid_partlist_numof_partitions(pl
);
887 if (n_partitions
< 0)
888 return errno_or_else(EIO
);
890 for (int i
= 0; i
< n_partitions
; i
++) {
891 _cleanup_free_
char *node
= NULL
;
892 unsigned long long pflags
;
893 blkid_loff_t start
, size
;
898 pp
= blkid_partlist_get_partition(pl
, i
);
900 return errno_or_else(EIO
);
902 pflags
= blkid_partition_get_flags(pp
);
905 nr
= blkid_partition_get_partno(pp
);
907 return errno_or_else(EIO
);
910 start
= blkid_partition_get_start(pp
);
912 return errno_or_else(EIO
);
914 assert((uint64_t) start
< UINT64_MAX
/512);
917 size
= blkid_partition_get_size(pp
);
919 return errno_or_else(EIO
);
921 assert((uint64_t) size
< UINT64_MAX
/512);
923 /* While probing we need the non-diskseq device node name to access the thing, hence mask off
924 * DISSECT_IMAGE_DISKSEQ_DEVNODE. */
925 r
= make_partition_devname(devname
, diskseq
, nr
, flags
& ~DISSECT_IMAGE_DISKSEQ_DEVNODE
, &node
);
929 /* So here's the thing: after the main ("whole") block device popped up it might take a while
930 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
931 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
932 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
933 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
934 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
935 * also good as the outcome is the same: the partition block device exists, and we can use
938 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
939 * partition already existent. */
941 if (FLAGS_SET(flags
, DISSECT_IMAGE_ADD_PARTITION_DEVICES
)) {
942 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
945 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
947 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
949 log_debug("We were quicker than kernel in adding partition %i.", nr
);
953 const char *fstype
= NULL
, *label
;
954 sd_id128_t type_id
, id
;
955 GptPartitionType type
;
956 bool rw
= true, growfs
= false;
958 r
= blkid_partition_get_uuid_id128(pp
, &id
);
960 log_debug_errno(r
, "Failed to read partition UUID, ignoring: %m");
964 r
= blkid_partition_get_type_id128(pp
, &type_id
);
966 log_debug_errno(r
, "Failed to read partition type UUID, ignoring: %m");
970 type
= gpt_partition_type_from_uuid(type_id
);
972 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
974 if (IN_SET(type
.designator
,
980 check_partition_flags(node
, pflags
,
981 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
983 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
986 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
987 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
989 } else if (type
.designator
== PARTITION_ESP
) {
991 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
992 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
993 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
996 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
1001 } else if (type
.designator
== PARTITION_ROOT
) {
1003 check_partition_flags(node
, pflags
,
1004 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1006 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1009 /* If a root ID is specified, ignore everything but the root id */
1010 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
1013 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1014 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1016 } else if (type
.designator
== PARTITION_ROOT_VERITY
) {
1018 check_partition_flags(node
, pflags
,
1019 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1021 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1024 m
->has_verity
= true;
1026 /* If no verity configuration is specified, then don't do verity */
1029 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
1032 /* If root hash is specified, then ignore everything but the root id */
1033 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
1036 fstype
= "DM_verity_hash";
1039 } else if (type
.designator
== PARTITION_ROOT_VERITY_SIG
) {
1041 check_partition_flags(node
, pflags
,
1042 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1044 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1047 m
->has_verity_sig
= true;
1051 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
1054 fstype
= "verity_hash_signature";
1057 } else if (type
.designator
== PARTITION_USR
) {
1059 check_partition_flags(node
, pflags
,
1060 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1062 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1065 /* If a usr ID is specified, ignore everything but the usr id */
1066 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
1069 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1070 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1072 } else if (type
.designator
== PARTITION_USR_VERITY
) {
1074 check_partition_flags(node
, pflags
,
1075 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1077 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1080 m
->has_verity
= true;
1084 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
1087 /* If usr hash is specified, then ignore everything but the usr id */
1088 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
1091 fstype
= "DM_verity_hash";
1094 } else if (type
.designator
== PARTITION_USR_VERITY_SIG
) {
1096 check_partition_flags(node
, pflags
,
1097 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1099 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1102 m
->has_verity_sig
= true;
1106 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
1109 fstype
= "verity_hash_signature";
1112 } else if (type
.designator
== PARTITION_SWAP
) {
1114 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
1116 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1119 /* Note: we don't set fstype = "swap" here, because we still need to probe if
1120 * it might be encrypted (i.e. fstype "crypt_LUKS") or unencrypted
1121 * (i.e. fstype "swap"), and the only way to figure that out is via fstype
1124 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
1125 } else if (sd_id128_equal(type
.uuid
, SD_GPT_LINUX_GENERIC
)) {
1127 check_partition_flags(node
, pflags
,
1128 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1130 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1134 multiple_generic
= true;
1137 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1138 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1140 generic_node
= TAKE_PTR(node
);
1143 } else if (type
.designator
== PARTITION_VAR
) {
1145 check_partition_flags(node
, pflags
,
1146 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1148 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1151 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
1152 sd_id128_t var_uuid
;
1154 /* For /var we insist that the uuid of the partition matches the
1155 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1156 * ID. Why? Unlike the other partitions /var is inherently
1157 * installation specific, hence we need to be careful not to mount it
1158 * in the wrong installation. By hashing the partition UUID from
1159 * /etc/machine-id we can securely bind the partition to the
1162 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
1166 if (!sd_id128_equal(var_uuid
, id
)) {
1167 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
1168 "(found: " SD_ID128_UUID_FORMAT_STR
", expected: " SD_ID128_UUID_FORMAT_STR
"), ignoring.",
1169 SD_ID128_FORMAT_VAL(id
), SD_ID128_FORMAT_VAL(var_uuid
));
1174 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1175 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1178 if (type
.designator
!= _PARTITION_DESIGNATOR_INVALID
) {
1179 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
, *n
= NULL
;
1180 _cleanup_close_
int mount_node_fd
= -EBADF
;
1181 const char *options
= NULL
;
1183 r
= image_policy_may_use(policy
, type
.designator
);
1187 /* Policy says: ignore; Remember this fact, so that we later can distinguish between "found but ignored" and "not found at all" */
1189 if (!m
->partitions
[type
.designator
].found
)
1190 m
->partitions
[type
.designator
].ignored
= true;
1195 if (m
->partitions
[type
.designator
].found
) {
1198 /* For most partition types the first one we see wins. Except for the
1199 * rootfs and /usr, where we do a version compare of the label, and
1200 * let the newest version win. This permits a simple A/B versioning
1201 * scheme in OS images. */
1203 c
= compare_arch(type
.arch
, m
->partitions
[type
.designator
].architecture
);
1204 if (c
< 0) /* the arch we already found is better than the one we found now */
1206 if (c
== 0 && /* same arch? then go by version in label */
1207 (!partition_designator_is_versioned(type
.designator
) ||
1208 strverscmp_improved(label
, m
->partitions
[type
.designator
].label
) <= 0))
1211 dissected_partition_done(m
->partitions
+ type
.designator
);
1214 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
) &&
1215 type
.designator
!= PARTITION_SWAP
) {
1216 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
1217 if (mount_node_fd
< 0)
1218 return mount_node_fd
;
1221 r
= make_partition_devname(devname
, diskseq
, nr
, flags
, &n
);
1237 options
= mount_options_from_designator(mount_options
, type
.designator
);
1239 o
= strdup(options
);
1244 m
->partitions
[type
.designator
] = (DissectedPartition
) {
1249 .architecture
= type
.arch
,
1250 .node
= TAKE_PTR(n
),
1251 .fstype
= TAKE_PTR(t
),
1252 .label
= TAKE_PTR(l
),
1254 .mount_options
= TAKE_PTR(o
),
1255 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1256 .offset
= (uint64_t) start
* 512,
1257 .size
= (uint64_t) size
* 512,
1258 .gpt_flags
= pflags
,
1259 .fsmount_fd
= -EBADF
,
1263 } else if (is_mbr
) {
1265 switch (blkid_partition_get_type(pp
)) {
1267 case 0x83: /* Linux partition */
1269 if (pflags
!= 0x80) /* Bootable flag */
1273 multiple_generic
= true;
1277 generic_growfs
= false;
1278 generic_node
= TAKE_PTR(node
);
1283 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1284 _cleanup_close_
int mount_node_fd
= -EBADF
;
1285 _cleanup_free_
char *o
= NULL
, *n
= NULL
;
1286 sd_id128_t id
= SD_ID128_NULL
;
1287 const char *options
= NULL
;
1289 r
= image_policy_may_use(policy
, PARTITION_XBOOTLDR
);
1292 if (r
== 0) { /* policy says: ignore */
1293 if (!m
->partitions
[PARTITION_XBOOTLDR
].found
)
1294 m
->partitions
[PARTITION_XBOOTLDR
].ignored
= true;
1299 /* First one wins */
1300 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
1303 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
1304 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
1305 if (mount_node_fd
< 0)
1306 return mount_node_fd
;
1309 (void) blkid_partition_get_uuid_id128(pp
, &id
);
1311 r
= make_partition_devname(devname
, diskseq
, nr
, flags
, &n
);
1315 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
1317 o
= strdup(options
);
1322 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
1327 .architecture
= _ARCHITECTURE_INVALID
,
1328 .node
= TAKE_PTR(n
),
1330 .mount_options
= TAKE_PTR(o
),
1331 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1332 .offset
= (uint64_t) start
* 512,
1333 .size
= (uint64_t) size
* 512,
1334 .fsmount_fd
= -EBADF
,
1342 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1343 (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
1344 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
))
1345 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
1347 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1348 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
1349 return -EADDRNOTAVAIL
;
1351 if (!m
->partitions
[PARTITION_USR
].found
&&
1352 (m
->partitions
[PARTITION_USR_VERITY
].found
||
1353 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
))
1354 return -EADDRNOTAVAIL
; /* as above */
1357 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1358 return -EADDRNOTAVAIL
;
1360 /* If root and /usr are combined then insist that the architecture matches */
1361 if (m
->partitions
[PARTITION_ROOT
].found
&&
1362 m
->partitions
[PARTITION_USR
].found
&&
1363 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1364 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1365 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1366 return -EADDRNOTAVAIL
;
1368 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1369 !m
->partitions
[PARTITION_USR
].found
&&
1370 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1371 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1373 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1374 * that. If the root hash was set however, then we won't fall back to a generic node, because
1375 * the root hash decides. */
1377 /* If we didn't find a properly marked root partition, but we did find a single suitable
1378 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1379 if (multiple_generic
)
1382 /* If we didn't find a generic node, then we can't fix this up either */
1384 r
= image_policy_may_use(policy
, PARTITION_ROOT
);
1388 /* Policy says: ignore; remember that we did */
1389 m
->partitions
[PARTITION_ROOT
].ignored
= true;
1391 _cleanup_close_
int mount_node_fd
= -EBADF
;
1392 _cleanup_free_
char *o
= NULL
, *n
= NULL
;
1393 const char *options
;
1395 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
1396 mount_node_fd
= open_partition(generic_node
, /* is_partition = */ true, m
->loop
);
1397 if (mount_node_fd
< 0)
1398 return mount_node_fd
;
1401 r
= make_partition_devname(devname
, diskseq
, generic_nr
, flags
, &n
);
1405 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1407 o
= strdup(options
);
1412 assert(generic_nr
>= 0);
1413 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1416 .growfs
= generic_growfs
,
1417 .partno
= generic_nr
,
1418 .architecture
= _ARCHITECTURE_INVALID
,
1419 .node
= TAKE_PTR(n
),
1420 .uuid
= generic_uuid
,
1421 .mount_options
= TAKE_PTR(o
),
1422 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1423 .offset
= UINT64_MAX
,
1425 .fsmount_fd
= -EBADF
,
1431 /* Check if we have a root fs if we are told to do check. /usr alone is fine too, but only if appropriate flag for that is set too */
1432 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1433 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1436 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1437 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1438 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1441 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1442 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1443 if (m
->partitions
[PARTITION_USR
].found
)
1444 return -EADDRNOTAVAIL
;
1448 /* If a verity designator is specified, then insist that the matching partition exists */
1449 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1450 return -EADDRNOTAVAIL
;
1452 bool have_verity_sig_partition
;
1453 if (verity
->designator
>= 0)
1454 have_verity_sig_partition
= m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR_VERITY_SIG
: PARTITION_ROOT_VERITY_SIG
].found
;
1456 have_verity_sig_partition
= m
->partitions
[PARTITION_USR_VERITY_SIG
].found
|| m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
;
1458 if (verity
->root_hash
) {
1459 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1460 * Verity, set things up for it */
1462 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1463 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1464 return -EADDRNOTAVAIL
;
1466 /* If we found a verity setup, then the root partition is necessarily read-only. */
1467 m
->partitions
[PARTITION_ROOT
].rw
= false;
1468 m
->verity_ready
= true;
1471 assert(verity
->designator
== PARTITION_USR
);
1473 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1474 return -EADDRNOTAVAIL
;
1476 m
->partitions
[PARTITION_USR
].rw
= false;
1477 m
->verity_ready
= true;
1480 if (m
->verity_ready
)
1481 m
->verity_sig_ready
= verity
->root_hash_sig
|| have_verity_sig_partition
;
1483 } else if (have_verity_sig_partition
) {
1485 /* If we found an embedded signature partition, we are ready, too. */
1487 m
->verity_ready
= m
->verity_sig_ready
= true;
1488 if (verity
->designator
>= 0)
1489 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR
: PARTITION_ROOT
].rw
= false;
1490 else if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
)
1491 m
->partitions
[PARTITION_USR
].rw
= false;
1492 else if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
)
1493 m
->partitions
[PARTITION_ROOT
].rw
= false;
1499 /* After we discovered all partitions let's see if the verity requirements match the policy. (Note:
1500 * we don't check encryption requirements here, because we haven't probed the file system yet, hence
1501 * don't know if this is encrypted or not) */
1502 for (PartitionDesignator di
= 0; di
< _PARTITION_DESIGNATOR_MAX
; di
++) {
1503 PartitionDesignator vi
, si
;
1504 PartitionPolicyFlags found_flags
;
1506 any
= any
|| m
->partitions
[di
].found
;
1508 vi
= partition_verity_of(di
);
1509 si
= partition_verity_sig_of(di
);
1511 /* Determine the verity protection level for this partition. */
1512 found_flags
= m
->partitions
[di
].found
?
1513 (vi
>= 0 && m
->partitions
[vi
].found
?
1514 (si
>= 0 && m
->partitions
[si
].found
? PARTITION_POLICY_SIGNED
: PARTITION_POLICY_VERITY
) :
1515 PARTITION_POLICY_ENCRYPTED
|PARTITION_POLICY_UNPROTECTED
) :
1516 (m
->partitions
[di
].ignored
? PARTITION_POLICY_UNUSED
: PARTITION_POLICY_ABSENT
);
1518 r
= image_policy_check_protection(policy
, di
, found_flags
);
1522 if (m
->partitions
[di
].found
) {
1523 r
= image_policy_check_partition_flags(policy
, di
, m
->partitions
[di
].gpt_flags
);
1529 if (!any
&& !FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_EMPTY
))
1532 r
= dissected_image_probe_filesystems(m
, fd
, policy
);
1540 int dissect_image_file(
1542 const VeritySettings
*verity
,
1543 const MountOptions
*mount_options
,
1544 const ImagePolicy
*image_policy
,
1545 DissectImageFlags flags
,
1546 DissectedImage
**ret
) {
1549 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1550 _cleanup_close_
int fd
= -EBADF
;
1556 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1560 if (fstat(fd
, &st
) < 0)
1563 r
= stat_verify_regular(&st
);
1567 r
= dissected_image_new(path
, &m
);
1571 m
->image_size
= st
.st_size
;
1573 r
= probe_sector_size(fd
, &m
->sector_size
);
1577 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, image_policy
, flags
);
1589 int dissect_log_error(int log_level
, int r
, const char *name
, const VeritySettings
*verity
) {
1590 assert(log_level
>= 0 && log_level
<= LOG_DEBUG
);
1595 case 0 ... INT_MAX
: /* success! */
1599 return log_full_errno(log_level
, r
, "Dissecting images is not supported, compiled without blkid support.");
1602 return log_full_errno(log_level
, r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
1605 return log_full_errno(log_level
, r
, "%s: The image does not pass os-release/extension-release validation.", name
);
1607 case -EADDRNOTAVAIL
:
1608 return log_full_errno(log_level
, r
, "%s: No root partition for specified root hash found.", name
);
1611 return log_full_errno(log_level
, r
, "%s: Multiple suitable root partitions found in image.", name
);
1614 return log_full_errno(log_level
, r
, "%s: No suitable root partition found in image.", name
);
1616 case -EPROTONOSUPPORT
:
1617 return log_full_errno(log_level
, r
, "Device '%s' is a loopback block device with partition scanning turned off, please turn it on.", name
);
1620 return log_full_errno(log_level
, r
, "%s: Image is not a block device.", name
);
1623 return log_full_errno(log_level
, r
,
1624 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
1625 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
1626 name
, strna(verity
? verity
->data_path
: NULL
));
1629 return log_full_errno(log_level
, r
, "%s: image does not match image policy.", name
);
1632 return log_full_errno(log_level
, r
, "%s: no suitable partitions found.", name
);
1635 return log_full_errno(log_level
, r
, "%s: cannot dissect image: %m", name
);
1639 int dissect_image_file_and_warn(
1641 const VeritySettings
*verity
,
1642 const MountOptions
*mount_options
,
1643 const ImagePolicy
*image_policy
,
1644 DissectImageFlags flags
,
1645 DissectedImage
**ret
) {
1647 return dissect_log_error(
1649 dissect_image_file(path
, verity
, mount_options
, image_policy
, flags
, ret
),
1654 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1658 /* First, clear dissected partitions. */
1659 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1660 dissected_partition_done(m
->partitions
+ i
);
1662 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1663 * DecryptedImage may try to deactivate partitions. */
1664 decrypted_image_unref(m
->decrypted_image
);
1666 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1667 * remove existing partitions on the loopback block device. */
1668 loop_device_unref(m
->loop
);
1670 free(m
->image_name
);
1672 strv_free(m
->machine_info
);
1673 strv_free(m
->os_release
);
1674 strv_free(m
->initrd_release
);
1675 strv_free(m
->confext_release
);
1676 strv_free(m
->sysext_release
);
1681 static int is_loop_device(const char *path
) {
1682 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1687 if (stat(path
, &st
) < 0)
1690 if (!S_ISBLK(st
.st_mode
))
1693 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1694 if (access(s
, F_OK
) < 0) {
1695 if (errno
!= ENOENT
)
1698 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1699 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1700 if (access(s
, F_OK
) < 0)
1701 return errno
== ENOENT
? false : -errno
;
1707 static int run_fsck(int node_fd
, const char *fstype
) {
1711 assert(node_fd
>= 0);
1714 r
= fsck_exists_for_fstype(fstype
);
1716 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1720 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd
), fstype
);
1727 &node_fd
, 1, /* Leave the node fd open */
1728 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG_SIGTERM
|FORK_REARRANGE_STDIO
|FORK_CLOEXEC_OFF
,
1731 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1734 execlp("fsck", "fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd
), NULL
);
1736 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1737 _exit(FSCK_OPERATIONAL_ERROR
);
1740 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1741 if (exit_status
< 0)
1742 return log_debug_errno(exit_status
, "Failed to fork off fsck: %m");
1744 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1745 log_debug("fsck failed with exit status %i.", exit_status
);
1747 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1748 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1750 log_debug("Ignoring fsck error.");
1756 static int fs_grow(const char *node_path
, int mount_fd
, const char *mount_path
) {
1757 _cleanup_close_
int _mount_fd
= -EBADF
, node_fd
= -EBADF
;
1758 uint64_t size
, newsize
;
1763 assert(mount_fd
>= 0 || mount_path
);
1765 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1767 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1769 r
= blockdev_get_device_size(node_fd
, &size
);
1771 return log_debug_errno(r
, "Failed to get block device size of %s: %m", node_path
);
1776 _mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1778 return log_debug_errno(errno
, "Failed to open mounted file system %s: %m", mount_path
);
1780 mount_fd
= _mount_fd
;
1782 mount_fd
= fd_reopen_condition(mount_fd
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, &_mount_fd
);
1784 return log_debug_errno(errno
, "Failed to reopen mount node: %m");
1787 id
= mount_path
?: node_path
;
1789 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", id
, size
);
1790 r
= resize_fs(mount_fd
, size
, &newsize
);
1792 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", id
, size
);
1794 if (newsize
== size
)
1795 log_debug("Successfully resized \"%s\" to %s bytes.",
1796 id
, FORMAT_BYTES(newsize
));
1798 assert(newsize
< size
);
1799 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1800 id
, FORMAT_BYTES(newsize
), size
- newsize
);
1806 int partition_pick_mount_options(
1807 PartitionDesignator d
,
1812 unsigned long *ret_ms_flags
) {
1814 _cleanup_free_
char *options
= NULL
;
1816 assert(ret_options
);
1818 /* Selects a baseline of bind mount flags, that should always apply.
1820 * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
1822 * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
1824 * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
1825 * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
1826 * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
1829 unsigned long flags
= MS_NODEV
;
1837 case PARTITION_XBOOTLDR
:
1838 flags
|= MS_NOSUID
|MS_NOEXEC
|ms_nosymfollow_supported();
1840 /* The ESP might contain a pre-boot random seed. Let's make this unaccessible to regular
1841 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
1842 if (!fstype
|| fstype_can_umask(fstype
))
1843 if (!strextend_with_separator(&options
, ",", "umask=0077"))
1855 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1856 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1857 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1858 * from the upper file system still get propagated through to the underlying file system,
1859 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1860 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1861 * carry a per file system table here.
1863 * Note that this means that we might not be able to mount corrupted file systems as read-only
1864 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1865 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1866 * mount options for loopback devices this is the right choice, since otherwise using the same
1867 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The use case of
1868 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1869 * access that actually modifies stuff work on such image files. Or to say this differently: if
1870 * people want their file systems to be fixed up they should just open them in writable mode, where
1871 * all these problems don't exist. */
1872 if (!rw
&& fstype
&& fstype_can_norecovery(fstype
))
1873 if (!strextend_with_separator(&options
, ",", "norecovery"))
1876 if (discard
&& fstype
&& fstype_can_discard(fstype
))
1877 if (!strextend_with_separator(&options
, ",", "discard"))
1880 if (!ret_ms_flags
) /* Fold flags into option string if ret_flags specified as NULL */
1881 if (!strextend_with_separator(&options
, ",",
1882 FLAGS_SET(flags
, MS_RDONLY
) ? "ro" : "rw",
1883 FLAGS_SET(flags
, MS_NODEV
) ? "nodev" : "dev",
1884 FLAGS_SET(flags
, MS_NOSUID
) ? "nosuid" : "suid",
1885 FLAGS_SET(flags
, MS_NOEXEC
) ? "noexec" : "exec",
1886 FLAGS_SET(flags
, MS_NOSYMFOLLOW
) ? "nosymfollow" : NULL
))
1887 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
1891 *ret_ms_flags
= flags
;
1893 *ret_options
= TAKE_PTR(options
);
1897 static bool need_user_mapping(uid_t uid_shift
, uid_t uid_range
) {
1899 if (!uid_is_valid(uid_shift
))
1902 return uid_shift
!= 0 || uid_range
!= UINT32_MAX
;
1905 static int mount_partition(
1906 PartitionDesignator d
,
1907 DissectedPartition
*m
,
1909 const char *directory
,
1913 DissectImageFlags flags
) {
1915 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1916 const char *p
= NULL
, *node
, *fstype
= NULL
;
1917 bool rw
, discard
, grow
;
1918 unsigned long ms_flags
;
1926 /* Check the various combinations when we can't do anything anymore */
1927 if (m
->fsmount_fd
< 0 && m
->mount_node_fd
< 0)
1929 if (m
->fsmount_fd
>= 0 && !where
)
1931 if (!where
&& m
->mount_node_fd
< 0)
1934 if (m
->fsmount_fd
< 0) {
1935 fstype
= dissected_partition_fstype(m
);
1937 return -EAFNOSUPPORT
;
1939 /* We are looking at an encrypted partition? This either means stacked encryption, or the
1940 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
1942 if (streq(fstype
, "crypto_LUKS"))
1945 r
= dissect_fstype_ok(fstype
);
1949 return -EIDRM
; /* Recognizable error */
1952 node
= m
->mount_node_fd
< 0 ? NULL
: FORMAT_PROC_FD_PATH(m
->mount_node_fd
);
1953 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
1955 discard
= ((flags
& DISSECT_IMAGE_DISCARD
) ||
1956 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && (m
->node
&& is_loop_device(m
->node
) > 0)));
1958 grow
= rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
);
1960 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
&& m
->mount_node_fd
>= 0 && m
->fsmount_fd
< 0) {
1961 r
= run_fsck(m
->mount_node_fd
, fstype
);
1968 /* Automatically create missing mount points inside the image, if necessary. */
1969 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755, NULL
);
1970 if (r
< 0 && r
!= -EROFS
)
1973 r
= chase(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
1979 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
1980 * image (as the branch above does) but the host hierarchy, and the created directory might
1981 * survive our mount in the host hierarchy hence. */
1982 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
1983 r
= mkdir_p(where
, 0755);
1992 if (m
->fsmount_fd
< 0) {
1993 r
= partition_pick_mount_options(d
, fstype
, rw
, discard
, &options
, &ms_flags
);
1997 if (need_user_mapping(uid_shift
, uid_range
) && fstype_can_uid_gid(fstype
)) {
1998 _cleanup_free_
char *uid_option
= NULL
;
2000 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
2003 if (!strextend_with_separator(&options
, ",", uid_option
))
2006 userns_fd
= -EBADF
; /* Not needed */
2009 if (!isempty(m
->mount_options
))
2010 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
2015 if (m
->fsmount_fd
>= 0) {
2016 /* Case #1: Attach existing fsmount fd to the file system */
2018 r
= mount_exchange_graceful(
2021 FLAGS_SET(flags
, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE
));
2023 return log_debug_errno(r
, "Failed to mount image on '%s': %m", p
);
2028 /* Case #2: Mount directly into place */
2029 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, ms_flags
, options
);
2034 (void) fs_grow(node
, -EBADF
, p
);
2036 if (userns_fd
>= 0) {
2037 r
= remount_idmap_fd(STRV_MAKE(p
), userns_fd
);
2045 /* Case #3: Create fsmount fd */
2047 m
->fsmount_fd
= make_fsmount(LOG_DEBUG
, node
, fstype
, ms_flags
, options
, userns_fd
);
2048 if (m
->fsmount_fd
< 0)
2049 return m
->fsmount_fd
;
2052 (void) fs_grow(node
, m
->fsmount_fd
, NULL
);
2058 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, uid_t uid_range
, DissectImageFlags flags
) {
2059 _cleanup_free_
char *options
= NULL
;
2064 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
2066 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
2067 r
= mkdir_p(where
, 0755);
2072 if (need_user_mapping(uid_shift
, uid_range
)) {
2073 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
2077 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
2084 static int mount_point_is_available(const char *where
, const char *path
, bool missing_ok
) {
2085 _cleanup_free_
char *p
= NULL
;
2088 /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
2089 * or does not exist at all (when missing_ok). */
2091 r
= chase(path
, where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
2095 return log_debug_errno(r
, "Failed to chase \"%s\": %m", path
);
2097 r
= dir_is_empty(p
, /* ignore_hidden_or_backup= */ false);
2101 return log_debug_errno(r
, "Failed to check directory \"%s\": %m", p
);
2105 int dissected_image_mount(
2111 DissectImageFlags flags
) {
2113 _cleanup_close_
int my_userns_fd
= -EBADF
;
2118 /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
2119 * store them in DissectedPartition.fsmount_fd.
2121 * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
2122 * or use DissectedPartition.fsmount_fd and bind it to the right places.
2124 * This allows splitting the setting up up the superblocks and the binding to file systems paths into
2125 * two distinct and differently privileged components: one that gets the fsmount fds, and the other
2126 * that then applies them.
2130 * -ENXIO → No root partition found
2131 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
2132 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
2133 * -EUCLEAN → fsck for file system failed
2134 * -EBUSY → File system already mounted/used elsewhere (kernel)
2135 * -EAFNOSUPPORT → File system type not supported or not known
2136 * -EIDRM → File system is not among allowlisted "common" file systems
2139 if (!where
&& (flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0)
2140 return -EOPNOTSUPP
; /* for now, not supported */
2142 if (!(m
->partitions
[PARTITION_ROOT
].found
||
2143 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
2144 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
2146 if (userns_fd
< 0 && need_user_mapping(uid_shift
, uid_range
) && FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
)) {
2148 my_userns_fd
= make_userns(uid_shift
, uid_range
, UID_INVALID
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
2149 if (my_userns_fd
< 0)
2150 return my_userns_fd
;
2152 userns_fd
= my_userns_fd
;
2155 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
2157 /* First mount the root fs. If there's none we use a tmpfs. */
2158 if (m
->partitions
[PARTITION_ROOT
].found
) {
2159 r
= mount_partition(PARTITION_ROOT
, m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, userns_fd
, flags
);
2164 r
= mount_root_tmpfs(where
, uid_shift
, uid_range
, flags
);
2169 /* For us mounting root always means mounting /usr as well */
2170 r
= mount_partition(PARTITION_USR
, m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, userns_fd
, flags
);
2175 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0 &&
2176 (flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
2177 /* If either one of the validation flags are set, ensure that the image qualifies as
2178 * one or the other (or both). */
2183 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
2184 r
= path_is_os_tree(where
);
2190 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
) && m
->image_name
) {
2191 r
= extension_has_forbidden_content(where
);
2195 r
= path_is_extension_tree(IMAGE_SYSEXT
, where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_EXTENSION_CHECK
));
2197 r
= path_is_extension_tree(IMAGE_CONFEXT
, where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_EXTENSION_CHECK
));
2209 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
2212 r
= mount_partition(PARTITION_HOME
, m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, userns_fd
, flags
);
2216 r
= mount_partition(PARTITION_SRV
, m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, userns_fd
, flags
);
2220 r
= mount_partition(PARTITION_VAR
, m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, userns_fd
, flags
);
2224 r
= mount_partition(PARTITION_TMP
, m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, userns_fd
, flags
);
2228 int slash_boot_is_available
= 0;
2230 r
= slash_boot_is_available
= mount_point_is_available(where
, "/boot", /* missing_ok = */ true);
2234 if (!where
|| slash_boot_is_available
) {
2235 r
= mount_partition(PARTITION_XBOOTLDR
, m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, userns_fd
, flags
);
2238 slash_boot_is_available
= !r
;
2241 if (m
->partitions
[PARTITION_ESP
].found
) {
2242 const char *esp_path
= NULL
;
2245 /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
2246 * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
2249 if (slash_boot_is_available
) {
2250 r
= mount_point_is_available(where
, "/boot", /* missing_ok = */ false);
2258 r
= mount_point_is_available(where
, "/efi", /* missing_ok = */ true);
2266 /* OK, let's mount the ESP now (possibly creating the dir if missing) */
2267 r
= mount_partition(PARTITION_ESP
, m
->partitions
+ PARTITION_ESP
, where
, esp_path
, uid_shift
, uid_range
, userns_fd
, flags
);
2275 int dissected_image_mount_and_warn(
2281 DissectImageFlags flags
) {
2287 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, userns_fd
, flags
);
2289 return log_error_errno(r
, "Not root file system found in image.");
2290 if (r
== -EMEDIUMTYPE
)
2291 return log_error_errno(r
, "No suitable os-release/extension-release file in image found.");
2293 return log_error_errno(r
, "Encrypted file system discovered, but decryption not requested.");
2295 return log_error_errno(r
, "File system check on image failed.");
2297 return log_error_errno(r
, "File system already mounted elsewhere.");
2298 if (r
== -EAFNOSUPPORT
)
2299 return log_error_errno(r
, "File system type not supported or not known.");
2301 return log_error_errno(r
, "File system is too uncommon, refused.");
2303 return log_error_errno(r
, "Failed to mount image: %m");
2308 #if HAVE_LIBCRYPTSETUP
2309 struct DecryptedPartition
{
2310 struct crypt_device
*device
;
2316 typedef struct DecryptedPartition DecryptedPartition
;
2318 struct DecryptedImage
{
2320 DecryptedPartition
*decrypted
;
2324 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
2325 #if HAVE_LIBCRYPTSETUP
2331 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2332 DecryptedPartition
*p
= d
->decrypted
+ i
;
2334 if (p
->device
&& p
->name
&& !p
->relinquished
) {
2335 _cleanup_free_
char *node
= NULL
;
2337 node
= path_join("/dev/mapper", p
->name
);
2339 r
= btrfs_forget_device(node
);
2340 if (r
< 0 && r
!= -ENOENT
)
2341 log_debug_errno(r
, "Failed to forget btrfs device %s, ignoring: %m", node
);
2345 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2346 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2348 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
2352 sym_crypt_free(p
->device
);
2362 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
2364 #if HAVE_LIBCRYPTSETUP
2365 static int decrypted_image_new(DecryptedImage
**ret
) {
2366 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2370 d
= new(DecryptedImage
, 1);
2374 *d
= (DecryptedImage
) {
2382 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
2383 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
2386 assert(original_node
);
2391 base
= strrchr(original_node
, '/');
2393 base
= original_node
;
2399 name
= strjoin(base
, suffix
);
2402 if (!filename_is_valid(name
))
2405 node
= path_join(sym_crypt_get_dir(), name
);
2409 *ret_name
= TAKE_PTR(name
);
2410 *ret_node
= TAKE_PTR(node
);
2415 static int decrypt_partition(
2416 DissectedPartition
*m
,
2417 const char *passphrase
,
2418 DissectImageFlags flags
,
2419 DecryptedImage
*d
) {
2421 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2422 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2423 _cleanup_close_
int fd
= -EBADF
;
2429 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2432 if (!streq(m
->fstype
, "crypto_LUKS"))
2438 r
= dlopen_cryptsetup();
2442 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
2446 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2449 r
= sym_crypt_init(&cd
, m
->node
);
2451 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
2453 cryptsetup_enable_logging(cd
);
2455 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
2457 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
2459 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
2460 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
2461 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
2463 log_debug_errno(r
, "Failed to activate LUKS device: %m");
2464 return r
== -EPERM
? -EKEYREJECTED
: r
;
2467 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2469 return log_debug_errno(errno
, "Failed to open %s: %m", node
);
2471 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2472 .name
= TAKE_PTR(name
),
2473 .device
= TAKE_PTR(cd
),
2476 m
->decrypted_node
= TAKE_PTR(node
);
2477 close_and_replace(m
->mount_node_fd
, fd
);
2482 static int verity_can_reuse(
2483 const VeritySettings
*verity
,
2485 struct crypt_device
**ret_cd
) {
2487 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2488 _cleanup_free_
char *root_hash_existing
= NULL
;
2489 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2490 struct crypt_params_verity crypt_params
= {};
2491 size_t root_hash_existing_size
;
2498 r
= sym_crypt_init_by_name(&cd
, name
);
2500 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
2502 cryptsetup_enable_logging(cd
);
2504 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
2506 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
2508 root_hash_existing_size
= verity
->root_hash_size
;
2509 root_hash_existing
= malloc0(root_hash_existing_size
);
2510 if (!root_hash_existing
)
2513 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
2515 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
2516 if (verity
->root_hash_size
!= root_hash_existing_size
||
2517 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
2518 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
2520 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2521 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2522 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2523 * signing for the new one, and vice versa. */
2524 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
2525 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
2528 *ret_cd
= TAKE_PTR(cd
);
2532 static char* dm_deferred_remove_clean(char *name
) {
2536 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
2539 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
2541 static int validate_signature_userspace(const VeritySettings
*verity
, DissectImageFlags flags
) {
2544 if (!FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
)) {
2545 log_debug("Userspace dm-verity signature authentication disabled via flag.");
2549 r
= getenv_bool_secure("SYSTEMD_ALLOW_USERSPACE_VERITY");
2550 if (r
< 0 && r
!= -ENXIO
) {
2551 log_debug_errno(r
, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
2555 log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
2560 r
= proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING
, &b
);
2562 log_debug_errno(r
, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
2566 log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line variable.");
2571 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
2572 _cleanup_strv_free_
char **certs
= NULL
;
2573 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
2574 _cleanup_free_
char *s
= NULL
;
2575 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
2576 * of declaration in place, please */
2577 const unsigned char *d
;
2580 assert(verity
->root_hash
);
2581 assert(verity
->root_hash_sig
);
2583 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
2584 * userspace validation. */
2586 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
2588 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
2589 if (strv_isempty(certs
)) {
2590 log_debug("No userspace dm-verity certificates found.");
2594 d
= verity
->root_hash_sig
;
2595 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
2597 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
2599 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2601 return log_oom_debug();
2603 bio
= BIO_new_mem_buf(s
, strlen(s
));
2605 return log_oom_debug();
2607 sk
= sk_X509_new_null();
2609 return log_oom_debug();
2611 STRV_FOREACH(i
, certs
) {
2612 _cleanup_(X509_freep
) X509
*c
= NULL
;
2613 _cleanup_fclose_
FILE *f
= NULL
;
2615 f
= fopen(*i
, "re");
2617 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
2621 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
2623 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
2627 if (sk_X509_push(sk
, c
) == 0)
2628 return log_oom_debug();
2633 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
2635 log_debug("Userspace PKCS#7 validation succeeded.");
2637 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
2641 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2646 static int do_crypt_activate_verity(
2647 struct crypt_device
*cd
,
2649 const VeritySettings
*verity
,
2650 DissectImageFlags flags
) {
2652 bool check_signature
;
2659 if (verity
->root_hash_sig
) {
2660 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2661 if (r
< 0 && r
!= -ENXIO
)
2662 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2664 check_signature
= r
!= 0;
2666 check_signature
= false;
2668 if (check_signature
) {
2670 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2671 /* First, if we have support for signed keys in the kernel, then try that first. */
2672 r
= sym_crypt_activate_by_signed_key(
2676 verity
->root_hash_size
,
2677 verity
->root_hash_sig
,
2678 verity
->root_hash_sig_size
,
2679 CRYPT_ACTIVATE_READONLY
);
2683 log_debug_errno(r
, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
2685 log_debug("Activation of verity device with signature requested, but not supported via the kernel by %s due to missing crypt_activate_by_signed_key(), trying userspace validation instead.",
2686 program_invocation_short_name
);
2687 r
= 0; /* Set for the propagation below */
2690 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2691 * works we'll try to activate without telling the kernel the signature. */
2693 /* Preferably propagate the original kernel error, so that the fallback logic can work,
2694 * as the device-mapper is finicky around concurrent activations of the same volume */
2695 k
= validate_signature_userspace(verity
, flags
);
2697 return r
< 0 ? r
: k
;
2699 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(ENOKEY
),
2700 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2703 return sym_crypt_activate_by_volume_key(
2707 verity
->root_hash_size
,
2708 CRYPT_ACTIVATE_READONLY
);
2711 static usec_t
verity_timeout(void) {
2712 usec_t t
= 100 * USEC_PER_MSEC
;
2716 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2717 * Let's make the timeout configurable. */
2719 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2723 r
= parse_sec(e
, &t
);
2726 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2727 "using the default timeout (%s).",
2728 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
2733 static int verity_partition(
2734 PartitionDesignator designator
,
2735 DissectedPartition
*m
,
2736 DissectedPartition
*v
,
2737 const VeritySettings
*verity
,
2738 DissectImageFlags flags
,
2739 DecryptedImage
*d
) {
2741 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2742 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2743 _cleanup_close_
int mount_node_fd
= -EBADF
;
2747 assert(v
|| (verity
&& verity
->data_path
));
2749 if (!verity
|| !verity
->root_hash
)
2751 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2752 (verity
->designator
== designator
)))
2755 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2757 if (!verity
->data_path
) {
2758 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2761 if (!streq(v
->fstype
, "DM_verity_hash"))
2765 r
= dlopen_cryptsetup();
2769 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2770 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2771 _cleanup_free_
char *root_hash_encoded
= NULL
;
2773 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2774 if (!root_hash_encoded
)
2777 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2779 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2783 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2787 cryptsetup_enable_logging(cd
);
2789 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2793 r
= sym_crypt_set_data_device(cd
, m
->node
);
2797 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2800 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2801 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2802 * retry a few times before giving up. */
2803 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2804 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2805 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2806 _cleanup_close_
int fd
= -EBADF
;
2808 /* First, check if the device already exists. */
2809 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2810 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2811 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2813 goto check
; /* The device already exists. Let's check it. */
2815 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2816 r
= do_crypt_activate_verity(cd
, name
, verity
, flags
);
2818 goto try_open
; /* The device is activated. Let's open it. */
2819 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2820 * There's no way to distinguish this situation from a genuine error due to invalid
2821 * parameters, so immediately fall back to activating the device with a unique name.
2822 * Improvements in libcrypsetup can ensure this never happens:
2823 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2824 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2826 /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
2827 * sharing is enabled. */
2828 if (r
== -ENODEV
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2831 -EEXIST
, /* Volume has already been opened and ready to be used. */
2832 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2833 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2836 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2837 r
= dm_deferred_remove_cancel(name
);
2838 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2839 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2840 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2841 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2844 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2846 restore_deferred_remove
= strdup(name
);
2847 if (!restore_deferred_remove
)
2848 return log_oom_debug();
2850 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2851 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2852 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2855 -ENOENT
, /* Removed?? */
2856 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2857 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2860 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2863 /* devmapper might say that the device exists, but the devlink might not yet have been
2864 * created. Check and wait for the udev event in that case. */
2865 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2866 /* Fallback to activation with a unique device if it's taking too long */
2867 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2870 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2875 /* Now, the device is activated and devlink is created. Let's open it. */
2876 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2878 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
2879 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2881 /* The device has already been removed?? */
2886 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2887 restore_deferred_remove
= mfree(restore_deferred_remove
);
2889 mount_node_fd
= TAKE_FD(fd
);
2891 crypt_free_and_replace(cd
, existing_cd
);
2896 /* Device is being removed by another process. Let's wait for a while. */
2897 (void) usleep_safe(2 * USEC_PER_MSEC
);
2900 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2901 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2902 /* Before trying to activate with unique name, we need to free crypt_device object.
2903 * Otherwise, we get error from libcryptsetup like the following:
2905 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2910 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2913 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2916 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2917 .name
= TAKE_PTR(name
),
2918 .device
= TAKE_PTR(cd
),
2921 m
->decrypted_node
= TAKE_PTR(node
);
2922 close_and_replace(m
->mount_node_fd
, mount_node_fd
);
2928 int dissected_image_decrypt(
2930 const char *passphrase
,
2931 const VeritySettings
*verity
,
2932 DissectImageFlags flags
) {
2934 #if HAVE_LIBCRYPTSETUP
2935 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2940 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
2944 * = 0 → There was nothing to decrypt
2945 * > 0 → Decrypted successfully
2946 * -ENOKEY → There's something to decrypt but no key was supplied
2947 * -EKEYREJECTED → Passed key was not correct
2950 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
2953 if (!m
->encrypted
&& !m
->verity_ready
)
2956 #if HAVE_LIBCRYPTSETUP
2957 r
= decrypted_image_new(&d
);
2961 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
2962 DissectedPartition
*p
= m
->partitions
+ i
;
2963 PartitionDesignator k
;
2968 r
= decrypt_partition(p
, passphrase
, flags
, d
);
2972 k
= partition_verity_of(i
);
2974 flags
|= getenv_bool("SYSTEMD_VERITY_SHARING") != 0 ? DISSECT_IMAGE_VERITY_SHARE
: 0;
2976 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
, d
);
2981 if (!p
->decrypted_fstype
&& p
->mount_node_fd
>= 0 && p
->decrypted_node
) {
2982 r
= probe_filesystem_full(p
->mount_node_fd
, p
->decrypted_node
, 0, UINT64_MAX
, &p
->decrypted_fstype
);
2983 if (r
< 0 && r
!= -EUCLEAN
)
2988 m
->decrypted_image
= TAKE_PTR(d
);
2996 int dissected_image_decrypt_interactively(
2998 const char *passphrase
,
2999 const VeritySettings
*verity
,
3000 DissectImageFlags flags
) {
3002 _cleanup_strv_free_erase_
char **z
= NULL
;
3009 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
3012 if (r
== -EKEYREJECTED
)
3013 log_error_errno(r
, "Incorrect passphrase, try again!");
3014 else if (r
!= -ENOKEY
)
3015 return log_error_errno(r
, "Failed to decrypt image: %m");
3018 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
3019 "Too many retries.");
3021 z
= strv_free_erase(z
);
3023 static const AskPasswordRequest req
= {
3024 .message
= "Please enter image passphrase:",
3026 .keyring
= "dissect",
3027 .credential
= "dissect.passphrase",
3030 r
= ask_password_auto(&req
, USEC_INFINITY
, /* flags= */ 0, &z
);
3032 return log_error_errno(r
, "Failed to query for passphrase: %m");
3038 static int decrypted_image_relinquish(DecryptedImage
*d
) {
3041 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
3042 * boolean so that we don't clean it up ourselves either anymore */
3044 #if HAVE_LIBCRYPTSETUP
3047 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
3048 DecryptedPartition
*p
= d
->decrypted
+ i
;
3050 if (p
->relinquished
)
3053 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
3055 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
3057 p
->relinquished
= true;
3064 int dissected_image_relinquish(DissectedImage
*m
) {
3069 if (m
->decrypted_image
) {
3070 r
= decrypted_image_relinquish(m
->decrypted_image
);
3076 loop_device_relinquish(m
->loop
);
3081 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
3088 e
= endswith(image
, ".raw");
3090 return strjoin(e
, suffix
);
3092 n
= new(char, e
- image
+ strlen(suffix
) + 1);
3096 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
3100 void verity_settings_done(VeritySettings
*v
) {
3103 v
->root_hash
= mfree(v
->root_hash
);
3104 v
->root_hash_size
= 0;
3106 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
3107 v
->root_hash_sig_size
= 0;
3109 v
->data_path
= mfree(v
->data_path
);
3112 int verity_settings_load(
3113 VeritySettings
*verity
,
3115 const char *root_hash_path
,
3116 const char *root_hash_sig_path
) {
3118 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
3119 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
3120 _cleanup_free_
char *verity_data_path
= NULL
;
3121 PartitionDesignator designator
;
3126 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
3128 /* If we are asked to load the root hash for a device node, exit early */
3129 if (is_device_path(image
))
3132 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
3133 if (r
< 0 && r
!= -ENXIO
)
3134 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
3138 designator
= verity
->designator
;
3140 /* We only fill in what isn't already filled in */
3142 if (!verity
->root_hash
) {
3143 _cleanup_free_
char *text
= NULL
;
3145 if (root_hash_path
) {
3146 /* If explicitly specified it takes precedence */
3147 r
= read_one_line_file(root_hash_path
, &text
);
3152 designator
= PARTITION_ROOT
;
3154 /* Otherwise look for xattr and separate file, and first for the data for root and if
3155 * that doesn't exist for /usr */
3157 if (designator
< 0 || designator
== PARTITION_ROOT
) {
3158 r
= getxattr_malloc(image
, "user.verity.roothash", &text
);
3160 _cleanup_free_
char *p
= NULL
;
3162 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
3165 p
= build_auxiliary_path(image
, ".roothash");
3169 r
= read_one_line_file(p
, &text
);
3170 if (r
< 0 && r
!= -ENOENT
)
3175 designator
= PARTITION_ROOT
;
3178 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
3179 /* So in the "roothash" xattr/file name above the "root" of course primarily
3180 * refers to the root of the Verity Merkle tree. But coincidentally it also
3181 * is the hash for the *root* file system, i.e. the "root" neatly refers to
3182 * two distinct concepts called "root". Taking benefit of this happy
3183 * coincidence we call the file with the root hash for the /usr/ file system
3184 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
3185 * confusing. We thus drop the reference to the root of the Merkle tree, and
3186 * just indicate which file system it's about. */
3187 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
);
3189 _cleanup_free_
char *p
= NULL
;
3191 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
3194 p
= build_auxiliary_path(image
, ".usrhash");
3198 r
= read_one_line_file(p
, &text
);
3199 if (r
< 0 && r
!= -ENOENT
)
3204 designator
= PARTITION_USR
;
3209 r
= unhexmem(text
, &root_hash
, &root_hash_size
);
3212 if (root_hash_size
< sizeof(sd_id128_t
))
3217 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
3218 if (root_hash_sig_path
) {
3219 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3220 if (r
< 0 && r
!= -ENOENT
)
3224 designator
= PARTITION_ROOT
;
3226 if (designator
< 0 || designator
== PARTITION_ROOT
) {
3227 _cleanup_free_
char *p
= NULL
;
3229 /* Follow naming convention recommended by the relevant RFC:
3230 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
3231 p
= build_auxiliary_path(image
, ".roothash.p7s");
3235 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3236 if (r
< 0 && r
!= -ENOENT
)
3239 designator
= PARTITION_ROOT
;
3242 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
3243 _cleanup_free_
char *p
= NULL
;
3245 p
= build_auxiliary_path(image
, ".usrhash.p7s");
3249 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3250 if (r
< 0 && r
!= -ENOENT
)
3253 designator
= PARTITION_USR
;
3257 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
3261 if (!verity
->data_path
) {
3262 _cleanup_free_
char *p
= NULL
;
3264 p
= build_auxiliary_path(image
, ".verity");
3268 if (access(p
, F_OK
) < 0) {
3269 if (errno
!= ENOENT
)
3272 verity_data_path
= TAKE_PTR(p
);
3276 verity
->root_hash
= TAKE_PTR(root_hash
);
3277 verity
->root_hash_size
= root_hash_size
;
3280 if (root_hash_sig
) {
3281 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
3282 verity
->root_hash_sig_size
= root_hash_sig_size
;
3285 if (verity_data_path
)
3286 verity
->data_path
= TAKE_PTR(verity_data_path
);
3288 if (verity
->designator
< 0)
3289 verity
->designator
= designator
;
3294 int dissected_image_load_verity_sig_partition(
3297 VeritySettings
*verity
) {
3299 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
3300 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
3301 size_t root_hash_size
, root_hash_sig_size
;
3302 _cleanup_free_
char *buf
= NULL
;
3303 PartitionDesignator d
;
3304 DissectedPartition
*p
;
3305 JsonVariant
*rh
, *sig
;
3314 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
3317 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_EMBEDDED");
3318 if (r
< 0 && r
!= -ENXIO
)
3319 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
3323 d
= partition_verity_sig_of(verity
->designator
< 0 ? PARTITION_ROOT
: verity
->designator
);
3326 p
= m
->partitions
+ d
;
3329 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
3332 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
3333 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG
), "Verity signature partition is larger than 4M, refusing.");
3335 buf
= new(char, p
->size
+1);
3339 n
= pread(fd
, buf
, p
->size
, p
->offset
);
3342 if ((uint64_t) n
!= p
->size
)
3345 e
= memchr(buf
, 0, p
->size
);
3347 /* If we found a NUL byte then the rest of the data must be NUL too */
3348 if (!memeqzero(e
, p
->size
- (e
- buf
)))
3349 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
3353 r
= json_parse(buf
, 0, &v
, NULL
, NULL
);
3355 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
3357 rh
= json_variant_by_key(v
, "rootHash");
3359 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
3360 if (!json_variant_is_string(rh
))
3361 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'rootHash' field of signature JSON object is not a string.");
3363 r
= unhexmem(json_variant_string(rh
), &root_hash
, &root_hash_size
);
3365 return log_debug_errno(r
, "Failed to parse root hash field: %m");
3367 /* Check if specified root hash matches if it is specified */
3368 if (verity
->root_hash
&&
3369 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
3370 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
3372 a
= hexmem(root_hash
, root_hash_size
);
3373 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
3375 return log_debug_errno(r
, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
3378 sig
= json_variant_by_key(v
, "signature");
3380 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
3381 if (!json_variant_is_string(sig
))
3382 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'signature' field of signature JSON object is not a string.");
3384 r
= unbase64mem(json_variant_string(sig
), &root_hash_sig
, &root_hash_sig_size
);
3386 return log_debug_errno(r
, "Failed to parse signature field: %m");
3388 free_and_replace(verity
->root_hash
, root_hash
);
3389 verity
->root_hash_size
= root_hash_size
;
3391 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
3392 verity
->root_hash_sig_size
= root_hash_sig_size
;
3397 int dissected_image_acquire_metadata(DissectedImage
*m
, DissectImageFlags extra_flags
) {
3404 META_INITRD_RELEASE
,
3405 META_SYSEXT_RELEASE
,
3406 META_CONFEXT_RELEASE
,
3407 META_HAS_INIT_SYSTEM
,
3411 static const char *const paths
[_META_MAX
] = {
3412 [META_HOSTNAME
] = "/etc/hostname\0",
3413 [META_MACHINE_ID
] = "/etc/machine-id\0",
3414 [META_MACHINE_INFO
] = "/etc/machine-info\0",
3415 [META_OS_RELEASE
] = "/etc/os-release\0"
3416 "/usr/lib/os-release\0",
3417 [META_INITRD_RELEASE
] = "/etc/initrd-release\0"
3418 "/usr/lib/initrd-release\0",
3419 [META_SYSEXT_RELEASE
] = "sysext-release\0", /* String used only for logging. */
3420 [META_CONFEXT_RELEASE
] = "confext-release\0", /* ditto */
3421 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
3424 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **initrd_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
3425 _cleanup_free_
char *hostname
= NULL
, *t
= NULL
;
3426 _cleanup_close_pair_
int error_pipe
[2] = EBADF_PAIR
;
3427 _cleanup_(sigkill_waitp
) pid_t child
= 0;
3428 sd_id128_t machine_id
= SD_ID128_NULL
;
3429 unsigned n_meta_initialized
= 0;
3430 int fds
[2 * _META_MAX
], r
, v
;
3431 int has_init_system
= -1;
3434 BLOCK_SIGNALS(SIGCHLD
);
3438 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
3439 assert(paths
[n_meta_initialized
]);
3441 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
3447 r
= get_common_dissect_directory(&t
);
3451 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
3456 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
, &child
);
3460 /* Child in a new mount namespace */
3461 error_pipe
[0] = safe_close(error_pipe
[0]);
3463 r
= dissected_image_mount(
3466 /* uid_shift= */ UID_INVALID
,
3467 /* uid_range= */ UID_INVALID
,
3468 /* userns_fd= */ -EBADF
,
3470 DISSECT_IMAGE_READ_ONLY
|
3471 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
3472 DISSECT_IMAGE_USR_NO_ROOT
);
3474 log_debug_errno(r
, "Failed to mount dissected image: %m");
3478 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
3479 _cleanup_close_
int fd
= -ENOENT
;
3483 fds
[2*k
] = safe_close(fds
[2*k
]);
3487 case META_SYSEXT_RELEASE
:
3491 /* As per the os-release spec, if the image is an extension it will have a
3492 * file named after the image name in extension-release.d/ - we use the image
3493 * name and try to resolve it with the extension-release helpers, as
3494 * sometimes the image names are mangled on deployment and do not match
3495 * anymore. Unlike other paths this is not fixed, and the image name can be
3496 * mangled on deployment, so by calling into the helper we allow a fallback
3497 * that matches on the first extension-release file found in the directory,
3498 * if one named after the image cannot be found first. */
3499 r
= open_extension_release(
3503 /* relax_extension_release_check= */ false,
3504 /* ret_path= */ NULL
,
3510 case META_CONFEXT_RELEASE
:
3515 r
= open_extension_release(
3519 /* relax_extension_release_check= */ false,
3520 /* ret_path= */ NULL
,
3527 case META_HAS_INIT_SYSTEM
: {
3530 FOREACH_STRING(init
,
3531 "/usr/lib/systemd/systemd", /* systemd on /usr/ merged system */
3532 "/lib/systemd/systemd", /* systemd on /usr/ non-merged systems */
3533 "/sbin/init") { /* traditional path the Linux kernel invokes */
3535 r
= chase(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
3538 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
3545 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
));
3553 NULSTR_FOREACH(p
, paths
[k
]) {
3554 fd
= chase_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
3561 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
3565 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
3570 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
3573 _exit(EXIT_SUCCESS
);
3576 /* Let parent know the error */
3577 (void) write(error_pipe
[1], &r
, sizeof(r
));
3578 _exit(EXIT_FAILURE
);
3581 error_pipe
[1] = safe_close(error_pipe
[1]);
3583 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
3584 _cleanup_fclose_
FILE *f
= NULL
;
3588 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
3590 f
= take_fdopen(&fds
[2*k
], "r");
3599 r
= read_etc_hostname_stream(f
, &hostname
);
3601 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
3605 case META_MACHINE_ID
: {
3606 _cleanup_free_
char *line
= NULL
;
3608 r
= read_line(f
, LONG_LINE_MAX
, &line
);
3610 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
3612 r
= sd_id128_from_string(line
, &machine_id
);
3614 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
3616 log_debug("/etc/machine-id file of image is empty.");
3617 else if (streq(line
, "uninitialized"))
3618 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3620 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
3625 case META_MACHINE_INFO
:
3626 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
3628 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
3632 case META_OS_RELEASE
:
3633 r
= load_env_file_pairs(f
, "os-release", &os_release
);
3635 log_debug_errno(r
, "Failed to read OS release file of image: %m");
3639 case META_INITRD_RELEASE
:
3640 r
= load_env_file_pairs(f
, "initrd-release", &initrd_release
);
3642 log_debug_errno(r
, "Failed to read initrd release file of image: %m");
3646 case META_SYSEXT_RELEASE
:
3647 r
= load_env_file_pairs(f
, "sysext-release", &sysext_release
);
3649 log_debug_errno(r
, "Failed to read sysext release file of image: %m");
3653 case META_CONFEXT_RELEASE
:
3654 r
= load_env_file_pairs(f
, "confext-release", &confext_release
);
3656 log_debug_errno(r
, "Failed to read confext release file of image: %m");
3660 case META_HAS_INIT_SYSTEM
: {
3665 nr
= fread(&b
, 1, sizeof(b
), f
);
3666 if (nr
!= sizeof(b
))
3667 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
3669 has_init_system
= b
;
3675 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
3680 n
= read(error_pipe
[0], &v
, sizeof(v
));
3685 if (n
== sizeof(v
)) {
3686 r
= v
; /* propagate error sent to us from child */
3693 if (r
!= EXIT_SUCCESS
) {
3698 free_and_replace(m
->hostname
, hostname
);
3699 m
->machine_id
= machine_id
;
3700 strv_free_and_replace(m
->machine_info
, machine_info
);
3701 strv_free_and_replace(m
->os_release
, os_release
);
3702 strv_free_and_replace(m
->initrd_release
, initrd_release
);
3703 strv_free_and_replace(m
->sysext_release
, sysext_release
);
3704 strv_free_and_replace(m
->confext_release
, confext_release
);
3705 m
->has_init_system
= has_init_system
;
3708 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
3709 safe_close_pair(fds
+ 2*k
);
3714 Architecture
dissected_image_architecture(DissectedImage
*img
) {
3717 if (img
->partitions
[PARTITION_ROOT
].found
&&
3718 img
->partitions
[PARTITION_ROOT
].architecture
>= 0)
3719 return img
->partitions
[PARTITION_ROOT
].architecture
;
3721 if (img
->partitions
[PARTITION_USR
].found
&&
3722 img
->partitions
[PARTITION_USR
].architecture
>= 0)
3723 return img
->partitions
[PARTITION_USR
].architecture
;
3725 return _ARCHITECTURE_INVALID
;
3728 int dissect_loop_device(
3730 const VeritySettings
*verity
,
3731 const MountOptions
*mount_options
,
3732 const ImagePolicy
*image_policy
,
3733 DissectImageFlags flags
,
3734 DissectedImage
**ret
) {
3737 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
3742 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
3746 m
->loop
= loop_device_ref(loop
);
3747 m
->image_size
= m
->loop
->device_size
;
3748 m
->sector_size
= m
->loop
->sector_size
;
3750 r
= dissect_image(m
, loop
->fd
, loop
->node
, verity
, mount_options
, image_policy
, flags
);
3763 int dissect_loop_device_and_warn(
3765 const VeritySettings
*verity
,
3766 const MountOptions
*mount_options
,
3767 const ImagePolicy
*image_policy
,
3768 DissectImageFlags flags
,
3769 DissectedImage
**ret
) {
3773 return dissect_log_error(
3775 dissect_loop_device(loop
, verity
, mount_options
, image_policy
, flags
, ret
),
3776 loop
->backing_file
?: loop
->node
,
3781 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3784 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3785 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3786 * images we only check the partition type.
3788 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3791 if (image
->single_file_system
)
3792 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
3794 return partition_verity_of(partition_designator
) >= 0;
3797 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3798 PartitionDesignator k
;
3802 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3803 * works for the root partition, for others only if the associated verity partition was found. */
3805 if (!image
->verity_ready
)
3808 if (image
->single_file_system
)
3809 return partition_designator
== PARTITION_ROOT
;
3811 k
= partition_verity_of(partition_designator
);
3812 return k
>= 0 && image
->partitions
[k
].found
;
3815 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3816 PartitionDesignator k
;
3820 /* Checks if this partition has verity signature data available that we can use. */
3822 if (!image
->verity_sig_ready
)
3825 if (image
->single_file_system
)
3826 return partition_designator
== PARTITION_ROOT
;
3828 k
= partition_verity_sig_of(partition_designator
);
3829 return k
>= 0 && image
->partitions
[k
].found
;
3832 MountOptions
* mount_options_free_all(MountOptions
*options
) {
3835 while ((m
= LIST_POP(mount_options
, options
))) {
3843 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
3844 LIST_FOREACH(mount_options
, m
, options
)
3845 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
3851 int mount_image_privately_interactively(
3853 const ImagePolicy
*image_policy
,
3854 DissectImageFlags flags
,
3855 char **ret_directory
,
3857 LoopDevice
**ret_loop_device
) {
3859 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3860 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3861 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3862 _cleanup_free_
char *dir
= NULL
;
3865 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3866 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3870 assert(ret_loop_device
);
3872 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
3873 flags
|= DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
3874 DISSECT_IMAGE_PIN_PARTITION_DEVICES
;
3876 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
3878 return log_error_errno(r
, "Failed to load root hash data: %m");
3880 r
= loop_device_make_by_path(
3882 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
3883 /* sector_size= */ UINT32_MAX
,
3884 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
3888 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
3890 r
= dissect_loop_device_and_warn(
3893 /* mount_options= */ NULL
,
3900 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
3904 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
3908 r
= detach_mount_namespace();
3910 return log_error_errno(r
, "Failed to detach mount namespace: %m");
3912 r
= mkdir_p("/run/systemd/mount-rootfs", 0555);
3914 return log_error_errno(r
, "Failed to create mount point: %m");
3916 r
= dissected_image_mount_and_warn(
3918 "/run/systemd/mount-rootfs",
3919 /* uid_shift= */ UID_INVALID
,
3920 /* uid_range= */ UID_INVALID
,
3921 /* userns_fd= */ -EBADF
,
3926 r
= loop_device_flock(d
, LOCK_UN
);
3930 r
= dissected_image_relinquish(dissected_image
);
3932 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
3934 if (ret_directory
) {
3935 dir
= strdup("/run/systemd/mount-rootfs");
3941 _cleanup_close_
int dir_fd
= -EBADF
;
3943 dir_fd
= open("/run/systemd/mount-rootfs", O_CLOEXEC
|O_DIRECTORY
);
3945 return log_error_errno(errno
, "Failed to open mount point directory: %m");
3947 *ret_dir_fd
= TAKE_FD(dir_fd
);
3951 *ret_directory
= TAKE_PTR(dir
);
3953 *ret_loop_device
= TAKE_PTR(d
);
3957 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
3961 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
3962 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
3963 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
3966 int verity_dissect_and_mount(
3970 const MountOptions
*options
,
3971 const ImagePolicy
*image_policy
,
3972 const char *required_host_os_release_id
,
3973 const char *required_host_os_release_version_id
,
3974 const char *required_host_os_release_sysext_level
,
3975 const char *required_host_os_release_confext_level
,
3976 const char *required_sysext_scope
,
3977 DissectedImage
**ret_image
) {
3979 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
3980 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3981 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3982 DissectImageFlags dissect_image_flags
;
3983 bool relax_extension_release_check
;
3987 /* Verifying release metadata requires mounted image for now, so ensure the check is skipped when
3988 * opening an image without mounting it immediately (i.e.: 'dest' is NULL). */
3989 assert(!required_host_os_release_id
|| dest
);
3991 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
3993 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
3994 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
3996 return log_debug_errno(r
, "Failed to load root hash: %m");
3998 dissect_image_flags
=
3999 (verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
4000 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_EXTENSION_CHECK
: 0) |
4001 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
4002 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
4003 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
4005 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
4006 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4007 r
= loop_device_make_by_path(
4008 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
4009 /* open_flags= */ -1,
4010 /* sector_size= */ UINT32_MAX
,
4011 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
4015 return log_debug_errno(r
, "Failed to create loop device for image: %m");
4017 r
= dissect_loop_device(
4022 dissect_image_flags
,
4024 /* No partition table? Might be a single-filesystem image, try again */
4025 if (!verity
.data_path
&& r
== -ENOPKG
)
4026 r
= dissect_loop_device(
4031 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
4034 return log_debug_errno(r
, "Failed to dissect image: %m");
4036 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, &verity
);
4040 r
= dissected_image_decrypt(
4044 dissect_image_flags
);
4046 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
4049 r
= mkdir_p_label(dest
, 0755);
4051 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
4052 r
= umount_recursive(dest
, 0);
4054 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
4057 r
= dissected_image_mount(
4060 /* uid_shift= */ UID_INVALID
,
4061 /* uid_range= */ UID_INVALID
,
4062 /* userns_fd= */ -EBADF
,
4063 dissect_image_flags
);
4065 return log_debug_errno(r
, "Failed to mount image: %m");
4067 r
= loop_device_flock(loop_device
, LOCK_UN
);
4069 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
4071 /* If we got os-release values from the caller, then we need to match them with the image's
4072 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
4073 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
4074 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
4075 * then a simple match on the ID will be performed. */
4076 if (required_host_os_release_id
) {
4077 _cleanup_strv_free_
char **extension_release
= NULL
;
4078 ImageClass
class = IMAGE_SYSEXT
;
4080 assert(!isempty(required_host_os_release_id
));
4082 r
= load_extension_release_pairs(dest
, IMAGE_SYSEXT
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
4084 r
= load_extension_release_pairs(dest
, IMAGE_CONFEXT
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
4086 class = IMAGE_CONFEXT
;
4089 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
4091 r
= extension_release_validate(
4092 dissected_image
->image_name
,
4093 required_host_os_release_id
,
4094 required_host_os_release_version_id
,
4095 class == IMAGE_SYSEXT
? required_host_os_release_sysext_level
: required_host_os_release_confext_level
,
4096 required_sysext_scope
,
4100 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
4102 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
4105 r
= dissected_image_relinquish(dissected_image
);
4107 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
4110 *ret_image
= TAKE_PTR(dissected_image
);
4115 int get_common_dissect_directory(char **ret
) {
4116 _cleanup_free_
char *t
= NULL
;
4119 /* A common location we mount dissected images to. The assumption is that everyone who uses this
4120 * function runs in their own private mount namespace (with mount propagation off on /run/systemd/,
4121 * and thus can mount something here without affecting anyone else). */
4123 t
= strdup("/run/systemd/dissect-root");
4125 return log_oom_debug();
4127 r
= mkdir_parents(t
, 0755);
4129 return log_debug_errno(r
, "Failed to create parent dirs of mount point '%s': %m", t
);
4131 r
= RET_NERRNO(mkdir(t
, 0000)); /* It's supposed to be overmounted, hence let's make this inaccessible */
4132 if (r
< 0 && r
!= -EEXIST
)
4133 return log_debug_errno(r
, "Failed to create mount point '%s': %m", t
);