Skip to contentSkip to conversation

fscrypt: key verification and KDF improvement

PATCH New Eric Biggers 1 participant 8 messages Jul 26, 2017

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v2 cover fscrypt: key verification and KDF improvement

From: Eric Biggers <[email protected]>

This patch series solves two major problems which filesystem-level encryption has currently. First, the user-supplied master keys are not verified, which means a malicious user can provide the wrong key for another user's file and cause a DOS attack or worse. This flaw has been criticized in the past [1]. Second, the KDF (Key Derivation Function) used to derive per-file keys is ad-hoc and nonstandard. While it meets the primary security requirement, it's inflexible and is missing some useful properties such as non-reversibility, which is important under some threat models. This weakness was noted by Unterluggauer and Mangard (2016) [2] who also demonstrated an EM attack against the current AES-based KDF.

These problems are solved together by introducing a new encryption policy version where the KDF is changed to HKDF-SHA512, i.e. RFC-5869
[3] with SHA-512 as the underlying hash function. HKDF is used to derive the per-file keys as well as to generate a "key hash" which is stored on-disk to allow key verification. The HMAC transform for each master key is pre-keyed and cached, which in practice makes the new KDF about as fast or even faster than the old one which did not use the crypto API efficiently.

Please give special consideration to the choice and usage of crypto algorithms and any other on-disk format and API changes, since we will be locked into these once merged.

As a sanity check, I have verified the new on-disk format on ext4 by dumping the encryption xattr and contents of an encrypted regular file using debugfs, then reproducing the key_hash field and the encrypted contents in userspace using the RFC-6234 example code and OpenSSL for HKDF-SHA512 and AES-256-XTS respectively --- given the master key and unencrypted file contents.

All these changes are independent of filesystem and encryption mode, i.e. the "v2" encryption policies can be used on any fscrypt-capable filesystem (ext4, f2fs, or ubifs currently) and with any of the supported encryption modes.

Changes since v1:
- Validate encryption modes and flags earlier in fscrypt_ioctl_set_policy(), since the modes are used in fscrypt_compute_key_hash().
- Various cleanups
- Base on v4.13-rc2

References:
[1] https://blog.quarkslab.com/a-glimpse-of-ext4-filesystem-level-encryption.html

[2] Unterluggauer and Mangard (2016). "Exploiting the Physical
Disparity: Side-Channel Attacks on Memory Encryption".
https://eprint.iacr.org/2016/473.pdf

[3] RFC 5869. "HMAC-based Extract-and-Expand Key Derivation Function

      (HKDF)".  https://tools.ietf.org/html/rfc5869

Eric Biggers (7):
fscrypt: add v2 encryption context and policy
fscrypt: rename ->ci_master_key to ->ci_master_key_descriptor
fscrypt: use HKDF-SHA512 to derive the per-inode encryption keys
fscrypt: validate modes and flags earlier when setting policy
fscrypt: verify that the correct master key was supplied
fscrypt: cache the HMAC transform for each master key
fscrypt: for v2 policies, support "fscrypt:" key prefix only

 fs/crypto/Kconfig              |   2 +
 fs/crypto/fscrypt_private.h    | 113 +++++--
 fs/crypto/keyinfo.c            | 668 ++++++++++++++++++++++++++++++++++-------
 fs/crypto/policy.c             | 138 ++++++---
 fs/super.c                     |   4 +
 include/linux/fs.h             |   5 +
 include/linux/fscrypt_common.h |   2 +-
 include/uapi/linux/fs.h        |   6 +
 8 files changed, 779 insertions(+), 159 deletions(-)
Signature · 1 line
2.14.0.rc0.400.g1c36432dff-goog
#1 lore raw

PATCH v2 1/7 fscrypt: add v2 encryption context and policy

From: Eric Biggers <[email protected]>

Currently, the fscrypt_context (i.e. the encryption xattr) does not contain a cryptographically secure identifier for the master key's payload. Therefore it's not possible to verify that the correct key was supplied, which is problematic in multi-user scenarios. To make this possible, define a new fscrypt_context version (v2) which includes a key_hash field, and allow userspace to opt-in to it when setting an encryption policy by setting fscrypt_policy.version to 2. For now just zero the new field; a later patch will start setting it for real.

Even though we aren't changing the layout of struct fscrypt_policy (i.e. the struct used by the ioctls), the new context version still has to be "opt-in" because old kernels will not recognize it, and the keyring key will now need to be available when setting an encryption policy, which is an API change. We'll also be taking the opportunity to make another API change (dropping support for the filesystem-specific key prefixes).

