HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/repart/repart.c
Git blob: b40c7a91acf99c5ac898f4de16e45b142c19fa8c
Lines 5001–6000 of 11,995
if (next == UINT64_MAX || q->offset < next)
next = q->offset;
}
if (next == UINT64_MAX) {
next = (sym_fdisk_get_last_lba(context->fdisk_context) + 1) * context->sector_size;
if (gap > next)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Partition end beyond disk end.");
}
assert(next >= gap);
r = context_discard_range(context, gap, next - gap);
if (r == -EOPNOTSUPP) {
if (p)
log_info("Storage does not support discard, not discarding gap after partition %" PRIu64 ".", p->partno);
else
log_info("Storage does not support discard, not discarding gap at beginning of disk.");
return 0;
}
if (r == 0) /* Too short */
return 0;
if (r < 0) {
if (p)
return log_error_errno(r, "Failed to discard gap after partition %" PRIu64 ".", p->partno);
else
return log_error_errno(r, "Failed to discard gap at beginning of disk.");
}
if (p)
log_info("Successfully discarded gap after partition %" PRIu64 ".", p->partno);
else
log_info("Successfully discarded gap at beginning of disk.");
return 0;
}
static bool partition_defer(const Context *c, const Partition *p) {
assert(c);
assert(p);
if (partition_type_defer(&p->type))
return true;
if (c->defer_partitions_empty && streq_ptr(p->new_label, "_empty"))
return true;
if (c->defer_partitions_factory_reset && p->factory_reset)
return true;
return false;
}
static int context_wipe_and_discard(Context *context) {
int r;
assert(context);
if (context->empty == EMPTY_CREATE) /* If we just created the image, no need to wipe */
return 0;
/* Wipe and discard the contents of all partitions we are about to create. We skip the discarding if
* we were supposed to start from scratch anyway, as in that case we just discard the whole block
* device in one go early on. */
LIST_FOREACH(partitions, p, context->partitions) {
if (!p->allocated_to_area)
continue;
if (partition_defer(context, p))
continue;
(void) context_notify(context, PROGRESS_WIPING_PARTITION, p->definition_path, UINT_MAX);
r = context_wipe_partition(context, p);
if (r < 0)
return r;
if (!context->from_scratch) {
r = context_discard_partition(context, p);
if (r < 0)
return r;
r = context_discard_gap_after(context, p);
if (r < 0)
return r;
}
}
if (!context->from_scratch) {
r = context_discard_gap_after(context, NULL);
if (r < 0)
return r;
}
return 0;
}
typedef struct DecryptedPartitionTarget {
int fd;
char *dm_name;
char *volume;
bool keep;
struct crypt_device *device;
} DecryptedPartitionTarget;
static DecryptedPartitionTarget* decrypted_partition_target_free(DecryptedPartitionTarget *t) {
#if HAVE_LIBCRYPTSETUP
int r;
if (!t)
return NULL;
safe_close(t->fd);
if (!t->keep) {
/* udev or so might access our block device in the background while we are done. Let's hence
* force detach the volume. We sync'ed before, hence this should be safe. */
r = sym_crypt_deactivate_by_name(t->device, t->dm_name, CRYPT_DEACTIVATE_FORCE);
if (r < 0)
log_warning_errno(r, "Failed to deactivate LUKS device, ignoring: %m");
} else
log_debug("Keeping encrypted device '%s' open.", t->dm_name);
sym_crypt_free(t->device);
free(t->dm_name);
free(t->volume);
free(t);
#endif
return NULL;
}
/* BlockPartition represents partitions that have been created with BLKPG */
typedef struct {
int fd;
int whole_fd; /* not owned */
int nr;
uint64_t offset;
uint64_t size;
char *node;
} BlockPartition;
static BlockPartition* block_partition_free(BlockPartition *p) {
if (!p)
return NULL;
safe_close(p->fd);
free(p->node);
return mfree(p);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(BlockPartition*, block_partition_free);
typedef struct {
LoopDevice *loop;
BlockPartition *block_partition;
int fd;
char *path;
int whole_fd;
DecryptedPartitionTarget *decrypted;
} PartitionTarget;
static int partition_target_fd(PartitionTarget *t) {
assert(t);
assert(t->loop || t->fd >= 0 || t->whole_fd >= 0 || t->block_partition);
if (t->decrypted)
return t->decrypted->fd;
if (t->loop)
return t->loop->fd;
if (t->block_partition)
return t->block_partition->fd;
if (t->fd >= 0)
return t->fd;
return t->whole_fd;
}
static const char* partition_target_path(PartitionTarget *t) {
assert(t);
assert(t->loop || t->path || t->block_partition);
if (t->decrypted)
return t->decrypted->volume;
if (t->loop)
return t->loop->node;
if (t->block_partition)
return t->block_partition->node;
return t->path;
}
static PartitionTarget* partition_target_free(PartitionTarget *t) {
if (!t)
return NULL;
decrypted_partition_target_free(t->decrypted);
loop_device_unref(t->loop);
safe_close(t->fd);
unlink_and_free(t->path);
block_partition_free(t->block_partition);
return mfree(t);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(PartitionTarget*, partition_target_free);
static int prepare_temporary_file(Context *context, PartitionTarget *t, uint64_t size) {
_cleanup_(unlink_and_freep) char *temp = NULL;
_cleanup_close_ int fd = -EBADF;
const char *vt;
unsigned attrs = 0;
int r;
assert(context);
assert(t);
r = var_tmp_dir(&vt);
if (r < 0)
return log_error_errno(r, "Could not determine temporary directory: %m");
temp = path_join(vt, "repart-XXXXXX");
if (!temp)
return log_oom();
fd = mkostemp_safe(temp);
if (fd < 0)
return log_error_errno(fd, "Failed to create temporary file: %m");
if (context->fdisk_context) {
r = read_attr_fd(sym_fdisk_get_devfd(context->fdisk_context), &attrs);
if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
log_warning_errno(r, "Failed to read file attributes of %s, ignoring: %m", context->node);
if (FLAGS_SET(attrs, FS_NOCOW_FL)) {
r = chattr_fd(fd, FS_NOCOW_FL, FS_NOCOW_FL);
if (r < 0 && !ERRNO_IS_IOCTL_NOT_SUPPORTED(r))
return log_error_errno(r, "Failed to disable copy-on-write on %s: %m", temp);
}
}
if (ftruncate(fd, size) < 0)
return log_error_errno(errno, "Failed to truncate temporary file to %s: %m",
FORMAT_BYTES(size));
t->fd = TAKE_FD(fd);
t->path = TAKE_PTR(temp);
return 0;
}
static bool loop_device_error_is_fatal(const Partition *p, int r) {
assert(p);
return arg_offline == 0 || (r != -ENOENT && !ERRNO_IS_PRIVILEGE(r));
}
static int partition_target_prepare(
Context *context,
Partition *p,
uint64_t size,
bool need_path,
PartitionTarget **ret) {
_cleanup_(partition_target_freep) PartitionTarget *t = NULL;
_cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
int whole_fd, r;
assert(context);
assert(p);
assert(ret);
assert_se((whole_fd = sym_fdisk_get_devfd(context->fdisk_context)) >= 0);
t = new(PartitionTarget, 1);
if (!t)
return log_oom();
*t = (PartitionTarget) {
.fd = -EBADF,
.whole_fd = -EBADF,
};
if (!need_path) {
if (lseek(whole_fd, p->offset, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek to partition offset: %m");
t->whole_fd = whole_fd;
*ret = TAKE_PTR(t);
return 0;
}
if (arg_offline <= 0) {
r = blockdev_partscan_enabled_fd(whole_fd);
if (r > 0) {
_cleanup_close_ int dev_fd = -EBADF;
_cleanup_free_ char *part_node = NULL;
_cleanup_(block_partition_freep) BlockPartition *b = NULL;
int nr;
/* blkpg takes int for partition numbers */
if (p->partno >= INT_MAX)
return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Partition number %" PRIu64 " is too large for blkpg.", p->partno);
nr = p->partno + 1;
part_node = sym_fdisk_partname(context->node, p->partno + 1);
if (!part_node)
return log_oom();
/* There is no corresponding call to block_device_remove_partition because we want to
* keep them alive if we succeed, and the rescan will remove them if possible if
* there is an error before writing the partition table.
*/
log_debug("Adding partition '%s' (nr=%i, offset=%" PRIu64 " [align=%" PRIu64 "], size=%" PRIu64 " [align=%" PRIu64 "])",
part_node, nr,
p->offset, NATURAL_ALIGNMENT(p->offset),
size, NATURAL_ALIGNMENT(size));
r = block_device_add_partition(whole_fd, nr, p->offset, size);
if (r < 0)
return log_error_errno(r, "Failed to create new partition '%s': %m", part_node);
context->needs_rescan = true;
dev_fd = open(part_node, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (dev_fd < 0) {
r = -errno;
int q = block_device_remove_partition(whole_fd, nr);
if (q < 0)
log_warning_errno(q, "Error while removing block device partition '%s', ignoring: %m", part_node);
return log_error_errno(r, "Failed to open new partition '%s': %m", part_node);
}
/* No need to flock for udev, the whole disk fd is already locked. */
b = new(BlockPartition, 1);
if (!b) {
r = block_device_remove_partition(whole_fd, nr);
if (r < 0)
log_warning_errno(r, "Error while removing block device partition '%s', ignoring: %m", part_node);
return log_oom();
}
*b = (BlockPartition) {
.fd = TAKE_FD(dev_fd),
.whole_fd = whole_fd,
.nr = nr,
.offset = p->offset,
.size = size,
.node = TAKE_PTR(part_node),
};
t->block_partition = TAKE_PTR(b);
*ret = TAKE_PTR(t);
return 0;
} else {
if (!IN_SET(r, 0, -ENOTBLK))
log_warning_errno(r, "Could not detect whether the device can be partitioned, assuming it cannot be: %m");
/* Loopback block devices are not only useful to turn regular files into block devices, but
* also to cut out sections of block devices into new block devices. */
r = loop_device_make(whole_fd, O_RDWR, p->offset, size, context->sector_size, /* loop_flags= */ 0, LOCK_EX, &d);
if (r < 0 && loop_device_error_is_fatal(p, r))
return log_error_errno(r, "Failed to make loopback device of future partition %" PRIu64 ": %m", p->partno);
if (r >= 0) {
t->loop = TAKE_PTR(d);
*ret = TAKE_PTR(t);
return 0;
}
log_debug_errno(r, "No access to loop devices, falling back to a regular file");
}
}
/* If we can't allocate a loop device, let's write to a regular file that we copy into the final
* image so we can run in containers and without needing root privileges. On filesystems with
* reflinking support, we can take advantage of this and just reflink the result into the image.
*/
r = prepare_temporary_file(context, t, size);
if (r < 0)
return r;
*ret = TAKE_PTR(t);
return 0;
}
static void partition_target_drop_decrypted(PartitionTarget *t) {
assert(t);
/* Deactivate the dm-crypt device again, so that subsequent access to the target reaches the
* encrypted data as it is stored on disk (i.e. the ciphertext). Requires the target to have been
* sync'ed first. */
t->decrypted = decrypted_partition_target_free(t->decrypted);
}
static int partition_target_grow(PartitionTarget *t, uint64_t size) {
int r;
assert(t);
assert(!t->decrypted);
if (t->loop) {
r = loop_device_refresh_size(t->loop, UINT64_MAX, size);
if (r < 0)
return log_error_errno(r, "Failed to refresh loopback device size: %m");
} else if (t->block_partition) {
r = block_device_resize_partition(t->block_partition->whole_fd, t->block_partition->nr, t->block_partition->offset, size);
if (r < 0)
return log_error_errno(r, "Failed to resize partition %d: %m", t->block_partition->nr);
t->block_partition->size = size;
} else if (t->fd >= 0) {
if (ftruncate(t->fd, size) < 0)
return log_error_errno(errno, "Failed to grow '%s' to %s by truncation: %m",
t->path, FORMAT_BYTES(size));
}
return 0;
}
static int partition_target_sync(Context *context, Partition *p, PartitionTarget *t) {
int whole_fd, r;
assert(context);
assert(p);
assert(t);
assert_se((whole_fd = sym_fdisk_get_devfd(context->fdisk_context)) >= 0);
log_info("Syncing future partition %"PRIu64" contents to disk.", p->partno);
if (t->decrypted && fsync(t->decrypted->fd) < 0)
return log_error_errno(errno, "Failed to sync changes to '%s': %m", t->decrypted->volume);
if (t->loop) {
r = loop_device_sync(t->loop);
if (r < 0)
return log_error_errno(r, "Failed to sync loopback device: %m");
} else if (t->block_partition) {
if (fsync(t->block_partition->fd) < 0)
return log_error_errno(errno, "Failed to sync blkpg partition: %m");
} else if (t->fd >= 0) {
struct stat st;
if (lseek(whole_fd, p->offset, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek to partition offset: %m");
if (fstat(t->fd, &st) < 0)
return log_error_errno(errno, "Failed to stat temporary file: %m");
if (st.st_size > (off_t) p->new_size)
return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
"Partition %" PRIu64 "'s contents (%s) don't fit in the partition (%s).",
p->partno, FORMAT_BYTES(st.st_size), FORMAT_BYTES(p->new_size));
r = copy_bytes(t->fd, whole_fd, UINT64_MAX, COPY_HOLES|COPY_FSYNC|COPY_SEEK0_SOURCE);
if (r < 0)
return log_error_errno(r, "Failed to copy bytes to partition: %m");
} else {
if (fsync(t->whole_fd) < 0)
return log_error_errno(errno, "Failed to sync changes: %m");
}
return 0;
}
/* libcryptsetup uses its own names for integrity algorithms, e.g. 'hmac(sha1)' but systemd
* prefers more standardized 'hmac-sha1', do the conversion here. Default to hmac(sha256). */
static const char* dmcrypt_integrity_alg_name(Partition *p) {
if (p->integrity != INTEGRITY_INLINE)
return NULL;
switch (p->integrity_alg) {
case INTEGRITY_ALG_HMAC_SHA1:
return "hmac(sha1)";
case INTEGRITY_ALG_HMAC_SHA512:
return "hmac(sha512)";
case INTEGRITY_ALG_HMAC_SHA256:
default:
return "hmac(sha256)";
}
}
/* Integrity puts specific limitations on the key size depending on the algorithm */
static size_t dmcrypt_proper_key_size(Partition *p) {
if (p->integrity != INTEGRITY_INLINE)
return VOLUME_KEY_SIZE;
switch (p->integrity_alg) {
case INTEGRITY_ALG_HMAC_SHA1:
return 672/8;
case INTEGRITY_ALG_HMAC_SHA512:
return 1024/8;
case INTEGRITY_ALG_HMAC_SHA256:
default:
return 768/8;
}
}
static int partition_encrypt(Context *context, Partition *p, PartitionTarget *target, bool offline, bool temporary) {
#if HAVE_LIBCRYPTSETUP
#if HAVE_TPM2
_cleanup_(erase_and_freep) char *base64_encoded = NULL;
#endif
_cleanup_fclose_ FILE *h = NULL;
_cleanup_free_ char *hp = NULL, *vol = NULL, *dm_name = NULL;
const char *passphrase = NULL;
const size_t volume_key_size = dmcrypt_proper_key_size(p);
size_t passphrase_size = 0;
const char *vt;
int r;
assert(context);
assert(p);
assert(p->encrypt != ENCRYPT_OFF);
r = dlopen_cryptsetup(LOG_ERR);
if (r < 0)
return r;
log_info("Encrypting future partition %" PRIu64 "...", p->partno);
_cleanup_free_ char *vl = NULL;
r = volume_label(p, &vl);
if (r < 0)
return r;
const char *node = partition_target_path(target);
struct crypt_params_luks2 luks_params = {
.label = vl,
.sector_size = partition_fs_sector_size(context, p),
.data_device = offline ? node : NULL,
.integrity = dmcrypt_integrity_alg_name(p),
};
struct crypt_params_reencrypt reencrypt_params = {
.mode = CRYPT_REENCRYPT_ENCRYPT,
.direction = CRYPT_REENCRYPT_BACKWARD,
.resilience = "datashift",
.data_shift = LUKS2_METADATA_SIZE / 512,
.luks2 = &luks_params,
.flags = CRYPT_REENCRYPT_INITIALIZE_ONLY|CRYPT_REENCRYPT_MOVE_FIRST_SEGMENT,
};
if (offline) {
/* libcryptsetup does not currently support reencryption of devices with integrity profiles.*/
if (p->integrity == INTEGRITY_INLINE)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Integrity=inline cannot be enabled in offline mode.");
r = var_tmp_dir(&vt);
if (r < 0)
return log_error_errno(r, "Failed to determine temporary files directory: %m");
r = fopen_temporary_child(vt, &h, &hp);
if (r < 0)
return log_error_errno(r, "Failed to create temporary LUKS header file: %m");
/* Weird cryptsetup requirement which requires the header file to be the size of at least one
* sector. */
if (ftruncate(fileno(h), luks_params.sector_size) < 0)
return log_error_errno(errno, "Failed to grow temporary LUKS header file: %m");
} else {
if (!temporary && p->volume_name)
dm_name = strdup(p->volume_name);
else if (!temporary && filename_is_valid(vl))
dm_name = strdup(vl);
else
dm_name = asprintf_safe("luks-repart-%08" PRIx64, random_u64());
if (!dm_name)
return log_oom();
vol = path_join("/dev/mapper/", dm_name);
if (!vol)
return log_oom();
}
_cleanup_(crypt_freep) struct crypt_device *cd = NULL;
r = sym_crypt_init(&cd, offline ? hp : node);
if (r < 0)
return log_error_errno(r, "Failed to allocate libcryptsetup context for %s: %m", hp);
cryptsetup_enable_logging(cd);
if (offline) {
/* Disable kernel keyring usage by libcryptsetup as a workaround for
* https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/273. This makes sure that we can
* do offline encryption even when repart is running in a container. */
r = sym_crypt_volume_key_keyring(cd, false);
if (r < 0)
return log_error_errno(r, "Failed to disable kernel keyring: %m");
r = sym_crypt_metadata_locking(cd, false);
if (r < 0)
return log_error_errno(r, "Failed to disable metadata locking: %m");
r = sym_crypt_set_data_offset(cd, LUKS2_METADATA_SIZE / 512);
if (r < 0)
return log_error_errno(r, "Failed to set data offset: %m");
}
r = sym_crypt_format(
cd,
CRYPT_LUKS2,
"aes",
"xts-plain64",
SD_ID128_TO_UUID_STRING(p->luks_uuid),
NULL,
/* volume_key_size= */ volume_key_size,
&luks_params);
if (r < 0)
return log_error_errno(r, "Failed to LUKS2 format future partition: %m");
/* If an explicit KDF is configured, apply it before adding any keyslots. */
if (p->encrypt_kdf >= 0) {
if (p->encrypt_kdf == ENCRYPT_KDF_MINIMAL) {
/* Minimal PBKDF2 with sha512, 1000 iterations, no benchmarking — appropriate
* for high-entropy keys where the KDF only satisfies the LUKS2 format requirement
* (e.g. kdump with crashkernel=512MB). */
r = cryptsetup_set_minimal_pbkdf(cd);
} else {
assert(IN_SET(p->encrypt_kdf, ENCRYPT_KDF_ARGON2ID, ENCRYPT_KDF_PBKDF2));
/* Use libcryptsetup's full defaults, including the benchmark target and hash. */
const char *kdf = p->encrypt_kdf == ENCRYPT_KDF_ARGON2ID ? CRYPT_KDF_ARGON2ID : CRYPT_KDF_PBKDF2;
const struct crypt_pbkdf_type *pbkdf = sym_crypt_get_pbkdf_type_params(kdf);
if (!pbkdf)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Failed to get default parameters for KDF type '%s'.", kdf);
r = sym_crypt_set_pbkdf_type(cd, pbkdf);
}
if (r < 0)
return log_error_errno(r, "Failed to set KDF type: %m");
}
bool allow_discards = p->integrity != INTEGRITY_INLINE && (arg_discard ? p->discard != 0 : p->discard > 0);
if (allow_discards) {
uint32_t flags;
r = sym_crypt_persistent_flags_get(cd, CRYPT_FLAGS_ACTIVATION, &flags);
if (r < 0)
return log_error_errno(r, "Failed to get persistent activation flags for %s: %m", node);
if (!FLAGS_SET(flags, CRYPT_ACTIVATE_ALLOW_DISCARDS)) {
flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
r = sym_crypt_persistent_flags_set(cd, CRYPT_FLAGS_ACTIVATION, flags);
if (r < 0)
return log_error_errno(r, "Failed to set persistent activation flags for %s: %m", node);
}
}
if (p->encrypted_volume && p->encrypted_volume->fixate_volume_key) {
_cleanup_free_ char *key_id = NULL, *hash_option = NULL;
r = sym_crypt_get_volume_key_size(cd);
if (r < 0)
return log_error_errno(r, "Failed to determine volume key size: %m");
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Volume key has zero size and 'fixate-volume-key' is used");
_cleanup_(iovec_done) struct iovec vk = {
.iov_base = malloc(r),
.iov_len = r,
};
if (!vk.iov_base)
return log_oom();
r = sym_crypt_volume_key_get(cd, CRYPT_ANY_SLOT, (char *) vk.iov_base, &vk.iov_len, NULL, 0);
if (r < 0)
return log_error_errno(r, "Failed to get volume key: %m");
r = cryptsetup_get_volume_key_id(
cd,
/* volume_name= */ p->encrypted_volume->name,
/* volume_key= */ vk.iov_base,
/* volume_key_size= */ vk.iov_len,
/* ret= */ &key_id);
if (r < 0)
return log_error_errno(r, "Failed to get volume key hash: %m");
hash_option = strjoin("fixate-volume-key=", key_id);
if (!hash_option)
return log_oom();
if (!strextend_with_separator(&p->encrypted_volume->options, ",", hash_option))
return log_oom();
}
if (IN_SET(p->encrypt, ENCRYPT_KEY_FILE, ENCRYPT_KEY_FILE_TPM2)) {
/* Use partition-specific key if available, otherwise fall back to global key */
struct iovec *iovec_key = arg_key.iov_base ? &arg_key : &p->key;
r = sym_crypt_keyslot_add_by_volume_key(
cd,
CRYPT_ANY_SLOT,
NULL,
/* volume_key_size= */ volume_key_size,
strempty(iovec_key->iov_base),
iovec_key->iov_len);
if (r < 0)
return log_error_errno(r, "Failed to add LUKS2 key: %m");
passphrase = strempty(iovec_key->iov_base);
passphrase_size = iovec_key->iov_len;
}
if (IN_SET(p->encrypt, ENCRYPT_TPM2, ENCRYPT_KEY_FILE_TPM2)) {
#if HAVE_TPM2
_cleanup_(iovec_done) struct iovec pubkey = {}, srk = {};
_cleanup_(iovec_done_erase) struct iovec secret = {};
_cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
ssize_t base64_encoded_size;
int keyslot;
TPM2Flags flags = 0;
Tpm2PCRValue *pcr_values = arg_tpm2_n_hash_pcr_values > 0 ? arg_tpm2_hash_pcr_values : p->tpm2_hash_pcr_values;
size_t n_pcr_values = arg_tpm2_n_hash_pcr_values > 0 ? arg_tpm2_n_hash_pcr_values : p->tpm2_n_hash_pcr_values;
if (n_pcr_values == 0 &&
arg_tpm2_public_key_pcr_mask == 0 &&
!arg_tpm2_pcrlock)
log_notice("Notice: encrypting future partition %" PRIu64 ", locking against TPM2 with an empty policy, i.e. without any state or access restrictions.\n"
"Use --tpm2-public-key=, --tpm2-pcrlock=, or --tpm2-pcrs= to enable one or more restrictions.", p->partno);
if (arg_tpm2_public_key_pcr_mask != 0) {
r = tpm2_load_pcr_public_key(arg_tpm2_public_key, &pubkey.iov_base, &pubkey.iov_len);
if (r < 0) {
if (arg_tpm2_public_key || r != -ENOENT)
return log_error_errno(r, "Failed to read TPM PCR public key: %m");
log_debug_errno(r, "Failed to read TPM2 PCR public key, proceeding without: %m");
arg_tpm2_public_key_pcr_mask = 0;
}
}
TPM2B_PUBLIC public;
if (iovec_is_set(&pubkey)) {
r = tpm2_tpm2b_public_from_pem(pubkey.iov_base, pubkey.iov_len, &public);
if (r < 0)
return log_error_errno(r, "Could not convert public key to TPM2B_PUBLIC: %m");
}
_cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy pcrlock_policy = {};
if (arg_tpm2_pcrlock) {
r = tpm2_pcrlock_policy_load(arg_tpm2_pcrlock, &pcrlock_policy);
if (r < 0)
return r;
flags |= TPM2_FLAGS_USE_PCRLOCK;
}
_cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
TPM2B_PUBLIC device_key_public = {};
if (arg_tpm2_device_key) {
r = tpm2_load_public_key_file(arg_tpm2_device_key, &device_key_public);
if (r < 0)
return r;
if (!tpm2_pcr_values_has_all_values(pcr_values, n_pcr_values))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Must provide all PCR values when using TPM2 device key.");
} else {
r = tpm2_context_new_or_warn(arg_tpm2_device, &tpm2_context);
if (r < 0)
return r;
if (!tpm2_pcr_values_has_all_values(pcr_values, n_pcr_values)) {
r = tpm2_pcr_read_missing_values(tpm2_context, pcr_values, n_pcr_values);
if (r < 0)
return log_error_errno(r, "Could not read pcr values: %m");
}
}
uint16_t hash_pcr_bank = 0;
uint32_t hash_pcr_mask = 0;
if (n_pcr_values > 0) {
size_t hash_count;
r = tpm2_pcr_values_hash_count(pcr_values, n_pcr_values, &hash_count);
if (r < 0)
return log_error_errno(r, "Could not get hash count: %m");
if (hash_count > 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Multiple PCR banks selected.");
hash_pcr_bank = pcr_values[0].hash;
r = tpm2_pcr_values_to_mask(pcr_values, n_pcr_values, hash_pcr_bank, &hash_pcr_mask);
if (r < 0)
return log_error_errno(r, "Could not get hash mask: %m");
}
TPM2B_DIGEST policy_hash[2] = {
TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE),
TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE),
};
size_t n_policy_hash = 1;
/* If both PCR public key unlock and pcrlock unlock is selected, then shard the encryption key. */
r = tpm2_calculate_sealing_policy(
pcr_values,
n_pcr_values,
iovec_is_set(&pubkey) ? &public : NULL,
iovec_is_set(&pubkey) ? arg_tpm2_public_key_policyref : NULL,
/* use_pin= */ false,
arg_tpm2_pcrlock && !iovec_is_set(&pubkey) ? &pcrlock_policy : NULL,
policy_hash + 0);
if (r < 0)
return log_error_errno(r, "Could not calculate sealing policy digest for shard 0: %m");
if (arg_tpm2_pcrlock && iovec_is_set(&pubkey)) {
r = tpm2_calculate_sealing_policy(
pcr_values,
n_pcr_values,
/* public= */ NULL, /* Turn this one off for the 2nd shard */
/* pubkey_policy_ref= */ NULL,
/* use_pin= */ false,
&pcrlock_policy, /* But turn this one on */
policy_hash + 1);
if (r < 0)
return log_error_errno(r, "Could not calculate sealing policy digest for shard 1: %m");
n_policy_hash++;
}
struct iovec *blobs = NULL;
size_t n_blobs = 0;
CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
if (arg_tpm2_device_key) {
if (n_policy_hash > 1)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Combined signed PCR policies and pcrlock policies cannot be calculated offline, currently.");
blobs = new0(struct iovec, 1);
if (!blobs)
return log_oom();
n_blobs = 1;
r = tpm2_calculate_seal(
arg_tpm2_seal_key_handle,
&device_key_public,
/* attributes= */ NULL,
/* secret= */ NULL,
policy_hash + 0,
/* pin= */ NULL,
&secret,
blobs + 0,
&srk);
} else
r = tpm2_seal(tpm2_context,
arg_tpm2_seal_key_handle,
policy_hash,
n_policy_hash,
/* pin= */ NULL,
&secret,
&blobs,
&n_blobs,
/* ret_primary_alg= */ NULL,
&srk);
if (r < 0)
return log_error_errno(r, "Failed to seal to TPM2: %m");
base64_encoded_size = base64mem(secret.iov_base, secret.iov_len, &base64_encoded);
if (base64_encoded_size < 0)
return log_error_errno(base64_encoded_size, "Failed to base64 encode secret key: %m");
r = cryptsetup_set_minimal_pbkdf(cd);
if (r < 0)
return log_error_errno(r, "Failed to set minimal PBKDF: %m");
keyslot = sym_crypt_keyslot_add_by_volume_key(
cd,
CRYPT_ANY_SLOT,
/* volume_key= */ NULL,
/* volume_key_size= */ volume_key_size,
base64_encoded,
base64_encoded_size);
if (keyslot < 0)
return log_error_errno(keyslot, "Failed to add new TPM2 key: %m");
struct iovec policy_hash_as_iovec[2] = {
IOVEC_MAKE(policy_hash[0].buffer, policy_hash[0].size),
IOVEC_MAKE(policy_hash[1].buffer, policy_hash[1].size),
};
r = tpm2_make_luks2_json(
keyslot,
hash_pcr_mask,
hash_pcr_bank,
&pubkey,
iovec_is_set(&pubkey) ? arg_tpm2_public_key_policyref : NULL,
arg_tpm2_public_key_pcr_mask,
/* primary_alg= */ 0,
blobs,
n_blobs,
policy_hash_as_iovec,
n_policy_hash,
/* salt= */ NULL, /* no salt because tpm2_seal has no pin */
&srk,
&pcrlock_policy.nv_handle,
flags,
&(Argon2IdParameters) {},
&v);
if (r < 0)
return log_error_errno(r, "Failed to prepare TPM2 JSON token object: %m");
r = cryptsetup_add_token_json(cd, v);
if (r < 0)
return log_error_errno(r, "Failed to add TPM2 JSON token to LUKS2 header: %m");
passphrase = base64_encoded;
passphrase_size = strlen(base64_encoded);
#else
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Support for TPM2 enrollment not enabled.");
#endif
}
if (offline) {
r = sym_crypt_reencrypt_init_by_passphrase(
cd,
NULL,
passphrase,
passphrase_size,
CRYPT_ANY_SLOT,
0,
sym_crypt_get_cipher(cd),
sym_crypt_get_cipher_mode(cd),
&reencrypt_params);
if (r < 0)
return log_error_errno(r, "Failed to prepare for reencryption: %m");
/* crypt_reencrypt_init_by_passphrase() doesn't actually put the LUKS header at the front, we
* have to do that ourselves. */
sym_crypt_free(cd);
cd = NULL;
r = sym_crypt_init(&cd, node);
if (r < 0)
return log_error_errno(r, "Failed to allocate libcryptsetup context for %s: %m", node);
r = sym_crypt_header_restore(cd, CRYPT_LUKS2, hp);
if (r < 0)
return log_error_errno(r, "Failed to place new LUKS header at head of %s: %m", node);
reencrypt_params.flags &= ~CRYPT_REENCRYPT_INITIALIZE_ONLY;
r = sym_crypt_reencrypt_init_by_passphrase(
cd,
NULL,
passphrase,
passphrase_size,
CRYPT_ANY_SLOT,
0,
NULL,
NULL,
&reencrypt_params);
if (r < 0)
return log_error_errno(r, "Failed to load reencryption context: %m");
r = sym_crypt_reencrypt_run(cd, NULL, NULL);
if (r < 0)
return log_error_errno(r, "Failed to encrypt %s: %m", node);
} else {
_cleanup_free_ DecryptedPartitionTarget *t = NULL;
_cleanup_close_ int dev_fd = -1;
r = sym_crypt_activate_by_volume_key(
cd,
dm_name,
NULL,
/* volume_key_size= */ volume_key_size,
(allow_discards ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0) | CRYPT_ACTIVATE_PRIVATE);
if (r < 0)
return log_error_errno(r, "Failed to activate LUKS superblock: %m");
/* crypt_wipe() the whole device to avoid integrity errors upon mkfs */
if (p->integrity == INTEGRITY_INLINE) {
r = sym_crypt_wipe(
cd,
vol,
CRYPT_WIPE_ZERO,
/* offset= */ 0,
/* length= */ 0,
/* wipe_block_size= */ 1 * U64_MB,
/* flags= */ 0,
/* progress= */ NULL,
/* usrptr= */ NULL);
if (r < 0)
return log_error_errno(r, "Failed to wipe LUKS device: %m");
log_info("%s integrity protection for future partition %" PRIu64 " initialized.",
integrity_alg_to_string(p->integrity_alg), p->partno);
}
dev_fd = open(vol, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (dev_fd < 0)