HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/dissect-image.c

242,096 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 9280a90974918216809a09219e8a3162bddcf789

Lines 1–1000 of 5,731

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fnmatch.h>
#include <linux/loop.h>
#include <sys/file.h>
#include <sys/mount.h>
#include <unistd.h>
 
#include "sd-device.h"
#include "sd-id128.h"
#include "sd-json.h"
#include "sd-varlink.h"
 
#include "architecture.h"
#include "ask-password-api.h"
#include "blkid-util.h"
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "chase.h"
#include "conf-files.h"
#include "constants.h"
#include "copy.h"
#include "crypto-util.h"
#include "cryptsetup-util.h"
#include "device-private.h"
#include "devnum-util.h"
#include "dissect-image.h"
#include "dm-util.h"
#include "env-file.h"
#include "env-util.h"
#include "errno-util.h"
#include "extension-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fsck-util.h"
#include "fstab-util.h"
#include "gpt.h"
#include "hash-funcs.h"
#include "hexdecoct.h"
#include "hostname-setup.h"
#include "image-policy.h"
#include "import-util.h"
#include "io-util.h"
#include "iovec-util.h"
#include "json-util.h"
#include "libmount-util.h"
#include "loop-util.h"
#include "mkdir.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "namespace-util.h"
#include "nulstr-util.h"
#include "os-util.h"
#include "path-util.h"
#include "pcrextend-util.h"
#include "pidref.h"
#include "proc-cmdline.h"
#include "process-util.h"
#include "resize-fs.h"
#include "rm-rf.h"
#include "runtime-scope.h"
#include "siphash24.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "udev-util.h"
#include "user-util.h"
#include "varlink-util.h"
#include "xattr-util.h"
 
/* how many times to wait for the device nodes to appear */
#define N_DEVICE_NODE_LIST_ATTEMPTS 10
 
static int allowed_fstypes(char ***ret_strv) {
        _cleanup_strv_free_ char **l = NULL;
        const char *e;
 
        assert(ret_strv);
 
        e = secure_getenv("SYSTEMD_DISSECT_FILE_SYSTEMS");
        if (e)
                l = strv_split(e, ":");
        else
                l = strv_new("btrfs",
                             "erofs",
                             "ext4",
                             "f2fs",
                             "squashfs",
                             "vfat",
                             "xfs");
        if (!l)
                return -ENOMEM;
 
        *ret_strv = TAKE_PTR(l);
        return 0;
}
 
int dissect_fstype_ok(const char *fstype) {
        _cleanup_strv_free_ char **l = NULL;
        int r;
 
        /* When we automatically mount file systems, be a bit conservative by default what we are willing to
         * mount, just as an extra safety net to not mount with badly maintained legacy file system
         * drivers. */
 
        r = allowed_fstypes(&l);
        if (r < 0)
                return r;
 
        if (strv_contains(l, fstype))
                return true;
 
        log_debug("File system type '%s' is not allowed to be mounted as result of automatic dissection.", fstype);
        return false;
}
 
#if HAVE_BLKID
static const char *getenv_fstype(PartitionDesignator d) {
 
        if (d < 0 ||
            partition_designator_is_verity(d) ||
            d == PARTITION_SWAP)
                return NULL;
 
        char *v = strjoina("SYSTEMD_DISSECT_FSTYPE_", partition_designator_to_string(d));
        return secure_getenv(ascii_strupper(v));
}
#endif
 
int probe_sector_size(int fd, uint32_t *ret) {
 
        assert(fd >= 0);
        assert(ret);
 
        ssize_t ssz = gpt_probe(fd, /* ret_header= */ NULL, /* ret_entries= */ NULL, /* ret_n_entries= */ NULL, /* ret_entry_size= */ NULL);
        if (ssz == -ENOTUNIQ)
                return log_debug_errno(ssz,
                                       "Detected valid partition table at offsets matching multiple sector sizes, refusing.");
        if (ssz < 0)
                return ssz;
        if (ssz == 0) {
                log_debug("Couldn't find any partition table to derive sector size of.");
                *ret = 512; /* pick the traditional default */
                return 0;   /* indicate we didn't find it */
        }
 
        log_debug("Determined sector size %" PRIu32 " based on discovered partition table.", (uint32_t) ssz);
        *ret = ssz;
        return 1; /* indicate we *did* find it */
}
 