Previously, the version numbers were 0 in the fscrypt_policy and 1 in the fscrypt_context. Rather than incrementing them to 1 and 2, make them both 2 to be consistent with each other. It's not required that these numbers match, but it should make things less confusing.

An alternative to adding a key_hash field would have been to reuse master_key_descriptor. However, master_key_descriptor is only 8 bytes, which is too short to be a cryptographically secure hash. Thus, master_key_descriptor would have needed to be lengthened to 16+ bytes, which would have required defining a fscrypt_policy_v2 structure and adding a FS_IOC_GET_ENCRYPTION_POLICY_V2 ioctl. It also would have required userspace to start using a specific hash algorithm to create the key descriptors, which would have made the API harder to use. Perhaps it should have been done that way originally, but at this point it seems better to keep the API simpler.

---
 fs/crypto/fscrypt_private.h    | 84 ++++++++++++++++++++++++++++++++++--------
 fs/crypto/keyinfo.c            | 14 +++----
 fs/crypto/policy.c             | 73 ++++++++++++++++++++++++++----------
 include/linux/fscrypt_common.h |  2 +-
 include/uapi/linux/fs.h        |  6 +++
 5 files changed, 135 insertions(+), 44 deletions(-)
fs/crypto/fscrypt_private.h +68 -16
index a1d5021c31ef..8329fb905ac6 100644
@@ -24,40 +24,92 @@
 #define FS_AES_256_CTS_KEY_SIZE		32
 #define FS_AES_256_XTS_KEY_SIZE		64
 
-#define FS_KEY_DERIVATION_NONCE_SIZE		16
+#define FS_KEY_DERIVATION_NONCE_SIZE	16
+#define FSCRYPT_KEY_HASH_SIZE		16
 
 /**
- * Encryption context for inode
+ * fscrypt_context - the encryption context for an inode
  *
- * Protector format:
- *  1 byte: Protector format (1 = this version)
- *  1 byte: File contents encryption mode
- *  1 byte: File names encryption mode
- *  1 byte: Flags
- *  8 bytes: Master Key descriptor
- *  16 bytes: Encryption Key derivation nonce
+ * Filesystems usually store this in an extended attribute.  It identifies the
+ * encryption algorithm and key with which the file is encrypted.
+ *
+ * Since this is stored on-disk, be careful not to reorder fields or add any
+ * implicit padding bytes!
  */
 struct fscrypt_context {
-	u8 format;
+	/* v1+ */
+
+	/* Version of this structure */
+	u8 version;
+
+	/* Encryption mode for the contents of regular files */
 	u8 contents_encryption_mode;
+
+	/* Encryption mode for filenames in directories and symlink targets */
 	u8 filenames_encryption_mode;
+
+	/* Options that affect how encryption is done (e.g. padding amount) */
 	u8 flags;
+
+	/* Descriptor for this file's master key in the keyring */
 	u8 master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
+
+	/*
+	 * A unique value used in combination with the master key to derive the
+	 * file's actual encryption key
+	 */
 	u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE];
-} __packed;
 
-#define FS_ENCRYPTION_CONTEXT_FORMAT_V1		1
+	/* v2+ */
+
+	/* Cryptographically secure hash of the master key */
+	u8 key_hash[FSCRYPT_KEY_HASH_SIZE];
+};
+
+#define FSCRYPT_CONTEXT_V1	1
+#define FSCRYPT_CONTEXT_V1_SIZE	offsetof(struct fscrypt_context, key_hash)
+
+#define FSCRYPT_CONTEXT_V2	2
+#define FSCRYPT_CONTEXT_V2_SIZE	sizeof(struct fscrypt_context)
+
+static inline int fscrypt_context_size(const struct fscrypt_context *ctx)
+{
+	switch (ctx->version) {
+	case FSCRYPT_CONTEXT_V1:
+		return FSCRYPT_CONTEXT_V1_SIZE;
+	case FSCRYPT_CONTEXT_V2:
+		return FSCRYPT_CONTEXT_V2_SIZE;
+	}
+	return 0;
+}
+
+static inline bool
+fscrypt_valid_context_format(const struct fscrypt_context *ctx, int size)
+{
+	return size >= 1 && size == fscrypt_context_size(ctx);
+}
 
 /*
- * A pointer to this structure is stored in the file system's in-core
- * representation of an inode.
+ * fscrypt_info - the "encryption key" for an inode
+ *
+ * When an encrypted file's key is made available, an instance of this struct is
+ * allocated and stored in ->i_crypt_info.  Once created, it remains until the
+ * inode is evicted.
  */
 struct fscrypt_info {
+
+	/* The actual crypto transforms needed for encryption and decryption */
+	struct crypto_skcipher *ci_ctfm;
+	struct crypto_cipher *ci_essiv_tfm;
+
+	/*
+	 * Cached fields from the fscrypt_context needed for encryption policy
+	 * inheritance and enforcement
+	 */
+	u8 ci_context_version;
 	u8 ci_data_mode;
 	u8 ci_filename_mode;
 	u8 ci_flags;
-	struct crypto_skcipher *ci_ctfm;
-	struct crypto_cipher *ci_essiv_tfm;
 	u8 ci_master_key[FS_KEY_DESCRIPTOR_SIZE];
 };
 
