1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/loop.h>
10 #include <openssl/err.h>
11 #include <openssl/pem.h>
12 #include <openssl/x509.h>
15 #include "sd-device.h"
18 #include "sd-varlink.h"
20 #include "architecture.h"
21 #include "ask-password-api.h"
22 #include "blkid-util.h"
23 #include "blockdev-util.h"
24 #include "btrfs-util.h"
26 #include "conf-files.h"
27 #include "constants.h"
29 #include "cryptsetup-util.h"
30 #include "device-private.h"
31 #include "devnum-util.h"
32 #include "dissect-image.h"
36 #include "errno-util.h"
37 #include "extension-util.h"
38 #include "extract-word.h"
41 #include "format-util.h"
42 #include "fsck-util.h"
44 #include "hash-funcs.h"
45 #include "hexdecoct.h"
46 #include "hostname-setup.h"
47 #include "image-policy.h"
48 #include "import-util.h"
50 #include "json-util.h"
51 #include "loop-util.h"
52 #include "mkdir-label.h"
53 #include "mount-util.h"
54 #include "mountpoint-util.h"
55 #include "namespace-util.h"
56 #include "nulstr-util.h"
57 #include "openssl-util.h"
59 #include "path-util.h"
60 #include "proc-cmdline.h"
61 #include "process-util.h"
62 #include "resize-fs.h"
63 #include "signal-util.h"
64 #include "siphash24.h"
65 #include "stat-util.h"
66 #include "string-util.h"
68 #include "time-util.h"
69 #include "udev-util.h"
70 #include "user-util.h"
71 #include "varlink-util.h"
72 #include "xattr-util.h"
74 /* how many times to wait for the device nodes to appear */
75 #define N_DEVICE_NODE_LIST_ATTEMPTS 10
77 int dissect_fstype_ok(const char *fstype
) {
81 /* When we automatically mount file systems, be a bit conservative by default what we are willing to
82 * mount, just as an extra safety net to not mount with badly maintained legacy file system
85 e
= secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
87 _cleanup_strv_free_
char **l
= NULL
;
89 l
= strv_split(e
, ":");
93 b
= strv_contains(l
, fstype
);
95 b
= STR_IN_SET(fstype
,
106 log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype
);
110 int probe_sector_size(int fd
, uint32_t *ret
) {
112 /* Disk images might be for 512B or for 4096 sector sizes, let's try to auto-detect that by searching
113 * for the GPT headers at the relevant byte offsets */
115 assert_cc(sizeof(GptHeader
) == 92);
117 /* We expect a sector size in the range 512…4096. The GPT header is located in the second
118 * sector. Hence it could be at byte 512 at the earliest, and at byte 4096 at the latest. And we must
119 * read with granularity of the largest sector size we care about. Which means 8K. */
120 uint8_t sectors
[2 * 4096];
127 n
= pread(fd
, sectors
, sizeof(sectors
), 0);
130 if (n
!= sizeof(sectors
)) /* too short? */
133 /* Let's see if we find the GPT partition header with various expected sector sizes */
134 for (uint32_t sz
= 512; sz
<= 4096; sz
<<= 1) {
137 assert(sizeof(sectors
) >= sz
* 2);
138 p
= (const GptHeader
*) (sectors
+ sz
);
140 if (!gpt_header_has_signature(p
))
144 return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
145 "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
151 log_debug("Determined sector size %" PRIu32
" based on discovered partition table.", found
);
153 return 1; /* indicate we *did* find it */
157 log_debug("Couldn't find any partition table to derive sector size of.");
158 *ret
= 512; /* pick the traditional default */
159 return 0; /* indicate we didn't find it */
162 int probe_sector_size_prefer_ioctl(int fd
, uint32_t *ret
) {
168 /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
169 * configured sector size rather than probing by contents */
171 if (fstat(fd
, &st
) < 0)
174 if (S_ISBLK(st
.st_mode
))
175 return blockdev_get_sector_size(fd
, ret
);
177 return probe_sector_size(fd
, ret
);
180 int probe_filesystem_full(
187 /* Try to find device content type and return it in *ret_fstype. If nothing is found,
188 * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
189 * different error otherwise. */
192 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
193 _cleanup_free_
char *path_by_fd
= NULL
;
194 _cleanup_close_
int fd_close
= -EBADF
;
198 assert(fd
>= 0 || path
);
202 fd_close
= open(path
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
210 r
= fd_get_path(fd
, &path_by_fd
);
217 if (size
== 0) /* empty size? nothing found! */
220 b
= blkid_new_probe();
224 /* The Linux kernel maintains separate block device caches for main ("whole") and partition block
225 * devices, which means making a change to one might not be reflected immediately when reading via
226 * the other. That's massively confusing when mixing accesses to such devices. Let's address this in
227 * a limited way: when probing a file system that is not at the beginning of the block device we
228 * apparently probe a partition via the main block device, and in that case let's first flush the
229 * main block device cache, so that we get the data that the per-partition block device last
232 * This only works under the assumption that any tools that write to the partition block devices
233 * issue an syncfs()/fsync() on the device after making changes. Typically file system formatting
234 * tools that write a superblock onto a partition block device do that, however. */
236 if (ioctl(fd
, BLKFLSBUF
, 0) < 0)
237 log_debug_errno(errno
, "Failed to flush block device cache, ignoring: %m");
240 r
= blkid_probe_set_device(
244 size
== UINT64_MAX
? 0 : size
); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
246 return errno_or_else(ENOMEM
);
248 blkid_probe_enable_superblocks(b
, 1);
249 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
);
252 r
= blkid_do_safeprobe(b
);
253 if (r
== _BLKID_SAFEPROBE_NOT_FOUND
)
255 if (r
== _BLKID_SAFEPROBE_AMBIGUOUS
)
256 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
257 "Results ambiguous for partition %s", path
);
258 if (r
== _BLKID_SAFEPROBE_ERROR
)
259 return log_debug_errno(errno_or_else(EIO
), "Failed to probe partition %s: %m", path
);
261 assert(r
== _BLKID_SAFEPROBE_FOUND
);
263 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
266 log_debug("Probed fstype '%s' on partition %s.", fstype
, path
);
267 return strdup_to_full(ret_fstype
, fstype
);
271 log_debug("No type detected on partition %s", path
);
280 static int image_policy_may_use(
281 const ImagePolicy
*policy
,
282 PartitionDesignator designator
) {
284 PartitionPolicyFlags f
;
286 /* For each partition we find in the partition table do a first check if it may exist at all given
287 * the policy, or if it shall be ignored. */
289 f
= image_policy_get_exhaustively(policy
, designator
);
293 if ((f
& _PARTITION_POLICY_USE_MASK
) == PARTITION_POLICY_ABSENT
)
294 /* only flag set in policy is "absent"? then this partition may not exist at all */
295 return log_debug_errno(
296 SYNTHETIC_ERRNO(ERFKILL
),
297 "Partition of designator '%s' exists, but not allowed by policy, refusing.",
298 partition_designator_to_string(designator
));
299 if ((f
& _PARTITION_POLICY_USE_MASK
& ~PARTITION_POLICY_ABSENT
) == PARTITION_POLICY_UNUSED
) {
300 /* only "unused" or "unused" + "absent" are set? then don't use it */
301 log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
302 partition_designator_to_string(designator
));
303 return false; /* ignore! */
306 return true; /* use! */
309 static int image_policy_check_protection(
310 const ImagePolicy
*policy
,
311 PartitionDesignator designator
,
312 PartitionPolicyFlags found_flags
) {
314 PartitionPolicyFlags policy_flags
;
316 /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
321 policy_flags
= image_policy_get_exhaustively(policy
, designator
);
322 if (policy_flags
< 0)
325 if ((found_flags
& policy_flags
) == 0) {
326 _cleanup_free_
char *found_flags_string
= NULL
, *policy_flags_string
= NULL
;
328 (void) partition_policy_flags_to_string(found_flags
, /* simplify= */ true, &found_flags_string
);
329 (void) partition_policy_flags_to_string(policy_flags
, /* simplify= */ true, &policy_flags_string
);
331 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
332 partition_designator_to_string(designator
),
333 strnull(found_flags_string
), strnull(policy_flags_string
));
339 static int image_policy_check_partition_flags(
340 const ImagePolicy
*policy
,
341 PartitionDesignator designator
,
342 uint64_t gpt_flags
) {
344 PartitionPolicyFlags policy_flags
;
347 /* Checks if the partition flags in the policy match reality */
349 policy_flags
= image_policy_get_exhaustively(policy
, designator
);
350 if (policy_flags
< 0)
353 b
= FLAGS_SET(gpt_flags
, SD_GPT_FLAG_READ_ONLY
);
354 if ((policy_flags
& _PARTITION_POLICY_READ_ONLY_MASK
) == (b
? PARTITION_POLICY_READ_ONLY_OFF
: PARTITION_POLICY_READ_ONLY_ON
))
355 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
356 partition_designator_to_string(designator
),
357 one_zero(!b
), one_zero(b
));
359 b
= FLAGS_SET(gpt_flags
, SD_GPT_FLAG_GROWFS
);
360 if ((policy_flags
& _PARTITION_POLICY_GROWFS_MASK
) == (b
? PARTITION_POLICY_GROWFS_OFF
: PARTITION_POLICY_GROWFS_ON
))
361 return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL
), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
362 partition_designator_to_string(designator
),
363 one_zero(!b
), one_zero(b
));
368 static int dissected_image_probe_filesystems(
371 const ImagePolicy
*policy
) {
377 /* Fill in file system types if we don't know them yet. */
379 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
380 DissectedPartition
*p
= m
->partitions
+ i
;
381 PartitionPolicyFlags found_flags
;
387 /* If we have an fd referring to the partition block device, use that. Otherwise go
388 * via the whole block device or backing regular file, and read via offset. */
389 if (p
->mount_node_fd
>= 0)
390 r
= probe_filesystem_full(p
->mount_node_fd
, p
->node
, 0, UINT64_MAX
, &p
->fstype
);
392 r
= probe_filesystem_full(fd
, p
->node
, p
->offset
, p
->size
, &p
->fstype
);
397 if (streq_ptr(p
->fstype
, "crypto_LUKS")) {
399 found_flags
= PARTITION_POLICY_UNUSED
|PARTITION_POLICY_ENCRYPTED
; /* found this one, and its definitely encrypted */
401 /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
402 * set all other ways that indicate "present". */
403 found_flags
= PARTITION_POLICY_UNUSED
|PARTITION_POLICY_UNPROTECTED
|PARTITION_POLICY_VERITY
|PARTITION_POLICY_SIGNED
;
405 if (p
->fstype
&& fstype_is_ro(p
->fstype
))
411 /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
412 * hence we need to validate this against policy again, to see if the policy still matches
413 * with this new information. Note that image_policy_check_protection() will check for
414 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
415 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
416 * OR verity OR signed), but that's fine since the earlier policy check already checked more
417 * specific which of those three cases where OK. Keep in mind that this function here only
418 * looks at specific partitions (and thus can only deduce encryption or not) but not the
419 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
420 * checks already did the relevant checks that look at the whole partition table, and
421 * enforced policy there as needed. */
422 r
= image_policy_check_protection(policy
, i
, found_flags
);
430 static void check_partition_flags(
432 unsigned long long pflags
,
433 unsigned long long supported
) {
437 /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
438 pflags
&= ~(supported
|
439 SD_GPT_FLAG_REQUIRED_PARTITION
|
440 SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
|
441 SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE
);
446 /* If there are other bits set, then log about it, to make things discoverable */
447 for (unsigned i
= 0; i
< sizeof(pflags
) * 8; i
++) {
448 unsigned long long bit
= 1ULL << i
;
449 if (!FLAGS_SET(pflags
, bit
))
452 log_debug("Unexpected partition flag %llu set on %s!", bit
, node
);
456 static int dissected_image_new(const char *path
, DissectedImage
**ret
) {
457 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
458 _cleanup_free_
char *name
= NULL
;
464 _cleanup_free_
char *filename
= NULL
;
466 r
= path_extract_filename(path
, &filename
);
470 r
= raw_strip_suffixes(filename
, &name
);
474 if (!image_name_is_valid(name
)) {
475 log_debug("Image name %s is not valid, ignoring.", strna(name
));
480 m
= new(DissectedImage
, 1);
484 *m
= (DissectedImage
) {
485 .has_init_system
= -1,
486 .image_name
= TAKE_PTR(name
),
489 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
490 m
->partitions
[i
] = DISSECTED_PARTITION_NULL
;
497 static void dissected_partition_done(DissectedPartition
*p
) {
503 free(p
->decrypted_fstype
);
504 free(p
->decrypted_node
);
505 free(p
->mount_options
);
506 safe_close(p
->mount_node_fd
);
507 safe_close(p
->fsmount_fd
);
509 *p
= DISSECTED_PARTITION_NULL
;
513 static int diskseq_should_be_used(
514 const char *whole_devname
,
516 DissectImageFlags flags
) {
520 assert(whole_devname
);
522 /* No diskseq. We cannot use by-diskseq symlink. */
526 /* Do not use by-diskseq link unless DISSECT_IMAGE_DISKSEQ_DEVNODE flag is explicitly set. */
527 if (!FLAGS_SET(flags
, DISSECT_IMAGE_DISKSEQ_DEVNODE
))
530 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
531 r
= sd_device_new_from_devname(&dev
, whole_devname
);
535 /* When ID_IGNORE_DISKSEQ udev property is set, the by-diskseq symlink will not be created. */
536 r
= device_get_property_bool(dev
, "ID_IGNORE_DISKSEQ");
538 return !r
; /* If explicitly specified, use it. */
545 static int make_partition_devname(
546 const char *whole_devname
,
549 DissectImageFlags flags
,
552 _cleanup_free_
char *s
= NULL
;
555 assert(whole_devname
);
556 assert(nr
!= 0); /* zero is not a valid partition nr */
559 r
= diskseq_should_be_used(whole_devname
, diskseq
, flags
);
561 log_debug_errno(r
, "Failed to determine if diskseq should be used for %s, assuming no, ignoring: %m", whole_devname
);
563 /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
564 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
565 * block device node name ends in a digit, then suffix a 'p', followed by the partition
566 * number. Otherwise, just suffix the partition number without any 'p'. */
568 if (nr
< 0) { /* whole disk? */
569 s
= strdup(whole_devname
);
573 size_t l
= strlen(whole_devname
);
574 if (l
< 1) /* underflow check for the subtraction below */
577 bool need_p
= ascii_isdigit(whole_devname
[l
-1]); /* Last char a digit? */
579 if (asprintf(&s
, "%s%s%i", whole_devname
, need_p
? "p" : "", nr
) < 0)
583 if (nr
< 0) /* whole disk? */
584 r
= asprintf(&s
, "/dev/disk/by-diskseq/%" PRIu64
, diskseq
);
586 r
= asprintf(&s
, "/dev/disk/by-diskseq/%" PRIu64
"-part%i", diskseq
, nr
);
595 static int open_partition(
598 const LoopDevice
*loop
) {
600 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
601 _cleanup_close_
int fd
= -EBADF
;
608 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
612 /* Check if the block device is a child of (or equivalent to) the originally provided one. */
613 r
= block_device_new_from_fd(fd
, is_partition
? BLOCK_DEVICE_LOOKUP_WHOLE_DISK
: 0, &dev
);
617 r
= sd_device_get_devnum(dev
, &devnum
);
621 if (loop
->devno
!= devnum
)
624 /* Also check diskseq. */
625 if (loop
->diskseq
!= 0) {
628 r
= fd_get_diskseq(fd
, &diskseq
);
632 if (loop
->diskseq
!= diskseq
)
636 log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR
", diskseq=%" PRIu64
").",
637 node
, fd
, DEVNUM_FORMAT_VAL(loop
->devno
), loop
->diskseq
);
641 static int compare_arch(Architecture a
, Architecture b
) {
645 if (a
== native_architecture())
648 if (b
== native_architecture())
651 #ifdef ARCHITECTURE_SECONDARY
652 if (a
== ARCHITECTURE_SECONDARY
)
655 if (b
== ARCHITECTURE_SECONDARY
)
662 static bool image_filter_test(const ImageFilter
*filter
, PartitionDesignator d
, const char *label
) {
663 assert(d
< _PARTITION_DESIGNATOR_MAX
);
665 if (d
< 0) /* For unspecified designators we have no filter expression */
668 if (!filter
|| !filter
->pattern
[d
])
671 return fnmatch(filter
->pattern
[d
], strempty(label
), FNM_NOESCAPE
) == 0;
674 static int dissect_image(
678 const VeritySettings
*verity
,
679 const MountOptions
*mount_options
,
680 const ImagePolicy
*policy
,
681 const ImageFilter
*filter
,
682 DissectImageFlags flags
) {
684 sd_id128_t root_uuid
= SD_ID128_NULL
, root_verity_uuid
= SD_ID128_NULL
;
685 sd_id128_t usr_uuid
= SD_ID128_NULL
, usr_verity_uuid
= SD_ID128_NULL
;
686 bool is_gpt
, is_mbr
, multiple_generic
= false,
687 generic_rw
= false, /* initialize to appease gcc */
688 generic_growfs
= false;
689 _cleanup_(blkid_free_probep
) blkid_probe b
= NULL
;
690 _cleanup_free_
char *generic_node
= NULL
;
691 sd_id128_t generic_uuid
= SD_ID128_NULL
;
692 const char *pttype
= NULL
, *sptuuid
= NULL
;
694 int r
, generic_nr
= -1, n_partitions
;
699 assert(!verity
|| verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
700 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
701 assert(!verity
|| verity
->root_hash_sig
|| verity
->root_hash_sig_size
== 0);
702 assert(!verity
|| (verity
->root_hash
|| !verity
->root_hash_sig
));
703 assert(!((flags
& DISSECT_IMAGE_GPT_ONLY
) && (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)));
704 assert(m
->sector_size
> 0);
706 /* Probes a disk image, and returns information about what it found in *ret.
708 * Returns -ENOPKG if no suitable partition table or file system could be found.
709 * Returns -EADDRNOTAVAIL if a root hash was specified but no matching root/verity partitions found.
710 * Returns -ENXIO if we couldn't find any partition suitable as root or /usr partition
711 * Returns -ENOTUNIQ if we only found multiple generic partitions and thus don't know what to do with that
712 * Returns -ERFKILL if image doesn't match image policy
713 * 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)
714 * Returns -EPROTONOSUPPORT if DISSECT_IMAGE_ADD_PARTITION_DEVICES is set but the block device does not have partition logic enabled
715 * Returns -ENOMSG if we didn't find a single usable partition (and DISSECT_IMAGE_REFUSE_EMPTY is set)
716 * Returns -EUCLEAN if some file system had an ambiguous file system superblock signature
719 uint64_t diskseq
= m
->loop
? m
->loop
->diskseq
: 0;
721 if (verity
&& verity
->root_hash
) {
722 sd_id128_t fsuuid
, vuuid
;
724 /* If a root hash is supplied, then we use the root partition that has a UUID that match the
725 * first 128-bit of the root hash. And we use the verity partition that has a UUID that match
726 * the final 128-bit. */
728 if (verity
->root_hash_size
< sizeof(sd_id128_t
))
731 memcpy(&fsuuid
, verity
->root_hash
, sizeof(sd_id128_t
));
732 memcpy(&vuuid
, (const uint8_t*) verity
->root_hash
+ verity
->root_hash_size
- sizeof(sd_id128_t
), sizeof(sd_id128_t
));
734 if (sd_id128_is_null(fsuuid
))
736 if (sd_id128_is_null(vuuid
))
739 /* If the verity data declares it's for the /usr partition, then search for that, in all
740 * other cases assume it's for the root partition. */
741 if (verity
->designator
== PARTITION_USR
) {
743 usr_verity_uuid
= vuuid
;
746 root_verity_uuid
= vuuid
;
750 b
= blkid_new_probe();
755 r
= blkid_probe_set_device(b
, fd
, 0, 0);
757 return errno_or_else(ENOMEM
);
760 r
= blkid_probe_set_sectorsize(b
, m
->sector_size
);
762 return errno_or_else(EIO
);
764 if ((flags
& DISSECT_IMAGE_GPT_ONLY
) == 0) {
765 /* Look for file system superblocks, unless we only shall look for GPT partition tables */
766 blkid_probe_enable_superblocks(b
, 1);
767 blkid_probe_set_superblocks_flags(b
, BLKID_SUBLKS_TYPE
|BLKID_SUBLKS_USAGE
|BLKID_SUBLKS_UUID
);
770 blkid_probe_enable_partitions(b
, 1);
771 blkid_probe_set_partitions_flags(b
, BLKID_PARTS_ENTRY_DETAILS
);
774 r
= blkid_do_safeprobe(b
);
775 if (r
== _BLKID_SAFEPROBE_ERROR
)
776 return errno_or_else(EIO
);
777 if (IN_SET(r
, _BLKID_SAFEPROBE_AMBIGUOUS
, _BLKID_SAFEPROBE_NOT_FOUND
))
778 return log_debug_errno(SYNTHETIC_ERRNO(ENOPKG
), "Failed to identify any partition table.");
780 assert(r
== _BLKID_SAFEPROBE_FOUND
);
782 if ((!(flags
& DISSECT_IMAGE_GPT_ONLY
) &&
783 (flags
& DISSECT_IMAGE_GENERIC_ROOT
)) ||
784 (flags
& DISSECT_IMAGE_NO_PARTITION_TABLE
)) {
785 const char *usage
= NULL
;
787 /* If flags permit this, also allow using non-partitioned single-filesystem images */
789 (void) blkid_probe_lookup_value(b
, "USAGE", &usage
, NULL
);
790 if (STRPTR_IN_SET(usage
, "filesystem", "crypto")) {
791 _cleanup_free_
char *t
= NULL
, *n
= NULL
, *o
= NULL
;
792 const char *fstype
= NULL
, *options
= NULL
, *suuid
= NULL
;
793 _cleanup_close_
int mount_node_fd
= -EBADF
;
794 sd_id128_t uuid
= SD_ID128_NULL
;
795 PartitionPolicyFlags found_flags
;
798 /* OK, we have found a file system, that's our root partition then. */
800 if (!image_filter_test(filter
, PARTITION_ROOT
, /* label= */ NULL
)) /* do a filter check with an empty partition label */
803 r
= image_policy_may_use(policy
, PARTITION_ROOT
);
806 if (r
== 0) /* policy says ignore this, so we ignore it */
809 (void) blkid_probe_lookup_value(b
, "TYPE", &fstype
, NULL
);
810 (void) blkid_probe_lookup_value(b
, "UUID", &suuid
, NULL
);
812 encrypted
= streq_ptr(fstype
, "crypto_LUKS");
814 if (verity_settings_data_covers(verity
, PARTITION_ROOT
))
815 found_flags
= verity
->root_hash_sig
? PARTITION_POLICY_SIGNED
: PARTITION_POLICY_VERITY
;
817 found_flags
= encrypted
? PARTITION_POLICY_ENCRYPTED
: PARTITION_POLICY_UNPROTECTED
;
819 r
= image_policy_check_protection(policy
, PARTITION_ROOT
, found_flags
);
823 r
= image_policy_check_partition_flags(policy
, PARTITION_ROOT
, 0); /* we have no gpt partition flags, hence check against all bits off */
827 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
828 mount_node_fd
= open_partition(devname
, /* is_partition = */ false, m
->loop
);
829 if (mount_node_fd
< 0)
830 return mount_node_fd
;
840 /* blkid will return FAT's serial number as UUID, hence it is quite possible
841 * that parsing this will fail. We'll ignore the ID, since it's just too
842 * short to be useful as true identifier. */
843 r
= sd_id128_from_string(suuid
, &uuid
);
845 log_debug_errno(r
, "Failed to parse file system UUID '%s', ignoring: %m", suuid
);
848 r
= make_partition_devname(devname
, diskseq
, -1, flags
, &n
);
852 m
->single_file_system
= true;
853 m
->encrypted
= encrypted
;
855 m
->has_verity
= verity
&& verity
->data_path
;
856 m
->verity_ready
= verity_settings_data_covers(verity
, PARTITION_ROOT
);
858 m
->has_verity_sig
= false; /* signature not embedded, must be specified */
859 m
->verity_sig_ready
= m
->verity_ready
&& verity
->root_hash_sig
;
861 m
->image_uuid
= uuid
;
863 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
870 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
872 .rw
= !m
->verity_ready
&& !fstype_is_ro(fstype
),
874 .architecture
= _ARCHITECTURE_INVALID
,
875 .fstype
= TAKE_PTR(t
),
877 .mount_options
= TAKE_PTR(o
),
878 .mount_node_fd
= TAKE_FD(mount_node_fd
),
881 .fsmount_fd
= -EBADF
,
888 (void) blkid_probe_lookup_value(b
, "PTTYPE", &pttype
, NULL
);
892 is_gpt
= streq_ptr(pttype
, "gpt");
893 is_mbr
= streq_ptr(pttype
, "dos");
895 if (!is_gpt
&& ((flags
& DISSECT_IMAGE_GPT_ONLY
) || !is_mbr
))
898 /* We support external verity data partitions only if the image has no partition table */
899 if (verity
&& verity
->data_path
)
902 if (FLAGS_SET(flags
, DISSECT_IMAGE_ADD_PARTITION_DEVICES
)) {
903 /* Safety check: refuse block devices that carry a partition table but for which the kernel doesn't
904 * do partition scanning. */
905 r
= blockdev_partscan_enabled_fd(fd
);
909 return -EPROTONOSUPPORT
;
912 (void) blkid_probe_lookup_value(b
, "PTUUID", &sptuuid
, NULL
);
914 r
= sd_id128_from_string(sptuuid
, &m
->image_uuid
);
916 log_debug_errno(r
, "Failed to parse partition table UUID '%s', ignoring: %m", sptuuid
);
920 pl
= blkid_probe_get_partitions(b
);
922 return errno_or_else(ENOMEM
);
925 n_partitions
= blkid_partlist_numof_partitions(pl
);
926 if (n_partitions
< 0)
927 return errno_or_else(EIO
);
929 for (int i
= 0; i
< n_partitions
; i
++) {
930 _cleanup_free_
char *node
= NULL
;
931 unsigned long long pflags
;
932 blkid_loff_t start
, size
;
937 pp
= blkid_partlist_get_partition(pl
, i
);
939 return errno_or_else(EIO
);
941 pflags
= blkid_partition_get_flags(pp
);
944 nr
= blkid_partition_get_partno(pp
);
946 return errno_or_else(EIO
);
949 start
= blkid_partition_get_start(pp
);
951 return errno_or_else(EIO
);
953 assert((uint64_t) start
< UINT64_MAX
/512);
956 size
= blkid_partition_get_size(pp
);
958 return errno_or_else(EIO
);
960 assert((uint64_t) size
< UINT64_MAX
/512);
962 /* While probing we need the non-diskseq device node name to access the thing, hence mask off
963 * DISSECT_IMAGE_DISKSEQ_DEVNODE. */
964 r
= make_partition_devname(devname
, diskseq
, nr
, flags
& ~DISSECT_IMAGE_DISKSEQ_DEVNODE
, &node
);
968 /* So here's the thing: after the main ("whole") block device popped up it might take a while
969 * before the kernel fully probed the partition table. Waiting for that to finish is icky in
970 * userspace. So here's what we do instead. We issue the BLKPG_ADD_PARTITION ioctl to add the
971 * partition ourselves, racing against the kernel. Good thing is: if this call fails with
972 * EBUSY then the kernel was quicker than us, and that's totally OK, the outcome is good for
973 * us: the device node will exist. If OTOH our call was successful we won the race. Which is
974 * also good as the outcome is the same: the partition block device exists, and we can use
977 * Kernel returns EBUSY if there's already a partition by that number or an overlapping
978 * partition already existent. */
980 if (FLAGS_SET(flags
, DISSECT_IMAGE_ADD_PARTITION_DEVICES
)) {
981 r
= block_device_add_partition(fd
, node
, nr
, (uint64_t) start
* 512, (uint64_t) size
* 512);
984 return log_debug_errno(r
, "BLKPG_ADD_PARTITION failed: %m");
986 log_debug_errno(r
, "Kernel was quicker than us in adding partition %i.", nr
);
988 log_debug("We were quicker than kernel in adding partition %i.", nr
);
992 const char *fstype
= NULL
, *label
;
993 sd_id128_t type_id
, id
;
994 GptPartitionType type
;
995 bool rw
= true, growfs
= false;
997 r
= blkid_partition_get_uuid_id128(pp
, &id
);
999 log_debug_errno(r
, "Failed to read partition UUID, ignoring: %m");
1003 r
= blkid_partition_get_type_id128(pp
, &type_id
);
1005 log_debug_errno(r
, "Failed to read partition type UUID, ignoring: %m");
1009 type
= gpt_partition_type_from_uuid(type_id
);
1011 label
= blkid_partition_get_name(pp
); /* libblkid returns NULL here if empty */
1013 /* systemd-sysupdate expects empty partitions to be marked with an "_empty" label, hence ignore them here. */
1014 if (streq_ptr(label
, "_empty"))
1017 if (!image_filter_test(filter
, type
.designator
, label
))
1020 log_debug("Dissecting %s partition with label %s and UUID %s",
1021 strna(partition_designator_to_string(type
.designator
)), strna(label
), SD_ID128_TO_UUID_STRING(id
));
1023 if (IN_SET(type
.designator
,
1029 check_partition_flags(node
, pflags
,
1030 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1032 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1035 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1036 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1038 } else if (type
.designator
== PARTITION_ESP
) {
1040 /* Note that we don't check the SD_GPT_FLAG_NO_AUTO flag for the ESP, as it is
1041 * not defined there. We instead check the SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL, as
1042 * recommended by the UEFI spec (See "12.3.3 Number and Location of System
1045 if (pflags
& SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL
)
1050 } else if (type
.designator
== PARTITION_ROOT
) {
1052 check_partition_flags(node
, pflags
,
1053 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1055 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1058 /* If a root ID is specified, ignore everything but the root id */
1059 if (!sd_id128_is_null(root_uuid
) && !sd_id128_equal(root_uuid
, id
))
1062 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1063 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1065 } else if (type
.designator
== PARTITION_ROOT_VERITY
) {
1067 check_partition_flags(node
, pflags
,
1068 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1070 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1073 m
->has_verity
= true;
1075 /* If no verity configuration is specified, then don't do verity */
1078 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
1081 /* If root hash is specified, then ignore everything but the root id */
1082 if (!sd_id128_is_null(root_verity_uuid
) && !sd_id128_equal(root_verity_uuid
, id
))
1085 fstype
= "DM_verity_hash";
1088 } else if (type
.designator
== PARTITION_ROOT_VERITY_SIG
) {
1090 check_partition_flags(node
, pflags
,
1091 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1093 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1096 m
->has_verity_sig
= true;
1100 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_ROOT
)
1103 fstype
= "verity_hash_signature";
1106 } else if (type
.designator
== PARTITION_USR
) {
1108 check_partition_flags(node
, pflags
,
1109 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1111 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1114 /* If a usr ID is specified, ignore everything but the usr id */
1115 if (!sd_id128_is_null(usr_uuid
) && !sd_id128_equal(usr_uuid
, id
))
1118 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1119 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1121 } else if (type
.designator
== PARTITION_USR_VERITY
) {
1123 check_partition_flags(node
, pflags
,
1124 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1126 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1129 m
->has_verity
= true;
1133 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
1136 /* If usr hash is specified, then ignore everything but the usr id */
1137 if (!sd_id128_is_null(usr_verity_uuid
) && !sd_id128_equal(usr_verity_uuid
, id
))
1140 fstype
= "DM_verity_hash";
1143 } else if (type
.designator
== PARTITION_USR_VERITY_SIG
) {
1145 check_partition_flags(node
, pflags
,
1146 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
);
1148 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1151 m
->has_verity_sig
= true;
1155 if (verity
->designator
>= 0 && verity
->designator
!= PARTITION_USR
)
1158 fstype
= "verity_hash_signature";
1161 } else if (type
.designator
== PARTITION_SWAP
) {
1163 check_partition_flags(node
, pflags
, SD_GPT_FLAG_NO_AUTO
);
1165 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1168 /* Note: we don't set fstype = "swap" here, because we still need to probe if
1169 * it might be encrypted (i.e. fstype "crypt_LUKS") or unencrypted
1170 * (i.e. fstype "swap"), and the only way to figure that out is via fstype
1173 /* We don't have a designator for SD_GPT_LINUX_GENERIC so check the UUID instead. */
1174 } else if (sd_id128_equal(type
.uuid
, SD_GPT_LINUX_GENERIC
)) {
1176 if (!image_filter_test(filter
, PARTITION_ROOT
, label
))
1179 check_partition_flags(node
, pflags
,
1180 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1182 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1186 multiple_generic
= true;
1189 generic_rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1190 generic_growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1192 generic_node
= TAKE_PTR(node
);
1195 } else if (type
.designator
== PARTITION_VAR
) {
1197 check_partition_flags(node
, pflags
,
1198 SD_GPT_FLAG_NO_AUTO
| SD_GPT_FLAG_READ_ONLY
| SD_GPT_FLAG_GROWFS
);
1200 if (pflags
& SD_GPT_FLAG_NO_AUTO
)
1203 if (!FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_VAR_CHECK
)) {
1204 sd_id128_t var_uuid
;
1206 /* For /var we insist that the uuid of the partition matches the
1207 * HMAC-SHA256 of the /var GPT partition type uuid, keyed by machine
1208 * ID. Why? Unlike the other partitions /var is inherently
1209 * installation specific, hence we need to be careful not to mount it
1210 * in the wrong installation. By hashing the partition UUID from
1211 * /etc/machine-id we can securely bind the partition to the
1214 r
= sd_id128_get_machine_app_specific(SD_GPT_VAR
, &var_uuid
);
1218 if (!sd_id128_equal(var_uuid
, id
)) {
1219 log_debug("Found a /var/ partition, but its UUID didn't match our expectations "
1220 "(found: " SD_ID128_UUID_FORMAT_STR
", expected: " SD_ID128_UUID_FORMAT_STR
"), ignoring.",
1221 SD_ID128_FORMAT_VAL(id
), SD_ID128_FORMAT_VAL(var_uuid
));
1226 rw
= !(pflags
& SD_GPT_FLAG_READ_ONLY
);
1227 growfs
= FLAGS_SET(pflags
, SD_GPT_FLAG_GROWFS
);
1230 if (type
.designator
!= _PARTITION_DESIGNATOR_INVALID
) {
1231 _cleanup_free_
char *t
= NULL
, *o
= NULL
, *l
= NULL
, *n
= NULL
;
1232 _cleanup_close_
int mount_node_fd
= -EBADF
;
1233 const char *options
= NULL
;
1235 r
= image_policy_may_use(policy
, type
.designator
);
1239 /* Policy says: ignore; Remember this fact, so that we later can distinguish between "found but ignored" and "not found at all" */
1241 if (!m
->partitions
[type
.designator
].found
)
1242 m
->partitions
[type
.designator
].ignored
= true;
1247 if (m
->partitions
[type
.designator
].found
) {
1250 /* For most partition types the first one we see wins. Except for the
1251 * rootfs and /usr, where we do a version compare of the label, and
1252 * let the newest version win. This permits a simple A/B versioning
1253 * scheme in OS images. */
1255 c
= compare_arch(type
.arch
, m
->partitions
[type
.designator
].architecture
);
1256 if (c
< 0) /* the arch we already found is better than the one we found now */
1258 if (c
== 0 && /* same arch? then go by version in label */
1259 (!partition_designator_is_versioned(type
.designator
) ||
1260 strverscmp_improved(label
, m
->partitions
[type
.designator
].label
) <= 0))
1263 dissected_partition_done(m
->partitions
+ type
.designator
);
1266 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
) &&
1267 type
.designator
!= PARTITION_SWAP
) {
1268 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
1269 if (mount_node_fd
< 0)
1270 return mount_node_fd
;
1273 r
= make_partition_devname(devname
, diskseq
, nr
, flags
, &n
);
1289 options
= mount_options_from_designator(mount_options
, type
.designator
);
1291 o
= strdup(options
);
1296 m
->partitions
[type
.designator
] = (DissectedPartition
) {
1301 .architecture
= type
.arch
,
1302 .node
= TAKE_PTR(n
),
1303 .fstype
= TAKE_PTR(t
),
1304 .label
= TAKE_PTR(l
),
1306 .mount_options
= TAKE_PTR(o
),
1307 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1308 .offset
= (uint64_t) start
* 512,
1309 .size
= (uint64_t) size
* 512,
1310 .gpt_flags
= pflags
,
1311 .fsmount_fd
= -EBADF
,
1315 } else if (is_mbr
) {
1317 switch (blkid_partition_get_type(pp
)) {
1319 case 0x83: /* Linux partition */
1321 if (pflags
!= 0x80) /* Bootable flag */
1324 if (!image_filter_test(filter
, PARTITION_ROOT
, /* label= */ NULL
))
1328 multiple_generic
= true;
1332 generic_growfs
= false;
1333 generic_node
= TAKE_PTR(node
);
1338 case 0xEA: { /* Boot Loader Spec extended $BOOT partition */
1339 _cleanup_close_
int mount_node_fd
= -EBADF
;
1340 _cleanup_free_
char *o
= NULL
, *n
= NULL
;
1341 sd_id128_t id
= SD_ID128_NULL
;
1342 const char *options
= NULL
;
1344 if (!image_filter_test(filter
, PARTITION_XBOOTLDR
, /* label= */ NULL
))
1347 r
= image_policy_may_use(policy
, PARTITION_XBOOTLDR
);
1350 if (r
== 0) { /* policy says: ignore */
1351 if (!m
->partitions
[PARTITION_XBOOTLDR
].found
)
1352 m
->partitions
[PARTITION_XBOOTLDR
].ignored
= true;
1357 /* First one wins */
1358 if (m
->partitions
[PARTITION_XBOOTLDR
].found
)
1361 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
1362 mount_node_fd
= open_partition(node
, /* is_partition = */ true, m
->loop
);
1363 if (mount_node_fd
< 0)
1364 return mount_node_fd
;
1367 (void) blkid_partition_get_uuid_id128(pp
, &id
);
1369 r
= make_partition_devname(devname
, diskseq
, nr
, flags
, &n
);
1373 options
= mount_options_from_designator(mount_options
, PARTITION_XBOOTLDR
);
1375 o
= strdup(options
);
1380 m
->partitions
[PARTITION_XBOOTLDR
] = (DissectedPartition
) {
1385 .architecture
= _ARCHITECTURE_INVALID
,
1386 .node
= TAKE_PTR(n
),
1388 .mount_options
= TAKE_PTR(o
),
1389 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1390 .offset
= (uint64_t) start
* 512,
1391 .size
= (uint64_t) size
* 512,
1392 .fsmount_fd
= -EBADF
,
1400 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1401 (m
->partitions
[PARTITION_ROOT_VERITY
].found
||
1402 m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
))
1403 return -EADDRNOTAVAIL
; /* Verity found but no matching rootfs? Something is off, refuse. */
1405 /* Hmm, we found a signature partition but no Verity data? Something is off. */
1406 if (m
->partitions
[PARTITION_ROOT_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_ROOT_VERITY
].found
)
1407 return -EADDRNOTAVAIL
;
1409 if (!m
->partitions
[PARTITION_USR
].found
&&
1410 (m
->partitions
[PARTITION_USR_VERITY
].found
||
1411 m
->partitions
[PARTITION_USR_VERITY_SIG
].found
))
1412 return -EADDRNOTAVAIL
; /* as above */
1415 if (m
->partitions
[PARTITION_USR_VERITY_SIG
].found
&& !m
->partitions
[PARTITION_USR_VERITY
].found
)
1416 return -EADDRNOTAVAIL
;
1418 /* If root and /usr are combined then insist that the architecture matches */
1419 if (m
->partitions
[PARTITION_ROOT
].found
&&
1420 m
->partitions
[PARTITION_USR
].found
&&
1421 (m
->partitions
[PARTITION_ROOT
].architecture
>= 0 &&
1422 m
->partitions
[PARTITION_USR
].architecture
>= 0 &&
1423 m
->partitions
[PARTITION_ROOT
].architecture
!= m
->partitions
[PARTITION_USR
].architecture
))
1424 return -EADDRNOTAVAIL
;
1426 if (!m
->partitions
[PARTITION_ROOT
].found
&&
1427 !m
->partitions
[PARTITION_USR
].found
&&
1428 (flags
& DISSECT_IMAGE_GENERIC_ROOT
) &&
1429 (!verity
|| !verity
->root_hash
|| verity
->designator
!= PARTITION_USR
)) {
1431 /* OK, we found nothing usable, then check if there's a single generic partition, and use
1432 * that. If the root hash was set however, then we won't fall back to a generic node, because
1433 * the root hash decides. */
1435 /* If we didn't find a properly marked root partition, but we did find a single suitable
1436 * generic Linux partition, then use this as root partition, if the caller asked for it. */
1437 if (multiple_generic
)
1440 /* If we didn't find a generic node, then we can't fix this up either */
1442 r
= image_policy_may_use(policy
, PARTITION_ROOT
);
1446 /* Policy says: ignore; remember that we did */
1447 m
->partitions
[PARTITION_ROOT
].ignored
= true;
1449 _cleanup_close_
int mount_node_fd
= -EBADF
;
1450 _cleanup_free_
char *o
= NULL
, *n
= NULL
;
1451 const char *options
;
1453 if (FLAGS_SET(flags
, DISSECT_IMAGE_PIN_PARTITION_DEVICES
)) {
1454 mount_node_fd
= open_partition(generic_node
, /* is_partition = */ true, m
->loop
);
1455 if (mount_node_fd
< 0)
1456 return mount_node_fd
;
1459 r
= make_partition_devname(devname
, diskseq
, generic_nr
, flags
, &n
);
1463 options
= mount_options_from_designator(mount_options
, PARTITION_ROOT
);
1465 o
= strdup(options
);
1470 assert(generic_nr
>= 0);
1471 m
->partitions
[PARTITION_ROOT
] = (DissectedPartition
) {
1474 .growfs
= generic_growfs
,
1475 .partno
= generic_nr
,
1476 .architecture
= _ARCHITECTURE_INVALID
,
1477 .node
= TAKE_PTR(n
),
1478 .uuid
= generic_uuid
,
1479 .mount_options
= TAKE_PTR(o
),
1480 .mount_node_fd
= TAKE_FD(mount_node_fd
),
1481 .offset
= UINT64_MAX
,
1483 .fsmount_fd
= -EBADF
,
1489 /* 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 */
1490 if (FLAGS_SET(flags
, DISSECT_IMAGE_REQUIRE_ROOT
) &&
1491 !(m
->partitions
[PARTITION_ROOT
].found
|| (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
1494 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
) {
1495 /* We only support one verity partition per image, i.e. can't do for both /usr and root fs */
1496 if (m
->partitions
[PARTITION_USR_VERITY
].found
)
1499 /* We don't support verity enabled root with a split out /usr. Neither with nor without
1500 * verity there. (Note that we do support verity-less root with verity-full /usr, though.) */
1501 if (m
->partitions
[PARTITION_USR
].found
)
1502 return -EADDRNOTAVAIL
;
1506 /* If a verity designator is specified, then insist that the matching partition exists */
1507 if (verity
->designator
>= 0 && !m
->partitions
[verity
->designator
].found
)
1508 return -EADDRNOTAVAIL
;
1510 if (verity
->root_hash
) {
1511 /* If we have an explicit root hash and found the partitions for it, then we are ready to use
1512 * Verity, set things up for it */
1514 if (verity
->designator
< 0 || verity
->designator
== PARTITION_ROOT
) {
1515 if (!m
->partitions
[PARTITION_ROOT_VERITY
].found
|| !m
->partitions
[PARTITION_ROOT
].found
)
1516 return -EADDRNOTAVAIL
;
1518 /* If we found a verity setup, then the root partition is necessarily read-only. */
1519 m
->partitions
[PARTITION_ROOT
].rw
= false;
1521 assert(verity
->designator
== PARTITION_USR
);
1523 if (!m
->partitions
[PARTITION_USR_VERITY
].found
|| !m
->partitions
[PARTITION_USR
].found
)
1524 return -EADDRNOTAVAIL
;
1526 m
->partitions
[PARTITION_USR
].rw
= false;
1529 m
->verity_ready
= true;
1531 if (verity
->root_hash_sig
)
1532 m
->verity_sig_ready
= true;
1538 /* After we discovered all partitions let's see if the verity requirements match the policy. (Note:
1539 * we don't check encryption requirements here, because we haven't probed the file system yet, hence
1540 * don't know if this is encrypted or not) */
1541 for (PartitionDesignator di
= 0; di
< _PARTITION_DESIGNATOR_MAX
; di
++) {
1542 any
= any
|| m
->partitions
[di
].found
;
1544 /* Determine the verity protection level for this partition. */
1545 PartitionPolicyFlags found_flags
;
1546 if (m
->partitions
[di
].found
) {
1547 found_flags
= PARTITION_POLICY_ENCRYPTED
|PARTITION_POLICY_UNPROTECTED
|PARTITION_POLICY_UNUSED
;
1549 PartitionDesignator vi
= partition_verity_of(di
);
1550 if (vi
>= 0 && m
->partitions
[vi
].found
) {
1551 found_flags
|= PARTITION_POLICY_VERITY
;
1553 PartitionDesignator si
= partition_verity_sig_of(di
);
1554 if (si
>= 0 && m
->partitions
[si
].found
)
1555 found_flags
|= PARTITION_POLICY_SIGNED
;
1558 found_flags
= m
->partitions
[di
].ignored
? PARTITION_POLICY_UNUSED
: PARTITION_POLICY_ABSENT
;
1560 if (DEBUG_LOGGING
) {
1561 _cleanup_free_
char *s
= NULL
;
1562 (void) partition_policy_flags_to_string(found_flags
, /* simplify= */ false, &s
);
1563 log_debug("Found for designator %s: %s", partition_designator_to_string(di
), strna(s
));
1566 r
= image_policy_check_protection(policy
, di
, found_flags
);
1570 if (m
->partitions
[di
].found
) {
1571 r
= image_policy_check_partition_flags(policy
, di
, m
->partitions
[di
].gpt_flags
);
1577 if (!any
&& !FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_EMPTY
))
1580 r
= dissected_image_probe_filesystems(m
, fd
, policy
);
1588 int dissect_image_file(
1590 const VeritySettings
*verity
,
1591 const MountOptions
*mount_options
,
1592 const ImagePolicy
*image_policy
,
1593 const ImageFilter
*image_filter
,
1594 DissectImageFlags flags
,
1595 DissectedImage
**ret
) {
1598 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
1599 _cleanup_close_
int fd
= -EBADF
;
1605 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1609 if (fstat(fd
, &st
) < 0)
1612 r
= stat_verify_regular(&st
);
1616 r
= dissected_image_new(path
, &m
);
1620 m
->image_size
= st
.st_size
;
1622 r
= probe_sector_size(fd
, &m
->sector_size
);
1626 r
= dissect_image(m
, fd
, path
, verity
, mount_options
, image_policy
, image_filter
, flags
);
1638 int dissect_log_error(int log_level
, int r
, const char *name
, const VeritySettings
*verity
) {
1639 assert(log_level
>= 0 && log_level
<= LOG_DEBUG
);
1644 case 0 ... INT_MAX
: /* success! */
1648 return log_full_errno(log_level
, r
, "Dissecting images is not supported, compiled without blkid support.");
1651 return log_full_errno(log_level
, r
, "%s: Couldn't identify a suitable partition table or file system.", name
);
1654 return log_full_errno(log_level
, r
, "%s: The image does not pass os-release/extension-release validation.", name
);
1656 case -EADDRNOTAVAIL
:
1657 return log_full_errno(log_level
, r
, "%s: No root partition for specified root hash found.", name
);
1660 return log_full_errno(log_level
, r
, "%s: Multiple suitable root partitions found in image.", name
);
1663 return log_full_errno(log_level
, r
, "%s: No suitable root partition found in image.", name
);
1665 case -EPROTONOSUPPORT
:
1666 return log_full_errno(log_level
, r
, "Device '%s' is a loopback block device with partition scanning turned off, please turn it on.", name
);
1669 return log_full_errno(log_level
, r
, "%s: Image is not a block device.", name
);
1672 return log_full_errno(log_level
, r
,
1673 "Combining partitioned images (such as '%s') with external Verity data (such as '%s') not supported. "
1674 "(Consider setting $SYSTEMD_DISSECT_VERITY_SIDECAR=0 to disable automatic discovery of external Verity data.)",
1675 name
, strna(verity
? verity
->data_path
: NULL
));
1678 return log_full_errno(log_level
, r
, "%s: Image does not match image policy.", name
);
1681 return log_full_errno(log_level
, r
, "%s: No suitable partitions found.", name
);
1684 return log_full_errno(log_level
, r
, "%s: Partition with ambiguous file system superblock signature found.", name
);
1687 return log_full_errno(log_level
, r
, "%s: Cannot dissect image: %m", name
);
1691 int dissect_image_file_and_warn(
1693 const VeritySettings
*verity
,
1694 const MountOptions
*mount_options
,
1695 const ImagePolicy
*image_policy
,
1696 const ImageFilter
*image_filter
,
1697 DissectImageFlags flags
,
1698 DissectedImage
**ret
) {
1700 return dissect_log_error(
1702 dissect_image_file(path
, verity
, mount_options
, image_policy
, image_filter
, flags
, ret
),
1707 void dissected_image_close(DissectedImage
*m
) {
1711 /* Closes all fds we keep open associated with this, but nothing else */
1713 FOREACH_ARRAY(p
, m
->partitions
, _PARTITION_DESIGNATOR_MAX
) {
1714 p
->mount_node_fd
= safe_close(p
->mount_node_fd
);
1715 p
->fsmount_fd
= safe_close(p
->fsmount_fd
);
1718 m
->loop
= loop_device_unref(m
->loop
);
1721 DissectedImage
* dissected_image_unref(DissectedImage
*m
) {
1725 /* First, clear dissected partitions. */
1726 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++)
1727 dissected_partition_done(m
->partitions
+ i
);
1729 /* Second, free decrypted images. This must be after dissected_partition_done(), as freeing
1730 * DecryptedImage may try to deactivate partitions. */
1731 decrypted_image_unref(m
->decrypted_image
);
1733 /* Third, unref LoopDevice. This must be called after the above two, as freeing LoopDevice may try to
1734 * remove existing partitions on the loopback block device. */
1735 loop_device_unref(m
->loop
);
1737 free(m
->image_name
);
1739 strv_free(m
->machine_info
);
1740 strv_free(m
->os_release
);
1741 strv_free(m
->initrd_release
);
1742 strv_free(m
->confext_release
);
1743 strv_free(m
->sysext_release
);
1748 static int is_loop_device(const char *path
) {
1749 char s
[SYS_BLOCK_PATH_MAX("/../loop/")];
1754 if (stat(path
, &st
) < 0)
1757 if (!S_ISBLK(st
.st_mode
))
1760 xsprintf_sys_block_path(s
, "/loop/", st
.st_dev
);
1761 if (access(s
, F_OK
) < 0) {
1762 if (errno
!= ENOENT
)
1765 /* The device itself isn't a loop device, but maybe it's a partition and its parent is? */
1766 xsprintf_sys_block_path(s
, "/../loop/", st
.st_dev
);
1767 if (access(s
, F_OK
) < 0)
1768 return errno
== ENOENT
? false : -errno
;
1774 static int run_fsck(int node_fd
, const char *fstype
) {
1778 assert(node_fd
>= 0);
1781 r
= fsck_exists_for_fstype(fstype
);
1783 log_debug_errno(r
, "Couldn't determine whether fsck for %s exists, proceeding anyway.", fstype
);
1787 log_debug("Not checking partition %s, as fsck for %s does not exist.", FORMAT_PROC_FD_PATH(node_fd
), fstype
);
1794 &node_fd
, 1, /* Leave the node fd open */
1795 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_RLIMIT_NOFILE_SAFE
|FORK_DEATHSIG_SIGTERM
|FORK_REARRANGE_STDIO
|FORK_CLOEXEC_OFF
,
1798 return log_debug_errno(r
, "Failed to fork off fsck: %m");
1801 execlp("fsck", "fsck", "-aT", FORMAT_PROC_FD_PATH(node_fd
), NULL
);
1803 log_debug_errno(errno
, "Failed to execl() fsck: %m");
1804 _exit(FSCK_OPERATIONAL_ERROR
);
1807 exit_status
= wait_for_terminate_and_check("fsck", pid
, 0);
1808 if (exit_status
< 0)
1809 return log_debug_errno(exit_status
, "Failed to fork off fsck: %m");
1811 if ((exit_status
& ~FSCK_ERROR_CORRECTED
) != FSCK_SUCCESS
) {
1812 log_debug("fsck failed with exit status %i.", exit_status
);
1814 if ((exit_status
& (FSCK_SYSTEM_SHOULD_REBOOT
|FSCK_ERRORS_LEFT_UNCORRECTED
)) != 0)
1815 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
), "File system is corrupted, refusing.");
1817 log_debug("Ignoring fsck error.");
1823 static int fs_grow(const char *node_path
, int mount_fd
, const char *mount_path
) {
1824 _cleanup_close_
int _mount_fd
= -EBADF
, node_fd
= -EBADF
;
1825 uint64_t size
, newsize
;
1830 assert(mount_fd
>= 0 || mount_path
);
1832 node_fd
= open(node_path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
1834 return log_debug_errno(errno
, "Failed to open node device %s: %m", node_path
);
1836 r
= blockdev_get_device_size(node_fd
, &size
);
1838 return log_debug_errno(r
, "Failed to get block device size of %s: %m", node_path
);
1843 _mount_fd
= open(mount_path
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
);
1845 return log_debug_errno(errno
, "Failed to open mounted file system %s: %m", mount_path
);
1847 mount_fd
= _mount_fd
;
1849 mount_fd
= fd_reopen_condition(mount_fd
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, O_RDONLY
|O_DIRECTORY
|O_CLOEXEC
, &_mount_fd
);
1851 return log_debug_errno(errno
, "Failed to reopen mount node: %m");
1854 id
= mount_path
?: node_path
;
1856 log_debug("Resizing \"%s\" to %"PRIu64
" bytes...", id
, size
);
1857 r
= resize_fs(mount_fd
, size
, &newsize
);
1859 return log_debug_errno(r
, "Failed to resize \"%s\" to %"PRIu64
" bytes: %m", id
, size
);
1861 if (newsize
== size
)
1862 log_debug("Successfully resized \"%s\" to %s bytes.",
1863 id
, FORMAT_BYTES(newsize
));
1865 assert(newsize
< size
);
1866 log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64
" bytes lost due to blocksize).",
1867 id
, FORMAT_BYTES(newsize
), size
- newsize
);
1873 int partition_pick_mount_options(
1874 PartitionDesignator d
,
1879 unsigned long *ret_ms_flags
) {
1881 _cleanup_free_
char *options
= NULL
;
1883 assert(ret_options
);
1885 /* Selects a baseline of bind mount flags, that should always apply.
1887 * Firstly, we set MS_NODEV universally on all mounts, since we don't want to allow device nodes outside of /dev/.
1889 * On /var/tmp/ we'll also set MS_NOSUID, same as we set for /tmp/ on the host.
1891 * On the ESP and XBOOTLDR partitions we'll also disable symlinks, and execution. These file systems
1892 * are generally untrusted (i.e. not encrypted or authenticated), and typically VFAT hence we should
1893 * be as restrictive as possible, and this shouldn't hurt, since the functionality is not available
1896 unsigned long flags
= MS_NODEV
;
1904 case PARTITION_XBOOTLDR
:
1905 flags
|= MS_NOSUID
|MS_NOEXEC
|ms_nosymfollow_supported();
1907 /* The ESP might contain a pre-boot random seed. Let's make this unaccessible to regular
1908 * userspace. ESP/XBOOTLDR is almost certainly VFAT, hence if we don't know assume it is. */
1909 if (!fstype
|| fstype_can_fmask_dmask(fstype
))
1910 if (!strextend_with_separator(&options
, ",", "fmask=0177,dmask=0077"))
1922 /* So, when you request MS_RDONLY from ext4, then this means nothing. It happily still writes to the
1923 * backing storage. What's worse, the BLKRO[GS]ET flag and (in case of loopback devices)
1924 * LO_FLAGS_READ_ONLY don't mean anything, they affect userspace accesses only, and write accesses
1925 * from the upper file system still get propagated through to the underlying file system,
1926 * unrestricted. To actually get ext4/xfs/btrfs to stop writing to the device we need to specify
1927 * "norecovery" as mount option, in addition to MS_RDONLY. Yes, this sucks, since it means we need to
1928 * carry a per file system table here.
1930 * Note that this means that we might not be able to mount corrupted file systems as read-only
1931 * anymore (since in some cases the kernel implementations will refuse mounting when corrupted,
1932 * read-only and "norecovery" is specified). But I think for the case of automatically determined
1933 * mount options for loopback devices this is the right choice, since otherwise using the same
1934 * loopback file twice even in read-only mode, is going to fail badly sooner or later. The use case of
1935 * making reuse of the immutable images "just work" is more relevant to us than having read-only
1936 * access that actually modifies stuff work on such image files. Or to say this differently: if
1937 * people want their file systems to be fixed up they should just open them in writable mode, where
1938 * all these problems don't exist. */
1939 if (!rw
&& fstype
) {
1940 const char *option
= fstype_norecovery_option(fstype
);
1942 if (option
&& !strextend_with_separator(&options
, ",", option
))
1946 if (discard
&& fstype
&& fstype_can_discard(fstype
))
1947 if (!strextend_with_separator(&options
, ",", "discard"))
1950 if (!ret_ms_flags
) /* Fold flags into option string if ret_flags specified as NULL */
1951 if (!strextend_with_separator(&options
, ",",
1952 FLAGS_SET(flags
, MS_RDONLY
) ? "ro" : "rw",
1953 FLAGS_SET(flags
, MS_NODEV
) ? "nodev" : "dev",
1954 FLAGS_SET(flags
, MS_NOSUID
) ? "nosuid" : "suid",
1955 FLAGS_SET(flags
, MS_NOEXEC
) ? "noexec" : "exec",
1956 FLAGS_SET(flags
, MS_NOSYMFOLLOW
) ? "nosymfollow" : NULL
))
1957 /* NB: we suppress 'symfollow' here, since it's the default, and old /bin/mount might not know it */
1961 *ret_ms_flags
= flags
;
1963 *ret_options
= TAKE_PTR(options
);
1967 static bool need_user_mapping(uid_t uid_shift
, uid_t uid_range
) {
1969 if (!uid_is_valid(uid_shift
))
1972 return uid_shift
!= 0 || uid_range
!= UINT32_MAX
;
1975 static int mount_partition(
1976 PartitionDesignator d
,
1977 DissectedPartition
*m
,
1979 const char *directory
,
1983 DissectImageFlags flags
) {
1985 _cleanup_free_
char *chased
= NULL
, *options
= NULL
;
1986 const char *p
= NULL
, *node
, *fstype
= NULL
;
1987 bool rw
, discard
, grow
;
1988 unsigned long ms_flags
;
1996 /* Check the various combinations when we can't do anything anymore */
1997 if (m
->fsmount_fd
< 0 && m
->mount_node_fd
< 0)
1999 if (m
->fsmount_fd
>= 0 && !where
)
2001 if (!where
&& m
->mount_node_fd
< 0)
2004 if (m
->fsmount_fd
< 0) {
2005 fstype
= dissected_partition_fstype(m
);
2007 return -EAFNOSUPPORT
;
2009 /* We are looking at an encrypted partition? This either means stacked encryption, or the
2010 * caller didn't call dissected_image_decrypt() beforehand. Let's return a recognizable error
2012 if (streq(fstype
, "crypto_LUKS"))
2015 r
= dissect_fstype_ok(fstype
);
2019 return -EIDRM
; /* Recognizable error */
2022 node
= m
->mount_node_fd
< 0 ? NULL
: FORMAT_PROC_FD_PATH(m
->mount_node_fd
);
2023 rw
= m
->rw
&& !(flags
& DISSECT_IMAGE_MOUNT_READ_ONLY
);
2025 discard
= ((flags
& DISSECT_IMAGE_DISCARD
) ||
2026 ((flags
& DISSECT_IMAGE_DISCARD_ON_LOOP
) && (m
->node
&& is_loop_device(m
->node
) > 0)));
2028 grow
= rw
&& m
->growfs
&& FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
);
2030 if (FLAGS_SET(flags
, DISSECT_IMAGE_FSCK
) && rw
&& m
->mount_node_fd
>= 0 && m
->fsmount_fd
< 0) {
2031 r
= run_fsck(m
->mount_node_fd
, fstype
);
2038 /* Automatically create missing mount points inside the image, if necessary. */
2039 r
= mkdir_p_root(where
, directory
, uid_shift
, (gid_t
) uid_shift
, 0755);
2040 if (r
< 0 && r
!= -EROFS
)
2043 r
= chase(directory
, where
, CHASE_PREFIX_ROOT
, &chased
, NULL
);
2049 /* Create top-level mount if missing – but only if this is asked for. This won't modify the
2050 * image (as the branch above does) but the host hierarchy, and the created directory might
2051 * survive our mount in the host hierarchy hence. */
2052 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
2053 r
= mkdir_p(where
, 0755);
2062 if (m
->fsmount_fd
< 0) {
2063 r
= partition_pick_mount_options(d
, fstype
, rw
, discard
, &options
, &ms_flags
);
2067 if (need_user_mapping(uid_shift
, uid_range
) && fstype_can_uid_gid(fstype
)) {
2068 _cleanup_free_
char *uid_option
= NULL
;
2070 if (asprintf(&uid_option
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
2073 if (!strextend_with_separator(&options
, ",", uid_option
))
2076 userns_fd
= -EBADF
; /* Not needed */
2079 if (!isempty(m
->mount_options
))
2080 if (!strextend_with_separator(&options
, ",", m
->mount_options
))
2085 if (m
->fsmount_fd
>= 0) {
2086 /* Case #1: Attach existing fsmount fd to the file system */
2088 r
= mount_exchange_graceful(
2091 FLAGS_SET(flags
, DISSECT_IMAGE_TRY_ATOMIC_MOUNT_EXCHANGE
));
2093 return log_debug_errno(r
, "Failed to mount image on '%s': %m", p
);
2098 /* Case #2: Mount directly into place */
2099 r
= mount_nofollow_verbose(LOG_DEBUG
, node
, p
, fstype
, ms_flags
, options
);
2104 (void) fs_grow(node
, -EBADF
, p
);
2106 if (userns_fd
>= 0) {
2107 r
= remount_idmap_fd(STRV_MAKE(p
), userns_fd
, /* extra_mount_attr_set= */ 0);
2115 /* Case #3: Create fsmount fd */
2117 m
->fsmount_fd
= make_fsmount(LOG_DEBUG
, node
, fstype
, ms_flags
, options
, userns_fd
);
2118 if (m
->fsmount_fd
< 0)
2119 return m
->fsmount_fd
;
2122 (void) fs_grow(node
, m
->fsmount_fd
, NULL
);
2128 static int mount_root_tmpfs(const char *where
, uid_t uid_shift
, uid_t uid_range
, DissectImageFlags flags
) {
2129 _cleanup_free_
char *options
= NULL
;
2134 /* For images that contain /usr/ but no rootfs, let's mount rootfs as tmpfs */
2136 if (FLAGS_SET(flags
, DISSECT_IMAGE_MKDIR
)) {
2137 r
= mkdir_p(where
, 0755);
2142 if (need_user_mapping(uid_shift
, uid_range
)) {
2143 if (asprintf(&options
, "uid=" UID_FMT
",gid=" GID_FMT
, uid_shift
, (gid_t
) uid_shift
) < 0)
2147 r
= mount_nofollow_verbose(LOG_DEBUG
, "rootfs", where
, "tmpfs", MS_NODEV
, options
);
2154 static int mount_point_is_available(const char *where
, const char *path
, bool missing_ok
) {
2155 _cleanup_free_
char *p
= NULL
;
2158 /* Check whether <path> is suitable as a mountpoint, i.e. is an empty directory
2159 * or does not exist at all (when missing_ok). */
2161 r
= chase(path
, where
, CHASE_PREFIX_ROOT
, &p
, NULL
);
2165 return log_debug_errno(r
, "Failed to chase \"%s\": %m", path
);
2167 r
= dir_is_empty(p
, /* ignore_hidden_or_backup= */ false);
2171 return log_debug_errno(r
, "Failed to check directory \"%s\": %m", p
);
2175 int dissected_image_mount(
2181 DissectImageFlags flags
) {
2183 _cleanup_close_
int my_userns_fd
= -EBADF
;
2188 if (FLAGS_SET(flags
, DISSECT_IMAGE_FOREIGN_UID
)) /* For image based mounts we currently require an identity mapping */
2191 /* If 'where' is NULL then we'll use the new mount API to create fsmount() fds for the mounts and
2192 * store them in DissectedPartition.fsmount_fd.
2194 * If 'where' is not NULL then we'll either mount the partitions to the right places ourselves,
2195 * or use DissectedPartition.fsmount_fd and bind it to the right places.
2197 * This allows splitting the setting up the superblocks and the binding to file systems paths into
2198 * two distinct and differently privileged components: one that gets the fsmount fds, and the other
2199 * that then applies them.
2203 * -ENXIO → No root partition found
2204 * -EMEDIUMTYPE → DISSECT_IMAGE_VALIDATE_OS set but no os-release/extension-release file found
2205 * -EUNATCH → Encrypted partition found for which no dm-crypt was set up yet
2206 * -EUCLEAN → fsck for file system failed
2207 * -EBUSY → File system already mounted/used elsewhere (kernel)
2208 * -EAFNOSUPPORT → File system type not supported or not known
2209 * -EIDRM → File system is not among allowlisted "common" file systems
2212 if (!where
&& (flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0)
2213 return -EOPNOTSUPP
; /* for now, not supported */
2215 if (!(m
->partitions
[PARTITION_ROOT
].found
||
2216 (m
->partitions
[PARTITION_USR
].found
&& FLAGS_SET(flags
, DISSECT_IMAGE_USR_NO_ROOT
))))
2217 return -ENXIO
; /* Require a root fs or at least a /usr/ fs (the latter is subject to a flag of its own) */
2219 if (userns_fd
< 0 && need_user_mapping(uid_shift
, uid_range
) && FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_IDMAPPED
)) {
2221 my_userns_fd
= make_userns(uid_shift
, uid_range
, UID_INVALID
, UID_INVALID
, REMOUNT_IDMAPPING_HOST_ROOT
);
2222 if (my_userns_fd
< 0)
2223 return my_userns_fd
;
2225 userns_fd
= my_userns_fd
;
2228 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0) {
2230 /* First mount the root fs. If there's none we use a tmpfs. */
2231 if (m
->partitions
[PARTITION_ROOT
].found
) {
2232 r
= mount_partition(PARTITION_ROOT
, m
->partitions
+ PARTITION_ROOT
, where
, NULL
, uid_shift
, uid_range
, userns_fd
, flags
);
2237 r
= mount_root_tmpfs(where
, uid_shift
, uid_range
, flags
);
2242 /* For us mounting root always means mounting /usr as well */
2243 r
= mount_partition(PARTITION_USR
, m
->partitions
+ PARTITION_USR
, where
, "/usr", uid_shift
, uid_range
, userns_fd
, flags
);
2248 if ((flags
& DISSECT_IMAGE_MOUNT_NON_ROOT_ONLY
) == 0 &&
2249 (flags
& (DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_VALIDATE_OS_EXT
)) != 0) {
2250 /* If either one of the validation flags are set, ensure that the image qualifies as
2251 * one or the other (or both). */
2256 if (FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS
)) {
2257 r
= path_is_os_tree(where
);
2263 if (!ok
&& FLAGS_SET(flags
, DISSECT_IMAGE_VALIDATE_OS_EXT
) && m
->image_name
) {
2264 r
= extension_has_forbidden_content(where
);
2268 r
= path_is_extension_tree(IMAGE_SYSEXT
, where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_EXTENSION_CHECK
));
2270 r
= path_is_extension_tree(IMAGE_CONFEXT
, where
, m
->image_name
, FLAGS_SET(flags
, DISSECT_IMAGE_RELAX_EXTENSION_CHECK
));
2282 if (flags
& DISSECT_IMAGE_MOUNT_ROOT_ONLY
)
2285 r
= mount_partition(PARTITION_HOME
, m
->partitions
+ PARTITION_HOME
, where
, "/home", uid_shift
, uid_range
, userns_fd
, flags
);
2289 r
= mount_partition(PARTITION_SRV
, m
->partitions
+ PARTITION_SRV
, where
, "/srv", uid_shift
, uid_range
, userns_fd
, flags
);
2293 r
= mount_partition(PARTITION_VAR
, m
->partitions
+ PARTITION_VAR
, where
, "/var", uid_shift
, uid_range
, userns_fd
, flags
);
2297 r
= mount_partition(PARTITION_TMP
, m
->partitions
+ PARTITION_TMP
, where
, "/var/tmp", uid_shift
, uid_range
, userns_fd
, flags
);
2301 int slash_boot_is_available
= 0;
2303 r
= slash_boot_is_available
= mount_point_is_available(where
, "/boot", /* missing_ok = */ true);
2307 if (!where
|| slash_boot_is_available
) {
2308 r
= mount_partition(PARTITION_XBOOTLDR
, m
->partitions
+ PARTITION_XBOOTLDR
, where
, "/boot", uid_shift
, uid_range
, userns_fd
, flags
);
2311 slash_boot_is_available
= !r
;
2314 if (m
->partitions
[PARTITION_ESP
].found
) {
2315 const char *esp_path
= NULL
;
2318 /* Mount the ESP to /boot/ if it exists and is empty and we didn't already mount the
2319 * XBOOTLDR partition into it. Otherwise, use /efi instead, but only if it exists
2322 if (slash_boot_is_available
) {
2323 r
= mount_point_is_available(where
, "/boot", /* missing_ok = */ false);
2331 r
= mount_point_is_available(where
, "/efi", /* missing_ok = */ true);
2339 /* OK, let's mount the ESP now (possibly creating the dir if missing) */
2340 r
= mount_partition(PARTITION_ESP
, m
->partitions
+ PARTITION_ESP
, where
, esp_path
, uid_shift
, uid_range
, userns_fd
, flags
);
2348 int dissected_image_mount_and_warn(
2354 DissectImageFlags flags
) {
2360 r
= dissected_image_mount(m
, where
, uid_shift
, uid_range
, userns_fd
, flags
);
2362 return log_error_errno(r
, "Failed to mount image: No root file system found in image.");
2363 if (r
== -EMEDIUMTYPE
)
2364 return log_error_errno(r
, "Failed to mount image: No suitable os-release/extension-release file in image found.");
2366 return log_error_errno(r
, "Failed to mount image: Encrypted file system discovered, but decryption not requested.");
2368 return log_error_errno(r
, "Failed to mount image: File system check on image failed.");
2370 return log_error_errno(r
, "Failed to mount image: File system already mounted elsewhere.");
2371 if (r
== -EAFNOSUPPORT
)
2372 return log_error_errno(r
, "Failed to mount image: File system type not supported or not known.");
2374 return log_error_errno(r
, "Failed to mount image: File system is too uncommon, refused.");
2376 return log_error_errno(r
, "Failed to mount image: %m");
2381 #if HAVE_LIBCRYPTSETUP
2382 struct DecryptedPartition
{
2383 struct crypt_device
*device
;
2389 typedef struct DecryptedPartition DecryptedPartition
;
2391 struct DecryptedImage
{
2393 DecryptedPartition
*decrypted
;
2397 static DecryptedImage
* decrypted_image_free(DecryptedImage
*d
) {
2398 #if HAVE_LIBCRYPTSETUP
2404 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
2405 DecryptedPartition
*p
= d
->decrypted
+ i
;
2407 if (p
->device
&& p
->name
&& !p
->relinquished
) {
2408 _cleanup_free_
char *node
= NULL
;
2410 node
= path_join("/dev/mapper", p
->name
);
2412 r
= btrfs_forget_device(node
);
2413 if (r
< 0 && r
!= -ENOENT
)
2414 log_debug_errno(r
, "Failed to forget btrfs device %s, ignoring: %m", node
);
2418 /* Let's deactivate lazily, as the dm volume may be already/still used by other processes. */
2419 r
= sym_crypt_deactivate_by_name(p
->device
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
2421 log_debug_errno(r
, "Failed to deactivate encrypted partition %s", p
->name
);
2425 sym_crypt_free(p
->device
);
2435 DEFINE_TRIVIAL_REF_UNREF_FUNC(DecryptedImage
, decrypted_image
, decrypted_image_free
);
2437 #if HAVE_LIBCRYPTSETUP
2438 static int decrypted_image_new(DecryptedImage
**ret
) {
2439 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
2443 d
= new(DecryptedImage
, 1);
2447 *d
= (DecryptedImage
) {
2455 static int make_dm_name_and_node(const void *original_node
, const char *suffix
, char **ret_name
, char **ret_node
) {
2456 _cleanup_free_
char *name
= NULL
, *node
= NULL
;
2459 assert(original_node
);
2464 base
= strrchr(original_node
, '/');
2466 base
= original_node
;
2472 name
= strjoin(base
, suffix
);
2475 if (!filename_is_valid(name
))
2478 node
= path_join(sym_crypt_get_dir(), name
);
2482 *ret_name
= TAKE_PTR(name
);
2483 *ret_node
= TAKE_PTR(node
);
2488 static int decrypt_partition(
2489 DissectedPartition
*m
,
2490 const char *passphrase
,
2491 DissectImageFlags flags
,
2492 DecryptedImage
*d
) {
2494 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2495 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2496 _cleanup_close_
int fd
= -EBADF
;
2502 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2505 if (!streq(m
->fstype
, "crypto_LUKS"))
2511 r
= dlopen_cryptsetup();
2515 r
= make_dm_name_and_node(m
->node
, "-decrypted", &name
, &node
);
2519 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2522 r
= sym_crypt_init(&cd
, m
->node
);
2524 return log_debug_errno(r
, "Failed to initialize dm-crypt: %m");
2526 cryptsetup_enable_logging(cd
);
2528 r
= sym_crypt_load(cd
, CRYPT_LUKS
, NULL
);
2530 return log_debug_errno(r
, "Failed to load LUKS metadata: %m");
2532 r
= sym_crypt_activate_by_passphrase(cd
, name
, CRYPT_ANY_SLOT
, passphrase
, strlen(passphrase
),
2533 ((flags
& DISSECT_IMAGE_DEVICE_READ_ONLY
) ? CRYPT_ACTIVATE_READONLY
: 0) |
2534 ((flags
& DISSECT_IMAGE_DISCARD_ON_CRYPTO
) ? CRYPT_ACTIVATE_ALLOW_DISCARDS
: 0));
2536 log_debug_errno(r
, "Failed to activate LUKS device: %m");
2537 return r
== -EPERM
? -EKEYREJECTED
: r
;
2540 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2542 return log_debug_errno(errno
, "Failed to open %s: %m", node
);
2544 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2545 .name
= TAKE_PTR(name
),
2546 .device
= TAKE_PTR(cd
),
2549 m
->decrypted_node
= TAKE_PTR(node
);
2550 close_and_replace(m
->mount_node_fd
, fd
);
2555 static int verity_can_reuse(
2556 const VeritySettings
*verity
,
2558 struct crypt_device
**ret_cd
) {
2560 /* If the same volume was already open, check that the root hashes match, and reuse it if they do */
2561 _cleanup_free_
char *root_hash_existing
= NULL
;
2562 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2563 struct crypt_params_verity crypt_params
= {};
2564 size_t root_hash_existing_size
;
2571 r
= sym_crypt_init_by_name(&cd
, name
);
2573 return log_debug_errno(r
, "Error opening verity device, crypt_init_by_name failed: %m");
2575 cryptsetup_enable_logging(cd
);
2577 r
= sym_crypt_get_verity_info(cd
, &crypt_params
);
2579 return log_debug_errno(r
, "Error opening verity device, crypt_get_verity_info failed: %m");
2581 root_hash_existing_size
= verity
->root_hash_size
;
2582 root_hash_existing
= malloc0(root_hash_existing_size
);
2583 if (!root_hash_existing
)
2586 r
= sym_crypt_volume_key_get(cd
, CRYPT_ANY_SLOT
, root_hash_existing
, &root_hash_existing_size
, NULL
, 0);
2588 return log_debug_errno(r
, "Error opening verity device, crypt_volume_key_get failed: %m");
2589 if (verity
->root_hash_size
!= root_hash_existing_size
||
2590 memcmp(root_hash_existing
, verity
->root_hash
, verity
->root_hash_size
) != 0)
2591 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but root hashes are different.");
2593 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2594 /* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
2595 * same settings, so that a previous unsigned mount will not be reused if the user asks to use
2596 * signing for the new one, and vice versa. */
2597 if (!!verity
->root_hash_sig
!= !!(crypt_params
.flags
& CRYPT_VERITY_ROOT_HASH_SIGNATURE
))
2598 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Error opening verity device, it already exists but signature settings are not the same.");
2601 *ret_cd
= TAKE_PTR(cd
);
2605 static char* dm_deferred_remove_clean(char *name
) {
2609 (void) sym_crypt_deactivate_by_name(NULL
, name
, CRYPT_DEACTIVATE_DEFERRED
);
2612 DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean
);
2614 static int validate_signature_userspace(const VeritySettings
*verity
, DissectImageFlags flags
) {
2617 if (!FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
)) {
2618 log_debug("Userspace dm-verity signature authentication disabled via flag.");
2622 r
= secure_getenv_bool("SYSTEMD_ALLOW_USERSPACE_VERITY");
2623 if (r
< 0 && r
!= -ENXIO
) {
2624 log_debug_errno(r
, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
2628 log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
2633 r
= proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING
, &b
);
2635 log_debug_errno(r
, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
2639 log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line variable.");
2644 _cleanup_(sk_X509_free_allp
) STACK_OF(X509
) *sk
= NULL
;
2645 _cleanup_strv_free_
char **certs
= NULL
;
2646 _cleanup_(PKCS7_freep
) PKCS7
*p7
= NULL
;
2647 _cleanup_free_
char *s
= NULL
;
2648 _cleanup_(BIO_freep
) BIO
*bio
= NULL
; /* 'bio' must be freed first, 's' second, hence keep this order
2649 * of declaration in place, please */
2650 const unsigned char *d
;
2653 assert(verity
->root_hash
);
2654 assert(verity
->root_hash_sig
);
2656 /* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
2657 * userspace validation. */
2659 r
= conf_files_list_nulstr(&certs
, ".crt", NULL
, CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, CONF_PATHS_NULSTR("verity.d"));
2661 return log_debug_errno(r
, "Failed to enumerate certificates: %m");
2662 if (strv_isempty(certs
)) {
2663 log_debug("No userspace dm-verity certificates found.");
2667 d
= verity
->root_hash_sig
;
2668 p7
= d2i_PKCS7(NULL
, &d
, (long) verity
->root_hash_sig_size
);
2670 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse PKCS7 DER signature data.");
2672 s
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2674 return log_oom_debug();
2676 bio
= BIO_new_mem_buf(s
, strlen(s
));
2678 return log_oom_debug();
2680 sk
= sk_X509_new_null();
2682 return log_oom_debug();
2684 STRV_FOREACH(i
, certs
) {
2685 _cleanup_(X509_freep
) X509
*c
= NULL
;
2686 _cleanup_fclose_
FILE *f
= NULL
;
2688 f
= fopen(*i
, "re");
2690 log_debug_errno(errno
, "Failed to open '%s', ignoring: %m", *i
);
2694 c
= PEM_read_X509(f
, NULL
, NULL
, NULL
);
2696 log_debug("Failed to load X509 certificate '%s', ignoring.", *i
);
2700 if (sk_X509_push(sk
, c
) == 0)
2701 return log_oom_debug();
2706 r
= PKCS7_verify(p7
, sk
, NULL
, bio
, NULL
, PKCS7_NOINTERN
|PKCS7_NOVERIFY
);
2708 log_debug("Userspace PKCS#7 validation succeeded.");
2710 log_debug("Userspace PKCS#7 validation failed: %s", ERR_error_string(ERR_get_error(), NULL
));
2714 log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
2719 static int do_crypt_activate_verity(
2720 struct crypt_device
*cd
,
2722 const VeritySettings
*verity
,
2723 DissectImageFlags flags
) {
2725 bool check_signature
;
2732 if (verity
->root_hash_sig
) {
2733 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
2734 if (r
< 0 && r
!= -ENXIO
)
2735 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
2737 check_signature
= r
!= 0;
2739 check_signature
= false;
2741 if (check_signature
) {
2743 #if HAVE_CRYPT_ACTIVATE_BY_SIGNED_KEY
2744 /* First, if we have support for signed keys in the kernel, then try that first. */
2745 r
= sym_crypt_activate_by_signed_key(
2749 verity
->root_hash_size
,
2750 verity
->root_hash_sig
,
2751 verity
->root_hash_sig_size
,
2752 CRYPT_ACTIVATE_READONLY
);
2756 log_debug_errno(r
, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
2758 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.",
2759 program_invocation_short_name
);
2760 r
= 0; /* Set for the propagation below */
2763 /* So this didn't work via the kernel, then let's try userspace validation instead. If that
2764 * works we'll try to activate without telling the kernel the signature. */
2766 /* Preferably propagate the original kernel error, so that the fallback logic can work,
2767 * as the device-mapper is finicky around concurrent activations of the same volume */
2768 k
= validate_signature_userspace(verity
, flags
);
2770 return r
< 0 ? r
: k
;
2772 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(ENOKEY
),
2773 "Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
2776 return sym_crypt_activate_by_volume_key(
2780 verity
->root_hash_size
,
2781 CRYPT_ACTIVATE_READONLY
);
2784 static usec_t
verity_timeout(void) {
2785 usec_t t
= 100 * USEC_PER_MSEC
;
2789 /* On slower machines, like non-KVM vm, setting up device may take a long time.
2790 * Let's make the timeout configurable. */
2792 e
= getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
2796 r
= parse_sec(e
, &t
);
2799 "Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
2800 "using the default timeout (%s).",
2801 FORMAT_TIMESPAN(t
, USEC_PER_MSEC
));
2806 static int verity_partition(
2807 PartitionDesignator designator
,
2808 DissectedPartition
*m
,
2809 DissectedPartition
*v
,
2810 const VeritySettings
*verity
,
2811 DissectImageFlags flags
,
2812 DecryptedImage
*d
) {
2814 _cleanup_(sym_crypt_freep
) struct crypt_device
*cd
= NULL
;
2815 _cleanup_free_
char *node
= NULL
, *name
= NULL
;
2816 _cleanup_close_
int mount_node_fd
= -EBADF
;
2820 assert(v
|| (verity
&& verity
->data_path
));
2822 if (!verity
|| !verity
->root_hash
)
2824 if (!((verity
->designator
< 0 && designator
== PARTITION_ROOT
) ||
2825 (verity
->designator
== designator
)))
2828 if (!m
->found
|| !m
->node
|| !m
->fstype
)
2830 if (!verity
->data_path
) {
2831 if (!v
->found
|| !v
->node
|| !v
->fstype
)
2834 if (!streq(v
->fstype
, "DM_verity_hash"))
2838 r
= dlopen_cryptsetup();
2842 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2843 /* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
2844 _cleanup_free_
char *root_hash_encoded
= NULL
;
2846 root_hash_encoded
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
2847 if (!root_hash_encoded
)
2850 r
= make_dm_name_and_node(root_hash_encoded
, "-verity", &name
, &node
);
2852 r
= make_dm_name_and_node(m
->node
, "-verity", &name
, &node
);
2856 r
= sym_crypt_init(&cd
, verity
->data_path
?: v
->node
);
2860 cryptsetup_enable_logging(cd
);
2862 r
= sym_crypt_load(cd
, CRYPT_VERITY
, NULL
);
2866 r
= sym_crypt_set_data_device(cd
, m
->node
);
2870 if (!GREEDY_REALLOC0(d
->decrypted
, d
->n_decrypted
+ 1))
2873 /* If activating fails because the device already exists, check the metadata and reuse it if it matches.
2874 * In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
2875 * retry a few times before giving up. */
2876 for (unsigned i
= 0; i
< N_DEVICE_NODE_LIST_ATTEMPTS
; i
++) {
2877 _cleanup_(dm_deferred_remove_cleanp
) char *restore_deferred_remove
= NULL
;
2878 _cleanup_(sym_crypt_freep
) struct crypt_device
*existing_cd
= NULL
;
2879 _cleanup_close_
int fd
= -EBADF
;
2881 /* First, check if the device already exists. */
2882 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2883 if (fd
< 0 && !ERRNO_IS_DEVICE_ABSENT(errno
))
2884 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2886 goto check
; /* The device already exists. Let's check it. */
2888 /* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
2889 r
= do_crypt_activate_verity(cd
, name
, verity
, flags
);
2891 goto try_open
; /* The device is activated. Let's open it. */
2892 /* libdevmapper can return EINVAL when the device is already in the activation stage.
2893 * There's no way to distinguish this situation from a genuine error due to invalid
2894 * parameters, so immediately fall back to activating the device with a unique name.
2895 * Improvements in libcrypsetup can ensure this never happens:
2896 * https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
2897 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2899 /* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
2900 * sharing is enabled. */
2901 if (r
== -ENODEV
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2904 -EEXIST
, /* Volume has already been opened and ready to be used. */
2905 -EBUSY
/* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
2906 return log_debug_errno(r
, "Failed to activate verity device %s: %m", node
);
2909 /* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
2910 r
= dm_deferred_remove_cancel(name
);
2911 /* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
2912 * use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
2913 * and dm_cancel_deferred_remove() in drivers/md/dm.c */
2914 if (IN_SET(r
, -EBUSY
, -ENXIO
))
2917 return log_debug_errno(r
, "Failed to disable automated deferred removal for verity device %s: %m", node
);
2919 restore_deferred_remove
= strdup(name
);
2920 if (!restore_deferred_remove
)
2921 return log_oom_debug();
2923 r
= verity_can_reuse(verity
, name
, &existing_cd
);
2924 /* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
2925 if (r
== -EINVAL
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2928 -ENOENT
, /* Removed?? */
2929 -EBUSY
, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
2930 -ENODEV
/* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
2933 return log_debug_errno(r
, "Failed to check if existing verity device %s can be reused: %m", node
);
2936 /* devmapper might say that the device exists, but the devlink might not yet have been
2937 * created. Check and wait for the udev event in that case. */
2938 r
= device_wait_for_devlink(node
, "block", verity_timeout(), NULL
);
2939 /* Fallback to activation with a unique device if it's taking too long */
2940 if (r
== -ETIMEDOUT
&& FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
))
2943 return log_debug_errno(r
, "Failed to wait device node symlink %s: %m", node
);
2948 /* Now, the device is activated and devlink is created. Let's open it. */
2949 fd
= open(node
, O_RDONLY
|O_NONBLOCK
|O_CLOEXEC
|O_NOCTTY
);
2951 if (!ERRNO_IS_DEVICE_ABSENT(errno
))
2952 return log_debug_errno(errno
, "Failed to open verity device %s: %m", node
);
2954 /* The device has already been removed?? */
2959 /* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
2960 restore_deferred_remove
= mfree(restore_deferred_remove
);
2962 mount_node_fd
= TAKE_FD(fd
);
2964 crypt_free_and_replace(cd
, existing_cd
);
2969 /* Device is being removed by another process. Let's wait for a while. */
2970 (void) usleep_safe(2 * USEC_PER_MSEC
);
2973 /* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
2974 if (FLAGS_SET(flags
, DISSECT_IMAGE_VERITY_SHARE
)) {
2975 /* Before trying to activate with unique name, we need to free crypt_device object.
2976 * Otherwise, we get error from libcryptsetup like the following:
2978 * systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
2983 return verity_partition(designator
, m
, v
, verity
, flags
& ~DISSECT_IMAGE_VERITY_SHARE
, d
);
2986 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY
), "All attempts to activate verity device %s failed.", name
);
2989 d
->decrypted
[d
->n_decrypted
++] = (DecryptedPartition
) {
2990 .name
= TAKE_PTR(name
),
2991 .device
= TAKE_PTR(cd
),
2994 m
->decrypted_node
= TAKE_PTR(node
);
2995 close_and_replace(m
->mount_node_fd
, mount_node_fd
);
3001 int dissected_image_decrypt(
3003 const char *passphrase
,
3004 const VeritySettings
*verity
,
3005 DissectImageFlags flags
) {
3007 #if HAVE_LIBCRYPTSETUP
3008 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*d
= NULL
;
3013 assert(!verity
|| verity
->root_hash
|| verity
->root_hash_size
== 0);
3017 * = 0 → There was nothing to decrypt
3018 * > 0 → Decrypted successfully
3019 * -ENOKEY → There's something to decrypt but no key was supplied
3020 * -EKEYREJECTED → Passed key was not correct
3021 * -EBUSY → Generic Verity error (kernel is not very explanatory)
3024 if (verity
&& verity
->root_hash
&& verity
->root_hash_size
< sizeof(sd_id128_t
))
3027 if (!m
->encrypted
&& !m
->verity_ready
)
3030 #if HAVE_LIBCRYPTSETUP
3031 r
= decrypted_image_new(&d
);
3035 for (PartitionDesignator i
= 0; i
< _PARTITION_DESIGNATOR_MAX
; i
++) {
3036 DissectedPartition
*p
= m
->partitions
+ i
;
3037 PartitionDesignator k
;
3042 r
= decrypt_partition(p
, passphrase
, flags
, d
);
3046 k
= partition_verity_of(i
);
3048 flags
|= getenv_bool("SYSTEMD_VERITY_SHARING") != 0 ? DISSECT_IMAGE_VERITY_SHARE
: 0;
3050 r
= verity_partition(i
, p
, m
->partitions
+ k
, verity
, flags
, d
);
3055 if (!p
->decrypted_fstype
&& p
->mount_node_fd
>= 0 && p
->decrypted_node
) {
3056 r
= probe_filesystem_full(p
->mount_node_fd
, p
->decrypted_node
, 0, UINT64_MAX
, &p
->decrypted_fstype
);
3057 if (r
< 0 && r
!= -EUCLEAN
)
3062 m
->decrypted_image
= TAKE_PTR(d
);
3070 int dissected_image_decrypt_interactively(
3072 const char *passphrase
,
3073 const VeritySettings
*verity
,
3074 DissectImageFlags flags
) {
3076 _cleanup_strv_free_erase_
char **z
= NULL
;
3083 r
= dissected_image_decrypt(m
, passphrase
, verity
, flags
);
3086 if (r
== -EKEYREJECTED
)
3087 log_error_errno(r
, "Incorrect passphrase, try again!");
3088 else if (r
!= -ENOKEY
)
3089 return log_error_errno(r
, "Failed to decrypt image: %m");
3092 return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED
),
3093 "Too many retries.");
3095 z
= strv_free_erase(z
);
3097 static const AskPasswordRequest req
= {
3099 .message
= "Please enter image passphrase:",
3101 .keyring
= "dissect",
3102 .credential
= "dissect.passphrase",
3103 .until
= USEC_INFINITY
,
3107 r
= ask_password_auto(&req
, /* flags= */ 0, &z
);
3109 return log_error_errno(r
, "Failed to query for passphrase: %m");
3111 assert(!strv_isempty(z
));
3116 static int decrypted_image_relinquish(DecryptedImage
*d
) {
3119 /* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
3120 * boolean so that we don't clean it up ourselves either anymore */
3122 #if HAVE_LIBCRYPTSETUP
3125 for (size_t i
= 0; i
< d
->n_decrypted
; i
++) {
3126 DecryptedPartition
*p
= d
->decrypted
+ i
;
3128 if (p
->relinquished
)
3131 r
= sym_crypt_deactivate_by_name(NULL
, p
->name
, CRYPT_DEACTIVATE_DEFERRED
);
3133 return log_debug_errno(r
, "Failed to mark %s for auto-removal: %m", p
->name
);
3135 p
->relinquished
= true;
3142 int dissected_image_relinquish(DissectedImage
*m
) {
3147 if (m
->decrypted_image
) {
3148 r
= decrypted_image_relinquish(m
->decrypted_image
);
3154 loop_device_relinquish(m
->loop
);
3159 void image_filter_done(ImageFilter
*f
) {
3162 FOREACH_ELEMENT(p
, f
->pattern
)
3166 ImageFilter
*image_filter_free(ImageFilter
*f
) {
3170 image_filter_done(f
);
3174 int image_filter_parse(const char *s
, ImageFilter
**ret
) {
3175 _cleanup_(image_filter_freep
) ImageFilter
*f
= NULL
;
3185 _cleanup_free_
char *word
= NULL
;
3187 r
= extract_first_word(&s
, &word
, ":", EXTRACT_UNQUOTE
|EXTRACT_DONT_COALESCE_SEPARATORS
);
3189 return log_debug_errno(r
, "Failed to extract word: %m");
3193 _cleanup_free_
char *designator
= NULL
, *pattern
= NULL
;
3194 const char *x
= word
;
3195 r
= extract_many_words(&x
, "=", EXTRACT_UNQUOTE
|EXTRACT_DONT_COALESCE_SEPARATORS
, &designator
, &pattern
);
3197 return log_debug_errno(r
, "Failed to extract designator: %m");
3198 if (r
!= 2 || !isempty(x
))
3199 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Unable to split: %m");
3201 PartitionDesignator d
= partition_designator_from_string(designator
);
3203 return log_debug_errno(d
, "Failed to parse partition designator: %s", designator
);
3206 f
= new0(ImageFilter
, 1);
3208 return log_oom_debug();
3209 } else if (f
->pattern
[d
])
3210 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Duplicate pattern for '%s', refusing.", partition_designator_to_string(d
));
3212 f
->pattern
[d
] = TAKE_PTR(pattern
);
3221 static char *build_auxiliary_path(const char *image
, const char *suffix
) {
3228 e
= endswith(image
, ".raw");
3230 return strjoin(e
, suffix
);
3232 n
= new(char, e
- image
+ strlen(suffix
) + 1);
3236 strcpy(mempcpy(n
, image
, e
- image
), suffix
);
3240 void verity_settings_done(VeritySettings
*v
) {
3243 v
->root_hash
= mfree(v
->root_hash
);
3244 v
->root_hash_size
= 0;
3246 v
->root_hash_sig
= mfree(v
->root_hash_sig
);
3247 v
->root_hash_sig_size
= 0;
3249 v
->data_path
= mfree(v
->data_path
);
3252 VeritySettings
* verity_settings_free(VeritySettings
*v
) {
3256 verity_settings_done(v
);
3260 void verity_settings_hash_func(const VeritySettings
*s
, struct siphash
*state
) {
3263 siphash24_compress_typesafe(s
->root_hash_size
, state
);
3264 siphash24_compress(s
->root_hash
, s
->root_hash_size
, state
);
3267 int verity_settings_compare_func(const VeritySettings
*x
, const VeritySettings
*y
) {
3270 r
= CMP(x
->root_hash_size
, y
->root_hash_size
);
3274 return memcmp(x
->root_hash
, y
->root_hash
, x
->root_hash_size
);
3277 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(verity_settings_hash_ops
, VeritySettings
, verity_settings_hash_func
, verity_settings_compare_func
, VeritySettings
, verity_settings_free
);
3279 int verity_settings_load(
3280 VeritySettings
*verity
,
3282 const char *root_hash_path
,
3283 const char *root_hash_sig_path
) {
3285 _cleanup_free_
void *root_hash
= NULL
, *root_hash_sig
= NULL
;
3286 size_t root_hash_size
= 0, root_hash_sig_size
= 0;
3287 _cleanup_free_
char *verity_data_path
= NULL
;
3288 PartitionDesignator designator
;
3293 assert(verity
->designator
< 0 || IN_SET(verity
->designator
, PARTITION_ROOT
, PARTITION_USR
));
3295 /* If we are asked to load the root hash for a device node, exit early */
3296 if (is_device_path(image
))
3299 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
3300 if (r
< 0 && r
!= -ENXIO
)
3301 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
3305 designator
= verity
->designator
;
3307 /* We only fill in what isn't already filled in */
3309 if (!verity
->root_hash
) {
3310 _cleanup_free_
char *text
= NULL
;
3312 if (root_hash_path
) {
3313 /* If explicitly specified it takes precedence */
3314 r
= read_one_line_file(root_hash_path
, &text
);
3319 designator
= PARTITION_ROOT
;
3321 /* Otherwise look for xattr and separate file, and first for the data for root and if
3322 * that doesn't exist for /usr */
3324 if (designator
< 0 || designator
== PARTITION_ROOT
) {
3325 r
= getxattr_malloc(image
, "user.verity.roothash", &text
, /* ret_size= */ NULL
);
3327 _cleanup_free_
char *p
= NULL
;
3329 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
3332 p
= build_auxiliary_path(image
, ".roothash");
3336 r
= read_one_line_file(p
, &text
);
3337 if (r
< 0 && r
!= -ENOENT
)
3342 designator
= PARTITION_ROOT
;
3345 if (!text
&& (designator
< 0 || designator
== PARTITION_USR
)) {
3346 /* So in the "roothash" xattr/file name above the "root" of course primarily
3347 * refers to the root of the Verity Merkle tree. But coincidentally it also
3348 * is the hash for the *root* file system, i.e. the "root" neatly refers to
3349 * two distinct concepts called "root". Taking benefit of this happy
3350 * coincidence we call the file with the root hash for the /usr/ file system
3351 * `usrhash`, because `usrroothash` or `rootusrhash` would just be too
3352 * confusing. We thus drop the reference to the root of the Merkle tree, and
3353 * just indicate which file system it's about. */
3354 r
= getxattr_malloc(image
, "user.verity.usrhash", &text
, /* ret_size= */ NULL
);
3356 _cleanup_free_
char *p
= NULL
;
3358 if (r
!= -ENOENT
&& !ERRNO_IS_XATTR_ABSENT(r
))
3361 p
= build_auxiliary_path(image
, ".usrhash");
3365 r
= read_one_line_file(p
, &text
);
3366 if (r
< 0 && r
!= -ENOENT
)
3371 designator
= PARTITION_USR
;
3376 r
= unhexmem(text
, &root_hash
, &root_hash_size
);
3379 if (root_hash_size
< sizeof(sd_id128_t
))
3384 if ((root_hash
|| verity
->root_hash
) && !verity
->root_hash_sig
) {
3385 if (root_hash_sig_path
) {
3386 r
= read_full_file(root_hash_sig_path
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3387 if (r
< 0 && r
!= -ENOENT
)
3391 designator
= PARTITION_ROOT
;
3393 if (designator
< 0 || designator
== PARTITION_ROOT
) {
3394 _cleanup_free_
char *p
= NULL
;
3396 /* Follow naming convention recommended by the relevant RFC:
3397 * https://tools.ietf.org/html/rfc5751#section-3.2.1 */
3398 p
= build_auxiliary_path(image
, ".roothash.p7s");
3402 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3403 if (r
< 0 && r
!= -ENOENT
)
3406 designator
= PARTITION_ROOT
;
3409 if (!root_hash_sig
&& (designator
< 0 || designator
== PARTITION_USR
)) {
3410 _cleanup_free_
char *p
= NULL
;
3412 p
= build_auxiliary_path(image
, ".usrhash.p7s");
3416 r
= read_full_file(p
, (char**) &root_hash_sig
, &root_hash_sig_size
);
3417 if (r
< 0 && r
!= -ENOENT
)
3420 designator
= PARTITION_USR
;
3424 if (root_hash_sig
&& root_hash_sig_size
== 0) /* refuse empty size signatures */
3428 if (!verity
->data_path
) {
3429 _cleanup_free_
char *p
= NULL
;
3431 p
= build_auxiliary_path(image
, ".verity");
3435 if (access(p
, F_OK
) < 0) {
3436 if (errno
!= ENOENT
)
3439 verity_data_path
= TAKE_PTR(p
);
3443 verity
->root_hash
= TAKE_PTR(root_hash
);
3444 verity
->root_hash_size
= root_hash_size
;
3447 if (root_hash_sig
) {
3448 verity
->root_hash_sig
= TAKE_PTR(root_hash_sig
);
3449 verity
->root_hash_sig_size
= root_hash_sig_size
;
3452 if (verity_data_path
)
3453 verity
->data_path
= TAKE_PTR(verity_data_path
);
3455 if (verity
->designator
< 0)
3456 verity
->designator
= designator
;
3461 int verity_settings_copy(VeritySettings
*dest
, const VeritySettings
*source
) {
3465 *dest
= VERITY_SETTINGS_DEFAULT
;
3469 _cleanup_free_
void *rh
= NULL
;
3470 if (source
->root_hash_size
> 0) {
3471 rh
= memdup(source
->root_hash
, source
->root_hash_size
);
3473 return log_oom_debug();
3476 _cleanup_free_
void *sig
= NULL
;
3477 if (source
->root_hash_sig_size
> 0) {
3478 sig
= memdup(source
->root_hash_sig
, source
->root_hash_sig_size
);
3480 return log_oom_debug();
3483 _cleanup_free_
char *p
= NULL
;
3484 if (source
->data_path
) {
3485 p
= strdup(source
->data_path
);
3487 return log_oom_debug();
3490 *dest
= (VeritySettings
) {
3491 .root_hash
= TAKE_PTR(rh
),
3492 .root_hash_size
= source
->root_hash_size
,
3493 .root_hash_sig
= TAKE_PTR(sig
),
3494 .root_hash_sig_size
= source
->root_hash_sig_size
,
3495 .data_path
= TAKE_PTR(p
),
3496 .designator
= source
->designator
,
3502 int dissected_image_load_verity_sig_partition(
3505 VeritySettings
*verity
) {
3513 if (verity
->root_hash
&& verity
->root_hash_sig
) /* Already loaded? */
3516 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_EMBEDDED");
3517 if (r
< 0 && r
!= -ENXIO
)
3518 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_EMBEDDED, ignoring: %m");
3522 PartitionDesignator dd
= verity
->designator
;
3524 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
3525 dd
= PARTITION_ROOT
;
3526 else if (m
->partitions
[PARTITION_USR_VERITY
].found
)
3532 if (!m
->partitions
[dd
].found
)
3535 PartitionDesignator dv
= partition_verity_of(dd
);
3537 if (!m
->partitions
[dv
].found
)
3540 PartitionDesignator ds
= partition_verity_sig_of(dd
);
3543 DissectedPartition
*p
= m
->partitions
+ ds
;
3546 if (p
->offset
== UINT64_MAX
|| p
->size
== UINT64_MAX
)
3549 if (p
->size
> 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
3550 return log_debug_errno(SYNTHETIC_ERRNO(EFBIG
), "Verity signature partition is larger than 4M, refusing.");
3552 _cleanup_free_
char *buf
= new(char, p
->size
+1);
3556 ssize_t n
= pread(fd
, buf
, p
->size
, p
->offset
);
3559 if ((uint64_t) n
!= p
->size
)
3562 const char *e
= memchr(buf
, 0, p
->size
);
3564 /* If we found a NUL byte then the rest of the data must be NUL too */
3565 if (!memeqzero(e
, p
->size
- (e
- buf
)))
3566 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature data contains embedded NUL byte.");
3570 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*v
= NULL
;
3571 r
= sd_json_parse(buf
, 0, &v
, /* reterr_line= */ NULL
, /* reterr_column= */ NULL
);
3573 return log_debug_errno(r
, "Failed to parse signature JSON data: %m");
3575 sd_json_variant
*rh
= sd_json_variant_by_key(v
, "rootHash");
3577 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'rootHash' field.");
3579 _cleanup_free_
void *root_hash
= NULL
;
3580 size_t root_hash_size
;
3581 r
= sd_json_variant_unhex(rh
, &root_hash
, &root_hash_size
);
3583 return log_debug_errno(r
, "Failed to parse root hash field: %m");
3585 /* Check if specified root hash matches if it is specified */
3586 if (verity
->root_hash
&&
3587 memcmp_nn(verity
->root_hash
, verity
->root_hash_size
, root_hash
, root_hash_size
) != 0) {
3588 _cleanup_free_
char *a
= NULL
, *b
= NULL
;
3590 a
= hexmem(root_hash
, root_hash_size
);
3591 b
= hexmem(verity
->root_hash
, verity
->root_hash_size
);
3593 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Root hash in signature JSON data (%s) doesn't match configured hash (%s).", strna(a
), strna(b
));
3596 sd_json_variant
*sig
= sd_json_variant_by_key(v
, "signature");
3598 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Signature JSON object lacks 'signature' field.");
3600 _cleanup_free_
void *root_hash_sig
= NULL
;
3601 size_t root_hash_sig_size
;
3602 r
= sd_json_variant_unbase64(sig
, &root_hash_sig
, &root_hash_sig_size
);
3604 return log_debug_errno(r
, "Failed to parse signature field: %m");
3606 free_and_replace(verity
->root_hash
, root_hash
);
3607 verity
->root_hash_size
= root_hash_size
;
3609 free_and_replace(verity
->root_hash_sig
, root_hash_sig
);
3610 verity
->root_hash_sig_size
= root_hash_sig_size
;
3612 verity
->designator
= dd
;
3614 m
->verity_ready
= true;
3615 m
->verity_sig_ready
= true;
3616 m
->partitions
[dd
].rw
= false;
3621 int dissected_image_guess_verity_roothash(
3623 VeritySettings
*verity
) {
3630 /* Guesses the Verity root hash from the partitions we found, taking into account that as per
3631 * https://uapi-group.org/specifications/specs/discoverable_partitions_specification/ the UUIDS of
3632 * the data and verity partitions are respectively the first and second halves of the dm-verity
3635 * Note of course that relying on this guesswork is mostly useful for later attestation, not so much
3636 * for a-priori security. */
3638 if (verity
->root_hash
) /* Already loaded? */
3641 r
= secure_getenv_bool("SYSTEMD_DISSECT_VERITY_GUESS");
3642 if (r
< 0 && r
!= -ENXIO
)
3643 log_debug_errno(r
, "Failed to parse $SYSTEMD_DISSECT_VERITY_GUESS, ignoring: %m");
3647 PartitionDesignator dd
= verity
->designator
;
3649 if (m
->partitions
[PARTITION_ROOT_VERITY
].found
)
3650 dd
= PARTITION_ROOT
;
3651 else if (m
->partitions
[PARTITION_USR_VERITY
].found
)
3657 DissectedPartition
*d
= m
->partitions
+ dd
;
3661 PartitionDesignator dv
= partition_verity_of(dd
);
3664 DissectedPartition
*p
= m
->partitions
+ dv
;
3668 _cleanup_free_
uint8_t *rh
= malloc(sizeof(sd_id128_t
) * 2);
3670 return log_oom_debug();
3672 memcpy(mempcpy(rh
, &d
->uuid
, sizeof(sd_id128_t
)), &p
->uuid
, sizeof(sd_id128_t
));
3673 verity
->root_hash
= TAKE_PTR(rh
);
3674 verity
->root_hash_size
= sizeof(sd_id128_t
) * 2;
3676 verity
->designator
= dd
;
3678 m
->verity_ready
= true;
3679 m
->partitions
[dd
].rw
= false;
3684 int dissected_image_acquire_metadata(
3687 DissectImageFlags extra_flags
) {
3694 META_INITRD_RELEASE
,
3695 META_SYSEXT_RELEASE
,
3696 META_CONFEXT_RELEASE
,
3697 META_HAS_INIT_SYSTEM
,
3701 static const char *const paths
[_META_MAX
] = {
3702 [META_HOSTNAME
] = "/etc/hostname\0",
3703 [META_MACHINE_ID
] = "/etc/machine-id\0",
3704 [META_MACHINE_INFO
] = "/etc/machine-info\0",
3705 [META_OS_RELEASE
] = "/etc/os-release\0"
3706 "/usr/lib/os-release\0",
3707 [META_INITRD_RELEASE
] = "/etc/initrd-release\0"
3708 "/usr/lib/initrd-release\0",
3709 [META_SYSEXT_RELEASE
] = "sysext-release\0", /* String used only for logging. */
3710 [META_CONFEXT_RELEASE
] = "confext-release\0", /* ditto */
3711 [META_HAS_INIT_SYSTEM
] = "has-init-system\0", /* ditto */
3714 _cleanup_strv_free_
char **machine_info
= NULL
, **os_release
= NULL
, **initrd_release
= NULL
, **sysext_release
= NULL
, **confext_release
= NULL
;
3715 _cleanup_free_
char *hostname
= NULL
, *t
= NULL
;
3716 _cleanup_close_pair_
int error_pipe
[2] = EBADF_PAIR
;
3717 _cleanup_(sigkill_waitp
) pid_t child
= 0;
3718 sd_id128_t machine_id
= SD_ID128_NULL
;
3719 unsigned n_meta_initialized
= 0;
3720 int fds
[2 * _META_MAX
], r
, v
;
3721 int has_init_system
= -1;
3724 BLOCK_SIGNALS(SIGCHLD
);
3728 for (; n_meta_initialized
< _META_MAX
; n_meta_initialized
++) {
3729 assert(paths
[n_meta_initialized
]);
3731 if (pipe2(fds
+ 2*n_meta_initialized
, O_CLOEXEC
) < 0) {
3737 r
= get_common_dissect_directory(&t
);
3741 if (pipe2(error_pipe
, O_CLOEXEC
) < 0) {
3746 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
, &child
);
3751 error_pipe
[0] = safe_close(error_pipe
[0]);
3754 r
= detach_mount_namespace_harder(0, 0);
3756 r
= detach_mount_namespace_userns(userns_fd
);
3758 log_debug_errno(r
, "Failed to detach mount namespace: %m");
3759 report_errno_and_exit(error_pipe
[1], r
);
3762 r
= dissected_image_mount(
3765 /* uid_shift= */ UID_INVALID
,
3766 /* uid_range= */ UID_INVALID
,
3767 /* userns_fd= */ -EBADF
,
3769 DISSECT_IMAGE_READ_ONLY
|
3770 DISSECT_IMAGE_MOUNT_ROOT_ONLY
|
3771 DISSECT_IMAGE_USR_NO_ROOT
);
3773 log_debug_errno(r
, "Failed to mount dissected image: %m");
3774 report_errno_and_exit(error_pipe
[1], r
);
3777 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
3778 _cleanup_close_
int fd
= -ENOENT
;
3782 fds
[2*k
] = safe_close(fds
[2*k
]);
3786 case META_SYSEXT_RELEASE
:
3790 /* As per the os-release spec, if the image is an extension it will have a
3791 * file named after the image name in extension-release.d/ - we use the image
3792 * name and try to resolve it with the extension-release helpers, as
3793 * sometimes the image names are mangled on deployment and do not match
3794 * anymore. Unlike other paths this is not fixed, and the image name can be
3795 * mangled on deployment, so by calling into the helper we allow a fallback
3796 * that matches on the first extension-release file found in the directory,
3797 * if one named after the image cannot be found first. */
3798 r
= open_extension_release(
3802 /* relax_extension_release_check= */ false,
3803 /* ret_path= */ NULL
,
3809 case META_CONFEXT_RELEASE
:
3814 r
= open_extension_release(
3818 /* relax_extension_release_check= */ false,
3819 /* ret_path= */ NULL
,
3826 case META_HAS_INIT_SYSTEM
: {
3829 FOREACH_STRING(init
,
3830 "/usr/lib/systemd/systemd", /* systemd on /usr/ merged system */
3831 "/lib/systemd/systemd", /* systemd on /usr/ non-merged systems */
3832 "/sbin/init") { /* traditional path the Linux kernel invokes */
3834 r
= chase(init
, t
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
3837 log_debug_errno(r
, "Failed to resolve %s, ignoring: %m", init
);
3844 r
= loop_write(fds
[2*k
+1], &found
, sizeof(found
));
3846 report_errno_and_exit(error_pipe
[1], r
);
3852 NULSTR_FOREACH(p
, paths
[k
]) {
3853 fd
= chase_and_open(p
, t
, CHASE_PREFIX_ROOT
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
, NULL
);
3860 log_debug_errno(fd
, "Failed to read %s file of image, ignoring: %m", paths
[k
]);
3864 r
= copy_bytes(fd
, fds
[2*k
+1], UINT64_MAX
, 0);
3866 report_errno_and_exit(error_pipe
[1], r
);
3869 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
3872 _exit(EXIT_SUCCESS
);
3875 error_pipe
[1] = safe_close(error_pipe
[1]);
3877 for (unsigned k
= 0; k
< _META_MAX
; k
++) {
3878 _cleanup_fclose_
FILE *f
= NULL
;
3882 fds
[2*k
+1] = safe_close(fds
[2*k
+1]);
3884 f
= take_fdopen(&fds
[2*k
], "r");
3893 r
= read_etc_hostname_stream(f
, /* substitute_wildcards= */ false, &hostname
);
3895 log_debug_errno(r
, "Failed to read /etc/hostname of image: %m");
3899 case META_MACHINE_ID
: {
3900 _cleanup_free_
char *line
= NULL
;
3902 r
= read_line(f
, LONG_LINE_MAX
, &line
);
3904 log_debug_errno(r
, "Failed to read /etc/machine-id of image: %m");
3906 r
= sd_id128_from_string(line
, &machine_id
);
3908 log_debug_errno(r
, "Image contains invalid /etc/machine-id: %s", line
);
3910 log_debug("/etc/machine-id file of image is empty.");
3911 else if (streq(line
, "uninitialized"))
3912 log_debug("/etc/machine-id file of image is uninitialized (likely aborted first boot).");
3914 log_debug("/etc/machine-id file of image has unexpected length %i.", r
);
3919 case META_MACHINE_INFO
:
3920 r
= load_env_file_pairs(f
, "machine-info", &machine_info
);
3922 log_debug_errno(r
, "Failed to read /etc/machine-info of image: %m");
3926 case META_OS_RELEASE
:
3927 r
= load_env_file_pairs(f
, "os-release", &os_release
);
3929 log_debug_errno(r
, "Failed to read OS release file of image: %m");
3933 case META_INITRD_RELEASE
:
3934 r
= load_env_file_pairs(f
, "initrd-release", &initrd_release
);
3936 log_debug_errno(r
, "Failed to read initrd release file of image: %m");
3940 case META_SYSEXT_RELEASE
:
3941 r
= load_env_file_pairs(f
, "sysext-release", &sysext_release
);
3943 log_debug_errno(r
, "Failed to read sysext release file of image: %m");
3947 case META_CONFEXT_RELEASE
:
3948 r
= load_env_file_pairs(f
, "confext-release", &confext_release
);
3950 log_debug_errno(r
, "Failed to read confext release file of image: %m");
3954 case META_HAS_INIT_SYSTEM
: {
3959 nr
= fread(&b
, 1, sizeof(b
), f
);
3960 if (nr
!= sizeof(b
))
3961 log_debug_errno(errno_or_else(EIO
), "Failed to read has-init-system boolean: %m");
3963 has_init_system
= b
;
3969 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
3974 n
= read(error_pipe
[0], &v
, sizeof(v
));
3979 if (n
== sizeof(v
)) {
3980 r
= v
; /* propagate error sent to us from child */
3987 if (r
!= EXIT_SUCCESS
) {
3992 free_and_replace(m
->hostname
, hostname
);
3993 m
->machine_id
= machine_id
;
3994 strv_free_and_replace(m
->machine_info
, machine_info
);
3995 strv_free_and_replace(m
->os_release
, os_release
);
3996 strv_free_and_replace(m
->initrd_release
, initrd_release
);
3997 strv_free_and_replace(m
->sysext_release
, sysext_release
);
3998 strv_free_and_replace(m
->confext_release
, confext_release
);
3999 m
->has_init_system
= has_init_system
;
4002 for (unsigned k
= 0; k
< n_meta_initialized
; k
++)
4003 safe_close_pair(fds
+ 2*k
);
4008 Architecture
dissected_image_architecture(DissectedImage
*img
) {
4011 if (img
->partitions
[PARTITION_ROOT
].found
&&
4012 img
->partitions
[PARTITION_ROOT
].architecture
>= 0)
4013 return img
->partitions
[PARTITION_ROOT
].architecture
;
4015 if (img
->partitions
[PARTITION_USR
].found
&&
4016 img
->partitions
[PARTITION_USR
].architecture
>= 0)
4017 return img
->partitions
[PARTITION_USR
].architecture
;
4019 return _ARCHITECTURE_INVALID
;
4022 bool dissected_image_is_portable(DissectedImage
*m
) {
4023 return m
&& strv_env_pairs_get(m
->os_release
, "PORTABLE_PREFIXES");
4026 bool dissected_image_is_initrd(DissectedImage
*m
) {
4027 return m
&& !strv_isempty(m
->initrd_release
);
4030 int dissect_loop_device(
4032 const VeritySettings
*verity
,
4033 const MountOptions
*mount_options
,
4034 const ImagePolicy
*image_policy
,
4035 const ImageFilter
*image_filter
,
4036 DissectImageFlags flags
,
4037 DissectedImage
**ret
) {
4040 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
4045 r
= dissected_image_new(loop
->backing_file
?: loop
->node
, &m
);
4049 m
->loop
= loop_device_ref(loop
);
4050 m
->image_size
= m
->loop
->device_size
;
4051 m
->sector_size
= m
->loop
->sector_size
;
4074 int dissect_loop_device_and_warn(
4076 const VeritySettings
*verity
,
4077 const MountOptions
*mount_options
,
4078 const ImagePolicy
*image_policy
,
4079 const ImageFilter
*image_filter
,
4080 DissectImageFlags flags
,
4081 DissectedImage
**ret
) {
4085 return dissect_log_error(
4087 dissect_loop_device(loop
, verity
, mount_options
, image_policy
, image_filter
, flags
, ret
),
4088 loop
->backing_file
?: loop
->node
,
4092 bool dissected_image_verity_candidate(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
4095 /* Checks if this partition could theoretically do Verity. For non-partitioned images this only works
4096 * if there's an external verity file supplied, for which we can consult .has_verity. For partitioned
4097 * images we only check the partition type.
4099 * This call is used to decide whether to suppress or show a verity column in tabular output of the
4102 if (image
->single_file_system
)
4103 return partition_designator
== PARTITION_ROOT
&& image
->has_verity
;
4105 return partition_verity_of(partition_designator
) >= 0;
4108 bool dissected_image_verity_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
4109 PartitionDesignator k
;
4113 /* Checks if this partition has verity data available that we can activate. For non-partitioned this
4114 * works for the root partition, for others only if the associated verity partition was found. */
4116 if (!image
->verity_ready
)
4119 if (image
->single_file_system
)
4120 return partition_designator
== PARTITION_ROOT
;
4122 k
= partition_verity_of(partition_designator
);
4123 return k
>= 0 && image
->partitions
[k
].found
;
4126 bool dissected_image_verity_sig_ready(const DissectedImage
*image
, PartitionDesignator partition_designator
) {
4127 PartitionDesignator k
;
4131 /* Checks if this partition has verity signature data available that we can use. */
4133 if (!image
->verity_sig_ready
)
4136 if (image
->single_file_system
)
4137 return partition_designator
== PARTITION_ROOT
;
4139 k
= partition_verity_sig_of(partition_designator
);
4140 return k
>= 0 && image
->partitions
[k
].found
;
4143 MountOptions
* mount_options_free_all(MountOptions
*options
) {
4146 while ((m
= LIST_POP(mount_options
, options
))) {
4154 const char* mount_options_from_designator(const MountOptions
*options
, PartitionDesignator designator
) {
4155 LIST_FOREACH(mount_options
, m
, options
)
4156 if (designator
== m
->partition_designator
&& !isempty(m
->options
))
4162 int mount_image_privately_interactively(
4164 const ImagePolicy
*image_policy
,
4165 DissectImageFlags flags
,
4166 char **ret_directory
,
4168 LoopDevice
**ret_loop_device
) {
4170 _cleanup_(verity_settings_done
) VeritySettings verity
= VERITY_SETTINGS_DEFAULT
;
4171 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
4172 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
4173 _cleanup_free_
char *dir
= NULL
;
4176 /* Mounts an OS image at a temporary place, inside a newly created mount namespace of our own. This
4177 * is used by tools such as systemd-tmpfiles or systemd-firstboot to operate on some disk image
4181 assert(ret_loop_device
);
4183 /* We intend to mount this right-away, hence add the partitions if needed and pin them. */
4184 flags
|= DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
4185 DISSECT_IMAGE_PIN_PARTITION_DEVICES
;
4187 r
= verity_settings_load(&verity
, image
, NULL
, NULL
);
4189 return log_error_errno(r
, "Failed to load root hash data: %m");
4191 r
= loop_device_make_by_path(
4193 FLAGS_SET(flags
, DISSECT_IMAGE_DEVICE_READ_ONLY
) ? O_RDONLY
: O_RDWR
,
4194 /* sector_size= */ UINT32_MAX
,
4195 FLAGS_SET(flags
, DISSECT_IMAGE_NO_PARTITION_TABLE
) ? 0 : LO_FLAGS_PARTSCAN
,
4199 return log_error_errno(r
, "Failed to set up loopback device for %s: %m", image
);
4201 r
= dissect_loop_device_and_warn(
4204 /* mount_options= */ NULL
,
4206 /* image_filter= */ NULL
,
4212 r
= dissected_image_load_verity_sig_partition(dissected_image
, d
->fd
, &verity
);
4216 r
= dissected_image_guess_verity_roothash(dissected_image
, &verity
);
4220 r
= dissected_image_decrypt_interactively(dissected_image
, NULL
, &verity
, flags
);
4224 r
= detach_mount_namespace();
4226 return log_error_errno(r
, "Failed to detach mount namespace: %m");
4228 r
= mkdir_p("/run/systemd/mount-rootfs", 0555);
4230 return log_error_errno(r
, "Failed to create mount point: %m");
4232 r
= dissected_image_mount_and_warn(
4234 "/run/systemd/mount-rootfs",
4235 /* uid_shift= */ UID_INVALID
,
4236 /* uid_range= */ UID_INVALID
,
4237 /* userns_fd= */ -EBADF
,
4242 r
= loop_device_flock(d
, LOCK_UN
);
4246 r
= dissected_image_relinquish(dissected_image
);
4248 return log_error_errno(r
, "Failed to relinquish DM and loopback block devices: %m");
4250 if (ret_directory
) {
4251 dir
= strdup("/run/systemd/mount-rootfs");
4257 _cleanup_close_
int dir_fd
= -EBADF
;
4259 dir_fd
= open("/run/systemd/mount-rootfs", O_CLOEXEC
|O_DIRECTORY
);
4261 return log_error_errno(errno
, "Failed to open mount point directory: %m");
4263 *ret_dir_fd
= TAKE_FD(dir_fd
);
4267 *ret_directory
= TAKE_PTR(dir
);
4269 *ret_loop_device
= TAKE_PTR(d
);
4273 static bool mount_options_relax_extension_release_checks(const MountOptions
*options
) {
4277 return string_contains_word(mount_options_from_designator(options
, PARTITION_ROOT
), ",", "x-systemd.relax-extension-release-check") ||
4278 string_contains_word(mount_options_from_designator(options
, PARTITION_USR
), ",", "x-systemd.relax-extension-release-check") ||
4279 string_contains_word(options
->options
, ",", "x-systemd.relax-extension-release-check");
4282 int verity_dissect_and_mount(
4286 const MountOptions
*options
,
4287 const ImagePolicy
*image_policy
,
4288 const ImageFilter
*image_filter
,
4289 const ExtensionReleaseData
*extension_release_data
,
4290 ImageClass required_class
,
4291 VeritySettings
*verity
,
4292 DissectedImage
**ret_image
) {
4294 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
4295 _cleanup_(dissected_image_unrefp
) DissectedImage
*dissected_image
= NULL
;
4296 _cleanup_(verity_settings_done
) VeritySettings local_verity
= VERITY_SETTINGS_DEFAULT
;
4297 DissectImageFlags dissect_image_flags
;
4298 bool relax_extension_release_check
;
4302 /* Verifying release metadata requires mounted image for now, so ensure the check is skipped when
4303 * opening an image without mounting it immediately (i.e.: 'dest' is NULL). */
4304 assert(!extension_release_data
|| dest
);
4306 relax_extension_release_check
= mount_options_relax_extension_release_checks(options
);
4308 /* We might get an FD for the image, but we use the original path to look for the dm-verity files.
4309 * The caller might also give us a pre-loaded VeritySettings, in which case we just use it. It will
4310 * also be extended, as dissected_image_load_verity_sig_partition() is invoked. */
4312 r
= verity_settings_load(&local_verity
, src
, NULL
, NULL
);
4314 return log_debug_errno(r
, "Failed to load root hash: %m");
4316 verity
= &local_verity
;
4319 dissect_image_flags
=
4320 (verity
->data_path
? DISSECT_IMAGE_NO_PARTITION_TABLE
: 0) |
4321 (relax_extension_release_check
? DISSECT_IMAGE_RELAX_EXTENSION_CHECK
: 0) |
4322 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
4323 DISSECT_IMAGE_PIN_PARTITION_DEVICES
|
4324 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
;
4326 /* Note that we don't use loop_device_make here, as the FD is most likely O_PATH which would not be
4327 * accepted by LOOP_CONFIGURE, so just let loop_device_make_by_path reopen it as a regular FD. */
4328 r
= loop_device_make_by_path(
4329 src_fd
>= 0 ? FORMAT_PROC_FD_PATH(src_fd
) : src
,
4330 /* open_flags= */ -1,
4331 /* sector_size= */ UINT32_MAX
,
4332 verity
->data_path
? 0 : LO_FLAGS_PARTSCAN
,
4336 return log_debug_errno(r
, "Failed to create loop device for image: %m");
4338 r
= dissect_loop_device(
4344 dissect_image_flags
,
4346 /* No partition table? Might be a single-filesystem image, try again */
4347 if (!verity
->data_path
&& r
== -ENOPKG
)
4348 r
= dissect_loop_device(
4354 dissect_image_flags
| DISSECT_IMAGE_NO_PARTITION_TABLE
,
4357 return log_debug_errno(r
, "Failed to dissect image: %m");
4359 r
= dissected_image_load_verity_sig_partition(dissected_image
, loop_device
->fd
, verity
);
4363 r
= dissected_image_guess_verity_roothash(dissected_image
, verity
);
4367 r
= dissected_image_decrypt(
4371 dissect_image_flags
);
4373 return log_debug_errno(r
, "Failed to decrypt dissected image: %m");
4376 r
= mkdir_p_label(dest
, 0755);
4378 return log_debug_errno(r
, "Failed to create destination directory %s: %m", dest
);
4379 r
= umount_recursive(dest
, 0);
4381 return log_debug_errno(r
, "Failed to umount under destination directory %s: %m", dest
);
4384 r
= dissected_image_mount(
4387 /* uid_shift= */ UID_INVALID
,
4388 /* uid_range= */ UID_INVALID
,
4389 /* userns_fd= */ -EBADF
,
4390 dissect_image_flags
);
4392 return log_debug_errno(r
, "Failed to mount image: %m");
4394 r
= loop_device_flock(loop_device
, LOCK_UN
);
4396 return log_debug_errno(r
, "Failed to unlock loopback device: %m");
4398 /* If we got os-release values from the caller, then we need to match them with the image's
4399 * extension-release.d/ content. Return -EINVAL if there's any mismatch.
4400 * First, check the distro ID. If that matches, then check the new SYSEXT_LEVEL value if
4401 * available, or else fallback to VERSION_ID. If neither is present (eg: rolling release),
4402 * then a simple match on the ID will be performed. Also if an extension class was specified,
4403 * check that it matches or return ENOCSI (which looks like error-no-class if one squints enough). */
4404 if ((extension_release_data
&& extension_release_data
->os_release_id
) || required_class
>= 0) {
4405 _cleanup_strv_free_
char **extension_release
= NULL
;
4406 ImageClass
class = IMAGE_SYSEXT
;
4408 assert(!isempty(extension_release_data
->os_release_id
));
4410 r
= load_extension_release_pairs(dest
, required_class
>= 0 ? required_class
: IMAGE_SYSEXT
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
4412 if (required_class
>= 0)
4413 return log_debug_errno(SYNTHETIC_ERRNO(ENOCSI
), "Image %s extension-release metadata does not match the expected class", dissected_image
->image_name
);
4415 r
= load_extension_release_pairs(dest
, IMAGE_CONFEXT
, dissected_image
->image_name
, relax_extension_release_check
, &extension_release
);
4417 class = IMAGE_CONFEXT
;
4420 return log_debug_errno(r
, "Failed to parse image %s extension-release metadata: %m", dissected_image
->image_name
);
4422 if (extension_release_data
&& !isempty(extension_release_data
->os_release_id
)) {
4423 r
= extension_release_validate(
4424 dissected_image
->image_name
,
4425 extension_release_data
->os_release_id
,
4426 extension_release_data
->os_release_id_like
,
4427 extension_release_data
->os_release_version_id
,
4428 class == IMAGE_SYSEXT
? extension_release_data
->os_release_sysext_level
: extension_release_data
->os_release_confext_level
,
4429 extension_release_data
->os_release_extension_scope
,
4433 return log_debug_errno(SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", dissected_image
->image_name
);
4435 return log_debug_errno(r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", dissected_image
->image_name
);
4439 r
= dissected_image_relinquish(dissected_image
);
4441 return log_debug_errno(r
, "Failed to relinquish dissected image: %m");
4444 *ret_image
= TAKE_PTR(dissected_image
);
4449 void extension_release_data_done(ExtensionReleaseData
*data
) {
4452 data
->os_release_id
= mfree(data
->os_release_id
);
4453 data
->os_release_id_like
= mfree(data
->os_release_id_like
);
4454 data
->os_release_version_id
= mfree(data
->os_release_version_id
);
4455 data
->os_release_sysext_level
= mfree(data
->os_release_sysext_level
);
4456 data
->os_release_confext_level
= mfree(data
->os_release_confext_level
);
4457 data
->os_release_extension_scope
= mfree(data
->os_release_extension_scope
);
4460 int get_common_dissect_directory(char **ret
) {
4461 _cleanup_free_
char *t
= NULL
;
4464 /* A common location we mount dissected images to. The assumption is that everyone who uses this
4465 * function runs in their own private mount namespace (with mount propagation off on /run/systemd/,
4466 * and thus can mount something here without affecting anyone else). */
4468 t
= strdup("/run/systemd/dissect-root");
4470 return log_oom_debug();
4472 r
= mkdir_parents(t
, 0755);
4474 return log_debug_errno(r
, "Failed to create parent dirs of mount point '%s': %m", t
);
4476 r
= RET_NERRNO(mkdir(t
, 0000)); /* It's supposed to be overmounted, hence let's make this inaccessible */
4477 if (r
< 0 && r
!= -EEXIST
)
4478 return log_debug_errno(r
, "Failed to create mount point '%s': %m", t
);
4488 static JSON_DISPATCH_ENUM_DEFINE(dispatch_architecture
, Architecture
, architecture_from_string
);
4489 static JSON_DISPATCH_ENUM_DEFINE(dispatch_partition_designator
, PartitionDesignator
, partition_designator_from_string
);
4491 typedef struct PartitionFields
{
4492 PartitionDesignator designator
;
4496 Architecture architecture
;
4502 unsigned fsmount_fd_idx
;
4505 static void partition_fields_done(PartitionFields
*f
) {
4508 f
->fstype
= mfree(f
->fstype
);
4509 f
->label
= mfree(f
->label
);
4512 typedef struct MountImageReplyParameters
{
4513 sd_json_variant
*partitions
;
4515 uint64_t image_size
;
4516 uint32_t sector_size
;
4517 sd_id128_t image_uuid
;
4518 } MountImageReplyParameters
;
4520 static void mount_image_reply_parameters_done(MountImageReplyParameters
*p
) {
4523 p
->image_policy
= mfree(p
->image_policy
);
4524 p
->partitions
= sd_json_variant_unref(p
->partitions
);
4529 int mountfsd_mount_image(
4532 const ImagePolicy
*image_policy
,
4533 DissectImageFlags flags
,
4534 DissectedImage
**ret
) {
4537 _cleanup_(mount_image_reply_parameters_done
) MountImageReplyParameters p
= {};
4539 static const sd_json_dispatch_field dispatch_table
[] = {
4540 { "partitions", SD_JSON_VARIANT_ARRAY
, sd_json_dispatch_variant
, offsetof(struct MountImageReplyParameters
, partitions
), SD_JSON_MANDATORY
},
4541 { "imagePolicy", SD_JSON_VARIANT_STRING
, sd_json_dispatch_string
, offsetof(struct MountImageReplyParameters
, image_policy
), 0 },
4542 { "imageSize", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint64
, offsetof(struct MountImageReplyParameters
, image_size
), SD_JSON_MANDATORY
},
4543 { "sectorSize", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint32
, offsetof(struct MountImageReplyParameters
, sector_size
), SD_JSON_MANDATORY
},
4544 { "imageUuid", SD_JSON_VARIANT_STRING
, sd_json_dispatch_id128
, offsetof(struct MountImageReplyParameters
, image_uuid
), 0 },
4548 _cleanup_(dissected_image_unrefp
) DissectedImage
*di
= NULL
;
4549 _cleanup_close_
int image_fd
= -EBADF
;
4550 _cleanup_(sd_varlink_unrefp
) sd_varlink
*vl
= NULL
;
4551 _cleanup_free_
char *ps
= NULL
;
4552 const char *error_id
;
4558 r
= sd_varlink_connect_address(&vl
, "/run/systemd/io.systemd.MountFileSystem");
4560 return log_error_errno(r
, "Failed to connect to mountfsd: %m");
4562 r
= sd_varlink_set_allow_fd_passing_input(vl
, true);
4564 return log_error_errno(r
, "Failed to enable varlink fd passing for read: %m");
4566 r
= sd_varlink_set_allow_fd_passing_output(vl
, true);
4568 return log_error_errno(r
, "Failed to enable varlink fd passing for write: %m");
4570 image_fd
= open(path
, O_RDONLY
|O_CLOEXEC
);
4572 return log_error_errno(errno
, "Failed to open '%s': %m", path
);
4574 r
= sd_varlink_push_dup_fd(vl
, image_fd
);
4576 return log_error_errno(r
, "Failed to push image fd into varlink connection: %m");
4578 if (userns_fd
>= 0) {
4579 r
= sd_varlink_push_dup_fd(vl
, userns_fd
);
4581 return log_error_errno(r
, "Failed to push image fd into varlink connection: %m");
4585 r
= image_policy_to_string(image_policy
, /* simplify= */ false, &ps
);
4587 return log_error_errno(r
, "Failed format image policy to string: %m");
4590 sd_json_variant
*reply
= NULL
;
4591 r
= varlink_callbo_and_log(
4593 "io.systemd.MountFileSystem.MountImage",
4596 SD_JSON_BUILD_PAIR("imageFileDescriptor", SD_JSON_BUILD_UNSIGNED(0)),
4597 SD_JSON_BUILD_PAIR_CONDITION(userns_fd
>= 0, "userNamespaceFileDescriptor", SD_JSON_BUILD_UNSIGNED(1)),
4598 SD_JSON_BUILD_PAIR("readOnly", SD_JSON_BUILD_BOOLEAN(FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_READ_ONLY
))),
4599 SD_JSON_BUILD_PAIR("growFileSystems", SD_JSON_BUILD_BOOLEAN(FLAGS_SET(flags
, DISSECT_IMAGE_GROWFS
))),
4600 SD_JSON_BUILD_PAIR_CONDITION(!!ps
, "imagePolicy", SD_JSON_BUILD_STRING(ps
)),
4601 SD_JSON_BUILD_PAIR("allowInteractiveAuthentication", SD_JSON_BUILD_BOOLEAN(FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH
))));
4605 r
= sd_json_dispatch(reply
, dispatch_table
, SD_JSON_ALLOW_EXTENSIONS
, &p
);
4607 return log_error_errno(r
, "Failed to parse MountImage() reply: %m");
4609 log_debug("Effective image policy: %s", p
.image_policy
);
4612 JSON_VARIANT_ARRAY_FOREACH(i
, p
.partitions
) {
4613 _cleanup_close_
int fsmount_fd
= -EBADF
;
4615 _cleanup_(partition_fields_done
) PartitionFields pp
= {
4616 .designator
= _PARTITION_DESIGNATOR_INVALID
,
4617 .architecture
= _ARCHITECTURE_INVALID
,
4619 .offset
= UINT64_MAX
,
4620 .fsmount_fd_idx
= UINT_MAX
,
4623 static const sd_json_dispatch_field partition_dispatch_table
[] = {
4624 { "designator", SD_JSON_VARIANT_STRING
, dispatch_partition_designator
, offsetof(struct PartitionFields
, designator
), SD_JSON_MANDATORY
},
4625 { "writable", SD_JSON_VARIANT_BOOLEAN
, sd_json_dispatch_stdbool
, offsetof(struct PartitionFields
, rw
), SD_JSON_MANDATORY
},
4626 { "growFileSystem", SD_JSON_VARIANT_BOOLEAN
, sd_json_dispatch_stdbool
, offsetof(struct PartitionFields
, growfs
), SD_JSON_MANDATORY
},
4627 { "partitionNumber", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint
, offsetof(struct PartitionFields
, partno
), 0 },
4628 { "architecture", SD_JSON_VARIANT_STRING
, dispatch_architecture
, offsetof(struct PartitionFields
, architecture
), 0 },
4629 { "partitionUuid", SD_JSON_VARIANT_STRING
, sd_json_dispatch_id128
, offsetof(struct PartitionFields
, uuid
), 0 },
4630 { "fileSystemType", SD_JSON_VARIANT_STRING
, sd_json_dispatch_string
, offsetof(struct PartitionFields
, fstype
), SD_JSON_MANDATORY
},
4631 { "partitionLabel", SD_JSON_VARIANT_STRING
, sd_json_dispatch_string
, offsetof(struct PartitionFields
, label
), 0 },
4632 { "size", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint64
, offsetof(struct PartitionFields
, size
), SD_JSON_MANDATORY
},
4633 { "offset", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint64
, offsetof(struct PartitionFields
, offset
), SD_JSON_MANDATORY
},
4634 { "mountFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint
, offsetof(struct PartitionFields
, fsmount_fd_idx
), SD_JSON_MANDATORY
},
4638 r
= sd_json_dispatch(i
, partition_dispatch_table
, SD_JSON_ALLOW_EXTENSIONS
, &pp
);
4640 return log_error_errno(r
, "Failed to parse partition data: %m");
4642 if (pp
.fsmount_fd_idx
!= UINT_MAX
) {
4643 fsmount_fd
= sd_varlink_take_fd(vl
, pp
.fsmount_fd_idx
);
4648 assert(pp
.designator
>= 0);
4651 r
= dissected_image_new(path
, &di
);
4653 return log_error_errno(r
, "Failed to allocated new dissected image structure: %m");
4656 if (di
->partitions
[pp
.designator
].found
)
4657 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Duplicate partition data for '%s'.", partition_designator_to_string(pp
.designator
));
4659 di
->partitions
[pp
.designator
] = (DissectedPartition
) {
4662 .growfs
= pp
.growfs
,
4663 .partno
= pp
.partno
,
4664 .architecture
= pp
.architecture
,
4666 .fstype
= TAKE_PTR(pp
.fstype
),
4667 .label
= TAKE_PTR(pp
.label
),
4668 .mount_node_fd
= -EBADF
,
4670 .offset
= pp
.offset
,
4671 .fsmount_fd
= TAKE_FD(fsmount_fd
),
4675 di
->image_size
= p
.image_size
;
4676 di
->sector_size
= p
.sector_size
;
4677 di
->image_uuid
= p
.image_uuid
;
4679 *ret
= TAKE_PTR(di
);
4686 int mountfsd_mount_directory(
4689 DissectImageFlags flags
,
4690 int *ret_mount_fd
) {
4694 /* Pick one identity, not both, that makes no sense. */
4695 assert(!FLAGS_SET(flags
, DISSECT_IMAGE_FOREIGN_UID
|DISSECT_IMAGE_IDENTITY_UID
));
4697 _cleanup_(sd_varlink_unrefp
) sd_varlink
*vl
= NULL
;
4698 r
= sd_varlink_connect_address(&vl
, "/run/systemd/io.systemd.MountFileSystem");
4700 return log_error_errno(r
, "Failed to connect to mountfsd: %m");
4702 r
= sd_varlink_set_allow_fd_passing_input(vl
, true);
4704 return log_error_errno(r
, "Failed to enable varlink fd passing for read: %m");
4706 r
= sd_varlink_set_allow_fd_passing_output(vl
, true);
4708 return log_error_errno(r
, "Failed to enable varlink fd passing for write: %m");
4710 _cleanup_close_
int directory_fd
= open(path
, O_DIRECTORY
|O_RDONLY
|O_CLOEXEC
);
4711 if (directory_fd
< 0)
4712 return log_error_errno(errno
, "Failed to open '%s': %m", path
);
4714 r
= sd_varlink_push_dup_fd(vl
, directory_fd
);
4716 return log_error_errno(r
, "Failed to push image fd into varlink connection: %m");
4718 if (userns_fd
>= 0) {
4719 r
= sd_varlink_push_dup_fd(vl
, userns_fd
);
4721 return log_error_errno(r
, "Failed to push image fd into varlink connection: %m");
4724 sd_json_variant
*reply
= NULL
;
4725 const char *error_id
= NULL
;
4726 r
= varlink_callbo_and_log(
4728 "io.systemd.MountFileSystem.MountDirectory",
4731 SD_JSON_BUILD_PAIR_UNSIGNED("directoryFileDescriptor", 0),
4732 SD_JSON_BUILD_PAIR_CONDITION(userns_fd
>= 0, "userNamespaceFileDescriptor", SD_JSON_BUILD_UNSIGNED(1)),
4733 SD_JSON_BUILD_PAIR_BOOLEAN("readOnly", FLAGS_SET(flags
, DISSECT_IMAGE_MOUNT_READ_ONLY
)),
4734 SD_JSON_BUILD_PAIR_STRING("mode", FLAGS_SET(flags
, DISSECT_IMAGE_FOREIGN_UID
) ? "foreign" :
4735 FLAGS_SET(flags
, DISSECT_IMAGE_IDENTITY_UID
) ? "identity" : "auto"),
4736 SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags
, DISSECT_IMAGE_ALLOW_INTERACTIVE_AUTH
)));
4740 static const sd_json_dispatch_field dispatch_table
[] = {
4741 { "mountFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID
, sd_json_dispatch_uint
, 0, SD_JSON_MANDATORY
},
4745 unsigned fsmount_fd_idx
= UINT_MAX
;
4746 r
= sd_json_dispatch(reply
, dispatch_table
, SD_JSON_ALLOW_EXTENSIONS
, &fsmount_fd_idx
);
4748 return log_error_errno(r
, "Failed to parse MountImage() reply: %m");
4750 _cleanup_close_
int fsmount_fd
= sd_varlink_take_fd(vl
, fsmount_fd_idx
);
4752 return log_error_errno(fsmount_fd
, "Failed to take mount fd from Varlink connection: %m");
4754 *ret_mount_fd
= TAKE_FD(fsmount_fd
);