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-private.h"
36 #include "device-util.h"
37 #include "devnum-util.h"
38 #include "discover-image.h"
39 #include "dissect-image.h"
43 #include "extension-util.h"
47 #include "fsck-util.h"
49 #include "hexdecoct.h"
50 #include "hostname-setup.h"
51 #include "id128-util.h"
52 #include "import-util.h"
54 #include "missing_mount.h"
55 #include "missing_syscall.h"
56 #include "mkdir-label.h"
57 #include "mount-util.h"
58 #include "mountpoint-util.h"
59 #include "namespace-util.h"
60 #include "nulstr-util.h"
61 #include "openssl-util.h"
63 #include "path-util.h"
64 #include "proc-cmdline.h"
65 #include "process-util.h"
66 #include "raw-clone.h"
67 #include "resize-fs.h"
68 #include "signal-util.h"
69 #include "sparse-endian.h"
70 #include "stat-util.h"
71 #include "stdio-util.h"
72 #include "string-table.h"
73 #include "string-util.h"
75 #include "tmpfile-util.h"
76 #include "udev-util.h"
77 #include "user-util.h"
79 #include "xattr-util.h"
81 /* how many times to wait for the device nodes to appear */
82 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
84 int dissect_fstype_ok(const char *fstype
) {
88 /* When we automatically mount file systems, be a bit conservative by default what we are willing to
89 * mount, just as an extra safety net to not mount with badly maintained legacy file system
92 e
= secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
94 _cleanup_strv_free_
char **l
= NULL
;
96 l
= strv_split(e
, ":");
100 b
= strv_contains(l
, fstype
);
102 b
= STR_IN_SET(fstype
,
113 log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype
);
117 int probe_sector_size(int fd
, uint32_t *ret
) {
119 /* Disk images might be for 512B or for 4096 sector sizes, let's try to auto-detect that by searching
120 * for the GPT headers at the relevant byte offsets */
122 assert_cc(sizeof(GptHeader
) == 92);
124 /* We expect a sector size in the range 512…4096. The GPT header is located in the second
125 * sector. Hence it could be at byte 512 at the earliest, and at byte 4096 at the latest. And we must
126 * read with granularity of the largest sector size we care about. Which means 8K. */
127 uint8_t sectors
[2 * 4096];
134 n
= pread(fd
, sectors
, sizeof(sectors
), 0);
137 if (n
!= sizeof(sectors
)) /* too short? */
140 /* Let's see if we find the GPT partition header with various expected sector sizes */
141 for (uint32_t sz
= 512; sz
<= 4096; sz
<<= 1) {
144 assert(sizeof(sectors
) >= sz
* 2);
145 p
= (const GptHeader
*) (sectors
+ sz
);
147 if (!gpt_header_has_signature(p
))
151 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
152 "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
158 log_debug("Determined sector size %" PRIu32
" based on discovered partition table.", found
);
160 return 1; /* indicate we *did* find it */
164 log_debug("Couldn't find any partition table to derive sector size of.");
165 *ret
= 512; /* pick the traditional default */
166 return 0; /* indicate we didn't find it */
169 int probe_sector_size_prefer_ioctl(int fd
, uint32_t *ret
) {
175 /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
176 * configured sector size rather than probing by contents */
178 if (fstat(fd
, &st
) < 0)
181 if (S_ISBLK(st
.st_mode
))
182 return blockdev_get_sector_size(fd
, ret
);
184 return probe_sector_size(fd
, ret
);
187 int probe_filesystem_full(
194 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
195 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
196 * different error otherwise. */
199 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
200 _cleanup_free_
char *path_by_fd
= NULL
;
201 _cleanup_close_
int fd_close
= -EBADF
;
205 assert(fd
>= 0 || path
);
209 fd_close
= open(path
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
217 r
= fd_get_path(fd
, &path_by_fd
);
224 if (size
== 0) /* empty size? nothing found! */
227 b
= blkid_new_probe();
231 /* The Linux kernel maintains separate block device caches for main ("whole") and partition block
232 * devices, which means making a change to one might not be reflected immediately when reading via
233 * the other. That's massively confusing when mixing accesses to such devices. Let's address this in
234 * a limited way: when probing a file system that is not at the beginning of the block device we
235 * apparently probe a partition via the main block device, and in that case let's first flush the
236 * main block device cache, so that we get the data that the per-partition block device last
239 * This only works under the assumption that any tools that write to the partition block devices
240 * issue an syncfs()/fsync() on the device after making changes. Typically file system formatting
241 * tools that write a superblock onto a partition block device do that, however. */
243 if (ioctl(fd
, BLKFLSBUF
, 0) < 0)
244 log_debug_errno(errno
, "Failed to flush block device cache, ignoring: %m");
247 r
= blkid_probe_set_device(
251 size
== UINT64_MAX
? 0 : size
); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
253 return errno_or_else(ENOMEM
);
255 blkid_probe_enable_superblocks(b
, 1);
256 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
259 r
= blkid_do_safeprobe(b
);
260 if (r
== _BLKID_SAFEPROBE_NOT_FOUND
)
262 if (r
== _BLKID_SAFEPROBE_AMBIGUOUS
)
263 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
264 "Results ambiguous for partition %s", path
);
265 if (r
== _BLKID_SAFEPROBE_ERROR
)
266 return log_debug_errno(errno_or_else(EIO
), "Failed to probe partition %s: %m", path
);
268 assert(r
== _BLKID_SAFEPROBE_FOUND
);
270 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
273 log_debug("Probed fstype '%s' on partition %s.", fstype
, path
);
274 return strdup_to_full(ret_fstype
, fstype
);
278 log_debug("No type detected on partition %s", path
);
287 static int image_policy_may_use(
288 const ImagePolicy
*policy
,
289 PartitionDesignator designator
) {
291 PartitionPolicyFlags f
;
293 /* For each partition we find in the partition table do a first check if it may exist at all given
294 * the policy, or if it shall be ignored. */
296 f
= image_policy_get_exhaustively(policy
, designator
);
300 if ((f
& _PARTITION_POLICY_USE_MASK
) == PARTITION_POLICY_ABSENT
)
301 /* only flag set in policy is "absent"? then this partition may not exist at all */
302 return log_debug_errno(
303 SYNTHETIC_ERRNO(ERFKILL
),
304 "Partition of designator '%s' exists, but not allowed by policy, refusing.",
305 partition_designator_to_string(designator
));
306 if ((f
& _PARTITION_POLICY_USE_MASK
& ~PARTITION_POLICY_ABSENT
) == PARTITION_POLICY_UNUSED
) {
307 /* only "unused" or "unused" + "absent" are set? then don't use it */
308 log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
309 partition_designator_to_string(designator
));
310 return false; /* ignore! */
313 return true; /* use! */
316 static int image_policy_check_protection(
317 const ImagePolicy
*policy
,
318 PartitionDesignator designator
,
319 PartitionPolicyFlags found_flags
) {
321 PartitionPolicyFlags policy_flags
;
323 /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
328 policy_flags
= image_policy_get_exhaustively(policy
, designator
);
329 if (policy_flags
< 0)
332 if ((found_flags
& policy_flags
) == 0) {
333 _cleanup_free_
char *found_flags_string
= NULL
, *policy_flags_string
= NULL
;
335 (void) partition_policy_flags_to_string(found_flags
, /* simplify= */ true, &found_flags_string
);
336 (void) partition_policy_flags_to_string(policy_flags
, /* simplify= */ true, &policy_flags_string
);
338 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
339 partition_designator_to_string(designator
),
340 strnull(found_flags_string
), strnull(policy_flags_string
));
346 static int image_policy_check_partition_flags(
347 const ImagePolicy
*policy
,
348 PartitionDesignator designator
,
349 uint64_t gpt_flags
) {
351 PartitionPolicyFlags policy_flags
;
354 /* Checks if the partition flags in the policy match reality */
356 policy_flags
= image_policy_get_exhaustively(policy
, designator
);
357 if (policy_flags
< 0)
360 b
= FLAGS_SET(gpt_flags
, SD_GPT_FLAG_READ_ONLY
);
361 if ((policy_flags
& _PARTITION_POLICY_READ_ONLY_MASK
) == (b
? PARTITION_POLICY_READ_ONLY_OFF
: PARTITION_POLICY_READ_ONLY_ON
))
362 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
363 partition_designator_to_string(designator
),
364 one_zero(!b
), one_zero(b
));
366 b
= FLAGS_SET(gpt_flags
, SD_GPT_FLAG_GROWFS
);
367 if ((policy_flags
& _PARTITION_POLICY_GROWFS_MASK
) == (b
? PARTITION_POLICY_GROWFS_OFF
: PARTITION_POLICY_GROWFS_ON
))
368 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
369 partition_designator_to_string(designator
),
370 one_zero(!b
), one_zero(b
));
375 static int dissected_image_probe_filesystems(
378 const ImagePolicy
*policy
) {
384 /* Fill in file system types if we don't know them yet. */
386 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
387 DissectedPartition
*p
= m
->partitions
+ i
;
388 PartitionPolicyFlags found_flags
;
394 /* If we have an fd referring to the partition block device, use that. Otherwise go
395 * via the whole block device or backing regular file, and read via offset. */
396 if (p
->mount_node_fd
>= 0)
397 r
= probe_filesystem_full(p
->mount_node_fd
, p
->node
, 0, UINT64_MAX
, &p
->fstype
);
399 r
= probe_filesystem_full(fd
, p
->node
, p
->offset
, p
->size
, &p
->fstype
);
404 if (streq_ptr(p
->fstype
, "crypto_LUKS")) {
406 found_flags
= PARTITION_POLICY_ENCRYPTED
; /* found this one, and its definitely encrypted */
408 /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
409 * set all other ways that indicate "present". */
410 found_flags
= PARTITION_POLICY_UNPROTECTED
|PARTITION_POLICY_VERITY
|PARTITION_POLICY_SIGNED
;
412 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
418 /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
419 * hence we need to validate this against policy again, to see if the policy still matches
420 * with this new information. Note that image_policy_check_protection() will check for
421 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
422 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
423 * OR verity OR signed), but that's fine since the earlier policy check already checked more
424 * specific which of those three cases where OK. Keep in mind that this function here only
425 * looks at specific partitions (and thus can only deduce encryption or not) but not the
426 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
427 * checks already did the relevant checks that look at the whole partition table, and
428 * enforced policy there as needed. */
429 r
= image_policy_check_protection(policy
, i
, found_flags
);
437 static void check_partition_flags(
439 unsigned long long pflags
,
440 unsigned long long supported
) {
444 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
445 pflags
&= ~(supported
|
446 SD_GPT_FLAG_REQUIRED_PARTITION
|
447 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
|
448 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
453 /* If there are other bits set, then log about it, to make things discoverable */
454 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
455 unsigned long long bit
= 1ULL << i
;
456 if (!FLAGS_SET(pflags
, bit
))
459 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
463 static int dissected_image_new(const char *path
, DissectedImage
**ret
) {
464 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
465 _cleanup_free_
char *name
= NULL
;
471 _cleanup_free_
char *filename
= NULL
;
473 r
= path_extract_filename(path
, &filename
);
477 r
= raw_strip_suffixes(filename
, &name
);
481 if (!image_name_is_valid(name
)) {
482 log_debug("Image name %s is not valid, ignoring.", strna(name
));
487 m
= new(DissectedImage
, 1);
491 *m
= (DissectedImage
) {
492 .has_init_system
= -1,
493 .image_name
= TAKE_PTR(name
),
496 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
497 m
->partitions
[i
] = DISSECTED_PARTITION_NULL
;
504 static void dissected_partition_done(DissectedPartition
*p
) {
510 free(p
->decrypted_fstype
);
511 free(p
->decrypted_node
);
512 free(p
->mount_options
);
513 safe_close(p
->mount_node_fd
);
514 safe_close(p
->fsmount_fd
);
516 *p
= DISSECTED_PARTITION_NULL
;
520 static int diskseq_should_be_used(
521 const char *whole_devname
,
523 DissectImageFlags flags
) {
527 assert(whole_devname
);
529 /* No diskseq. We cannot use by-diskseq symlink. */
533 /* Do not use by-diskseq link unless DISSECT_IMAGE_DISKSEQ_DEVNODE flag is explicitly set. */
534 if (!FLAGS_SET(flags
, DISSECT_IMAGE_DISKSEQ_DEVNODE
))
537 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
538 r
= sd_device_new_from_devname(&dev
, whole_devname
);
542 /* When ID_IGNORE_DISKSEQ udev property is set, the by-diskseq symlink will not be created. */
543 r
= device_get_property_bool(dev
, "ID_IGNORE_DISKSEQ");
545 return !r
; /* If explicitly specified, use it. */
552 static int make_partition_devname(
553 const char *whole_devname
,
556 DissectImageFlags flags
,
559 _cleanup_free_
char *s
= NULL
;
562 assert(whole_devname
);
563 assert(nr
!= 0); /* zero is not a valid partition nr */
566 r
= diskseq_should_be_used(whole_devname
, diskseq
, flags
);
568 log_debug_errno(r
, "Failed to determine if diskseq should be used for %s, assuming no, ignoring: %m", whole_devname
);
570 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
571 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
572 * block device node name ends in a digit, then suffix a 'p', followed by the partition
573 * number. Otherwise, just suffix the partition number without any 'p'. */
575 if (nr
< 0) { /* whole disk? */
576 s
= strdup(whole_devname
);
580 size_t l
= strlen(whole_devname
);
581 if (l
< 1) /* underflow check for the subtraction below */
584 bool need_p
= ascii_isdigit(whole_devname
[l
-1]); /* Last char a digit? */
586 if (asprintf(&s
, "%s%s%i", whole_devname
, need_p
? "p" : "", nr
) < 0)
590 if (nr
< 0) /* whole disk? */
591 r
= asprintf(&s
, "/dev/disk/by-diskseq/%" PRIu64
, diskseq
);
593 r
= asprintf(&s
, "/dev/disk/by-diskseq/%" PRIu64
"-part%i", diskseq
, nr
);
602 static int open_partition(
605 const LoopDevice
*loop
) {
607 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
608 _cleanup_close_
int fd
= -EBADF
;
615 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
619 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
620 r
= block_device_new_from_fd(fd
, is_partition
? BLOCK_DEVICE_LOOKUP_WHOLE_DISK
: 0, &dev
);
624 r
= sd_device_get_devnum(dev
, &devnum
);
628 if (loop
->devno
!= devnum
)
631 /* Also check diskseq. */
632 if (loop
->diskseq
!= 0) {
635 r
= fd_get_diskseq(fd
, &diskseq
);
639 if (loop
->diskseq
!= diskseq
)
643 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR
", diskseq=%" PRIu64
").",
644 node
, fd
, DEVNUM_FORMAT_VAL(loop
->devno
), loop
->diskseq
);
648 static int compare_arch(Architecture a
, Architecture b
) {
652 if (a
== native_architecture())
655 if (b
== native_architecture())
658 #ifdef ARCHITECTURE_SECONDARY
659 if (a
== ARCHITECTURE_SECONDARY
)
662 if (b
== ARCHITECTURE_SECONDARY
)
669 static int dissect_image(
673 const VeritySettings
*verity
,
674 const MountOptions
*mount_options
,
675 const ImagePolicy
*policy
,
676 DissectImageFlags flags
) {
678 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
679 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
680 bool is_gpt
, is_mbr
, multiple_generic
= false,
681 generic_rw
= false, /* initialize to appease gcc */
682 generic_growfs
= false;
683 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
684 _cleanup_free_
char *generic_node
= NULL
;
685 sd_id128_t generic_uuid
= SD_ID128_NULL
;
686 const char *pttype
= NULL
, *sptuuid
= NULL
;
688 int r
, generic_nr
= -1, n_partitions
;
693 assert(!verity
|| verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
694 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
695 assert(!verity
|| verity
->root_hash_sig
|| verity
->root_hash_sig_size
== 0);
696 assert(!verity
|| (verity
->root_hash
|| !verity
->root_hash_sig
));
697 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
698 assert(m
->sector_size
> 0);
700 /* Probes a disk image, and returns information about what it found in *ret.
702 * Returns -ENOPKG if no suitable partition table or file system could be found.
703 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
704 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
705 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that
706 * Returns -ERFKILL if image doesn't match image policy
707 * 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)
708 * Returns -EPROTONOSUPPORT if DISSECT_IMAGE_ADD_PARTITION_DEVICES is set but the block device does not have partition logic enabled
709 * Returns -ENOMSG if we didn't find a single usable partition (and DISSECT_IMAGE_REFUSE_EMPTY is set) */
711 uint64_t diskseq
= m
->loop
? m
->loop
->diskseq
: 0;
713 if (verity
&& verity
->root_hash
) {
714 sd_id128_t fsuuid
, vuuid
;
716 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
717 * first 128-bit of the root hash. And we use the verity partition that has a UUID that match
718 * the final 128-bit. */
720 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
723 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
724 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
726 if (sd_id128_is_null(fsuuid
))
728 if (sd_id128_is_null(vuuid
))
731 /* If the verity data declares it's for the /usr partition, then search for that, in all
732 * other cases assume it's for the root partition. */
733 if (verity
->designator
== PARTITION_USR
) {
735 usr_verity_uuid
= vuuid
;
738 root_verity_uuid
= vuuid
;
742 b
= blkid_new_probe();
747 r
= blkid_probe_set_device(b
, fd
, 0, 0);
749 return errno_or_else(ENOMEM
);
752 r
= blkid_probe_set_sectorsize(b
, m
->sector_size
);
754 return errno_or_else(EIO
);
756 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
757 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
758 blkid_probe_enable_superblocks(b
, 1);
759 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
|BLKID_SUBLKS_UUID
);
762 blkid_probe_enable_partitions(b
, 1);
763 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
766 r
= blkid_do_safeprobe(b
);
767 if (r
== _BLKID_SAFEPROBE_ERROR
)
768 return errno_or_else(EIO
);
769 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
))
770 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
772 assert(r
== _BLKID_SAFEPROBE_FOUND
);
774 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
775 (flags
& DISSECT_IMAGE_GENERIC_ROOT
)) ||
776 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
777 const char *usage
= NULL
;
779 /* If flags permit this, also allow using non-partitioned single-filesystem images */
781 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
782 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
783 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
784 const char *fstype
= NULL
, *options
= NULL
, *suuid
= NULL
;
785 _cleanup_close_
int mount_node_fd
= -EBADF
;
786 sd_id128_t uuid
= SD_ID128_NULL
;
787 PartitionPolicyFlags found_flags
;
790 /* OK, we have found a file system, that's our root partition then. */
792 r
= image_policy_may_use(policy
, PARTITION_ROOT
);
795 if (r
== 0) /* policy says ignore this, so we ignore it */
798 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
799 (void) blkid_probe_lookup_value(b
, "UUID", &suuid
, NULL
);
801 encrypted
= streq_ptr(fstype
, "crypto_LUKS");
803 if (verity_settings_data_covers(verity
, PARTITION_ROOT
))
804 found_flags
= verity
->root_hash_sig
? PARTITION_POLICY_SIGNED
: PARTITION_POLICY_VERITY
;
806 found_flags
= encrypted
? PARTITION_POLICY_ENCRYPTED
: PARTITION_POLICY_UNPROTECTED
;
808 r
= image_policy_check_protection(policy
, PARTITION_ROOT
, found_flags
);
812 r
= image_policy_check_partition_flags(policy
, PARTITION_ROOT
, 0); /* we have no gpt partition flags, hence check against all bits off */
816 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
817 mount_node_fd
= open_partition(devname
, /* is_partition = */ false, m
->loop
);
818 if (mount_node_fd
< 0)
819 return mount_node_fd
;
829 /* blkid will return FAT's serial number as UUID, hence it is quite possible
830 * that parsing this will fail. We'll ignore the ID, since it's just too
831 * short to be useful as true identifier. */
832 r
= sd_id128_from_string(suuid
, &uuid
);
834 log_debug_errno(r
, "Failed to parse file system UUID '%s', ignoring: %m", suuid
);
837 r
= make_partition_devname(devname
, diskseq
, -1, flags
, &n
);
841 m
->single_file_system
= true;
842 m
->encrypted
= encrypted
;
844 m
->has_verity
= verity
&& verity
->data_path
;
845 m
->verity_ready
= verity_settings_data_covers(verity
, PARTITION_ROOT
);
847 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
848 m
->verity_sig_ready
= m
->verity_ready
&& verity
->root_hash_sig
;
850 m
->image_uuid
= uuid
;
852 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
859 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
861 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
863 .architecture
= _ARCHITECTURE_INVALID
,
864 .fstype
= TAKE_PTR(t
),
866 .mount_options
= TAKE_PTR(o
),
867 .mount_node_fd
= TAKE_FD(mount_node_fd
),
870 .fsmount_fd
= -EBADF
,
877 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
881 is_gpt
= streq_ptr(pttype
, "gpt");
882 is_mbr
= streq_ptr(pttype
, "dos");
884 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
887 /* We support external verity data partitions only if the image has no partition table */
888 if (verity
&& verity
->data_path
)
891 if (FLAGS_SET(flags
, DISSECT_IMAGE_ADD_PARTITION_DEVICES
)) {
892 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
893 * do partition scanning. */
894 r
= blockdev_partscan_enabled(fd
);
898 return -EPROTONOSUPPORT
;
901 (void) blkid_probe_lookup_value(b
, "PTUUID", &sptuuid
, NULL
);
903 r
= sd_id128_from_string(sptuuid
, &m
->image_uuid
);
905 log_debug_errno(r
, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid
);
909 pl
= blkid_probe_get_partitions(b
);
911 return errno_or_else(ENOMEM
);
914 n_partitions
= blkid_partlist_numof_partitions(pl
);
915 if (n_partitions
< 0)
916 return errno_or_else(EIO
);
918 for (int i
= 0; i
< n_partitions
; i
++) {
919 _cleanup_free_
char *node
= NULL
;
920 unsigned long long pflags
;
921 blkid_loff_t start
, size
;
926 pp
= blkid_partlist_get_partition(pl
, i
);
928 return errno_or_else(EIO
);
930 pflags
= blkid_partition_get_flags(pp
);
933 nr
= blkid_partition_get_partno(pp
);
935 return errno_or_else(EIO
);
938 start
= blkid_partition_get_start(pp
);
940 return errno_or_else(EIO
);
942 assert((uint64_t) start
< UINT64_MAX
/512);
945 size
= blkid_partition_get_size(pp
);
947 return errno_or_else(EIO
);
949 assert((uint64_t) size
< UINT64_MAX
/512);
951 /* While probing we need the non-diskseq device node name to access the thing, hence mask off
952 * DISSECT_IMAGE_DISKSEQ_DEVNODE. */
953 r
= make_partition_devname(devname
, diskseq
, nr
, flags
& ~DISSECT_IMAGE_DISKSEQ_DEVNODE
, &node
);
957 /* So here's the thing: after the main ("whole") block device popped up it might take a while
958 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
959 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
960 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
961 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
962 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
963 * also good as the outcome is the same: the partition block device exists, and we can use
966 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
967 * partition already existent. */
969 if (FLAGS_SET(flags
, DISSECT_IMAGE_ADD_PARTITION_DEVICES
)) {
970 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
973 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
975 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
977 log_debug("We were quicker than kernel in adding partition %i.", nr
);
981 const char *fstype
= NULL
, *label
;
982 sd_id128_t type_id
, id
;
983 GptPartitionType type
;
984 bool rw
= true, growfs
= false;
986 r
= blkid_partition_get_uuid_id128(pp
, &id
);
988 log_debug_errno(r
, "Failed to read partition UUID, ignoring: %m");
992 r
= blkid_partition_get_type_id128(pp
, &type_id
);
994 log_debug_errno(r
, "Failed to read partition type UUID, ignoring: %m");
998 type
= gpt_partition_type_from_uuid(type_id
);
1000 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
1002 if (IN_SET(type
.designator
,
1008 check_partition_flags(node
, pflags
,
1009 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1011 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1014 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1015 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1017 } else if (type
.designator
== PARTITION_ESP
) {
1019 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
1020 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
1021 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
1024 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
1029 } else if (type
.designator
== PARTITION_ROOT
) {
1031 check_partition_flags(node
, pflags
,
1032 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1034 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1037 /* If a root ID is specified, ignore everything but the root id */
1038 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
1041 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1042 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1044 } else if (type
.designator
== PARTITION_ROOT_VERITY
) {
1046 check_partition_flags(node
, pflags
,
1047 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1049 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1052 m
->has_verity
= true;
1054 /* If no verity configuration is specified, then don't do verity */
1057 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
1060 /* If root hash is specified, then ignore everything but the root id */
1061 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
1064 fstype
= "DM_verity_hash";
1067 } else if (type
.designator
== PARTITION_ROOT_VERITY_SIG
) {
1069 check_partition_flags(node
, pflags
,
1070 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1072 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1075 m
->has_verity_sig
= true;
1079 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
1082 fstype
= "verity_hash_signature";
1085 } else if (type
.designator
== PARTITION_USR
) {
1087 check_partition_flags(node
, pflags
,
1088 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1090 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1093 /* If a usr ID is specified, ignore everything but the usr id */
1094 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
1097 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1098 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1100 } else if (type
.designator
== PARTITION_USR_VERITY
) {
1102 check_partition_flags(node
, pflags
,
1103 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1105 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1108 m
->has_verity
= true;
1112 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
1115 /* If usr hash is specified, then ignore everything but the usr id */
1116 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
1119 fstype
= "DM_verity_hash";
1122 } else if (type
.designator
== PARTITION_USR_VERITY_SIG
) {
1124 check_partition_flags(node
, pflags
,
1125 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1127 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1130 m
->has_verity_sig
= true;
1134 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
1137 fstype
= "verity_hash_signature";
1140 } else if (type
.designator
== PARTITION_SWAP
) {
1142 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
1144 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1147 /* Note: we don't set fstype = "swap" here, because we still need to probe if
1148 * it might be encrypted (i.e. fstype "crypt_LUKS") or unencrypted
1149 * (i.e. fstype "swap"), and the only way to figure that out is via fstype
1152 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
1153 } else if (sd_id128_equal(type
.uuid
, SD_GPT_LINUX_GENERIC
)) {
1155 check_partition_flags(node
, pflags
,
1156 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1158 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1162 multiple_generic
= true;
1165 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1166 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1168 generic_node
= TAKE_PTR(node
);
1171 } else if (type
.designator
== PARTITION_VAR
) {
1173 check_partition_flags(node
, pflags
,
1174 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1176 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1179 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
1180 sd_id128_t var_uuid
;
1182 /* For /var we insist that the uuid of the partition matches the
1183 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1184 * ID. Why? Unlike the other partitions /var is inherently
1185 * installation specific, hence we need to be careful not to mount it
1186 * in the wrong installation. By hashing the partition UUID from
1187 * /etc/machine-id we can securely bind the partition to the
1190 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
1194 if (!sd_id128_equal(var_uuid
, id
)) {
1195 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
1196 "(found: " SD_ID128_UUID_FORMAT_STR
", expected: " SD_ID128_UUID_FORMAT_STR
"), ignoring.",
1197 SD_ID128_FORMAT_VAL(id
), SD_ID128_FORMAT_VAL(var_uuid
));
1202 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1203 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1206 if (type
.designator
!= _PARTITION_DESIGNATOR_INVALID
) {
1207 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
, *n
= NULL
;
1208 _cleanup_close_
int mount_node_fd
= -EBADF
;
1209 const char *options
= NULL
;
1211 r
= image_policy_may_use(policy
, type
.designator
);
1215 /* Policy says: ignore; Remember this fact, so that we later can distinguish between "found but ignored" and "not found at all" */
1217 if (!m
->partitions
[type
.designator
].found
)
1218 m
->partitions
[type
.designator
].ignored
= true;
1223 if (m
->partitions
[type
.designator
].found
) {
1226 /* For most partition types the first one we see wins. Except for the
1227 * rootfs and /usr, where we do a version compare of the label, and
1228 * let the newest version win. This permits a simple A/B versioning
1229 * scheme in OS images. */
1231 c
= compare_arch(type
.arch
, m
->partitions
[type
.designator
].architecture
);
1232 if (c
< 0) /* the arch we already found is better than the one we found now */
1234 if (c
== 0 && /* same arch? then go by version in label */
1235 (!partition_designator_is_versioned(type
.designator
) ||
1236 strverscmp_improved(label
, m
->partitions
[type
.designator
].label
) <= 0))
1239 dissected_partition_done(m
->partitions
+ type
.designator
);
1242 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
) &&
1243 type
.designator
!= PARTITION_SWAP
) {
1244 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
1245 if (mount_node_fd
< 0)
1246 return mount_node_fd
;
1249 r
= make_partition_devname(devname
, diskseq
, nr
, flags
, &n
);
1265 options
= mount_options_from_designator(mount_options
, type
.designator
);
1267 o
= strdup(options
);
1272 m
->partitions
[type
.designator
] = (DissectedPartition
) {
1277 .architecture
= type
.arch
,
1278 .node
= TAKE_PTR(n
),
1279 .fstype
= TAKE_PTR(t
),
1280 .label
= TAKE_PTR(l
),
1282 .mount_options
= TAKE_PTR(o
),
1283 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1284 .offset
= (uint64_t) start
* 512,
1285 .size
= (uint64_t) size
* 512,
1286 .gpt_flags
= pflags
,
1287 .fsmount_fd
= -EBADF
,
1291 } else if (is_mbr
) {
1293 switch (blkid_partition_get_type(pp
)) {
1295 case 0x83: /* Linux partition */
1297 if (pflags
!= 0x80) /* Bootable flag */
1301 multiple_generic
= true;
1305 generic_growfs
= false;
1306 generic_node
= TAKE_PTR(node
);
1311 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1312 _cleanup_close_
int mount_node_fd
= -EBADF
;
1313 _cleanup_free_
char *o
= NULL
, *n
= NULL
;
1314 sd_id128_t id
= SD_ID128_NULL
;
1315 const char *options
= NULL
;
1317 r
= image_policy_may_use(policy
, PARTITION_XBOOTLDR
);
1320 if (r
== 0) { /* policy says: ignore */
1321 if (!m
->partitions
[PARTITION_XBOOTLDR
].found
)
1322 m
->partitions
[PARTITION_XBOOTLDR
].ignored
= true;
1327 /* First one wins */
1328 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
1331 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
1332 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
1333 if (mount_node_fd
< 0)
1334 return mount_node_fd
;
1337 (void) blkid_partition_get_uuid_id128(pp
, &id
);
1339 r
= make_partition_devname(devname
, diskseq
, nr
, flags
, &n
);
1343 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
1345 o
= strdup(options
);
1350 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
1355 .architecture
= _ARCHITECTURE_INVALID
,
1356 .node
= TAKE_PTR(n
),
1358 .mount_options
= TAKE_PTR(o
),
1359 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1360 .offset
= (uint64_t) start
* 512,
1361 .size
= (uint64_t) size
* 512,
1362 .fsmount_fd
= -EBADF
,
1370 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1371 (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
1372 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
))
1373 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
1375 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1376 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
1377 return -EADDRNOTAVAIL
;
1379 if (!m
->partitions
[PARTITION_USR
].found
&&
1380 (m
->partitions
[PARTITION_USR_VERITY
].found
||
1381 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
))
1382 return -EADDRNOTAVAIL
; /* as above */
1385 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1386 return -EADDRNOTAVAIL
;
1388 /* If root and /usr are combined then insist that the architecture matches */
1389 if (m
->partitions
[PARTITION_ROOT
].found
&&
1390 m
->partitions
[PARTITION_USR
].found
&&
1391 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1392 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1393 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1394 return -EADDRNOTAVAIL
;
1396 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1397 !m
->partitions
[PARTITION_USR
].found
&&
1398 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1399 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1401 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1402 * that. If the root hash was set however, then we won't fall back to a generic node, because
1403 * the root hash decides. */
1405 /* If we didn't find a properly marked root partition, but we did find a single suitable
1406 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1407 if (multiple_generic
)
1410 /* If we didn't find a generic node, then we can't fix this up either */
1412 r
= image_policy_may_use(policy
, PARTITION_ROOT
);
1416 /* Policy says: ignore; remember that we did */
1417 m
->partitions
[PARTITION_ROOT
].ignored
= true;
1419 _cleanup_close_
int mount_node_fd
= -EBADF
;
1420 _cleanup_free_
char *o
= NULL
, *n
= NULL
;
1421 const char *options
;
1423 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
1424 mount_node_fd
= open_partition(generic_node
, /* is_partition = */ true, m
->loop
);
1425 if (mount_node_fd
< 0)
1426 return mount_node_fd
;
1429 r
= make_partition_devname(devname
, diskseq
, generic_nr
, flags
, &n
);
1433 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1435 o
= strdup(options
);
1440 assert(generic_nr
>= 0);
1441 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1444 .growfs
= generic_growfs
,
1445 .partno
= generic_nr
,
1446 .architecture
= _ARCHITECTURE_INVALID
,
1447 .node
= TAKE_PTR(n
),
1448 .uuid
= generic_uuid
,
1449 .mount_options
= TAKE_PTR(o
),
1450 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1451 .offset
= UINT64_MAX
,
1453 .fsmount_fd
= -EBADF
,
1459 /* 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 */
1460 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1461 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1464 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1465 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1466 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1469 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1470 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1471 if (m
->partitions
[PARTITION_USR
].found
)
1472 return -EADDRNOTAVAIL
;
1476 /* If a verity designator is specified, then insist that the matching partition exists */
1477 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1478 return -EADDRNOTAVAIL
;
1480 bool have_verity_sig_partition
;
1481 if (verity
->designator
>= 0)
1482 have_verity_sig_partition
= m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR_VERITY_SIG
: PARTITION_ROOT_VERITY_SIG
].found
;
1484 have_verity_sig_partition
= m
->partitions
[PARTITION_USR_VERITY_SIG
].found
|| m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
;
1486 if (verity
->root_hash
) {
1487 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1488 * Verity, set things up for it */
1490 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1491 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1492 return -EADDRNOTAVAIL
;
1494 /* If we found a verity setup, then the root partition is necessarily read-only. */
1495 m
->partitions
[PARTITION_ROOT
].rw
= false;
1496 m
->verity_ready
= true;
1499 assert(verity
->designator
== PARTITION_USR
);
1501 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1502 return -EADDRNOTAVAIL
;
1504 m
->partitions
[PARTITION_USR
].rw
= false;
1505 m
->verity_ready
= true;
1508 if (m
->verity_ready
)
1509 m
->verity_sig_ready
= verity
->root_hash_sig
|| have_verity_sig_partition
;
1511 } else if (have_verity_sig_partition
) {
1513 /* If we found an embedded signature partition, we are ready, too. */
1515 m
->verity_ready
= m
->verity_sig_ready
= true;
1516 if (verity
->designator
>= 0)
1517 m
->partitions
[verity
->designator
== PARTITION_USR
? PARTITION_USR
: PARTITION_ROOT
].rw
= false;
1518 else if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
)
1519 m
->partitions
[PARTITION_USR
].rw
= false;
1520 else if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
)
1521 m
->partitions
[PARTITION_ROOT
].rw
= false;
1527 /* After we discovered all partitions let's see if the verity requirements match the policy. (Note:
1528 * we don't check encryption requirements here, because we haven't probed the file system yet, hence
1529 * don't know if this is encrypted or not) */
1530 for (PartitionDesignator di
= 0; di
< _PARTITION_DESIGNATOR_MAX
; di
++) {
1531 PartitionDesignator vi
, si
;
1532 PartitionPolicyFlags found_flags
;
1534 any
= any
|| m
->partitions
[di
].found
;
1536 vi
= partition_verity_of(di
);
1537 si
= partition_verity_sig_of(di
);
1539 /* Determine the verity protection level for this partition. */
1540 found_flags
= m
->partitions
[di
].found
?
1541 (vi
>= 0 && m
->partitions
[vi
].found
?
1542 (si
>= 0 && m
->partitions
[si
].found
? PARTITION_POLICY_SIGNED
: PARTITION_POLICY_VERITY
) :
1543 PARTITION_POLICY_ENCRYPTED
|PARTITION_POLICY_UNPROTECTED
) :
1544 (m
->partitions
[di
].ignored
? PARTITION_POLICY_UNUSED
: PARTITION_POLICY_ABSENT
);
1546 r
= image_policy_check_protection(policy
, di
, found_flags
);
1550 if (m
->partitions
[di
].found
) {
1551 r
= image_policy_check_partition_flags(policy
, di
, m
->partitions
[di
].gpt_flags
);
1557 if (!any
&& !FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_EMPTY
))
1560 r
= dissected_image_probe_filesystems(m
, fd
, policy
);
1568 int dissect_image_file(
1570 const VeritySettings
*verity
,
1571 const MountOptions
*mount_options
,
1572 const ImagePolicy
*image_policy
,
1573 DissectImageFlags flags
,
1574 DissectedImage
**ret
) {
1577 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1578 _cleanup_close_
int fd
= -EBADF
;
1584 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1588 if (fstat(fd
, &st
) < 0)
1591 r
= stat_verify_regular(&st
);
1595 r
= dissected_image_new(path
, &m
);
1599 m
->image_size
= st
.st_size
;
1601 r
= probe_sector_size(fd
, &m
->sector_size
);
1605 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, image_policy
, flags
);
1617 int dissect_log_error(int log_level
, int r
, const char *name
, const VeritySettings
*verity
) {
1618 assert(log_level
>= 0 && log_level
<= LOG_DEBUG
);
1623 case 0 ... INT_MAX
: /* success! */
1627 return log_full_errno(log_level
, r
, "Dissecting images is not supported, compiled without blkid support.");
1630 return log_full_errno(log_level
, r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
1633 return log_full_errno(log_level
, r
, "%s: The image does not pass os-release/extension-release validation.", name
);
1635 case -EADDRNOTAVAIL
:
1636 return log_full_errno(log_level
, r
, "%s: No root partition for specified root hash found.", name
);
1639 return log_full_errno(log_level
, r
, "%s: Multiple suitable root partitions found in image.", name
);
1642 return log_full_errno(log_level
, r
, "%s: No suitable root partition found in image.", name
);
1644 case -EPROTONOSUPPORT
:
1645 return log_full_errno(log_level
, r
, "Device '%s' is a loopback block device with partition scanning turned off, please turn it on.", name
);
1648 return log_full_errno(log_level
, r
, "%s: Image is not a block device.", name
);
1651 return log_full_errno(log_level
, r
,
1652 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
1653 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
1654 name
, strna(verity
? verity
->data_path
: NULL
));
1657 return log_full_errno(log_level
, r
, "%s: image does not match image policy.", name
);
1660 return log_full_errno(log_level
, r
, "%s: no suitable partitions found.", name
);
1663 return log_full_errno(log_level
, r
, "%s: cannot dissect image: %m", name
);
1667 int dissect_image_file_and_warn(
1669 const VeritySettings
*verity
,
1670 const MountOptions
*mount_options
,
1671 const ImagePolicy
*image_policy
,
1672 DissectImageFlags flags
,
1673 DissectedImage
**ret
) {
1675 return dissect_log_error(
1677 dissect_image_file(path
, verity
, mount_options
, image_policy
, flags
, ret
),
1682 void dissected_image_close(DissectedImage
*m
) {
1686 /* Closes all fds we keep open associated with this, but nothing else */
1688 FOREACH_ARRAY(p
, m
->partitions
, _PARTITION_DESIGNATOR_MAX
) {
1689 p
->mount_node_fd
= safe_close(p
->mount_node_fd
);
1690 p
->fsmount_fd
= safe_close(p
->fsmount_fd
);
1693 m
->loop
= loop_device_unref(m
->loop
);
1696 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1700 /* First, clear dissected partitions. */
1701 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1702 dissected_partition_done(m
->partitions
+ i
);
1704 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1705 * DecryptedImage may try to deactivate partitions. */
1706 decrypted_image_unref(m
->decrypted_image
);
1708 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1709 * remove existing partitions on the loopback block device. */
1710 loop_device_unref(m
->loop
);
1712 free(m
->image_name
);
1714 strv_free(m
->machine_info
);
1715 strv_free(m
->os_release
);
1716 strv_free(m
->initrd_release
);
1717 strv_free(m
->confext_release
);
1718 strv_free(m
->sysext_release
);
1723 static int is_loop_device(const char *path
) {
1724 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1729 if (stat(path
, &st
) < 0)
1732 if (!S_ISBLK(st
.st_mode
))
1735 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1736 if (access(s
, F_OK
) < 0) {
1737 if (errno
!= ENOENT
)
1740 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1741 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1742 if (access(s
, F_OK
) < 0)
1743 return errno
== ENOENT
? false : -errno
;
1749 static int run_fsck(int node_fd
, const char *fstype
) {
1753 assert(node_fd
>= 0);
1756 r
= fsck_exists_for_fstype(fstype
);
1758 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1762 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd
), fstype
);
1769 &node_fd
, 1, /* Leave the node fd open */
1770 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG_SIGTERM
|FORK_REARRANGE_STDIO
|FORK_CLOEXEC_OFF
,
1773 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1776 execlp("fsck", "fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd
), NULL
);
1778 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1779 _exit(FSCK_OPERATIONAL_ERROR
);
1782 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1783 if (exit_status
< 0)
1784 return log_debug_errno(exit_status
, "Failed to fork off fsck: %m");
1786 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1787 log_debug("fsck failed with exit status %i.", exit_status
);
1789 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1790 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1792 log_debug("Ignoring fsck error.");
1798 static int fs_grow(const char *node_path
, int mount_fd
, const char *mount_path
) {
1799 _cleanup_close_
int _mount_fd
= -EBADF
, node_fd
= -EBADF
;
1800 uint64_t size
, newsize
;
1805 assert(mount_fd
>= 0 || mount_path
);
1807 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1809 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1811 r
= blockdev_get_device_size(node_fd
, &size
);
1813 return log_debug_errno(r
, "Failed to get block device size of %s: %m", node_path
);
1818 _mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1820 return log_debug_errno(errno
, "Failed to open mounted file system %s: %m", mount_path
);
1822 mount_fd
= _mount_fd
;
1824 mount_fd
= fd_reopen_condition(mount_fd
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, &_mount_fd
);
1826 return log_debug_errno(errno
, "Failed to reopen mount node: %m");
1829 id
= mount_path
?: node_path
;
1831 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", id
, size
);
1832 r
= resize_fs(mount_fd
, size
, &newsize
);
1834 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", id
, size
);
1836 if (newsize
== size
)
1837 log_debug("Successfully resized \"%s\" to %s bytes.",
1838 id
, FORMAT_BYTES(newsize
));
1840 assert(newsize
< size
);
1841 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1842 id
, FORMAT_BYTES(newsize
), size
- newsize
);
1848 int partition_pick_mount_options(
1849 PartitionDesignator d
,
1854 unsigned long *ret_ms_flags
) {
1856 _cleanup_free_
char *options
= NULL
;
1858 assert(ret_options
);
1860 /* Selects a baseline of bind mount flags, that should always apply.
1862 * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
1864 * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
1866 * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
1867 * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
1868 * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
1871 unsigned long flags
= MS_NODEV
;
1879 case PARTITION_XBOOTLDR
:
1880 flags
|= MS_NOSUID
|MS_NOEXEC
|ms_nosymfollow_supported();
1882 /* The ESP might contain a pre-boot random seed. Let's make this unaccessible to regular
1883 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
1884 if (!fstype
|| fstype_can_umask(fstype
))
1885 if (!strextend_with_separator(&options
, ",", "umask=0077"))
1897 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1898 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1899 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1900 * from the upper file system still get propagated through to the underlying file system,
1901 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1902 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1903 * carry a per file system table here.
1905 * Note that this means that we might not be able to mount corrupted file systems as read-only
1906 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1907 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1908 * mount options for loopback devices this is the right choice, since otherwise using the same
1909 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The use case of
1910 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1911 * access that actually modifies stuff work on such image files. Or to say this differently: if
1912 * people want their file systems to be fixed up they should just open them in writable mode, where
1913 * all these problems don't exist. */
1914 if (!rw
&& fstype
) {
1915 const char *option
= fstype_norecovery_option(fstype
);
1917 if (option
&& !strextend_with_separator(&options
, ",", option
))
1921 if (discard
&& fstype
&& fstype_can_discard(fstype
))
1922 if (!strextend_with_separator(&options
, ",", "discard"))
1925 if (!ret_ms_flags
) /* Fold flags into option string if ret_flags specified as NULL */
1926 if (!strextend_with_separator(&options
, ",",
1927 FLAGS_SET(flags
, MS_RDONLY
) ? "ro" : "rw",
1928 FLAGS_SET(flags
, MS_NODEV
) ? "nodev" : "dev",
1929 FLAGS_SET(flags
, MS_NOSUID
) ? "nosuid" : "suid",
1930 FLAGS_SET(flags
, MS_NOEXEC
) ? "noexec" : "exec",
1931 FLAGS_SET(flags
, MS_NOSYMFOLLOW
) ? "nosymfollow" : NULL
))
1932 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
1936 *ret_ms_flags
= flags
;
1938 *ret_options
= TAKE_PTR(options
);
1942 static bool need_user_mapping(uid_t uid_shift
, uid_t uid_range
) {
1944 if (!uid_is_valid(uid_shift
))
1947 return uid_shift
!= 0 || uid_range
!= UINT32_MAX
;
1950 static int mount_partition(
1951 PartitionDesignator d
,
1952 DissectedPartition
*m
,
1954 const char *directory
,
1958 DissectImageFlags flags
) {
1960 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1961 const char *p
= NULL
, *node
, *fstype
= NULL
;
1962 bool rw
, discard
, grow
;
1963 unsigned long ms_flags
;
1971 /* Check the various combinations when we can't do anything anymore */
1972 if (m
->fsmount_fd
< 0 && m
->mount_node_fd
< 0)
1974 if (m
->fsmount_fd
>= 0 && !where
)
1976 if (!where
&& m
->mount_node_fd
< 0)
1979 if (m
->fsmount_fd
< 0) {
1980 fstype
= dissected_partition_fstype(m
);
1982 return -EAFNOSUPPORT
;
1984 /* We are looking at an encrypted partition? This either means stacked encryption, or the
1985 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
1987 if (streq(fstype
, "crypto_LUKS"))
1990 r
= dissect_fstype_ok(fstype
);
1994 return -EIDRM
; /* Recognizable error */
1997 node
= m
->mount_node_fd
< 0 ? NULL
: FORMAT_PROC_FD_PATH(m
->mount_node_fd
);
1998 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
2000 discard
= ((flags
& DISSECT_IMAGE_DISCARD
) ||
2001 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && (m
->node
&& is_loop_device(m
->node
) > 0)));
2003 grow
= rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
);
2005 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
&& m
->mount_node_fd
>= 0 && m
->fsmount_fd
< 0) {
2006 r
= run_fsck(m
->mount_node_fd
, fstype
);
2013 /* Automatically create missing mount points inside the image, if necessary. */
2014 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
2015 if (r
< 0 && r
!= -EROFS
)
2018 r
= chase(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
2024 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
2025 * image (as the branch above does) but the host hierarchy, and the created directory might
2026 * survive our mount in the host hierarchy hence. */
2027 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
2028 r
= mkdir_p(where
, 0755);
2037 if (m
->fsmount_fd
< 0) {
2038 r
= partition_pick_mount_options(d
, fstype
, rw
, discard
, &options
, &ms_flags
);
2042 if (need_user_mapping(uid_shift
, uid_range
) && fstype_can_uid_gid(fstype
)) {
2043 _cleanup_free_
char *uid_option
= NULL
;
2045 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
2048 if (!strextend_with_separator(&options
, ",", uid_option
))
2051 userns_fd
= -EBADF
; /* Not needed */
2054 if (!isempty(m
->mount_options
))
2055 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
2060 if (m
->fsmount_fd
>= 0) {
2061 /* Case #1: Attach existing fsmount fd to the file system */
2063 r
= mount_exchange_graceful(
2066 FLAGS_SET(flags
, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE
));
2068 return log_debug_errno(r
, "Failed to mount image on '%s': %m", p
);
2073 /* Case #2: Mount directly into place */
2074 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, ms_flags
, options
);
2079 (void) fs_grow(node
, -EBADF
, p
);
2081 if (userns_fd
>= 0) {
2082 r
= remount_idmap_fd(STRV_MAKE(p
), userns_fd
);
2090 /* Case #3: Create fsmount fd */
2092 m
->fsmount_fd
= make_fsmount(LOG_DEBUG
, node
, fstype
, ms_flags
, options
, userns_fd
);
2093 if (m
->fsmount_fd
< 0)
2094 return m
->fsmount_fd
;
2097 (void) fs_grow(node
, m
->fsmount_fd
, NULL
);
2103 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, uid_t uid_range
, DissectImageFlags flags
) {
2104 _cleanup_free_
char *options
= NULL
;
2109 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
2111 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
2112 r
= mkdir_p(where
, 0755);
2117 if (need_user_mapping(uid_shift
, uid_range
)) {
2118 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
2122 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
2129 static int mount_point_is_available(const char *where
, const char *path
, bool missing_ok
) {
2130 _cleanup_free_
char *p
= NULL
;
2133 /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
2134 * or does not exist at all (when missing_ok). */
2136 r
= chase(path
, where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
2140 return log_debug_errno(r
, "Failed to chase \"%s\": %m", path
);
2142 r
= dir_is_empty(p
, /* ignore_hidden_or_backup= */ false);
2146 return log_debug_errno(r
, "Failed to check directory \"%s\": %m", p
);
2150 int dissected_image_mount(
2156 DissectImageFlags flags
) {
2158 _cleanup_close_
int my_userns_fd
= -EBADF
;
2163 /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
2164 * store them in DissectedPartition.fsmount_fd.
2166 * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
2167 * or use DissectedPartition.fsmount_fd and bind it to the right places.
2169 * This allows splitting the setting up the superblocks and the binding to file systems paths into
2170 * two distinct and differently privileged components: one that gets the fsmount fds, and the other
2171 * that then applies them.
2175 * -ENXIO → No root partition found
2176 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
2177 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
2178 * -EUCLEAN → fsck for file system failed
2179 * -EBUSY → File system already mounted/used elsewhere (kernel)
2180 * -EAFNOSUPPORT → File system type not supported or not known
2181 * -EIDRM → File system is not among allowlisted "common" file systems
2184 if (!where
&& (flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0)
2185 return -EOPNOTSUPP
; /* for now, not supported */
2187 if (!(m
->partitions
[PARTITION_ROOT
].found
||
2188 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
2189 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
2191 if (userns_fd
< 0 && need_user_mapping(uid_shift
, uid_range
) && FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
)) {
2193 my_userns_fd
= make_userns(uid_shift
, uid_range
, UID_INVALID
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
2194 if (my_userns_fd
< 0)
2195 return my_userns_fd
;
2197 userns_fd
= my_userns_fd
;
2200 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
2202 /* First mount the root fs. If there's none we use a tmpfs. */
2203 if (m
->partitions
[PARTITION_ROOT
].found
) {
2204 r
= mount_partition(PARTITION_ROOT
, m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, userns_fd
, flags
);
2209 r
= mount_root_tmpfs(where
, uid_shift
, uid_range
, flags
);
2214 /* For us mounting root always means mounting /usr as well */
2215 r
= mount_partition(PARTITION_USR
, m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, userns_fd
, flags
);
2220 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0 &&
2221 (flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
2222 /* If either one of the validation flags are set, ensure that the image qualifies as
2223 * one or the other (or both). */
2228 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
2229 r
= path_is_os_tree(where
);
2235 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
) && m
->image_name
) {
2236 r
= extension_has_forbidden_content(where
);
2240 r
= path_is_extension_tree(IMAGE_SYSEXT
, where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_EXTENSION_CHECK
));
2242 r
= path_is_extension_tree(IMAGE_CONFEXT
, where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_EXTENSION_CHECK
));
2254 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
2257 r
= mount_partition(PARTITION_HOME
, m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, userns_fd
, flags
);
2261 r
= mount_partition(PARTITION_SRV
, m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, userns_fd
, flags
);
2265 r
= mount_partition(PARTITION_VAR
, m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, userns_fd
, flags
);
2269 r
= mount_partition(PARTITION_TMP
, m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, userns_fd
, flags
);
2273 int slash_boot_is_available
= 0;
2275 r
= slash_boot_is_available
= mount_point_is_available(where
, "/boot", /* missing_ok = */ true);
2279 if (!where
|| slash_boot_is_available
) {
2280 r
= mount_partition(PARTITION_XBOOTLDR
, m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, userns_fd
, flags
);
2283 slash_boot_is_available
= !r
;
2286 if (m
->partitions
[PARTITION_ESP
].found
) {
2287 const char *esp_path
= NULL
;
2290 /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
2291 * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
2294 if (slash_boot_is_available
) {
2295 r
= mount_point_is_available(where
, "/boot", /* missing_ok = */ false);
2303 r
= mount_point_is_available(where
, "/efi", /* missing_ok = */ true);
2311 /* OK, let's mount the ESP now (possibly creating the dir if missing) */
2312 r
= mount_partition(PARTITION_ESP
, m
->partitions
+ PARTITION_ESP
, where
, esp_path
, uid_shift
, uid_range
, userns_fd
, flags
);
2320 int dissected_image_mount_and_warn(
2326 DissectImageFlags flags
) {
2332 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, userns_fd
, flags
);
2334 return log_error_errno(r
, "Failed to mount image: No root file system found in image.");
2335 if (r
== -EMEDIUMTYPE
)
2336 return log_error_errno(r
, "Failed to mount image: No suitable os-release/extension-release file in image found.");
2338 return log_error_errno(r
, "Failed to mount image: Encrypted file system discovered, but decryption not requested.");
2340 return log_error_errno(r
, "Failed to mount image: File system check on image failed.");
2342 return log_error_errno(r
, "Failed to mount image: File system already mounted elsewhere.");
2343 if (r
== -EAFNOSUPPORT
)
2344 return log_error_errno(r
, "Failed to mount image: File system type not supported or not known.");
2346 return log_error_errno(r
, "Failed to mount image: File system is too uncommon, refused.");
2348 return log_error_errno(r
, "Failed to mount image: %m");
2353 #if HAVE_LIBCRYPTSETUP
2354 struct DecryptedPartition
{
2355 struct crypt_device
*device
;
2361 typedef struct DecryptedPartition DecryptedPartition
;
2363 struct DecryptedImage
{
2365 DecryptedPartition
*decrypted
;
2369 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
2370 #if HAVE_LIBCRYPTSETUP
2376 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2377 DecryptedPartition
*p
= d
->decrypted
+ i
;
2379 if (p
->device
&& p
->name
&& !p
->relinquished
) {
2380 _cleanup_free_
char *node
= NULL
;
2382 node
= path_join("/dev/mapper", p
->name
);
2384 r
= btrfs_forget_device(node
);
2385 if (r
< 0 && r
!= -ENOENT
)
2386 log_debug_errno(r
, "Failed to forget btrfs device %s, ignoring: %m", node
);
2390 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2391 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2393 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
2397 sym_crypt_free(p
->device
);
2407 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
2409 #if HAVE_LIBCRYPTSETUP
2410 static int decrypted_image_new(DecryptedImage
**ret
) {
2411 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2415 d
= new(DecryptedImage
, 1);
2419 *d
= (DecryptedImage
) {
2427 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
2428 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
2431 assert(original_node
);
2436 base
= strrchr(original_node
, '/');
2438 base
= original_node
;
2444 name
= strjoin(base
, suffix
);
2447 if (!filename_is_valid(name
))
2450 node
= path_join(sym_crypt_get_dir(), name
);
2454 *ret_name
= TAKE_PTR(name
);
2455 *ret_node
= TAKE_PTR(node
);
2460 static int decrypt_partition(
2461 DissectedPartition
*m
,
2462 const char *passphrase
,
2463 DissectImageFlags flags
,
2464 DecryptedImage
*d
) {
2466 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2467 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2468 _cleanup_close_
int fd
= -EBADF
;
2474 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2477 if (!streq(m
->fstype
, "crypto_LUKS"))
2483 r
= dlopen_cryptsetup();
2487 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
2491 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2494 r
= sym_crypt_init(&cd
, m
->node
);
2496 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
2498 cryptsetup_enable_logging(cd
);
2500 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
2502 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
2504 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
2505 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
2506 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
2508 log_debug_errno(r
, "Failed to activate LUKS device: %m");
2509 return r
== -EPERM
? -EKEYREJECTED
: r
;
2512 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2514 return log_debug_errno(errno
, "Failed to open %s: %m", node
);
2516 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2517 .name
= TAKE_PTR(name
),
2518 .device
= TAKE_PTR(cd
),
2521 m
->decrypted_node
= TAKE_PTR(node
);
2522 close_and_replace(m
->mount_node_fd
, fd
);
2527 static int verity_can_reuse(
2528 const VeritySettings
*verity
,
2530 struct crypt_device
**ret_cd
) {
2532 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2533 _cleanup_free_
char *root_hash_existing
= NULL
;
2534 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2535 struct crypt_params_verity crypt_params
= {};
2536 size_t root_hash_existing_size
;
2543 r
= sym_crypt_init_by_name(&cd
, name
);
2545 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
2547 cryptsetup_enable_logging(cd
);
2549 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
2551 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
2553 root_hash_existing_size
= verity
->root_hash_size
;
2554 root_hash_existing
= malloc0(root_hash_existing_size
);
2555 if (!root_hash_existing
)
2558 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
2560 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
2561 if (verity
->root_hash_size
!= root_hash_existing_size
||
2562 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
2563 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
2565 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2566 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2567 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2568 * signing for the new one, and vice versa. */
2569 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
2570 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
2573 *ret_cd
= TAKE_PTR(cd
);
2577 static char* dm_deferred_remove_clean(char *name
) {
2581 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
2584 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
2586 static int validate_signature_userspace(const VeritySettings
*verity
, DissectImageFlags flags
) {
2589 if (!FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
)) {
2590 log_debug("Userspace dm-verity signature authentication disabled via flag.");
2594 r
= secure_getenv_bool("SYSTEMD_ALLOW_USERSPACE_VERITY");
2595 if (r
< 0 && r
!= -ENXIO
) {
2596 log_debug_errno(r
, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
2600 log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
2605 r
= proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING
, &b
);
2607 log_debug_errno(r
, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
2611 log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line variable.");
2616 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
2617 _cleanup_strv_free_
char **certs
= NULL
;
2618 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
2619 _cleanup_free_
char *s
= NULL
;
2620 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
2621 * of declaration in place, please */
2622 const unsigned char *d
;
2625 assert(verity
->root_hash
);
2626 assert(verity
->root_hash_sig
);
2628 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
2629 * userspace validation. */
2631 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
2633 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
2634 if (strv_isempty(certs
)) {
2635 log_debug("No userspace dm-verity certificates found.");
2639 d
= verity
->root_hash_sig
;
2640 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
2642 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
2644 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2646 return log_oom_debug();
2648 bio
= BIO_new_mem_buf(s
, strlen(s
));
2650 return log_oom_debug();
2652 sk
= sk_X509_new_null();
2654 return log_oom_debug();
2656 STRV_FOREACH(i
, certs
) {
2657 _cleanup_(X509_freep
) X509
*c
= NULL
;
2658 _cleanup_fclose_
FILE *f
= NULL
;
2660 f
= fopen(*i
, "re");
2662 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
2666 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
2668 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
2672 if (sk_X509_push(sk
, c
) == 0)
2673 return log_oom_debug();
2678 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
2680 log_debug("Userspace PKCS#7 validation succeeded.");
2682 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
2686 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2691 static int do_crypt_activate_verity(
2692 struct crypt_device
*cd
,
2694 const VeritySettings
*verity
,
2695 DissectImageFlags flags
) {
2697 bool check_signature
;
2704 if (verity
->root_hash_sig
) {
2705 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2706 if (r
< 0 && r
!= -ENXIO
)
2707 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2709 check_signature
= r
!= 0;
2711 check_signature
= false;
2713 if (check_signature
) {
2715 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2716 /* First, if we have support for signed keys in the kernel, then try that first. */
2717 r
= sym_crypt_activate_by_signed_key(
2721 verity
->root_hash_size
,
2722 verity
->root_hash_sig
,
2723 verity
->root_hash_sig_size
,
2724 CRYPT_ACTIVATE_READONLY
);
2728 log_debug_errno(r
, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
2730 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.",
2731 program_invocation_short_name
);
2732 r
= 0; /* Set for the propagation below */
2735 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2736 * works we'll try to activate without telling the kernel the signature. */
2738 /* Preferably propagate the original kernel error, so that the fallback logic can work,
2739 * as the device-mapper is finicky around concurrent activations of the same volume */
2740 k
= validate_signature_userspace(verity
, flags
);
2742 return r
< 0 ? r
: k
;
2744 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(ENOKEY
),
2745 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2748 return sym_crypt_activate_by_volume_key(
2752 verity
->root_hash_size
,
2753 CRYPT_ACTIVATE_READONLY
);
2756 static usec_t
verity_timeout(void) {
2757 usec_t t
= 100 * USEC_PER_MSEC
;
2761 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2762 * Let's make the timeout configurable. */
2764 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2768 r
= parse_sec(e
, &t
);
2771 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2772 "using the default timeout (%s).",
2773 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
2778 static int verity_partition(
2779 PartitionDesignator designator
,
2780 DissectedPartition
*m
,
2781 DissectedPartition
*v
,
2782 const VeritySettings
*verity
,
2783 DissectImageFlags flags
,
2784 DecryptedImage
*d
) {
2786 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2787 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2788 _cleanup_close_
int mount_node_fd
= -EBADF
;
2792 assert(v
|| (verity
&& verity
->data_path
));
2794 if (!verity
|| !verity
->root_hash
)
2796 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2797 (verity
->designator
== designator
)))
2800 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2802 if (!verity
->data_path
) {
2803 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2806 if (!streq(v
->fstype
, "DM_verity_hash"))
2810 r
= dlopen_cryptsetup();
2814 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2815 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2816 _cleanup_free_
char *root_hash_encoded
= NULL
;
2818 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2819 if (!root_hash_encoded
)
2822 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2824 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2828 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2832 cryptsetup_enable_logging(cd
);
2834 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2838 r
= sym_crypt_set_data_device(cd
, m
->node
);
2842 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2845 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2846 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2847 * retry a few times before giving up. */
2848 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2849 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2850 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2851 _cleanup_close_
int fd
= -EBADF
;
2853 /* First, check if the device already exists. */
2854 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2855 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2856 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2858 goto check
; /* The device already exists. Let's check it. */
2860 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2861 r
= do_crypt_activate_verity(cd
, name
, verity
, flags
);
2863 goto try_open
; /* The device is activated. Let's open it. */
2864 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2865 * There's no way to distinguish this situation from a genuine error due to invalid
2866 * parameters, so immediately fall back to activating the device with a unique name.
2867 * Improvements in libcrypsetup can ensure this never happens:
2868 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2869 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2871 /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
2872 * sharing is enabled. */
2873 if (r
== -ENODEV
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2876 -EEXIST
, /* Volume has already been opened and ready to be used. */
2877 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2878 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2881 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2882 r
= dm_deferred_remove_cancel(name
);
2883 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2884 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2885 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2886 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2889 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2891 restore_deferred_remove
= strdup(name
);
2892 if (!restore_deferred_remove
)
2893 return log_oom_debug();
2895 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2896 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2897 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2900 -ENOENT
, /* Removed?? */
2901 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2902 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2905 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2908 /* devmapper might say that the device exists, but the devlink might not yet have been
2909 * created. Check and wait for the udev event in that case. */
2910 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2911 /* Fallback to activation with a unique device if it's taking too long */
2912 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2915 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2920 /* Now, the device is activated and devlink is created. Let's open it. */
2921 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2923 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
2924 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2926 /* The device has already been removed?? */
2931 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2932 restore_deferred_remove
= mfree(restore_deferred_remove
);
2934 mount_node_fd
= TAKE_FD(fd
);
2936 crypt_free_and_replace(cd
, existing_cd
);
2941 /* Device is being removed by another process. Let's wait for a while. */
2942 (void) usleep_safe(2 * USEC_PER_MSEC
);
2945 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2946 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2947 /* Before trying to activate with unique name, we need to free crypt_device object.
2948 * Otherwise, we get error from libcryptsetup like the following:
2950 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2955 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2958 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2961 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2962 .name
= TAKE_PTR(name
),
2963 .device
= TAKE_PTR(cd
),
2966 m
->decrypted_node
= TAKE_PTR(node
);
2967 close_and_replace(m
->mount_node_fd
, mount_node_fd
);
2973 int dissected_image_decrypt(
2975 const char *passphrase
,
2976 const VeritySettings
*verity
,
2977 DissectImageFlags flags
) {
2979 #if HAVE_LIBCRYPTSETUP
2980 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2985 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
2989 * = 0 → There was nothing to decrypt
2990 * > 0 → Decrypted successfully
2991 * -ENOKEY → There's something to decrypt but no key was supplied
2992 * -EKEYREJECTED → Passed key was not correct
2993 * -EBUSY → Generic Verity error (kernel is not very explanatory)
2996 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
2999 if (!m
->encrypted
&& !m
->verity_ready
)
3002 #if HAVE_LIBCRYPTSETUP
3003 r
= decrypted_image_new(&d
);
3007 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
3008 DissectedPartition
*p
= m
->partitions
+ i
;
3009 PartitionDesignator k
;
3014 r
= decrypt_partition(p
, passphrase
, flags
, d
);
3018 k
= partition_verity_of(i
);
3020 flags
|= getenv_bool("SYSTEMD_VERITY_SHARING") != 0 ? DISSECT_IMAGE_VERITY_SHARE
: 0;
3022 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
, d
);
3027 if (!p
->decrypted_fstype
&& p
->mount_node_fd
>= 0 && p
->decrypted_node
) {
3028 r
= probe_filesystem_full(p
->mount_node_fd
, p
->decrypted_node
, 0, UINT64_MAX
, &p
->decrypted_fstype
);
3029 if (r
< 0 && r
!= -EUCLEAN
)
3034 m
->decrypted_image
= TAKE_PTR(d
);
3042 int dissected_image_decrypt_interactively(
3044 const char *passphrase
,
3045 const VeritySettings
*verity
,
3046 DissectImageFlags flags
) {
3048 _cleanup_strv_free_erase_
char **z
= NULL
;
3055 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
3058 if (r
== -EKEYREJECTED
)
3059 log_error_errno(r
, "Incorrect passphrase, try again!");
3060 else if (r
!= -ENOKEY
)
3061 return log_error_errno(r
, "Failed to decrypt image: %m");
3064 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
3065 "Too many retries.");
3067 z
= strv_free_erase(z
);
3069 static const AskPasswordRequest req
= {
3070 .message
= "Please enter image passphrase:",
3072 .keyring
= "dissect",
3073 .credential
= "dissect.passphrase",
3076 r
= ask_password_auto(&req
, USEC_INFINITY
, /* flags= */ 0, &z
);
3078 return log_error_errno(r
, "Failed to query for passphrase: %m");
3084 static int decrypted_image_relinquish(DecryptedImage
*d
) {
3087 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
3088 * boolean so that we don't clean it up ourselves either anymore */
3090 #if HAVE_LIBCRYPTSETUP
3093 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
3094 DecryptedPartition
*p
= d
->decrypted
+ i
;
3096 if (p
->relinquished
)
3099 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
3101 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
3103 p
->relinquished
= true;
3110 int dissected_image_relinquish(DissectedImage
*m
) {
3115 if (m
->decrypted_image
) {
3116 r
= decrypted_image_relinquish(m
->decrypted_image
);
3122 loop_device_relinquish(m
->loop
);
3127 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
3134 e
= endswith(image
, ".raw");
3136 return strjoin(e
, suffix
);
3138 n
= new(char, e
- image
+ strlen(suffix
) + 1);
3142 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
3146 void verity_settings_done(VeritySettings
*v
) {
3149 v
->root_hash
= mfree(v
->root_hash
);
3150 v
->root_hash_size
= 0;
3152 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
3153 v
->root_hash_sig_size
= 0;
3155 v
->data_path
= mfree(v
->data_path
);
3158 int verity_settings_load(
3159 VeritySettings
*verity
,
3161 const char *root_hash_path
,
3162 const char *root_hash_sig_path
) {
3164 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
3165 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
3166 _cleanup_free_
char *verity_data_path
= NULL
;
3167 PartitionDesignator designator
;
3172 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
3174 /* If we are asked to load the root hash for a device node, exit early */
3175 if (is_device_path(image
))
3178 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
3179 if (r
< 0 && r
!= -ENXIO
)
3180 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
3184 designator
= verity
->designator
;
3186 /* We only fill in what isn't already filled in */
3188 if (!verity
->root_hash
) {
3189 _cleanup_free_
char *text
= NULL
;
3191 if (root_hash_path
) {
3192 /* If explicitly specified it takes precedence */
3193 r
= read_one_line_file(root_hash_path
, &text
);
3198 designator
= PARTITION_ROOT
;
3200 /* Otherwise look for xattr and separate file, and first for the data for root and if
3201 * that doesn't exist for /usr */
3203 if (designator
< 0 || designator
== PARTITION_ROOT
) {
3204 r
= getxattr_malloc(image
, "user.verity.roothash", &text
);
3206 _cleanup_free_
char *p
= NULL
;
3208 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
3211 p
= build_auxiliary_path(image
, ".roothash");
3215 r
= read_one_line_file(p
, &text
);
3216 if (r
< 0 && r
!= -ENOENT
)
3221 designator
= PARTITION_ROOT
;
3224 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
3225 /* So in the "roothash" xattr/file name above the "root" of course primarily
3226 * refers to the root of the Verity Merkle tree. But coincidentally it also
3227 * is the hash for the *root* file system, i.e. the "root" neatly refers to
3228 * two distinct concepts called "root". Taking benefit of this happy
3229 * coincidence we call the file with the root hash for the /usr/ file system
3230 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
3231 * confusing. We thus drop the reference to the root of the Merkle tree, and
3232 * just indicate which file system it's about. */
3233 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
);
3235 _cleanup_free_
char *p
= NULL
;
3237 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
3240 p
= build_auxiliary_path(image
, ".usrhash");
3244 r
= read_one_line_file(p
, &text
);
3245 if (r
< 0 && r
!= -ENOENT
)
3250 designator
= PARTITION_USR
;
3255 r
= unhexmem(text
, &root_hash
, &root_hash_size
);
3258 if (root_hash_size
< sizeof(sd_id128_t
))
3263 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
3264 if (root_hash_sig_path
) {
3265 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3266 if (r
< 0 && r
!= -ENOENT
)
3270 designator
= PARTITION_ROOT
;
3272 if (designator
< 0 || designator
== PARTITION_ROOT
) {
3273 _cleanup_free_
char *p
= NULL
;
3275 /* Follow naming convention recommended by the relevant RFC:
3276 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
3277 p
= build_auxiliary_path(image
, ".roothash.p7s");
3281 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3282 if (r
< 0 && r
!= -ENOENT
)
3285 designator
= PARTITION_ROOT
;
3288 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
3289 _cleanup_free_
char *p
= NULL
;
3291 p
= build_auxiliary_path(image
, ".usrhash.p7s");
3295 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3296 if (r
< 0 && r
!= -ENOENT
)
3299 designator
= PARTITION_USR
;
3303 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
3307 if (!verity
->data_path
) {
3308 _cleanup_free_
char *p
= NULL
;
3310 p
= build_auxiliary_path(image
, ".verity");
3314 if (access(p
, F_OK
) < 0) {
3315 if (errno
!= ENOENT
)
3318 verity_data_path
= TAKE_PTR(p
);
3322 verity
->root_hash
= TAKE_PTR(root_hash
);
3323 verity
->root_hash_size
= root_hash_size
;
3326 if (root_hash_sig
) {
3327 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
3328 verity
->root_hash_sig_size
= root_hash_sig_size
;
3331 if (verity_data_path
)
3332 verity
->data_path
= TAKE_PTR(verity_data_path
);
3334 if (verity
->designator
< 0)
3335 verity
->designator
= designator
;
3340 int dissected_image_load_verity_sig_partition(
3343 VeritySettings
*verity
) {
3345 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
3346 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
3347 size_t root_hash_size
, root_hash_sig_size
;
3348 _cleanup_free_
char *buf
= NULL
;
3349 PartitionDesignator d
;
3350 DissectedPartition
*p
;
3351 JsonVariant
*rh
, *sig
;
3360 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
3363 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_EMBEDDED");
3364 if (r
< 0 && r
!= -ENXIO
)
3365 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
3369 d
= partition_verity_sig_of(verity
->designator
< 0 ? PARTITION_ROOT
: verity
->designator
);
3372 p
= m
->partitions
+ d
;
3375 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
3378 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
3379 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG
), "Verity signature partition is larger than 4M, refusing.");
3381 buf
= new(char, p
->size
+1);
3385 n
= pread(fd
, buf
, p
->size
, p
->offset
);
3388 if ((uint64_t) n
!= p
->size
)
3391 e
= memchr(buf
, 0, p
->size
);
3393 /* If we found a NUL byte then the rest of the data must be NUL too */
3394 if (!memeqzero(e
, p
->size
- (e
- buf
)))
3395 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
3399 r
= json_parse(buf
, 0, &v
, NULL
, NULL
);
3401 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
3403 rh
= json_variant_by_key(v
, "rootHash");
3405 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
3406 if (!json_variant_is_string(rh
))
3407 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'rootHash' field of signature JSON object is not a string.");
3409 r
= unhexmem(json_variant_string(rh
), &root_hash
, &root_hash_size
);
3411 return log_debug_errno(r
, "Failed to parse root hash field: %m");
3413 /* Check if specified root hash matches if it is specified */
3414 if (verity
->root_hash
&&
3415 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
3416 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
3418 a
= hexmem(root_hash
, root_hash_size
);
3419 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
3421 return log_debug_errno(r
, "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
3424 sig
= json_variant_by_key(v
, "signature");
3426 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
3427 if (!json_variant_is_string(sig
))
3428 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "'signature' field of signature JSON object is not a string.");
3430 r
= unbase64mem(json_variant_string(sig
), &root_hash_sig
, &root_hash_sig_size
);
3432 return log_debug_errno(r
, "Failed to parse signature field: %m");
3434 free_and_replace(verity
->root_hash
, root_hash
);
3435 verity
->root_hash_size
= root_hash_size
;
3437 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
3438 verity
->root_hash_sig_size
= root_hash_sig_size
;
3443 int dissected_image_acquire_metadata(
3446 DissectImageFlags extra_flags
) {
3453 META_INITRD_RELEASE
,
3454 META_SYSEXT_RELEASE
,
3455 META_CONFEXT_RELEASE
,
3456 META_HAS_INIT_SYSTEM
,
3460 static const char *const paths
[_META_MAX
] = {
3461 [META_HOSTNAME
] = "/etc/hostname\0",
3462 [META_MACHINE_ID
] = "/etc/machine-id\0",
3463 [META_MACHINE_INFO
] = "/etc/machine-info\0",
3464 [META_OS_RELEASE
] = "/etc/os-release\0"
3465 "/usr/lib/os-release\0",
3466 [META_INITRD_RELEASE
] = "/etc/initrd-release\0"
3467 "/usr/lib/initrd-release\0",
3468 [META_SYSEXT_RELEASE
] = "sysext-release\0", /* String used only for logging. */
3469 [META_CONFEXT_RELEASE
] = "confext-release\0", /* ditto */
3470 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
3473 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **initrd_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
3474 _cleanup_free_
char *hostname
= NULL
, *t
= NULL
;
3475 _cleanup_close_pair_
int error_pipe
[2] = EBADF_PAIR
;
3476 _cleanup_(sigkill_waitp
) pid_t child
= 0;
3477 sd_id128_t machine_id
= SD_ID128_NULL
;
3478 unsigned n_meta_initialized
= 0;
3479 int fds
[2 * _META_MAX
], r
, v
;
3480 int has_init_system
= -1;
3483 BLOCK_SIGNALS(SIGCHLD
);
3487 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
3488 assert(paths
[n_meta_initialized
]);
3490 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
3496 r
= get_common_dissect_directory(&t
);
3500 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
3505 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
, &child
);
3510 error_pipe
[0] = safe_close(error_pipe
[0]);
3513 r
= detach_mount_namespace_harder(0, 0);
3515 r
= detach_mount_namespace_userns(userns_fd
);
3517 log_debug_errno(r
, "Failed to detach mount namespace: %m");
3521 r
= dissected_image_mount(
3524 /* uid_shift= */ UID_INVALID
,
3525 /* uid_range= */ UID_INVALID
,
3526 /* userns_fd= */ -EBADF
,
3528 DISSECT_IMAGE_READ_ONLY
|
3529 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
3530 DISSECT_IMAGE_USR_NO_ROOT
);
3532 log_debug_errno(r
, "Failed to mount dissected image: %m");
3536 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
3537 _cleanup_close_
int fd
= -ENOENT
;
3541 fds
[2*k
] = safe_close(fds
[2*k
]);
3545 case META_SYSEXT_RELEASE
:
3549 /* As per the os-release spec, if the image is an extension it will have a
3550 * file named after the image name in extension-release.d/ - we use the image
3551 * name and try to resolve it with the extension-release helpers, as
3552 * sometimes the image names are mangled on deployment and do not match
3553 * anymore. Unlike other paths this is not fixed, and the image name can be
3554 * mangled on deployment, so by calling into the helper we allow a fallback
3555 * that matches on the first extension-release file found in the directory,
3556 * if one named after the image cannot be found first. */
3557 r
= open_extension_release(
3561 /* relax_extension_release_check= */ false,
3562 /* ret_path= */ NULL
,
3568 case META_CONFEXT_RELEASE
:
3573 r
= open_extension_release(
3577 /* relax_extension_release_check= */ false,
3578 /* ret_path= */ NULL
,
3585 case META_HAS_INIT_SYSTEM
: {
3588 FOREACH_STRING(init
,
3589 "/usr/lib/systemd/systemd", /* systemd on /usr/ merged system */
3590 "/lib/systemd/systemd", /* systemd on /usr/ non-merged systems */
3591 "/sbin/init") { /* traditional path the Linux kernel invokes */
3593 r
= chase(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
3596 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
3603 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
));
3611 NULSTR_FOREACH(p
, paths
[k
]) {
3612 fd
= chase_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
3619 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
3623 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
3628 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
3631 _exit(EXIT_SUCCESS
);
3634 /* Let parent know the error */
3635 (void) write(error_pipe
[1], &r
, sizeof(r
));
3636 _exit(EXIT_FAILURE
);
3639 error_pipe
[1] = safe_close(error_pipe
[1]);
3641 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
3642 _cleanup_fclose_
FILE *f
= NULL
;
3646 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
3648 f
= take_fdopen(&fds
[2*k
], "r");
3657 r
= read_etc_hostname_stream(f
, &hostname
);
3659 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
3663 case META_MACHINE_ID
: {
3664 _cleanup_free_
char *line
= NULL
;
3666 r
= read_line(f
, LONG_LINE_MAX
, &line
);
3668 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
3670 r
= sd_id128_from_string(line
, &machine_id
);
3672 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
3674 log_debug("/etc/machine-id file of image is empty.");
3675 else if (streq(line
, "uninitialized"))
3676 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3678 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
3683 case META_MACHINE_INFO
:
3684 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
3686 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
3690 case META_OS_RELEASE
:
3691 r
= load_env_file_pairs(f
, "os-release", &os_release
);
3693 log_debug_errno(r
, "Failed to read OS release file of image: %m");
3697 case META_INITRD_RELEASE
:
3698 r
= load_env_file_pairs(f
, "initrd-release", &initrd_release
);
3700 log_debug_errno(r
, "Failed to read initrd release file of image: %m");
3704 case META_SYSEXT_RELEASE
:
3705 r
= load_env_file_pairs(f
, "sysext-release", &sysext_release
);
3707 log_debug_errno(r
, "Failed to read sysext release file of image: %m");
3711 case META_CONFEXT_RELEASE
:
3712 r
= load_env_file_pairs(f
, "confext-release", &confext_release
);
3714 log_debug_errno(r
, "Failed to read confext release file of image: %m");
3718 case META_HAS_INIT_SYSTEM
: {
3723 nr
= fread(&b
, 1, sizeof(b
), f
);
3724 if (nr
!= sizeof(b
))
3725 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
3727 has_init_system
= b
;
3733 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
3738 n
= read(error_pipe
[0], &v
, sizeof(v
));
3743 if (n
== sizeof(v
)) {
3744 r
= v
; /* propagate error sent to us from child */
3751 if (r
!= EXIT_SUCCESS
) {
3756 free_and_replace(m
->hostname
, hostname
);
3757 m
->machine_id
= machine_id
;
3758 strv_free_and_replace(m
->machine_info
, machine_info
);
3759 strv_free_and_replace(m
->os_release
, os_release
);
3760 strv_free_and_replace(m
->initrd_release
, initrd_release
);
3761 strv_free_and_replace(m
->sysext_release
, sysext_release
);
3762 strv_free_and_replace(m
->confext_release
, confext_release
);
3763 m
->has_init_system
= has_init_system
;
3766 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
3767 safe_close_pair(fds
+ 2*k
);
3772 Architecture
dissected_image_architecture(DissectedImage
*img
) {
3775 if (img
->partitions
[PARTITION_ROOT
].found
&&
3776 img
->partitions
[PARTITION_ROOT
].architecture
>= 0)
3777 return img
->partitions
[PARTITION_ROOT
].architecture
;
3779 if (img
->partitions
[PARTITION_USR
].found
&&
3780 img
->partitions
[PARTITION_USR
].architecture
>= 0)
3781 return img
->partitions
[PARTITION_USR
].architecture
;
3783 return _ARCHITECTURE_INVALID
;
3786 int dissect_loop_device(
3788 const VeritySettings
*verity
,
3789 const MountOptions
*mount_options
,
3790 const ImagePolicy
*image_policy
,
3791 DissectImageFlags flags
,
3792 DissectedImage
**ret
) {
3795 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
3800 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
3804 m
->loop
= loop_device_ref(loop
);
3805 m
->image_size
= m
->loop
->device_size
;
3806 m
->sector_size
= m
->loop
->sector_size
;
3808 r
= dissect_image(m
, loop
->fd
, loop
->node
, verity
, mount_options
, image_policy
, flags
);
3821 int dissect_loop_device_and_warn(
3823 const VeritySettings
*verity
,
3824 const MountOptions
*mount_options
,
3825 const ImagePolicy
*image_policy
,
3826 DissectImageFlags flags
,
3827 DissectedImage
**ret
) {
3831 return dissect_log_error(
3833 dissect_loop_device(loop
, verity
, mount_options
, image_policy
, flags
, ret
),
3834 loop
->backing_file
?: loop
->node
,
3839 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3842 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
3843 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
3844 * images we only check the partition type.
3846 * This call is used to decide whether to suppress or show a verity column in tabular output of the
3849 if (image
->single_file_system
)
3850 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
3852 return partition_verity_of(partition_designator
) >= 0;
3855 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3856 PartitionDesignator k
;
3860 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
3861 * works for the root partition, for others only if the associated verity partition was found. */
3863 if (!image
->verity_ready
)
3866 if (image
->single_file_system
)
3867 return partition_designator
== PARTITION_ROOT
;
3869 k
= partition_verity_of(partition_designator
);
3870 return k
>= 0 && image
->partitions
[k
].found
;
3873 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
3874 PartitionDesignator k
;
3878 /* Checks if this partition has verity signature data available that we can use. */
3880 if (!image
->verity_sig_ready
)
3883 if (image
->single_file_system
)
3884 return partition_designator
== PARTITION_ROOT
;
3886 k
= partition_verity_sig_of(partition_designator
);
3887 return k
>= 0 && image
->partitions
[k
].found
;
3890 MountOptions
* mount_options_free_all(MountOptions
*options
) {
3893 while ((m
= LIST_POP(mount_options
, options
))) {
3901 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
3902 LIST_FOREACH(mount_options
, m
, options
)
3903 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
3909 int mount_image_privately_interactively(
3911 const ImagePolicy
*image_policy
,
3912 DissectImageFlags flags
,
3913 char **ret_directory
,
3915 LoopDevice
**ret_loop_device
) {
3917 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
3918 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
3919 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
3920 _cleanup_free_
char *dir
= NULL
;
3923 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
3924 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
3928 assert(ret_loop_device
);
3930 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
3931 flags
|= DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
3932 DISSECT_IMAGE_PIN_PARTITION_DEVICES
;
3934 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
3936 return log_error_errno(r
, "Failed to load root hash data: %m");
3938 r
= loop_device_make_by_path(
3940 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
3941 /* sector_size= */ UINT32_MAX
,
3942 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
3946 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
3948 r
= dissect_loop_device_and_warn(
3951 /* mount_options= */ NULL
,
3958 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
3962 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
3966 r
= detach_mount_namespace();
3968 return log_error_errno(r
, "Failed to detach mount namespace: %m");
3970 r
= mkdir_p("/run/systemd/mount-rootfs", 0555);
3972 return log_error_errno(r
, "Failed to create mount point: %m");
3974 r
= dissected_image_mount_and_warn(
3976 "/run/systemd/mount-rootfs",
3977 /* uid_shift= */ UID_INVALID
,
3978 /* uid_range= */ UID_INVALID
,
3979 /* userns_fd= */ -EBADF
,
3984 r
= loop_device_flock(d
, LOCK_UN
);
3988 r
= dissected_image_relinquish(dissected_image
);
3990 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
3992 if (ret_directory
) {
3993 dir
= strdup("/run/systemd/mount-rootfs");
3999 _cleanup_close_
int dir_fd
= -EBADF
;
4001 dir_fd
= open("/run/systemd/mount-rootfs", O_CLOEXEC
|O_DIRECTORY
);
4003 return log_error_errno(errno
, "Failed to open mount point directory: %m");
4005 *ret_dir_fd
= TAKE_FD(dir_fd
);
4009 *ret_directory
= TAKE_PTR(dir
);
4011 *ret_loop_device
= TAKE_PTR(d
);
4015 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
4019 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
4020 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
4021 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
4024 int verity_dissect_and_mount(
4028 const MountOptions
*options
,
4029 const ImagePolicy
*image_policy
,
4030 const char *required_host_os_release_id
,
4031 const char *required_host_os_release_version_id
,
4032 const char *required_host_os_release_sysext_level
,
4033 const char *required_host_os_release_confext_level
,
4034 const char *required_sysext_scope
,
4035 DissectedImage
**ret_image
) {
4037 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
4038 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
4039 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
4040 DissectImageFlags dissect_image_flags
;
4041 bool relax_extension_release_check
;
4045 /* Verifying release metadata requires mounted image for now, so ensure the check is skipped when
4046 * opening an image without mounting it immediately (i.e.: 'dest' is NULL). */
4047 assert(!required_host_os_release_id
|| dest
);
4049 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
4051 /* We might get an FD for the image, but we use the original path to look for the dm-verity files */
4052 r
= verity_settings_load(&verity
, src
, NULL
, NULL
);
4054 return log_debug_errno(r
, "Failed to load root hash: %m");
4056 dissect_image_flags
=
4057 (verity
.data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
4058 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_EXTENSION_CHECK
: 0) |
4059 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
4060 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
4061 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
4063 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
4064 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4065 r
= loop_device_make_by_path(
4066 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
4067 /* open_flags= */ -1,
4068 /* sector_size= */ UINT32_MAX
,
4069 verity
.data_path
? 0 : LO_FLAGS_PARTSCAN
,
4073 return log_debug_errno(r
, "Failed to create loop device for image: %m");
4075 r
= dissect_loop_device(
4080 dissect_image_flags
,
4082 /* No partition table? Might be a single-filesystem image, try again */
4083 if (!verity
.data_path
&& r
== -ENOPKG
)
4084 r
= dissect_loop_device(
4089 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
4092 return log_debug_errno(r
, "Failed to dissect image: %m");
4094 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, &verity
);
4098 r
= dissected_image_decrypt(
4102 dissect_image_flags
);
4104 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
4107 r
= mkdir_p_label(dest
, 0755);
4109 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
4110 r
= umount_recursive(dest
, 0);
4112 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
4115 r
= dissected_image_mount(
4118 /* uid_shift= */ UID_INVALID
,
4119 /* uid_range= */ UID_INVALID
,
4120 /* userns_fd= */ -EBADF
,
4121 dissect_image_flags
);
4123 return log_debug_errno(r
, "Failed to mount image: %m");
4125 r
= loop_device_flock(loop_device
, LOCK_UN
);
4127 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
4129 /* If we got os-release values from the caller, then we need to match them with the image's
4130 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
4131 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
4132 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
4133 * then a simple match on the ID will be performed. */
4134 if (required_host_os_release_id
) {
4135 _cleanup_strv_free_
char **extension_release
= NULL
;
4136 ImageClass
class = IMAGE_SYSEXT
;
4138 assert(!isempty(required_host_os_release_id
));
4140 r
= load_extension_release_pairs(dest
, IMAGE_SYSEXT
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
4142 r
= load_extension_release_pairs(dest
, IMAGE_CONFEXT
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
4144 class = IMAGE_CONFEXT
;
4147 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
4149 r
= extension_release_validate(
4150 dissected_image
->image_name
,
4151 required_host_os_release_id
,
4152 required_host_os_release_version_id
,
4153 class == IMAGE_SYSEXT
? required_host_os_release_sysext_level
: required_host_os_release_confext_level
,
4154 required_sysext_scope
,
4158 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
4160 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
4163 r
= dissected_image_relinquish(dissected_image
);
4165 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
4168 *ret_image
= TAKE_PTR(dissected_image
);
4173 int get_common_dissect_directory(char **ret
) {
4174 _cleanup_free_
char *t
= NULL
;
4177 /* A common location we mount dissected images to. The assumption is that everyone who uses this
4178 * function runs in their own private mount namespace (with mount propagation off on /run/systemd/,
4179 * and thus can mount something here without affecting anyone else). */
4181 t
= strdup("/run/systemd/dissect-root");
4183 return log_oom_debug();
4185 r
= mkdir_parents(t
, 0755);
4187 return log_debug_errno(r
, "Failed to create parent dirs of mount point '%s': %m", t
);
4189 r
= RET_NERRNO(mkdir(t
, 0000)); /* It's supposed to be overmounted, hence let's make this inaccessible */
4190 if (r
< 0 && r
!= -EEXIST
)
4191 return log_debug_errno(r
, "Failed to create mount point '%s': %m", t
);
4201 static JSON_DISPATCH_ENUM_DEFINE(dispatch_architecture
, Architecture
, architecture_from_string
);
4202 static JSON_DISPATCH_ENUM_DEFINE(dispatch_partition_designator
, PartitionDesignator
, partition_designator_from_string
);
4204 typedef struct PartitionFields
{
4205 PartitionDesignator designator
;
4209 Architecture architecture
;
4215 unsigned fsmount_fd_idx
;
4218 static void partition_fields_done(PartitionFields
*f
) {
4221 f
->fstype
= mfree(f
->fstype
);
4222 f
->label
= mfree(f
->label
);
4225 typedef struct ReplyParameters
{
4226 JsonVariant
*partitions
;
4228 uint64_t image_size
;
4229 uint32_t sector_size
;
4230 sd_id128_t image_uuid
;
4233 static void reply_parameters_done(ReplyParameters
*p
) {
4236 p
->image_policy
= mfree(p
->image_policy
);
4237 p
->partitions
= json_variant_unref(p
->partitions
);
4242 int mountfsd_mount_image(
4245 const ImagePolicy
*image_policy
,
4246 DissectImageFlags flags
,
4247 DissectedImage
**ret
) {
4250 _cleanup_(reply_parameters_done
) ReplyParameters p
= {};
4252 static const JsonDispatch dispatch_table
[] = {
4253 { "partitions", JSON_VARIANT_ARRAY
, json_dispatch_variant
, offsetof(struct ReplyParameters
, partitions
), JSON_MANDATORY
},
4254 { "imagePolicy", JSON_VARIANT_STRING
, json_dispatch_string
, offsetof(struct ReplyParameters
, image_policy
), 0 },
4255 { "imageSize", _JSON_VARIANT_TYPE_INVALID
, json_dispatch_uint64
, offsetof(struct ReplyParameters
, image_size
), JSON_MANDATORY
},
4256 { "sectorSize", _JSON_VARIANT_TYPE_INVALID
, json_dispatch_uint32
, offsetof(struct ReplyParameters
, sector_size
), JSON_MANDATORY
},
4257 { "imageUuid", JSON_VARIANT_STRING
, json_dispatch_id128
, offsetof(struct ReplyParameters
, image_uuid
), 0 },
4261 _cleanup_(dissected_image_unrefp
) DissectedImage
*di
= NULL
;
4262 _cleanup_close_
int image_fd
= -EBADF
;
4263 _cleanup_(varlink_unrefp
) Varlink
*vl
= NULL
;
4264 _cleanup_free_
char *ps
= NULL
;
4265 unsigned max_fd
= UINT_MAX
;
4266 const char *error_id
;
4272 r
= varlink_connect_address(&vl
, "/run/systemd/io.systemd.MountFileSystem");
4274 return log_error_errno(r
, "Failed to connect to mountfsd: %m");
4276 r
= varlink_set_allow_fd_passing_input(vl
, true);
4278 return log_error_errno(r
, "Failed to enable varlink fd passing for read: %m");
4280 r
= varlink_set_allow_fd_passing_output(vl
, true);
4282 return log_error_errno(r
, "Failed to enable varlink fd passing for write: %m");
4284 image_fd
= open(path
, O_RDONLY
|O_CLOEXEC
);
4286 return log_error_errno(errno
, "Failed to open '%s': %m", path
);
4288 r
= varlink_push_dup_fd(vl
, image_fd
);
4290 return log_error_errno(r
, "Failed to push image fd into varlink connection: %m");
4292 if (userns_fd
>= 0) {
4293 r
= varlink_push_dup_fd(vl
, userns_fd
);
4295 return log_error_errno(r
, "Failed to push image fd into varlink connection: %m");
4299 r
= image_policy_to_string(image_policy
, /* simplify= */ false, &ps
);
4301 return log_error_errno(r
, "Failed format image policy to string: %m");
4304 JsonVariant
*reply
= NULL
;
4307 "io.systemd.MountFileSystem.MountImage",
4311 JSON_BUILD_PAIR("imageFileDescriptor", JSON_BUILD_UNSIGNED(0)),
4312 JSON_BUILD_PAIR_CONDITION(userns_fd
>= 0, "userNamespaceFileDescriptor", JSON_BUILD_UNSIGNED(1)),
4313 JSON_BUILD_PAIR("readOnly", JSON_BUILD_BOOLEAN(FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_READ_ONLY
))),
4314 JSON_BUILD_PAIR("growFileSystems", JSON_BUILD_BOOLEAN(FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
))),
4315 JSON_BUILD_PAIR_CONDITION(ps
, "imagePolicy", JSON_BUILD_STRING(ps
)),
4316 JSON_BUILD_PAIR("allowInteractiveAuthentication", JSON_BUILD_BOOLEAN(FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH
)))));
4318 return log_error_errno(r
, "Failed to call MountImage() varlink call: %m");
4319 if (!isempty(error_id
))
4320 return log_error_errno(varlink_error_to_errno(error_id
, reply
), "Failed to call MountImage() varlink call: %s", error_id
);
4322 r
= json_dispatch(reply
, dispatch_table
, JSON_ALLOW_EXTENSIONS
, &p
);
4324 return log_error_errno(r
, "Failed to parse MountImage() reply: %m");
4326 log_debug("Effective image policy: %s", p
.image_policy
);
4329 JSON_VARIANT_ARRAY_FOREACH(i
, p
.partitions
) {
4330 _cleanup_close_
int fsmount_fd
= -EBADF
;
4332 _cleanup_(partition_fields_done
) PartitionFields pp
= {
4333 .designator
= _PARTITION_DESIGNATOR_INVALID
,
4334 .architecture
= _ARCHITECTURE_INVALID
,
4336 .offset
= UINT64_MAX
,
4337 .fsmount_fd_idx
= UINT_MAX
,
4340 static const JsonDispatch partition_dispatch_table
[] = {
4341 { "designator", JSON_VARIANT_STRING
, dispatch_partition_designator
, offsetof(struct PartitionFields
, designator
), JSON_MANDATORY
},
4342 { "writable", JSON_VARIANT_BOOLEAN
, json_dispatch_boolean
, offsetof(struct PartitionFields
, rw
), JSON_MANDATORY
},
4343 { "growFileSystem", JSON_VARIANT_BOOLEAN
, json_dispatch_boolean
, offsetof(struct PartitionFields
, growfs
), JSON_MANDATORY
},
4344 { "partitionNumber", _JSON_VARIANT_TYPE_INVALID
, json_dispatch_uint
, offsetof(struct PartitionFields
, partno
), 0 },
4345 { "architecture", JSON_VARIANT_STRING
, dispatch_architecture
, offsetof(struct PartitionFields
, architecture
), 0 },
4346 { "partitionUuid", JSON_VARIANT_STRING
, json_dispatch_id128
, offsetof(struct PartitionFields
, uuid
), 0 },
4347 { "fileSystemType", JSON_VARIANT_STRING
, json_dispatch_string
, offsetof(struct PartitionFields
, fstype
), JSON_MANDATORY
},
4348 { "partitionLabel", JSON_VARIANT_STRING
, json_dispatch_string
, offsetof(struct PartitionFields
, label
), 0 },
4349 { "size", _JSON_VARIANT_TYPE_INVALID
, json_dispatch_uint64
, offsetof(struct PartitionFields
, size
), JSON_MANDATORY
},
4350 { "offset", _JSON_VARIANT_TYPE_INVALID
, json_dispatch_uint64
, offsetof(struct PartitionFields
, offset
), JSON_MANDATORY
},
4351 { "mountFileDescriptor", _JSON_VARIANT_TYPE_INVALID
, json_dispatch_uint
, offsetof(struct PartitionFields
, fsmount_fd_idx
), JSON_MANDATORY
},
4355 r
= json_dispatch(i
, partition_dispatch_table
, JSON_ALLOW_EXTENSIONS
, &pp
);
4357 return log_error_errno(r
, "Failed to parse partition data: %m");
4359 if (pp
.fsmount_fd_idx
!= UINT_MAX
) {
4360 if (max_fd
== UINT_MAX
|| pp
.fsmount_fd_idx
> max_fd
)
4361 max_fd
= pp
.fsmount_fd_idx
;
4363 fsmount_fd
= varlink_take_fd(vl
, pp
.fsmount_fd_idx
);
4368 assert(pp
.designator
>= 0);
4371 r
= dissected_image_new(path
, &di
);
4373 return log_error_errno(r
, "Failed to allocated new dissected image structure: %m");
4376 if (di
->partitions
[pp
.designator
].found
)
4377 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Duplicate partition data for '%s'.", partition_designator_to_string(pp
.designator
));
4379 di
->partitions
[pp
.designator
] = (DissectedPartition
) {
4382 .growfs
= pp
.growfs
,
4383 .partno
= pp
.partno
,
4384 .architecture
= pp
.architecture
,
4386 .fstype
= TAKE_PTR(pp
.fstype
),
4387 .label
= TAKE_PTR(pp
.label
),
4388 .mount_node_fd
= -EBADF
,
4390 .offset
= pp
.offset
,
4391 .fsmount_fd
= TAKE_FD(fsmount_fd
),
4395 di
->image_size
= p
.image_size
;
4396 di
->sector_size
= p
.sector_size
;
4397 di
->image_uuid
= p
.image_uuid
;
4399 *ret
= TAKE_PTR(di
);