fs/crypto/keyinfo.c +6 -8
index 018c588c7ac3..7e664a11340a 100644
@@ -272,29 +272,27 @@ int fscrypt_get_encryption_info(struct inode *inode)
 			return res;
 		/* Fake up a context for an unencrypted directory */
 		memset(&ctx, 0, sizeof(ctx));
-		ctx.format = FS_ENCRYPTION_CONTEXT_FORMAT_V1;
+		ctx.version = FSCRYPT_CONTEXT_V1;
 		ctx.contents_encryption_mode = FS_ENCRYPTION_MODE_AES_256_XTS;
 		ctx.filenames_encryption_mode = FS_ENCRYPTION_MODE_AES_256_CTS;
 		memset(ctx.master_key_descriptor, 0x42, FS_KEY_DESCRIPTOR_SIZE);
-	} else if (res != sizeof(ctx)) {
-		return -EINVAL;
+		res = FSCRYPT_CONTEXT_V1_SIZE;
 	}
 
-	if (ctx.format != FS_ENCRYPTION_CONTEXT_FORMAT_V1)
+	if (!fscrypt_valid_context_format(&ctx, res))
 		return -EINVAL;
 
 	if (ctx.flags & ~FS_POLICY_FLAGS_VALID)
 		return -EINVAL;
 
-	crypt_info = kmem_cache_alloc(fscrypt_info_cachep, GFP_NOFS);
+	crypt_info = kmem_cache_zalloc(fscrypt_info_cachep, GFP_NOFS);
 	if (!crypt_info)
 		return -ENOMEM;
 
-	crypt_info->ci_flags = ctx.flags;
+	crypt_info->ci_context_version = ctx.version;
 	crypt_info->ci_data_mode = ctx.contents_encryption_mode;
 	crypt_info->ci_filename_mode = ctx.filenames_encryption_mode;
-	crypt_info->ci_ctfm = NULL;
-	crypt_info->ci_essiv_tfm = NULL;
+	crypt_info->ci_flags = ctx.flags;
 	memcpy(crypt_info->ci_master_key, ctx.master_key_descriptor,
 				sizeof(crypt_info->ci_master_key));
 
fs/crypto/policy.c +54 -19

157 lines not on this page · raw message

include/linux/fscrypt_common.h +1 -1
index 97f738628b36..c08e8ae63a02 100644
@@ -84,7 +84,7 @@ struct fscrypt_operations {
 };
 
 /* Maximum value for the third parameter of fscrypt_operations.set_context(). */
