HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/shared/dissect-image.c
Git blob: 9280a90974918216809a09219e8a3162bddcf789
Lines 3001–4000 of 5,731
DissectedImage *di,
DissectedPartition *m,
const char *passphrase,
DissectImageFlags flags,
PartitionPolicyFlags policy_flags,
DecryptedImage *d) {
_cleanup_free_ char *node = NULL, *name = NULL;
_cleanup_(crypt_freep) struct crypt_device *cd = NULL;
_cleanup_close_ int fd = -EBADF;
int r;
assert(di);
assert(m);
assert(d);
if (!m->found || !m->node || !m->fstype)
return 0;
if (!streq(m->fstype, "crypto_LUKS"))
return 0;
if (!passphrase)
return -ENOKEY;
if (!FLAGS_SET(policy_flags, PARTITION_POLICY_ENCRYPTED))
return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL), "Attempted to unlock partition via LUKS, but it's prohibited.");
/* If a dm-verity device was already set up on this partition, then the partition is both Verity
* protected and LUKS encrypted, with Verity being the outer envelope and LUKS the inner. In that
* case open the LUKS device on top of the verity device, so that everything we read is
* authenticated. Since verity devices are read-only, the LUKS layer must then be read-only, too. */
const char *source_node = m->decrypted_node ?: m->node;
bool on_verity = !!m->decrypted_node;
r = dlopen_cryptsetup(LOG_DEBUG);
if (r < 0)
return r;
r = make_dm_name_and_node_from_node(m->node, dissected_image_diskseq(di), "-decrypted", &name, &node);
if (r < 0)
return r;
if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
return -ENOMEM;
r = sym_crypt_init(&cd, source_node);
if (r < 0)
return log_debug_errno(r, "Failed to initialize dm-crypt: %m");
cryptsetup_enable_logging(cd);
r = sym_crypt_load(cd, CRYPT_LUKS, NULL);
if (r < 0)
return log_debug_errno(r, "Failed to load LUKS metadata: %m");
r = sym_crypt_activate_by_passphrase(cd, name, CRYPT_ANY_SLOT, passphrase, strlen(passphrase),
((flags & DISSECT_IMAGE_DEVICE_READ_ONLY) || on_verity ? CRYPT_ACTIVATE_READONLY : 0) |
((flags & DISSECT_IMAGE_DISCARD_ON_CRYPTO) && !on_verity ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0));
if (r < 0) {
log_debug_errno(r, "Failed to activate LUKS device: %m");
return r == -EPERM ? -EKEYREJECTED : r;
}
fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return log_debug_errno(errno, "Failed to open %s: %m", node);
d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
.name = TAKE_PTR(name),
.device = TAKE_PTR(cd),
};
free_and_replace(m->decrypted_node, node);
close_and_replace(m->mount_node_fd, fd);
return 0;
}
static int verity_can_reuse(
const VeritySettings *verity,
const char *name,
struct crypt_device **ret_cd) {
/* If the same volume was already open, check that the root hashes match, and reuse it if they do */
_cleanup_(crypt_freep) struct crypt_device *cd = NULL;
struct crypt_params_verity crypt_params = {};
int r;
assert(verity);
assert(name);
assert(ret_cd);
r = sym_crypt_init_by_name(&cd, name);
if (r < 0)
return log_debug_errno(r, "Error opening verity device, crypt_init_by_name failed: %m");
cryptsetup_enable_logging(cd);
r = sym_crypt_get_verity_info(cd, &crypt_params);
if (r < 0)
return log_debug_errno(r, "Error opening verity device, crypt_get_verity_info failed: %m");
_cleanup_(iovec_done) struct iovec root_hash_existing = {
.iov_base = malloc0(verity->root_hash.iov_len),
.iov_len = verity->root_hash.iov_len,
};
if (!root_hash_existing.iov_base)
return -ENOMEM;
r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, root_hash_existing.iov_base, &root_hash_existing.iov_len, NULL, 0);
if (r < 0)
return log_debug_errno(r, "Error opening verity device, crypt_volume_key_get failed: %m");
if (!iovec_equal(&verity->root_hash, &root_hash_existing))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but root hashes are different.");
/* Ensure that, if signatures are supported, we only reuse the device if the previous mount used the
* same settings, so that a previous unsigned mount will not be reused if the user asks to use
* signing for the new one, and vice versa. */
if (iovec_is_set(&verity->root_hash_sig) != FLAGS_SET(crypt_params.flags, CRYPT_VERITY_ROOT_HASH_SIGNATURE))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Error opening verity device, it already exists but signature settings are not the same.");
*ret_cd = TAKE_PTR(cd);
return 0;
}
static char* dm_deferred_remove_clean(char *name) {
if (!name)
return NULL;
(void) sym_crypt_deactivate_by_name(NULL, name, CRYPT_DEACTIVATE_DEFERRED);
return mfree(name);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(char *, dm_deferred_remove_clean);
static int validate_signature_userspace(const VeritySettings *verity, const char *root, DissectImageFlags flags) {
int r;
/* Returns > 0 if signature checks out, == 0 if not, < 0 on unexpected errors */
if (!FLAGS_SET(flags, DISSECT_IMAGE_ALLOW_USERSPACE_VERITY)) {
log_debug("Userspace dm-verity signature authentication disabled via flag.");
return 0;
}
r = secure_getenv_bool("SYSTEMD_ALLOW_USERSPACE_VERITY");
if (r < 0 && r != -ENXIO) {
log_debug_errno(r, "Failed to parse $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable, refusing userspace dm-verity signature authentication.");
return 0;
}
if (!r) {
log_debug("Userspace dm-verity signature authentication disabled via $SYSTEMD_ALLOW_USERSPACE_VERITY environment variable.");
return 0;
}
bool b;
r = proc_cmdline_get_bool("systemd.allow_userspace_verity", PROC_CMDLINE_TRUE_WHEN_MISSING, &b);
if (r < 0) {
log_debug_errno(r, "Failed to parse systemd.allow_userspace_verity= kernel command line option, refusing userspace dm-verity signature authentication.");
return 0;
}
if (!b) {
log_debug("Userspace dm-verity signature authentication disabled via systemd.allow_userspace_verity= kernel command line option.");
return 0;
}
#if HAVE_OPENSSL
_cleanup_(sk_X509_free_allp) STACK_OF(X509) *sk = NULL;
_cleanup_strv_free_ char **certs = NULL;
_cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
_cleanup_free_ char *s = NULL;
_cleanup_(BIO_freep) BIO *bio = NULL; /* 'bio' must be freed first, 's' second, hence keep this order
* of declaration in place, please */
assert(verity);
assert(iovec_is_set(&verity->root_hash));
assert(iovec_is_set(&verity->root_hash_sig));
r = dlopen_libcrypto(LOG_DEBUG);
if (r < 0)
return r;
/* Because installing a signature certificate into the kernel chain is so messy, let's optionally do
* userspace validation. */
r = conf_files_list_nulstr(&certs, ".crt", root, CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, CONF_PATHS_NULSTR("verity.d"));
if (r < 0)
return log_debug_errno(r, "Failed to enumerate certificates: %m");
if (strv_isempty(certs)) {
log_debug("No userspace dm-verity certificates found.");
return 0;
}
const unsigned char *d = verity->root_hash_sig.iov_base;
p7 = sym_d2i_PKCS7(NULL, &d, (long) verity->root_hash_sig.iov_len);
if (!p7)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse PKCS7 DER signature data.");
s = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
if (!s)
return log_oom_debug();
bio = sym_BIO_new_mem_buf(s, strlen(s));
if (!bio)
return log_oom_debug();
sk = sym_sk_X509_new_null();
if (!sk)
return log_oom_debug();
STRV_FOREACH(i, certs) {
_cleanup_(X509_freep) X509 *c = NULL;
_cleanup_fclose_ FILE *f = NULL;
f = fopen(*i, "re");
if (!f) {
log_debug_errno(errno, "Failed to open '%s', ignoring: %m", *i);
continue;
}
c = sym_PEM_read_X509(f, NULL, NULL, NULL);
if (!c) {
log_debug("Failed to load X509 certificate '%s', ignoring.", *i);
continue;
}
if (sym_sk_X509_push(sk, c) == 0)
return log_oom_debug();
TAKE_PTR(c);
}
r = sym_PKCS7_verify(p7, sk, NULL, bio, NULL, PKCS7_NOINTERN|PKCS7_NOVERIFY);
if (r)
log_debug("Userspace PKCS#7 validation succeeded.");
else
log_openssl_errors(LOG_DEBUG, "Userspace PKCS#7 validation failed");
return r;
#else
log_debug("Not doing client-side validation of dm-verity root hash signatures, OpenSSL support disabled.");
return 0;
#endif
}
static int do_crypt_activate_verity(
struct crypt_device *cd,
const char *root,
const char *name,
const VeritySettings *verity,
DissectImageFlags flags,
PartitionPolicyFlags policy_flags) {
int r;
assert(cd);
assert(name);
assert(verity);
bool check_signature;
if (iovec_is_set(&verity->root_hash_sig) && FLAGS_SET(policy_flags, PARTITION_POLICY_SIGNED)) {
r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIGNATURE");
if (r < 0 && r != -ENXIO)
log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIGNATURE");
check_signature = r != 0;
} else
check_signature = false;
bool measure_signature;
if (check_signature) {
int k;
/* First, if we have support for signed keys in the kernel, then try that first. */
r = sym_crypt_activate_by_signed_key(
cd,
name,
verity->root_hash.iov_base,
verity->root_hash.iov_len,
verity->root_hash_sig.iov_base,
verity->root_hash_sig.iov_len,
CRYPT_ACTIVATE_READONLY);
if (r >= 0) {
log_debug("Verity activation via kernel signature logic worked.");
measure_signature = true;
goto done;
}
log_debug_errno(r, "Validation of dm-verity signature failed via the kernel, trying userspace validation instead: %m");
/* Let's mangle ENOKEY → EDESTADDRREQ, so that we return a clear, recognizable error if
* there's a signature we don't recognize, that is distinct from the LUKS/encryption
* -ENOKEY, which means "password required, but I have none". */
if (r == -ENOKEY)
r = -EDESTADDRREQ;
/* So this didn't work via the kernel, then let's try userspace validation instead. If that
* works we'll try to activate without telling the kernel the signature. */
/* Preferably propagate the original kernel error, so that the fallback logic can work,
* as the device-mapper is finicky around concurrent activations of the same volume */
k = validate_signature_userspace(verity, root, flags);
if (k < 0)
return k;
if (k == 0) {
log_debug("Activation of signed Verity volume worked neither via the kernel nor in userspace, can't activate.");
/* So if we had a signature and we're supposed to exclusively allow
* signature-based activation, then return the error now */
if (!FLAGS_SET(policy_flags, PARTITION_POLICY_VERITY))
return r < 0 ? r : -EDESTADDRREQ;
log_debug("Activation of signed Verity volume without validating signature is permitted by policy. Continuing.");
} else
log_debug("Verity activation via userspace signature logic worked, activating by root hash.");
/* Otherwise let's see what signature-less activation results in. */
measure_signature = true;
} else if (!FLAGS_SET(policy_flags, PARTITION_POLICY_VERITY))
return log_debug_errno(SYNTHETIC_ERRNO(ERFKILL),
"No-signature activation of Verity volume not allowed by policy, refusing.");
else
measure_signature = false;
r = sym_crypt_activate_by_volume_key(
cd,
name,
verity->root_hash.iov_base,
verity->root_hash.iov_len,
CRYPT_ACTIVATE_READONLY);
if (r < 0)
return log_debug_errno(r, "Activation of Verity via root hash failed: %m");
log_debug("Activation of Verity via root hash succeeded.");
done:
(void) pcrextend_verity_now(
name,
&verity->root_hash,
measure_signature ? &verity->root_hash_sig : NULL);
return 0;
}
static usec_t verity_timeout(void) {
usec_t t = 100 * USEC_PER_MSEC;
const char *e;
int r;
/* On slower machines, like non-KVM vm, setting up device may take a long time.
* Let's make the timeout configurable. */
e = getenv("SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC");
if (!e)
return t;
r = parse_sec(e, &t);
if (r < 0)
log_debug_errno(r,
"Failed to parse timeout specified in $SYSTEMD_DISSECT_VERITY_TIMEOUT_SEC, "
"using the default timeout (%s).",
FORMAT_TIMESPAN(t, USEC_PER_MSEC));
return t;
}
static int verity_partition(
DissectedImage *di,
PartitionDesignator designator,
DissectedPartition *m, /* data partition */
DissectedPartition *v, /* verity partition */
const char *root, /* The root to get user verity certs from (for a sysext) */
const VeritySettings *verity,
DissectImageFlags flags,
PartitionPolicyFlags policy_flags,
DecryptedImage *d) {
_cleanup_(crypt_freep) struct crypt_device *cd = NULL;
_cleanup_free_ char *node = NULL, *name = NULL;
_cleanup_close_ int mount_node_fd = -EBADF;
int r;
assert(di);
assert(m);
assert(v || (verity && verity->data_path));
if (!verity || !iovec_is_set(&verity->root_hash))
return 0;
if (!((verity->designator < 0 && designator == PARTITION_ROOT) ||
(verity->designator == designator)))
return 0;
if (!m->found || !m->node || !m->fstype)
return 0;
if (!verity->data_path) {
if (!v->found || !v->node || !v->fstype)
return 0;
if (!streq(v->fstype, "DM_verity_hash"))
return 0;
}
if (!(policy_flags & (PARTITION_POLICY_VERITY|PARTITION_POLICY_SIGNED))) {
log_debug("Attempted to unlock partition via Verity, but it's prohibited, skipping.");
return 0;
}
r = dlopen_cryptsetup(LOG_DEBUG);
if (r < 0)
return r;
if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
/* Use the roothash, which is unique per volume, as the device node name, so that it can be reused */
_cleanup_free_ char *root_hash_encoded = NULL;
root_hash_encoded = hexmem(verity->root_hash.iov_base, verity->root_hash.iov_len);
if (!root_hash_encoded)
return -ENOMEM;
r = make_dm_name_and_node(root_hash_encoded, /* diskseq= */ 0, "-verity", &name, &node);
} else
r = make_dm_name_and_node_from_node(m->node, dissected_image_diskseq(di), "-verity", &name, &node);
if (r < 0)
return r;
r = sym_crypt_init(&cd, verity->data_path ?: v->node);
if (r < 0)
return r;
cryptsetup_enable_logging(cd);
r = sym_crypt_load(cd, CRYPT_VERITY, NULL);
if (r < 0)
return r;
r = sym_crypt_set_data_device(cd, m->node);
if (r < 0)
return r;
if (!GREEDY_REALLOC0(d->decrypted, d->n_decrypted + 1))
return -ENOMEM;
/* If activating fails because the device already exists, check the metadata and reuse it if it matches.
* In case of ENODEV/ENOENT, which can happen if another process is activating at the exact same time,
* retry a few times before giving up. */
for (unsigned i = 0; i < N_DEVICE_NODE_LIST_ATTEMPTS; i++) {
_cleanup_(dm_deferred_remove_cleanp) char *restore_deferred_remove = NULL;
_cleanup_(crypt_freep) struct crypt_device *existing_cd = NULL;
_cleanup_close_ int fd = -EBADF;
/* First, check if the device already exists. */
fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
if (fd < 0 && !ERRNO_IS_DEVICE_ABSENT(errno))
return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
if (fd >= 0)
goto check; /* The device already exists. Let's check it. */
/* The symlink to the device node does not exist yet. Assume not activated, and let's activate it. */
r = do_crypt_activate_verity(cd, root, name, verity, flags, policy_flags);
if (r >= 0)
goto try_open; /* The device is activated. Let's open it. */
/* libdevmapper can return EINVAL when the device is already in the activation stage.
* There's no way to distinguish this situation from a genuine error due to invalid
* parameters, so immediately fall back to activating the device with a unique name.
* Improvements in libcrypsetup can ensure this never happens:
* https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/96 */
if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
break;
/* Volume is being opened but not ready, crypt_init_by_name would fail, try to open again if
* sharing is enabled. */
if (r == -ENODEV && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
goto try_again;
if (!IN_SET(r,
-EEXIST, /* Volume has already been opened and ready to be used. */
-EBUSY /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */))
return log_debug_errno(r, "Failed to activate verity device %s: %m", node);
check:
/* To avoid races, disable automatic removal on umount while setting up the new device. Restore it on failure. */
r = dm_deferred_remove_cancel(name);
/* -EBUSY and -ENXIO: the device has already been removed or being removed. We cannot
* use the device, try to open again. See target_message() in drivers/md/dm-ioctl.c
* and dm_cancel_deferred_remove() in drivers/md/dm.c */
if (IN_SET(r, -EBUSY, -ENXIO))
goto try_again;
if (r < 0)
return log_debug_errno(r, "Failed to disable automated deferred removal for verity device %s: %m", node);
restore_deferred_remove = strdup(name);
if (!restore_deferred_remove)
return log_oom_debug();
r = verity_can_reuse(verity, name, &existing_cd);
/* Same as above, -EINVAL can randomly happen when it actually means -EEXIST */
if (r == -EINVAL && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
break;
if (IN_SET(r,
-ENOENT, /* Removed?? */
-EBUSY, /* Volume is being opened but not ready, crypt_init_by_name() can fetch details. */
-ENODEV /* Volume is being opened but not ready, crypt_init_by_name() would fail, try to open again. */ ))
goto try_again;
if (r < 0)
return log_debug_errno(r, "Failed to check if existing verity device %s can be reused: %m", node);
if (fd < 0) {
/* devmapper might say that the device exists, but the devlink might not yet have been
* created. Check and wait for the udev event in that case. */
r = device_wait_for_devlink(node, "block", verity_timeout(), NULL);
/* Fallback to activation with a unique device if it's taking too long */
if (r == -ETIMEDOUT && FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE))
break;
if (r < 0)
return log_debug_errno(r, "Failed to wait device node symlink %s: %m", node);
}
try_open:
if (fd < 0) {
/* Now, the device is activated and devlink is created. Let's open it. */
fd = open(node, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
if (fd < 0) {
if (!ERRNO_IS_DEVICE_ABSENT(errno))
return log_debug_errno(errno, "Failed to open verity device %s: %m", node);
/* The device has already been removed?? */
goto try_again;
}
}
/* Everything looks good and we'll be able to mount the device, so deferred remove will be re-enabled at that point. */
restore_deferred_remove = mfree(restore_deferred_remove);
mount_node_fd = TAKE_FD(fd);
if (existing_cd)
crypt_free_and_replace(cd, existing_cd);
goto success;
try_again:
/* Device is being removed by another process. Let's wait for a while. */
(void) usleep_safe(2 * USEC_PER_MSEC);
}
/* All trials failed or a conflicting verity device exists. Let's try to activate with a unique name. */
if (FLAGS_SET(flags, DISSECT_IMAGE_VERITY_SHARE)) {
/* Before trying to activate with unique name, we need to free crypt_device object.
* Otherwise, we get error from libcryptsetup like the following:
* ------
* systemd[1234]: Cannot use device /dev/loop5 which is in use (already mapped or mounted).
* ------
*/
sym_crypt_free(cd);
cd = NULL;
return verity_partition(
di,
designator,
m,
v,
root,
verity,
flags & ~DISSECT_IMAGE_VERITY_SHARE,
policy_flags,
d);
}
return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All attempts to activate verity device %s failed.", name);
success:
d->decrypted[d->n_decrypted++] = (DecryptedPartition) {
.name = TAKE_PTR(name),
.device = TAKE_PTR(cd),
};
free_and_replace(m->decrypted_node, node);
close_and_replace(m->mount_node_fd, mount_node_fd);
return 0;
}
static void dissected_image_undo_decrypt(DissectedImage *m) {
assert(m);
FOREACH_ELEMENT(p, m->partitions) {
if (!p->decrypted_node) /* Only look at partitions which we decrypted */
continue;
p->decrypted_node = mfree(p->decrypted_node);
p->decrypted_fstype = mfree(p->decrypted_fstype);
p->mount_node_fd = safe_close(p->mount_node_fd);
}
}
#endif
int dissected_image_decrypt(
DissectedImage *m,
const char *root, /* The root to get user verity certs from (for a sysext) */
const char *passphrase,
const VeritySettings *verity,
const ImagePolicy *policy,
DissectImageFlags flags) {
#if HAVE_LIBCRYPTSETUP
_cleanup_(decrypted_image_unrefp) DecryptedImage *d = NULL;
#endif
int r;
assert(m);
assert(!verity || iovec_is_valid(&verity->root_hash));
assert(!verity || iovec_is_valid(&verity->root_hash_sig));
/* Returns:
*
* = 0 → There was nothing to decrypt/setup
* > 0 → Decrypted/setup successfully
* -ENOKEY → dm-crypt: there's something to decrypt but no decryption key was supplied
* -EKEYREJECTED → dm-crypt: Passed key was not correct
* -EDESTADDRREQ → dm-verity: there's something to setup but no signature was supplied
* -EBUSY → dm-verity: Generic Verity error (kernel is not very explanatory)
* -ERFKILL → image policy not compatible with request
* -EEXIST → DM device already exists under the specified name
*/
if (verity && iovec_is_set(&verity->root_hash) && verity->root_hash.iov_len < sizeof(sd_id128_t))
return -EINVAL;
if (!m->encrypted && !m->verity_ready)
return 0;
r = secure_getenv_bool("SYSTEMD_VERITY_SHARING");
if (r >= 0)
SET_FLAG(flags, DISSECT_IMAGE_VERITY_SHARE, r);
#if HAVE_LIBCRYPTSETUP
r = decrypted_image_new(&d);
if (r < 0)
return r;
for (PartitionDesignator i = 0; i < _PARTITION_DESIGNATOR_MAX; i++) {
DissectedPartition *p = m->partitions + i;
PartitionDesignator k;
if (!p->found)
continue;
PartitionPolicyFlags fl = image_policy_get_exhaustively(policy, i);
/* Set up Verity first, and only then LUKS: if a partition is both Verity protected and
* encrypted, Verity is the outer envelope and LUKS the inner, i.e. the Verity hash data
* covers the LUKS ciphertext, and decrypt_partition() then stacks the LUKS device on top of
* the verity device. */
k = partition_verity_hash_of(i);
if (k >= 0) {
r = verity_partition(m, i, p, m->partitions + k, root, verity, flags, fl, d);
if (r < 0)
goto fail;
}
r = decrypt_partition(m, p, passphrase, flags, fl, d);
if (r < 0)
goto fail;
if (!p->decrypted_fstype && p->mount_node_fd >= 0 && p->decrypted_node) {
r = probe_filesystem_full(p->mount_node_fd, p->decrypted_node, 0, UINT64_MAX, /* bool restrict_fstypes= */ true, &p->decrypted_fstype);
if (r < 0 && r != -EUCLEAN)
goto fail;
}
}
m->decrypted_image = TAKE_PTR(d);
return 1;
fail:
/* Undo partial activation */
dissected_image_undo_decrypt(m);
return r;
#else
return -EOPNOTSUPP;
#endif
}
int dissected_image_decrypt_interactively(
DissectedImage *m,
const char *passphrase,
const VeritySettings *verity,
const ImagePolicy *image_policy,
DissectImageFlags flags) {
_cleanup_strv_free_erase_ char **z = NULL;
int n = 3, r;
if (passphrase)
n--;
for (;;) {
r = dissected_image_decrypt(m, /* root= */ NULL, passphrase, verity, image_policy, flags);
if (r >= 0)
return r;
if (r == -EKEYREJECTED)
log_error_errno(r, "Incorrect passphrase, try again!");
else if (r == -EDESTADDRREQ)
return log_error_errno(r, "Image lacks recognized signature.");
else if (r == -ERFKILL)
return log_error_errno(r, "Unlocking of Verity/LUKS volumes not permitted by policy.");
else if (r != -ENOKEY)
return log_error_errno(r, "Failed to decrypt/set up image: %m");
if (--n < 0)
return log_error_errno(SYNTHETIC_ERRNO(EKEYREJECTED),
"Too many retries.");
z = strv_free_erase(z);
static const AskPasswordRequest req = {
.tty_fd = -EBADF,
.message = "Please enter image passphrase:",
.id = "dissect",
.keyring = "dissect",
.credential = "dissect.passphrase",
.until = USEC_INFINITY,
.hup_fd = -EBADF,
};
r = ask_password_auto(&req, /* flags= */ 0, &z);
if (r < 0)
return log_error_errno(r, "Failed to query for passphrase: %m");
assert(!strv_isempty(z));
passphrase = z[0];
}
}
static int decrypted_image_relinquish(DecryptedImage *d) {
assert(d);
/* Turns on automatic removal after the last use ended for all DM devices of this image, and sets a
* boolean so that we don't clean it up ourselves either anymore */
#if HAVE_LIBCRYPTSETUP
int r;
for (size_t i = 0; i < d->n_decrypted; i++) {
DecryptedPartition *p = d->decrypted + i;
if (p->relinquished)
continue;
r = sym_crypt_deactivate_by_name(NULL, p->name, CRYPT_DEACTIVATE_DEFERRED);
if (r < 0)
return log_debug_errno(r, "Failed to mark %s for auto-removal: %m", p->name);
p->relinquished = true;
}
#endif
return 0;
}
int dissected_image_relinquish(DissectedImage *m) {
int r;
assert(m);
if (m->decrypted_image) {
r = decrypted_image_relinquish(m->decrypted_image);
if (r < 0)
return r;
}
if (m->loop)
loop_device_relinquish(m->loop);
return 0;
}
void image_filter_done(ImageFilter *f) {
assert(f);
FOREACH_ELEMENT(p, f->pattern)
*p = mfree(*p);
}
ImageFilter *image_filter_free(ImageFilter *f) {
if (!f)
return NULL;
image_filter_done(f);
return mfree(f);
}
int image_filter_parse(const char *s, ImageFilter **ret) {
_cleanup_(image_filter_freep) ImageFilter *f = NULL;
int r;
if (isempty(s)) {
if (ret)
*ret = NULL;
return 0;
}
for (;;) {
_cleanup_free_ char *word = NULL;
r = extract_first_word(&s, &word, ":", EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return log_debug_errno(r, "Failed to extract word: %m");
if (r == 0)
break;
_cleanup_free_ char *designator = NULL, *pattern = NULL;
const char *x = word;
r = extract_many_words(&x, "=", EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS, &designator, &pattern);
if (r < 0)
return log_debug_errno(r, "Failed to extract designator: %m");
if (r != 2 || !isempty(x))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to split: %s", word);
PartitionDesignator d = partition_designator_from_string(designator);
if (d < 0)
return log_debug_errno(d, "Failed to parse partition designator: %s", designator);
if (!f) {
f = new0(ImageFilter, 1);
if (!f)
return log_oom_debug();
} else if (f->pattern[d])
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Duplicate pattern for '%s', refusing.", partition_designator_to_string(d));
f->pattern[d] = TAKE_PTR(pattern);
}
if (ret)
*ret = TAKE_PTR(f);
return 0;
}
static char *build_auxiliary_path(const char *image, const char *suffix) {
const char *e;
char *n;
assert(image);
assert(suffix);
e = endswith(image, ".raw");
if (!e)
return strjoin(image, suffix);
n = new(char, e - image + strlen(suffix) + 1);
if (!n)
return NULL;
strcpy(mempcpy(n, image, e - image), suffix);
return n;
}
void verity_settings_done(VeritySettings *v) {
assert(v);
iovec_done(&v->root_hash);
iovec_done(&v->root_hash_sig);
v->data_path = mfree(v->data_path);
}
VeritySettings* verity_settings_free(VeritySettings *v) {
if (!v)
return NULL;
verity_settings_done(v);
return mfree(v);
}
void verity_settings_hash_func(const VeritySettings *s, struct siphash *state) {
assert(s);
siphash24_compress_typesafe(s->root_hash.iov_len, state);
siphash24_compress(s->root_hash.iov_base, s->root_hash.iov_len, state);
}
int verity_settings_compare_func(const VeritySettings *x, const VeritySettings *y) {
assert(x);
assert(y);
return iovec_memcmp(&x->root_hash, &y->root_hash);
}
DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(verity_settings_hash_ops, VeritySettings, verity_settings_hash_func, verity_settings_compare_func, VeritySettings, verity_settings_free);
int verity_settings_load(
VeritySettings *verity,
const char *image,
const char *root_hash_path,
const char *root_hash_sig_path) {
PartitionDesignator designator;
int r;
assert(verity);
assert(image);
assert(verity->designator < 0 || IN_SET(verity->designator, PARTITION_ROOT, PARTITION_USR));
/* If we are asked to load the root hash for a device node, exit early */
if (is_device_path(image))
return 0;
r = secure_getenv_bool("SYSTEMD_DISSECT_VERITY_SIDECAR");
if (r < 0 && r != -ENXIO)
log_debug_errno(r, "Failed to parse $SYSTEMD_DISSECT_VERITY_SIDECAR, ignoring: %m");
if (r == 0)
return 0;
designator = verity->designator;
/* We only fill in what isn't already filled in */
_cleanup_(iovec_done) struct iovec root_hash = {};
if (!iovec_is_set(&verity->root_hash)) {
_cleanup_free_ char *text = NULL;
if (root_hash_path) {
/* If explicitly specified it takes precedence */
r = read_one_line_file(root_hash_path, &text);
if (r < 0)
return r;
if (designator < 0)
designator = PARTITION_ROOT;
} else {
/* Otherwise look for xattr and separate file, and first for the data for root and if
* that doesn't exist for /usr */
if (designator < 0 || designator == PARTITION_ROOT) {
r = getxattr_malloc(image, "user.verity.roothash", &text, /* ret_size= */ NULL);
if (r < 0) {
_cleanup_free_ char *p = NULL;
if (!ERRNO_IS_XATTR_ABSENT(r))
return r;
p = build_auxiliary_path(image, ".roothash");
if (!p)
return -ENOMEM;
r = read_one_line_file(p, &text);
if (r < 0 && r != -ENOENT)
return r;
}
if (text)
designator = PARTITION_ROOT;
}
if (!text && (designator < 0 || designator == PARTITION_USR)) {
/* So in the "roothash" xattr/file name above the "root" of course primarily
* refers to the root of the Verity Merkle tree. But coincidentally it also
* is the hash for the *root* file system, i.e. the "root" neatly refers to
* two distinct concepts called "root". Taking benefit of this happy
* coincidence we call the file with the root hash for the /usr/ file system
* `usrhash`, because `usrroothash` or `rootusrhash` would just be too
* confusing. We thus drop the reference to the root of the Merkle tree, and
* just indicate which file system it's about. */
r = getxattr_malloc(image, "user.verity.usrhash", &text, /* ret_size= */ NULL);
if (r < 0) {
_cleanup_free_ char *p = NULL;
if (!ERRNO_IS_XATTR_ABSENT(r))
return r;
p = build_auxiliary_path(image, ".usrhash");
if (!p)
return -ENOMEM;
r = read_one_line_file(p, &text);
if (r < 0 && r != -ENOENT)
return r;
}
if (text)
designator = PARTITION_USR;
}
}
if (text) {
r = unhexmem(text, &root_hash.iov_base, &root_hash.iov_len);
if (r < 0)
return r;
if (root_hash.iov_len < sizeof(sd_id128_t))
return -EINVAL;
}
}
_cleanup_(iovec_done) struct iovec root_hash_sig = {};
if ((iovec_is_set(&root_hash) || iovec_is_set(&verity->root_hash)) && !iovec_is_set(&verity->root_hash_sig)) {
if (root_hash_sig_path) {
r = read_full_file(root_hash_sig_path, (char**) &root_hash_sig.iov_base, &root_hash_sig.iov_len);
if (r < 0 && r != -ENOENT)
return r;
if (r >= 0 && root_hash_sig.iov_len == 0) /* refuse empty size signatures */
return -EINVAL;
if (designator < 0)