int probe_sector_size_prefer_ioctl(int fd, uint32_t *ret) {
        struct stat st;
 
        assert(fd >= 0);
        assert(ret);
 
        /* Just like probe_sector_size(), but if we are looking at a block device, will use the already
         * configured sector size rather than probing by contents */
 
        if (fstat(fd, &st) < 0)
                return -errno;
 
        if (S_ISBLK(st.st_mode)) {
                int r;
 
                r = blockdev_get_sector_size(fd, ret);
                if (r < 0)
                        return r;
 
                return 1; /* indicate we *did* find it, like probe_sector_size() does */
        }
 
        return probe_sector_size(fd, ret);
}
 
#if HAVE_BLKID
static int probe_blkid_filter(blkid_probe p) {
        _cleanup_strv_free_ char **fstypes = NULL;
        int r;
 
        assert(p);
 
        r = allowed_fstypes(&fstypes);
        if (r < 0)
                return r;
 
        /* allowed_fstypes() returns the list of filesystem types that we are willing to mount. For the
         * blkid probe filter we additionally need to be able to detect crypto_LUKS (so that we can set up
         * LUKS decryption for encrypted partitions) and swap (so that we can identify swap partitions). */
        r = strv_extend_many(&fstypes, "crypto_LUKS", "swap");
        if (r < 0)
                return r;
 
        errno = 0;
        r = sym_blkid_probe_filter_superblocks_type(p, BLKID_FLTR_ONLYIN, fstypes);
        if (r != 0)
                return errno_or_else(EINVAL);
 
        /* Note: don't call blkid_probe_filter_superblocks_usage() here. Both filter functions share the
         * same bitmap internally, and each call resets it before applying its own filter — so a subsequent
         * usage filter would wipe the type filter we just set. The ONLYIN type filter above already
         * excludes everything not in the allowed list, including RAID superblocks, so a separate usage
         * filter is redundant anyway. */
 
        return 0;
}
#endif
 
int probe_filesystem_full(
                int fd,
                const char *path,
                uint64_t offset,
                uint64_t size,
                bool restrict_fstypes,
                char **ret_fstype) {
 
        /* Try to find device content type and return it in *ret_fstype. If nothing is found,
         * 0/NULL will be returned. -EUCLEAN will be returned for ambiguous results, and a
         * different error otherwise. */
 
#if HAVE_BLKID
        _cleanup_(blkid_free_probep) blkid_probe b = NULL;
        _cleanup_free_ char *path_by_fd = NULL;
        _cleanup_close_ int fd_close = -EBADF;
        const char *fstype;
        int r;
 
        assert(fd >= 0 || path);
        assert(ret_fstype);
 
        r = dlopen_libblkid(LOG_DEBUG);
        if (r < 0)
                return r;
 
        if (fd < 0) {
                fd_close = open(path, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
                if (fd_close < 0)
                        return -errno;
 
                fd = fd_close;
        }
 
        if (!path) {
                r = fd_get_path(fd, &path_by_fd);
                if (r < 0)
                        return r;
 
                path = path_by_fd;
        }
 
        if (size == 0) /* empty size? nothing found! */
                goto not_found;
 
        b = sym_blkid_new_probe();
        if (!b)
                return -ENOMEM;
 
        if (restrict_fstypes) {
                r = probe_blkid_filter(b);
                if (r < 0)
                        return r;
        }
 
        /* The Linux kernel maintains separate block device caches for main ("whole") and partition block
         * devices, which means making a change to one might not be reflected immediately when reading via
         * the other. That's massively confusing when mixing accesses to such devices. Let's address this in
         * a limited way: when probing a file system that is not at the beginning of the block device we
         * apparently probe a partition via the main block device, and in that case let's first flush the
         * main block device cache, so that we get the data that the per-partition block device last
         * sync'ed on.
         *
         * This only works under the assumption that any tools that write to the partition block devices
         * issue an syncfs()/fsync() on the device after making changes. Typically file system formatting
         * tools that write a superblock onto a partition block device do that, however. */
        if (offset != 0)
                if (ioctl(fd, BLKFLSBUF, 0) < 0)
                        log_debug_errno(errno, "Failed to flush block device cache, ignoring: %m");
 
        errno = 0;
        r = sym_blkid_probe_set_device(
                        b,
                        fd,
                        offset,
                        size == UINT64_MAX ? 0 : size); /* when blkid sees size=0 it understands "everything". We prefer using UINT64_MAX for that */
        if (r != 0)
                return errno_or_else(ENOMEM);
 
        sym_blkid_probe_enable_superblocks(b, 1);
        sym_blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
 
        errno = 0;
        r = sym_blkid_do_safeprobe(b);
        if (r == _BLKID_SAFEPROBE_NOT_FOUND)
                goto not_found;
        if (r == _BLKID_SAFEPROBE_AMBIGUOUS)
                return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
                                       "Results ambiguous for partition %s", path);
        if (r == _BLKID_SAFEPROBE_ERROR)
                return log_debug_errno(errno_or_else(EIO), "Failed to probe partition %s: %m", path);
 
        assert(r == _BLKID_SAFEPROBE_FOUND);
 
        (void) sym_blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
        if (fstype) {
                log_debug("Probed fstype '%s' on partition %s.", fstype, path);
                return strdup_to_full(ret_fstype, fstype);
        }
 
not_found:
        log_debug("No type detected on partition %s", path);
        *ret_fstype = NULL;
        return 0;
#else
        return -EOPNOTSUPP;
#endif
}
 
int probe_partition_table(int fd, char **ret_pttype) {
 
        /* Probes the whole device referenced by fd for a partition table and returns its blkid type (e.g.
         * "gpt" or "dos") in *ret_pttype, or NULL if none is found. Returns a negative error on failure
         * (including -EUCLEAN for ambiguous results). */
 
#if HAVE_BLKID
        _cleanup_(blkid_free_probep) blkid_probe b = NULL;
        const char *pttype = NULL;
        int r;
 
        assert(fd >= 0);
        assert(ret_pttype);
 
        r = dlopen_libblkid(LOG_DEBUG);
        if (r < 0)
                return r;
 
        b = sym_blkid_new_probe();
        if (!b)
                return -ENOMEM;
 
        errno = 0;
        r = sym_blkid_probe_set_device(b, fd, /* offset= */ 0, /* size= */ 0 /* i.e. everything */);
        if (r != 0)
                return errno_or_else(ENOMEM);
 
        sym_blkid_probe_enable_partitions(b, 1);
 
        errno = 0;
        r = sym_blkid_do_safeprobe(b);
        if (r == _BLKID_SAFEPROBE_NOT_FOUND) {
                log_debug("No partition table detected.");
                *ret_pttype = NULL;
                return 0;
        }
        if (r == _BLKID_SAFEPROBE_AMBIGUOUS)
                return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "Partition table results ambiguous.");
        if (r == _BLKID_SAFEPROBE_ERROR)
                return log_debug_errno(errno_or_else(EIO), "Failed to probe for partition table: %m");
 
        assert(r == _BLKID_SAFEPROBE_FOUND);
 
        (void) sym_blkid_probe_lookup_value(b, "PTTYPE", &pttype, /* len= */ NULL);
        if (!pttype) {
                log_debug("No partition table detected.");
                *ret_pttype = NULL;
                return 0;
        }
 
        log_debug("Probed partition table type '%s'.", pttype);
        return strdup_to_full(ret_pttype, pttype);
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Compiled without blkid support, cannot probe for partition table.");
#endif
}
 
#if HAVE_BLKID
static int image_policy_may_use(
                const ImagePolicy *policy,
                PartitionDesignator designator) {
 
        PartitionPolicyFlags f;
 
        /* For each partition we find in the partition table do a first check if it may exist at all given
         * the policy, or if it shall be ignored. */
 
        f = image_policy_get_exhaustively(policy, designator);
        if (f < 0)
                return f;
 
        if ((f & _PARTITION_POLICY_USE_MASK) == PARTITION_POLICY_ABSENT)
                /* only flag set in policy is "absent"? then this partition may not exist at all */
                return log_debug_errno(
                                SYNTHETIC_ERRNO(ERFKILL),
                                "Partition of designator '%s' exists, but not allowed by policy, refusing.",
                                partition_designator_to_string(designator));
        if ((f & _PARTITION_POLICY_USE_MASK & ~PARTITION_POLICY_ABSENT) == PARTITION_POLICY_UNUSED) {
                /* only "unused" or "unused" + "absent" are set? then don't use it */
                log_debug("Partition of designator '%s' exists, and policy dictates to ignore it, doing so.",
                          partition_designator_to_string(designator));
                return false; /* ignore! */
        }
 
        return true; /* use! */
}
 
static int image_policy_check_protection(
                const ImagePolicy *policy,
                PartitionDesignator designator,
                PartitionPolicyFlags found_flags) {
 
        PartitionPolicyFlags policy_flags;
 
        /* Checks if the flags in the policy for the designated partition overlap the flags of what we found */
 
        if (found_flags < 0)
                return found_flags;
 
        policy_flags = image_policy_get_exhaustively(policy, designator);
        if (policy_flags < 0)
                return policy_flags;
 
        if ((found_flags & policy_flags) == 0) {
                _cleanup_free_ char *found_flags_string = NULL, *policy_flags_string = NULL;
 
                (void) partition_policy_flags_to_string(found_flags, /* simplify= */ true, &found_flags_string);
                (void) partition_policy_flags_to_string(policy_flags, /* simplify= */ true, &policy_flags_string);
 
                return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s discovered with policy '%s' but '%s' was required, refusing.",
                                       partition_designator_to_string(designator),
                                       strnull(found_flags_string), strnull(policy_flags_string));
        }
 
        return 0;
}
 
/* internal LUKS2 header defines */
#define LUKS2_FIXED_HDR_SIZE UINT64_C(0x1000)
#define LUKS2_MAGIC "LUKS\xba\xbe"
 
/* Matches the beginning of 'struct luks2_hdr_disk' from cryptsetup */
struct luks_header_incomplete {
                char luks_magic[sizeof(LUKS2_MAGIC) - 1];
                be16_t version;
                be64_t hdr_len;
};
 
/* 'integrity' information from LUKS JSON header. Currently, only 'type' is extracted/checked. */
struct luks_integrity_data {
        char *type;
};
 
static int integrity_information(const char *name, sd_json_variant *v, sd_json_dispatch_flags_t flags, void *userdata) {
        static const sd_json_dispatch_field table[] = {
                { "type", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(struct luks_integrity_data, type), SD_JSON_MANDATORY },
                {}
        };
 
        return sd_json_dispatch(v, table, flags, userdata);
}
 
/* cryptsetup needs a loop device to work with a partition which has offset/size but
 * dissect may be running unprivileged. Implement a minimal custom LUKS header parser
 * checking integrity protection information. */
static int partition_is_luks2_integrity(int part_fd, uint64_t offset, uint64_t size) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_free_ char *json = NULL;
        sd_json_variant *w;
        const char *key;
        struct luks_header_incomplete header;
        ssize_t sz, json_len;
        int r;
 
        assert(part_fd >= 0);
 
        if (size < LUKS2_FIXED_HDR_SIZE) {
                log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Partition is too small to contain a LUKS header.");
                return 0;
        }
 
        sz = pread(part_fd, &header, sizeof(header), offset);
        if (sz < 0)
                return log_error_errno(errno, "Failed to read LUKS header.");
        if (sz != sizeof(header))
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read LUKS header.");
 
        if (memcmp(header.luks_magic, LUKS2_MAGIC, sizeof(header.luks_magic)) != 0) {
                log_debug("Partition does not have a LUKS magic header, assuming no integrity.");
                return 0;
        }
 
        if (be16toh(header.version) != 2) {
                log_debug("Partition is LUKS v%" PRIu16 ", not LUKS2, assuming no integrity.", be16toh(header.version));
                return 0;
        }
 
        if (be64toh(header.hdr_len) > size)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS header length exceeds partition size.");
 
        if (be64toh(header.hdr_len) <= LUKS2_FIXED_HDR_SIZE || offset > UINT64_MAX - be64toh(header.hdr_len))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid LUKS header length: %" PRIu64 ".", be64toh(header.hdr_len));
 
        if (be64toh(header.hdr_len) - LUKS2_FIXED_HDR_SIZE > 16U * 1024U * 1024U)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS header JSON area too large: %" PRIu64 ".", be64toh(header.hdr_len));
 
        json_len = be64toh(header.hdr_len) - LUKS2_FIXED_HDR_SIZE;
        json = malloc(json_len + 1);
        if (!json)
                return -ENOMEM;
 
        sz = pread(part_fd, json, json_len, offset + LUKS2_FIXED_HDR_SIZE);
        if (sz < 0)
                return log_error_errno(errno, "Failed to read LUKS JSON header.");
        if (sz != json_len)
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read LUKS JSON header.");
        json[sz] = '\0';
 
        r = sd_json_parse(json, /* flags= */ 0, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to parse LUKS JSON header.");
 
        v = sd_json_variant_by_key(v, "segments");
        if (!v || !sd_json_variant_is_object(v)) {
                log_debug("LUKS JSON header lacks 'segments' information, assuming no integrity.");
                return 0;
        }
 
        /* Verify that all segments have integrity protection */
        JSON_VARIANT_OBJECT_FOREACH(key, w, v) {
                struct luks_integrity_data data = {};
 
                static const sd_json_dispatch_field dispatch_segment[] = {
                        { "integrity", SD_JSON_VARIANT_OBJECT, integrity_information, 0, SD_JSON_MANDATORY },
                        {}
                };
 
                r = sd_json_dispatch(w, dispatch_segment, SD_JSON_ALLOW_EXTENSIONS, &data);
                if (r < 0) {
                        log_debug("Failed to get integrity information from LUKS JSON for segment %s, assuming no integrity.", key);
                        return 0;
                }
 
                /* We don't require a particular integrity algorithm, everything but 'none' (which shouldn't
                 * be there in the first place but is theoretically possible) works. */
                if (streq(data.type, "none"))
                        return 0;
        }
 
        return 1;
}
 
static int image_policy_check_partition_flags(
                const ImagePolicy *policy,
                PartitionDesignator designator,
                uint64_t gpt_flags) {
 
        PartitionPolicyFlags policy_flags;
        bool b;
 
        /* Checks if the partition flags in the policy match reality */
 
        policy_flags = image_policy_get_exhaustively(policy, designator);
        if (policy_flags < 0)
                return policy_flags;
 
        b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_READ_ONLY);
        if ((policy_flags & _PARTITION_POLICY_READ_ONLY_MASK) == (b ? PARTITION_POLICY_READ_ONLY_OFF : PARTITION_POLICY_READ_ONLY_ON))
                return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'read-only' flag incorrectly set (must be %s, is %s), refusing.",
                                       partition_designator_to_string(designator),
                                       one_zero(!b), one_zero(b));
 
        b = FLAGS_SET(gpt_flags, SD_GPT_FLAG_GROWFS);
        if ((policy_flags & _PARTITION_POLICY_GROWFS_MASK) == (b ? PARTITION_POLICY_GROWFS_OFF : PARTITION_POLICY_GROWFS_ON))
                return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Partition %s has 'growfs' flag incorrectly set (must be %s, is %s), refusing.",
                                       partition_designator_to_string(designator),
                                       one_zero(!b), one_zero(b));
 
        return 0;
}
 
static int dissected_image_probe_filesystems(
                DissectedImage *m,
                int fd,
                const ImagePolicy *policy) {
 
        int r;
 
        assert(m);
 
        /* Fill in file system types if we don't know them yet. */
 
        for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
                DissectedPartition *p = m->partitions + i;
                PartitionPolicyFlags found_flags;
 
                if (!p->found)
                        continue;
 
                if (!p->fstype) {
                        /* If we have an fd referring to the partition block device, use that. Otherwise go
                         * via the whole block device or backing regular file, and read via offset. */
                        if (p->mount_node_fd >= 0)
                                r = probe_filesystem_full(p->mount_node_fd, p->node, 0, UINT64_MAX, /* bool restrict_fstypes= */ true, &p->fstype);
                        else
                                r = probe_filesystem_full(fd, p->node, p->offset, p->size, /* bool restrict_fstypes= */ true, &p->fstype);
                        if (r < 0)
                                return r;
                }
 
                if (streq_ptr(p->fstype, "crypto_LUKS")) {
                        m->encrypted = true;
 
                        if (p->mount_node_fd >= 0)
                                r = partition_is_luks2_integrity(p->mount_node_fd, /* offset= */ 0, /* size= */ UINT64_MAX);
                        else
                                r = partition_is_luks2_integrity(fd, p->offset, p->size);
                        if (r < 0)
                                return r;
 
                        /* found this one, it's definitely encrypted + with or without integrity checking */
                        found_flags = PARTITION_POLICY_UNUSED|(r > 0 ? PARTITION_POLICY_ENCRYPTEDWITHINTEGRITY : PARTITION_POLICY_ENCRYPTED);
                } else
                        /* found it, but it's definitely not encrypted, hence mask the encrypted flag, but
                         * set all other ways that indicate "present". */
                        found_flags = PARTITION_POLICY_UNUSED|PARTITION_POLICY_UNPROTECTED|PARTITION_POLICY_VERITY|PARTITION_POLICY_SIGNED;
 
                if (p->fstype && fstype_is_ro(p->fstype))
                        p->rw = false;
 
                if (!p->rw)
                        p->growfs = false;
 
                /* We might have learnt more about the file system now (i.e. whether it is encrypted or not),
                 * hence we need to validate this against policy again, to see if the policy still matches
                 * with this new information. Note that image_policy_check_protection() will check for
                 * overlap between what's allowed in the policy and what we pass as 'found_policy' here. In
                 * the unencrypted case we thus might pass an overly unspecific mask here (i.e. unprotected
                 * OR verity OR signed), but that's fine since the earlier policy check already checked more
                 * specific which of those three cases where OK. Keep in mind that this function here only
                 * looks at specific partitions (and thus can only deduce encryption or not) but not the
                 * overall partition table (and thus cannot deduce verity or not). The earlier dissection
                 * checks already did the relevant checks that look at the whole partition table, and
                 * enforced policy there as needed. */
                r = image_policy_check_protection(policy, i, found_flags);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static void check_partition_flags(
                const char *node,
                unsigned long long pflags,
                unsigned long long supported) {
 
        assert(node);
 
        /* Mask away all flags supported by this partition's type and the three flags the UEFI spec defines generically */
        pflags &= ~(supported |
                    SD_GPT_FLAG_REQUIRED_PARTITION |
                    SD_GPT_FLAG_NO_BLOCK_IO_PROTOCOL |
                    SD_GPT_FLAG_LEGACY_BIOS_BOOTABLE);
 
        if (pflags == 0)
                return;
 
        /* If there are other bits set, then log about it, to make things discoverable */
        for (unsigned i = 0; i < sizeof(pflags) * 8; i++) {
                unsigned long long bit = 1ULL << i;
                if (!FLAGS_SET(pflags, bit))
                        continue;
 
                log_debug("Unexpected partition flag %llu set on %s!", bit, node);
        }
}
#endif
 
int dissected_image_name_from_path(const char *path, char **ret) {
        int r;
 
        assert(path);
        assert(ret);
 
        _cleanup_free_ char *filename = NULL;
        r = path_extract_filename(path, &filename);
        if (r < 0)
                return r;
 
        _cleanup_free_ char *name = NULL;
        r = raw_strip_suffixes(filename, &name);
        if (r < 0)
                return r;
 
        if (!image_name_is_valid(name)) {
                log_debug("Image name %s is not valid, ignoring.", strna(name));
                *ret = NULL;
                return 0;
        }
 
        *ret = TAKE_PTR(name);
        return 1;
}
 
#if HAVE_BLKID
static int dissected_image_new(const char *path, DissectedImage **ret) {
        _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
        _cleanup_free_ char *name = NULL;
        int r;
 
        assert(ret);
 
        if (path) {
                r = dissected_image_name_from_path(path, &name);
                if (r < 0)
                        return r;
        }
 
        m = new(DissectedImage, 1);
        if (!m)
                return -ENOMEM;
 
        *m = (DissectedImage) {
                .has_init_system = -1,
                .image_name = TAKE_PTR(name),
        };
 
        for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++)
                m->partitions[i] = DISSECTED_PARTITION_NULL;
 
        *ret = TAKE_PTR(m);
        return 0;
}
#endif
 
static void dissected_partition_done(DissectedPartition *p) {
        assert(p);
 
        free(p->fstype);
        free(p->node);
        free(p->label);
        free(p->decrypted_fstype);
        free(p->decrypted_node);
        free(p->mount_options);
        safe_close(p->mount_node_fd);
        safe_close(p->fsmount_fd);
 
        *p = DISSECTED_PARTITION_NULL;
}
 
static int acquire_sig_for_roothash(
                int fd,
                uint64_t partition_offset,
                uint64_t partition_size,
                struct iovec *ret_root_hash,
                struct iovec *ret_root_hash_sig) {
 
        int r;
 
        assert(fd >= 0);
 
        if (partition_offset == UINT64_MAX || partition_size == UINT64_MAX)
                return -EINVAL;
 
        if (partition_size > 4*1024*1024) /* Signature data cannot possible be larger than 4M, refuse that */
                return log_debug_errno(SYNTHETIC_ERRNO(EFBIG), "Verity signature partition is larger than 4M, refusing.");
 
        _cleanup_free_ char *buf = new(char, partition_size+1);
        if (!buf)
                return -ENOMEM;
 
        ssize_t n = pread(fd, buf, partition_size, partition_offset);
        if (n < 0)
                return -errno;
        if ((uint64_t) n != partition_size)
                return -EIO;
 
        const char *e = memchr(buf, 0, partition_size);
        if (e) {
                /* If we found a NUL byte then the rest of the data must be NUL too */
                if (!memeqzero(e, partition_size - (e - buf)))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature data contains embedded NUL byte.");
        } else
                buf[partition_size] = 0;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_parse(buf, 0, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
        if (r < 0)
                return log_debug_errno(r, "Failed to parse signature JSON data: %m");
 
        sd_json_variant *rh = sd_json_variant_by_key(v, "rootHash");
        if (!rh)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'rootHash' field.");
 
        _cleanup_(iovec_done) struct iovec root_hash = {};
        r = sd_json_variant_unhex(rh, &root_hash.iov_base, &root_hash.iov_len);
        if (r < 0)
                return log_debug_errno(r, "Failed to parse root hash field: %m");
 
        sd_json_variant *sig = sd_json_variant_by_key(v, "signature");
        if (!sig)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Signature JSON object lacks 'signature' field.");
 
        _cleanup_(iovec_done) struct iovec root_hash_sig = {};
        r = sd_json_variant_unbase64(sig, &root_hash_sig.iov_base, &root_hash_sig.iov_len);
        if (r < 0)
                return log_debug_errno(r, "Failed to parse signature field: %m");
 
        if (ret_root_hash)
                *ret_root_hash = TAKE_STRUCT(root_hash);
 
        if (ret_root_hash_sig)
                *ret_root_hash_sig = TAKE_STRUCT(root_hash_sig);
 
        return 0;
}
 
#if HAVE_BLKID
static int diskseq_should_be_used(
                const char *whole_devname,
                uint64_t diskseq,
                DissectImageFlags flags) {
 
        int r;
 
        assert(whole_devname);
 
        /* No diskseq. We cannot use by-diskseq symlink. */
        if (diskseq == 0)
                return false;
 
        /* Do not use by-diskseq link unless DISSECT_IMAGE_DISKSEQ_DEVNODE flag is explicitly set. */
        if (!FLAGS_SET(flags, DISSECT_IMAGE_DISKSEQ_DEVNODE))
                return false;
 
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
        r = sd_device_new_from_devname(&dev, whole_devname);
        if (r < 0)
                return r;
 
        /* When ID_IGNORE_DISKSEQ udev property is set, the by-diskseq symlink will not be created. */
        r = device_get_property_bool(dev, "ID_IGNORE_DISKSEQ");
        if (r >= 0)
                return !r; /* If explicitly specified, use it. */
        if (r != -ENOENT)
                return r;
 
        return true;
}
 
static int make_partition_devname(
                const char *whole_devname,
                uint64_t diskseq,
                int nr,
                DissectImageFlags flags,
                char **ret) {
 
        _cleanup_free_ char *s = NULL;
        int r;
 
        assert(whole_devname);
        assert(nr != 0); /* zero is not a valid partition nr */
        assert(ret);
 
        r = diskseq_should_be_used(whole_devname, diskseq, flags);
        if (r < 0)
                log_debug_errno(r, "Failed to determine if diskseq should be used for %s, assuming no, ignoring: %m", whole_devname);
        if (r <= 0) {
                /* Given a whole block device node name (e.g. /dev/sda or /dev/loop7) generate a partition
                 * device name (e.g. /dev/sda7 or /dev/loop7p5). The rule the kernel uses is simple: if whole
                 * block device node name ends in a digit, then suffix a 'p', followed by the partition
                 * number. Otherwise, just suffix the partition number without any 'p'. */
 
                if (nr < 0) { /* whole disk? */
                        s = strdup(whole_devname);
                        if (!s)
                                return -ENOMEM;
                } else {
                        r = partition_node_of(whole_devname, nr, &s);
                        if (r < 0)
                                return r;
                }
        } else {
                if (nr < 0) /* whole disk? */
                        r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64, diskseq);
                else
                        r = asprintf(&s, "/dev/disk/by-diskseq/%" PRIu64 "-part%i", diskseq, nr);
                if (r < 0)
                        return -ENOMEM;
        }
 
        *ret = TAKE_PTR(s);
        return 0;
}
 
static int open_partition(
                const char *node,
                bool is_partition,
                const LoopDevice *loop) {
 
        _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
        _cleanup_close_ int fd = -EBADF;
        dev_t devnum;
        int r;
 
        assert(node);
        assert(loop || !is_partition);
 
        fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
        if (fd < 0)
                return -errno;
 
        if (!loop)
                return TAKE_FD(fd);
 
        /* Check if the block device is a child of (or equivalent to) the originally provided one. */
        r = block_device_new_from_fd(fd, is_partition ? BLOCK_DEVICE_LOOKUP_WHOLE_DISK : 0, &dev);
        if (r < 0)
                return r;
 
        r = sd_device_get_devnum(dev, &devnum);
        if (r < 0)
                return r;
 
        if (loop->devno != devnum)
                return -ENXIO;
 
        /* Also check diskseq. */
        if (loop->diskseq != 0) {
                uint64_t diskseq;
 
                r = fd_get_diskseq(fd, &diskseq);
                if (r < 0)
                        return r;
 
                if (loop->diskseq != diskseq)
                        return -ENXIO;
        }
 
        log_debug("Opened %s (fd=%i, whole_block_devnum=" DEVNUM_FORMAT_STR ", diskseq=%" PRIu64 ").",
                  node, fd, DEVNUM_FORMAT_VAL(loop->devno), loop->diskseq);
        return TAKE_FD(fd);
}
 
static int compare_arch(Architecture a, Architecture b) {
        if (a == b)
                return 0;
 
        if (a == native_architecture())
                return 1;
 
        if (b == native_architecture())
                return -1;
 
#ifdef ARCHITECTURE_SECONDARY
        if (a == ARCHITECTURE_SECONDARY)
                return 1;
 
        if (b == ARCHITECTURE_SECONDARY)
                return -1;
#endif
 
        return 0;
}
 
bool image_filter_test(const ImageFilter *filter, PartitionDesignator d, const char *label) {
        assert(d < _PARTITION_DESIGNATOR_MAX);
 
        if (d < 0) /* For unspecified designators we have no filter expression */
                return true;
 
        if (!filter)
                return true;
 
        const char *pattern = filter->pattern[d];
 
        /* If there's no filter for this specific designator but it's a verity partition, fall back to the
         * filter for the corresponding data partition. This ensures that e.g. image_filter=usr=250 also
         * constrains which usr verity (and verity sig) partitions are selected. This assumes verity
         * partitions carry the same label as their corresponding data partition. */
        if (!pattern) {
                PartitionDesignator data = partition_verity_to_data(d);
                if (data >= 0)
                        pattern = filter->pattern[data];
        }
 
        if (!pattern)
                return true;
 
        return fnmatch(pattern, strempty(label), FNM_NOESCAPE) == 0;
}
 
static int dissect_image_from_unpartitioned(
                const char *devname,
                uint64_t diskseq,
                const sd_id128_t *uuid,
                bool encrypted,