-#define FSCRYPT_SET_CONTEXT_MAX_SIZE	28
+#define FSCRYPT_SET_CONTEXT_MAX_SIZE	44
 
 static inline bool fscrypt_dummy_context_enabled(struct inode *inode)
 {
include/uapi/linux/fs.h +6 -0
index b7495d05e8de..a5423ddd3b67 100644
@@ -257,6 +257,12 @@ struct fsxattr {
  * File system encryption support
  */
 /* Policy provided via an ioctl on the topmost directory */
+
+/* original policy version, no key verification (potentially insecure) */
+#define FS_POLICY_VERSION_ORIGINAL	0
+/* new version w/ HKDF and key verification (recommended) */
+#define FS_POLICY_VERSION_HKDF		2
+
 #define FS_KEY_DESCRIPTOR_SIZE	8
 
 #define FS_POLICY_FLAGS_PAD_4		0x00
Signature · 1 line
2.14.0.rc0.400.g1c36432dff-goog
#2 lore raw

PATCH v2 2/7 fscrypt: rename ->ci_master_key to ->ci_master_key_descriptor

In reply to Eric Biggers

From: Eric Biggers <[email protected]>

In struct fscrypt_info, ->ci_master_key is the master key descriptor, not the master key itself. In preparation for introducing a struct fscrypt_master_key and making ->ci_master_key point to it, rename the existing ->ci_master_key to ->ci_master_key_descriptor.

---
 fs/crypto/fscrypt_private.h | 2 +-
 fs/crypto/keyinfo.c         | 4 ++--
 fs/crypto/policy.c          | 5 +++--
 3 files changed, 6 insertions(+), 5 deletions(-)
fs/crypto/fscrypt_private.h +1 -1
index 8329fb905ac6..4b0205accae9 100644
@@ -110,7 +110,7 @@ struct fscrypt_info {
 	u8 ci_data_mode;
 	u8 ci_filename_mode;
 	u8 ci_flags;
-	u8 ci_master_key[FS_KEY_DESCRIPTOR_SIZE];
+	u8 ci_master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
 };
 
 typedef enum {
fs/crypto/keyinfo.c +2 -2
index 7e664a11340a..5591fd24e4b2 100644
@@ -293,8 +293,8 @@ int fscrypt_get_encryption_info(struct inode *inode)
 	crypt_info->ci_data_mode = ctx.contents_encryption_mode;
 	crypt_info->ci_filename_mode = ctx.filenames_encryption_mode;
 	crypt_info->ci_flags = ctx.flags;
-	memcpy(crypt_info->ci_master_key, ctx.master_key_descriptor,
-				sizeof(crypt_info->ci_master_key));
+	memcpy(crypt_info->ci_master_key_descriptor, ctx.master_key_descriptor,
+	       FS_KEY_DESCRIPTOR_SIZE);
 
 	res = determine_cipher_type(crypt_info, inode, &cipher_str, &keysize);
 	if (res)
fs/crypto/policy.c +3 -2
index d6beb48f08fc..fe525da9e79c 100644
@@ -226,7 +226,8 @@ int fscrypt_has_permitted_context(struct inode *parent, struct inode *child)
 	child_ci = child->i_crypt_info;
 
 	if (parent_ci && child_ci) {
-		return memcmp(parent_ci->ci_master_key, child_ci->ci_master_key,
+		return memcmp(parent_ci->ci_master_key_descriptor,
+			      child_ci->ci_master_key_descriptor,
 			      FS_KEY_DESCRIPTOR_SIZE) == 0 &&
 			(parent_ci->ci_context_version ==
 			 child_ci->ci_context_version) &&
@@ -284,7 +285,7 @@ int fscrypt_inherit_context(struct inode *parent, struct inode *child,
 	ctx.contents_encryption_mode = ci->ci_data_mode;
 	ctx.filenames_encryption_mode = ci->ci_filename_mode;
 	ctx.flags = ci->ci_flags;
-	memcpy(ctx.master_key_descriptor, ci->ci_master_key,
+	memcpy(ctx.master_key_descriptor, ci->ci_master_key_descriptor,
 	       FS_KEY_DESCRIPTOR_SIZE);
 	get_random_bytes(ctx.nonce, FS_KEY_DERIVATION_NONCE_SIZE);
 	if (ctx.version != FSCRYPT_CONTEXT_V1)
Signature · 6 lines
2.14.0.rc0.400.g1c36432dff-goog


------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot
#3 lore raw

PATCH v2 3/7 fscrypt: use HKDF-SHA512 to derive the per-inode encryption keys

In reply to Eric Biggers

From: Eric Biggers <[email protected]>

By design, the keys which userspace provides in the keyring are not used to encrypt data directly. Instead, a KDF (Key Derivation Function) is used to derive a unique encryption key for each inode, given a "master" key and a nonce. The current KDF encrypts the master key with AES-128-ECB using the nonce as the AES key. This KDF is ad-hoc and is not specified in any standard. While it does generate unique derived keys with sufficient entropy, it has several disadvantages:

- It's reversible: an attacker who compromises a derived key, e.g. using a side channel attack, can "decrypt" it to get back to the master key.

- It's not very extensible because it cannot easily be used to derive other key material that may be needed and it ties the length of the derived key closely to the length of the master key.

- It doesn't evenly distribute the entropy from the master key. For example, the first 16 bytes of each derived key depend only on the first 16 bytes of the master key.

- It uses a public value as an AES key, which is unusual. Ciphers are rarely evaluated under a threat model where the keys are public and the messages are secret.

Solve all these problems for v2 encryption policies by changing the KDF to HKDF with SHA-512 as the underlying hash function. To derive each inode's encryption key, HKDF is executed with the master key as the input key material, a fixed salt, and the per-inode nonce prefixed with a context byte as the application-specific information string. Unlike the current KDF, HKDF has been formally published and standardized [1][2], is nonreversible, can be used to derive any number and length of secret and/or non-secret keys, and evenly distributes the entropy from the master key (excepting limits inherent to not using a random salt).

Note that this introduces a dependency on the security and implementation of SHA-512, whereas before we were using only AES for both key derivation and encryption. However, by using HMAC rather than the hash function directly, HKDF is designed to remain secure even if various classes of attacks, e.g. collision attacks, are found against the underlying unkeyed hash function. Even HMAC-MD5 is still considered secure in practice, despite MD5 itself having been heavily compromised.

We *could* avoid introducing a hash function by instantiating HKDF-Expand with CMAC-AES256 as the pseudorandom function rather than HMAC-SHA512. This would work; however, the HKDF specification doesn't explicitly allow a non-HMAC pseudorandom function, so it would be less standard. It would also require skipping HKDF-Extract and changing the API to accept only 32-byte master keys (since otherwise HKDF-Extract using CMAC-AES would produce a pseudorandom key only 16 bytes long which is only enough for AES-128, not AES-256).

HKDF-SHA512 can require more "crypto work" per key derivation when compared to the current KDF. However, later in this series, we'll start caching the HMAC transform for each master key, which will actually make the real-world performance about the same or even significantly better than the AES-based KDF as currently implemented. Also, each KDF can actually be executed on the order of 1 million times per second, so KDF performance probably isn't actually the bottleneck in practice anyway.

References:
[1] Krawczyk (2010). "Cryptographic Extraction and Key Derivation: The

      HKDF Scheme".  https://eprint.iacr.org/2010/264.pdf

[2] RFC 5869. "HMAC-based Extract-and-Expand Key Derivation Function

      (HKDF)".  https://tools.ietf.org/html/rfc5869
---
 fs/crypto/Kconfig           |   2 +
 fs/crypto/fscrypt_private.h |  13 ++
 fs/crypto/keyinfo.c         | 484 +++++++++++++++++++++++++++++++++++---------
 3 files changed, 403 insertions(+), 96 deletions(-)
fs/crypto/Kconfig +2 -0
index 02b7d91c9231..bbd4e38b293c 100644
@@ -8,6 +8,8 @@ config FS_ENCRYPTION
 	select CRYPTO_CTS
 	select CRYPTO_CTR
 	select CRYPTO_SHA256
+	select CRYPTO_SHA512
+	select CRYPTO_HMAC
 	select KEYS
 	help
 	  Enable encryption of files and directories.  This
fs/crypto/fscrypt_private.h +13 -0
index 4b0205accae9..b5881cb26e8f 100644
@@ -89,6 +89,13 @@ fscrypt_valid_context_format(const struct fscrypt_context *ctx, int size)
 	return size >= 1 && size == fscrypt_context_size(ctx);
 }
 
+/*
+ * fscrypt_master_key - an in-use master key
+ */
+struct fscrypt_master_key {
+	struct crypto_shash	*mk_hmac;
+};
+
 /*
  * fscrypt_info - the "encryption key" for an inode
  *
@@ -102,6 +109,12 @@ struct fscrypt_info {
 	struct crypto_skcipher *ci_ctfm;
 	struct crypto_cipher *ci_essiv_tfm;
 
+	/*
+	 * The master key with which this inode was "unlocked"
+	 * (only set for inodes that use a v2+ encryption policy)
+	 */
+	struct fscrypt_master_key *ci_master_key;
+
 	/*
 	 * Cached fields from the fscrypt_context needed for encryption policy
 	 * inheritance and enforcement
fs/crypto/keyinfo.c +388 -96

583 lines not on this page · raw message

Signature · 1 line
2.14.0.rc0.400.g1c36432dff-goog
#4 lore raw

PATCH v2 4/7 fscrypt: validate modes and flags earlier when setting policy

In reply to Eric Biggers

From: Eric Biggers <[email protected]>

For FS_IOC_SET_ENCRYPTION_POLICY, currently the encryption modes and flags are only validated when a new encryption policy is being set, not when an existing policy is being compared to the one specified. However, we're going to start needing to compute the key_hash in both cases, and for this it's helpful to validate that the master key has the minimum length required by the specified encryption modes. Therefore, move the modes and flags validation earlier in the ioctl, next to where we validate the policy version.

---
 fs/crypto/policy.c | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
fs/crypto/policy.c +7 -7
index fe525da9e79c..d1e58798da3c 100644
@@ -60,13 +60,6 @@ static int create_encryption_context_from_policy(struct inode *inode,
 {
 	struct fscrypt_context ctx;
 
-	if (!fscrypt_valid_enc_modes(policy->contents_encryption_mode,
-				     policy->filenames_encryption_mode))
-		return -EINVAL;
-
-	if (policy->flags & ~FS_POLICY_FLAGS_VALID)
-		return -EINVAL;
-
 	ctx.version = context_version_for_policy(policy);
 	ctx.contents_encryption_mode = policy->contents_encryption_mode;
 	ctx.filenames_encryption_mode = policy->filenames_encryption_mode;
@@ -100,6 +93,13 @@ int fscrypt_ioctl_set_policy(struct file *filp, const void __user *arg)
 	    policy.version != FS_POLICY_VERSION_HKDF)
 		return -EINVAL;
 
+	if (!fscrypt_valid_enc_modes(policy.contents_encryption_mode,
+				     policy.filenames_encryption_mode))
+		return -EINVAL;
+
+	if (policy.flags & ~FS_POLICY_FLAGS_VALID)
+		return -EINVAL;
+
 	ret = mnt_want_write_file(filp);
 	if (ret)
 		return ret;
Signature · 1 line
2.14.0.rc0.400.g1c36432dff-goog
#5 lore raw

PATCH v2 5/7 fscrypt: verify that the correct master key was supplied

In reply to Eric Biggers

From: Eric Biggers <[email protected]>

Currently, while a fscrypt master key is required to have a certain description in the keyring, its payload is never verified to be correct. While sufficient for well-behaved userspace, this is insecure in a multi-user system where a user has been given only read-only access to an encrypted file or directory. Specifically, if an encrypted file or directory does not yet have its key cached by the kernel, the first user who accesses it can provide an arbitrary key in their own keyring, which the kernel will then associate with the inode and use for read(), write(), readdir(), etc. by other users as well.

Consequently, it's trivial for a user with *read-only* access to an encrypted file or directory to make it appear as garbage to everyone. Creative users might be able to accomplish more sophisticated attacks by careful choice of the key, e.g. choosing a key causes certain bytes of file contents to have certain values or that causes filenames containing the '/' character to appear.

Solve the problem for v2 encryption policies by storing a "hash" of the master encryption key in the encryption xattr and verifying it before accepting the user-provided key. We generate the "hash" using HKDF-SHA512 by passing a distinct application-specific info string. This produces a value which is cryptographically isolated and can be stored in the clear without leaking any information about the master key or any other derived keys (in a computational sense). Reusing HKDF is better than doing e.g. SHA-512(master_key) because it avoids passing the same key into different cryptographic primitives.

We make the hash field 16 bytes long, as this should provide sufficient collision and preimage resistance while not wasting too much space for the encryption xattr.

---
 fs/crypto/fscrypt_private.h |  4 ++++
 fs/crypto/keyinfo.c         | 46 +++++++++++++++++++++++++++++++++++++
 fs/crypto/policy.c          | 55 ++++++++++++++++++++++++++++++++++++---------
 3 files changed, 95 insertions(+), 10 deletions(-)
fs/crypto/fscrypt_private.h +4 -0
index b5881cb26e8f..f9469a71cc29 100644
@@ -94,6 +94,7 @@ fscrypt_valid_context_format(const struct fscrypt_context *ctx, int size)
  */
 struct fscrypt_master_key {
 	struct crypto_shash	*mk_hmac;
+	u8			mk_hash[FSCRYPT_KEY_HASH_SIZE];
 };
 
 /*
@@ -157,6 +158,9 @@ extern struct page *fscrypt_alloc_bounce_page(struct fscrypt_ctx *ctx,
 					      gfp_t gfp_flags);
 
 /* keyinfo.c */
+extern int fscrypt_compute_key_hash(const struct inode *inode,
+				    const struct fscrypt_policy *policy,
+				    u8 hash[FSCRYPT_KEY_HASH_SIZE]);
 extern void __exit fscrypt_essiv_cleanup(void);
 
 #endif /* _FSCRYPT_PRIVATE_H */
fs/crypto/keyinfo.c +46 -0

72 lines not on this page · raw message

fs/crypto/policy.c +45 -10

114 lines not on this page · raw message

Signature · 1 line
2.14.0.rc0.400.g1c36432dff-goog
#6 lore raw

PATCH v2 6/7 fscrypt: cache the HMAC transform for each master key

In reply to Eric Biggers

From: Eric Biggers <[email protected]>

Now that we have a key_hash field which securely identifies a master key payload, introduce a cache of the HMAC transforms for the master keys currently in use for inodes using v2+ encryption policies. The entries in this cache are called 'struct fscrypt_master_key' and are identified by key_hash. The cache is per-superblock. (It could be global, but making it per-superblock should reduce the lock contention a bit, and we may need to keep track of keys on a per-superblock basis for other reasons later, e.g. to implement an ioctl for evicting keys.)

This results in a large efficiency gain: we now only have to allocate and key an "hmac(sha512)" transformation, execute HKDF-Extract, and compute key_hash once per master key rather than once per inode. Note that this optimization can't easily be applied to the original AES-based KDF because that uses a different AES key for each KDF execution. In practice, this difference makes the HKDF per-inode encryption key derivation performance comparable to or even faster than the old KDF, which typically spends more time allocating an "ecb(aes)" transformation from the crypto API than doing actual crypto work.

Note that it would have been possible to make the mapping be from raw_key => fscrypt_master_key (where raw_key denotes the actual bytes of the master key) rather than from key_hash => fscrypt_master_key. However, an advantage of doing lookups by key_hash is that it replaces the keyring lookup in most cases, which opens up the future possibilities of not even having the master key in memory following an initial provisioning step (if the HMAC-SHA512 implementation is hardware-backed), or of introducing an ioctl to provision a key to the filesystem directly, avoiding keyrings and their visibility problems entirely. Also, because key_hash is public information while raw_key is secret information, it would have been very difficult to use raw_key as a map key in a way that would prevent timing attacks while still being scalable to a large number of entries.

---
 fs/crypto/fscrypt_private.h |  11 ++++
 fs/crypto/keyinfo.c         | 134 +++++++++++++++++++++++++++++++++++++++++++-
 fs/crypto/policy.c          |   5 +-
 fs/super.c                  |   4 ++
 include/linux/fs.h          |   5 ++
 5 files changed, 152 insertions(+), 7 deletions(-)
fs/crypto/fscrypt_private.h +11 -0
index f9469a71cc29..4221c5b23882 100644
@@ -91,10 +91,21 @@ fscrypt_valid_context_format(const struct fscrypt_context *ctx, int size)
 
 /*
  * fscrypt_master_key - an in-use master key
+ *
+ * This is referenced from each in-core inode that has been "unlocked" using a
+ * particular master key.  It's primarily used to cache the HMAC transform so
+ * that the per-inode encryption keys can be derived efficiently with HKDF.  It
+ * is securely erased once all inodes referencing it have been evicted.
+ *
+ * If the same master key is used on different filesystems (unusual, but
+ * possible), we'll create one of these structs for each filesystem.
  */
 struct fscrypt_master_key {
 	struct crypto_shash	*mk_hmac;
 	u8			mk_hash[FSCRYPT_KEY_HASH_SIZE];
+	refcount_t		mk_refcount;
+	struct rb_node		mk_node;
+	struct super_block	*mk_sb;
 };
 
 /*
fs/crypto/keyinfo.c +131 -3

158 lines not on this page · raw message

fs/crypto/policy.c +1 -4
index c0a047559736..ece55350cee8 100644
@@ -261,10 +261,7 @@ int fscrypt_has_permitted_context(struct inode *parent, struct inode *child)
 			(parent_ci->ci_filename_mode ==
 			 child_ci->ci_filename_mode) &&
 			(parent_ci->ci_flags == child_ci->ci_flags) &&
-			(parent_ci->ci_context_version == FSCRYPT_CONTEXT_V1 ||
-			 (memcmp(parent_ci->ci_master_key->mk_hash,
-				 child_ci->ci_master_key->mk_hash,
-				 FSCRYPT_KEY_HASH_SIZE) == 0));
+			(parent_ci->ci_master_key == child_ci->ci_master_key);
 	}
 
 	res = cops->get_context(parent, &parent_ctx, sizeof(parent_ctx));
fs/super.c +4 -0
index 6bc3352adcf3..de9be131b5ee 100644
@@ -214,6 +214,10 @@ static struct super_block *alloc_super(struct file_system_type *type, int flags,
 	spin_lock_init(&s->s_inode_list_lock);
 	INIT_LIST_HEAD(&s->s_inodes_wb);
 	spin_lock_init(&s->s_inode_wblist_lock);
+#if IS_ENABLED(CONFIG_FS_ENCRYPTION)
+	s->s_master_keys = RB_ROOT;
+	spin_lock_init(&s->s_master_keys_lock);
+#endif
 
 	if (list_lru_init_memcg(&s->s_dentry_lru))
 		goto fail;
include/linux/fs.h +5 -0
index 6e1fd5d21248..e6e494e6ef10 100644
@@ -1413,6 +1413,11 @@ struct super_block {
 
 	spinlock_t		s_inode_wblist_lock;
 	struct list_head	s_inodes_wb;	/* writeback inodes */
+
+#if IS_ENABLED(CONFIG_FS_ENCRYPTION)
+	spinlock_t		s_master_keys_lock;
+	struct rb_root		s_master_keys;	/* master crypto keys in use */
+#endif
 } __randomize_layout;
 
 /* Helper functions so that in most cases filesystems will
Signature · 6 lines
2.14.0.rc0.400.g1c36432dff-goog


------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot
#7 lore raw

PATCH v2 7/7 fscrypt: for v2 policies, support "fscrypt:" key prefix only

In reply to Eric Biggers

From: Eric Biggers <[email protected]>

Since v2 encryption policies are opt-in, take the opportunity to also drop support for the legacy filesystem-specific key description prefixes "ext4:", "f2fs:", and "ubifs:", instead requiring the generic prefix "fscrypt:". The generic prefix is preferred since it works for all filesystems. Also there is a performance benefit from not having to search the keyrings twice.

The old prefixes remain supported for v1 encryption policies.

---
 fs/crypto/fscrypt_private.h |  3 +--
 fs/crypto/keyinfo.c         | 16 ++++------------
 fs/crypto/policy.c          |  2 +-
 3 files changed, 6 insertions(+), 15 deletions(-)
fs/crypto/fscrypt_private.h +1 -2
index 4221c5b23882..c9de15d4b5b0 100644
@@ -169,8 +169,7 @@ extern struct page *fscrypt_alloc_bounce_page(struct fscrypt_ctx *ctx,
 					      gfp_t gfp_flags);
 
 /* keyinfo.c */
-extern int fscrypt_compute_key_hash(const struct inode *inode,
-				    const struct fscrypt_policy *policy,
+extern int fscrypt_compute_key_hash(const struct fscrypt_policy *policy,
 				    u8 hash[FSCRYPT_KEY_HASH_SIZE]);
 extern void __exit fscrypt_essiv_cleanup(void);
 
fs/crypto/keyinfo.c +4 -12
index 2fca72826768..81b08d4a7efe 100644
@@ -384,8 +384,7 @@ find_and_lock_keyring_key(const char *prefix,
 }
 
 static struct fscrypt_master_key *
-load_master_key_from_keyring(const struct inode *inode,
-			     const u8 descriptor[FS_KEY_DESCRIPTOR_SIZE],
+load_master_key_from_keyring(const u8 descriptor[FS_KEY_DESCRIPTOR_SIZE],
 			     unsigned int min_keysize)
 {
 	struct key *keyring_key;
@@ -394,11 +393,6 @@ load_master_key_from_keyring(const struct inode *inode,
 
 	keyring_key = find_and_lock_keyring_key(FS_KEY_DESC_PREFIX, descriptor,
 						min_keysize, &payload);
-	if (keyring_key == ERR_PTR(-ENOKEY) && inode->i_sb->s_cop->key_prefix) {
-		keyring_key = find_and_lock_keyring_key(
-					inode->i_sb->s_cop->key_prefix,
-					descriptor, min_keysize, &payload);
-	}
 	if (IS_ERR(keyring_key))
 		return ERR_CAST(keyring_key);
 
@@ -440,8 +434,7 @@ find_or_create_master_key(const struct inode *inode,
 	/*
 	 * The needed master key isn't in memory yet.  Load it from the keyring.
 	 */
-	master_key = load_master_key_from_keyring(inode,
-						  ctx->master_key_descriptor,
+	master_key = load_master_key_from_keyring(ctx->master_key_descriptor,
 						  min_keysize);
 	if (IS_ERR(master_key))
 		return master_key;
@@ -675,8 +668,7 @@ void __exit fscrypt_essiv_cleanup(void)
 	crypto_free_shash(essiv_hash_tfm);
 }
 
-int fscrypt_compute_key_hash(const struct inode *inode,
-			     const struct fscrypt_policy *policy,
+int fscrypt_compute_key_hash(const struct fscrypt_policy *policy,
 			     u8 hash[FSCRYPT_KEY_HASH_SIZE])
 {
 	struct fscrypt_master_key *k;
@@ -690,7 +682,7 @@ int fscrypt_compute_key_hash(const struct inode *inode,
 		max(available_modes[policy->contents_encryption_mode].keysize,
 		    available_modes[policy->filenames_encryption_mode].keysize);
 
-	k = load_master_key_from_keyring(inode, policy->master_key_descriptor,
+	k = load_master_key_from_keyring(policy->master_key_descriptor,
 					 min_keysize);
 	if (IS_ERR(k))
 		return PTR_ERR(k);
fs/crypto/policy.c +1 -1
index ece55350cee8..fa5599005a72 100644
@@ -119,7 +119,7 @@ int fscrypt_ioctl_set_policy(struct file *filp, const void __user *arg)
 		pr_warn_once("%s (pid %d) is setting less secure v0 encryption policy; recommend upgrading to v2.\n",
 			     current->comm, current->pid);
 	} else {
-		ret = fscrypt_compute_key_hash(inode, &policy, key_hash);
+		ret = fscrypt_compute_key_hash(&policy, key_hash);
 		if (ret)
 			return ret;
 	}
Signature · 6 lines
2.14.0.rc0.400.g1c36432dff-goog


------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot