Skip to contentSkip to conversation

crypto: Add GCM-AES implementation to lib/crypto

PATCH Superseded Ard Biesheuvel 2 participants 6 messages Oct 18, 2022

Subsystems (3)

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Ard Biesheuvel

author maintainer
#0 lore raw

v3 cover crypto: Add GCM-AES implementation to lib/crypto

Provide a generic library implementation of GCM-AES which can be used really early during boot, e.g., to communicate with the security coprocessor on SEV-SNP virtual machines to bring up secondary cores. This is needed because the crypto API is not available yet this early.

We cannot rely on special instructions for AES or polynomial multiplication, which are arch specific and rely on in-kernel SIMD infrastructure. Instead, add a generic C implementation that combines the existing C implementations of AES and multiplication in GF(2^128).

To reduce the risk of forgery attacks, replace data dependent table lookups and conditional branches in the used gf128mul routine with constant-time equivalents. The AES library has already been robustified to some extent to prevent known-plaintext timing attacks on the key, but we call it with interrupts disabled to make it a bit more robust. (Note that in SEV-SNP context, the VMM is untrusted, and is able to inject interrupts arbitrarily, and potentially maliciously.)

Changes since v2:
- move gf128mul to lib/crypto
- add patch #2 to make gf128mul_lle constant time
- fix kerneldoc headers and drop them from the .h file

Changes since v1:
- rename gcm to gcmaes to reflect that GCM is also used in combination with other symmetric ciphers (Jason)
- add Nikunj's Tested-by

Ard Biesheuvel (3):
crypto: move gf128mul library into lib/crypto
crypto: gf128mul - make gf128mul_lle time invariant
crypto: gcmaes - Provide minimal library implementation

 arch/x86/crypto/aesni-intel_glue.c |  24 +-
 crypto/Kconfig                     |   3 -
 crypto/Makefile                    |   1 -
 include/crypto/gcm.h               |  22 +
 lib/crypto/Kconfig                 |   9 +
 lib/crypto/Makefile                |   5 +
 lib/crypto/gcmaes.c                | 720 ++++++++++++++++++++
 {crypto => lib/crypto}/gf128mul.c  |  58 +-
 8 files changed, 807 insertions(+), 35 deletions(-)
 create mode 100644 lib/crypto/gcmaes.c
 rename {crypto => lib/crypto}/gf128mul.c (87%)
Signature · 1 line
2.35.1
author maintainer
#1 lore raw

PATCH v3 1/3 crypto: move gf128mul library into lib/crypto

The gf128mul library does not depend on the crypto API at all, so it can be moved into lib/crypto. This will allow us to use it in other library code in a subsequent patch without having to depend on CONFIG_CRYPTO.

---
 crypto/Kconfig                    | 3 ---
 crypto/Makefile                   | 1 -
 lib/crypto/Kconfig                | 3 +++
 lib/crypto/Makefile               | 2 ++
 {crypto => lib/crypto}/gf128mul.c | 0
 5 files changed, 5 insertions(+), 4 deletions(-)
crypto/Kconfig +0 -3
index 2589ad5357df..a466beb64a69 100644
@@ -175,9 +175,6 @@ config CRYPTO_MANAGER_EXTRA_TESTS
 	  This is intended for developer use only, as these tests take much
 	  longer to run than the normal self tests.
 
-config CRYPTO_GF128MUL
-	tristate
-
 config CRYPTO_NULL
 	tristate "Null algorithms"
 	select CRYPTO_NULL2
crypto/Makefile +0 -1
index 303b21c43df0..d0126c915834 100644
@@ -85,7 +85,6 @@ obj-$(CONFIG_CRYPTO_WP512) += wp512.o
 CFLAGS_wp512.o := $(call cc-option,-fno-schedule-insns)  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79149
 obj-$(CONFIG_CRYPTO_BLAKE2B) += blake2b_generic.o
 CFLAGS_blake2b_generic.o := -Wframe-larger-than=4096 #  https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105930
-obj-$(CONFIG_CRYPTO_GF128MUL) += gf128mul.o
 obj-$(CONFIG_CRYPTO_ECB) += ecb.o
 obj-$(CONFIG_CRYPTO_CBC) += cbc.o
 obj-$(CONFIG_CRYPTO_CFB) += cfb.o
lib/crypto/Kconfig +3 -0
index 7e9683e9f5c6..2a4b57779fd7 100644
@@ -8,6 +8,9 @@ config CRYPTO_LIB_UTILS
 config CRYPTO_LIB_AES
 	tristate
 
+config CRYPTO_GF128MUL
+	tristate
+
 config CRYPTO_LIB_ARC4
 	tristate
 
lib/crypto/Makefile +2 -0
index c852f067ab06..60bb566eed78 100644
@@ -10,6 +10,8 @@ obj-$(CONFIG_CRYPTO_LIB_CHACHA_GENERIC)		+= libchacha.o
 obj-$(CONFIG_CRYPTO_LIB_AES)			+= libaes.o
 libaes-y					:= aes.o
 
+obj-$(CONFIG_CRYPTO_GF128MUL)			+= gf128mul.o
+
 obj-$(CONFIG_CRYPTO_LIB_ARC4)			+= libarc4.o
 libarc4-y					:= arc4.o
 
lib/crypto/gf128mul.c renamed from crypto/gf128mul.c +0 -0
similarity index 100%
rename from crypto/gf128mul.c
rename to lib/crypto/gf128mul.c
Signature · 1 line
2.35.1
author maintainer
#2 lore raw

PATCH v3 2/3 crypto: gf128mul - make gf128mul_lle time invariant

In reply to Ard Biesheuvel

The gf128mul library has different variants with different memory/performance tradeoffs, where the faster ones use 4k or 64k lookup tables precomputed at runtime, which are based on one of the multiplication factors, which is commonly the key for keyed hash algorithms such as GHASH.

The slowest variant is gf128_mul_lle() [and its bbe/ble counterparts], which does not use precomputed lookup tables, but it still relies on a single u16[256] lookup table which is input independent. The use of such a table may cause the execution time of gf128_mul_lle() to correlate with the value of the inputs, which is generally something that must be avoided for cryptographic algorithms. On top of that, the function uses a sequence of if () statements that conditionally invoke be128_xor() based on which bits are set in the second argument of the function, which is usually a pointer to the multiplication factor that represents the key.

In order to remove the correlation between the execution time of gf128_mul_lle() and the value of its inputs, let's address the identified shortcomings:
- add a time invariant version of gf128mul_x8_lle() that replaces the table lookup with the expression that is used at compile time to populate the lookup table;
- make the invocations of be128_xor() unconditional, but pass a zero vector as the third argument if the associated bit in the key is cleared.

The resulting code is likely to be significantly slower. However, given that this is the slowest version already, making it even slower in order to make it more secure is assumed to be justified.

The bbe and ble counterparts could receive the same treatment, but the former is never used anywhere in the kernel, and the latter is only used in the driver for a asynchronous crypto h/w accelerator (Chelsio), where timing variances are unlikely to matter.

---
 lib/crypto/gf128mul.c | 58 +++++++++++++-------
 1 file changed, 39 insertions(+), 19 deletions(-)
lib/crypto/gf128mul.c +39 -19
index a69ae3e6c16c..cd0cb1d3bf36 100644
@@ -146,6 +146,17 @@ static void gf128mul_x8_lle(be128 *x)
 	x->a = cpu_to_be64((a >> 8) ^ (_tt << 48));
 }
 
+/* time invariant version of gf128mul_x8_lle */
+static void gf128mul_x8_lle_ti(be128 *x)
+{
+	u64 a = be64_to_cpu(x->a);
+	u64 b = be64_to_cpu(x->b);
+	u64 _tt = xda_le(b & 0xff); /* avoid table lookup */
+
+	x->b = cpu_to_be64((b >> 8) | (a << 56));
+	x->a = cpu_to_be64((a >> 8) ^ (_tt << 48));
+}
+
 static void gf128mul_x8_bbe(be128 *x)
 {
 	u64 a = be64_to_cpu(x->a);
@@ -169,38 +180,47 @@ EXPORT_SYMBOL(gf128mul_x8_ble);
 
 void gf128mul_lle(be128 *r, const be128 *b)
 {
-	be128 p[8];
+	/*
+	 * The p array should be aligned to twice the size of its element type,
+	 * so that every even/odd pair is guaranteed to share a cacheline
+	 * (assuming a cacheline size of 32 bytes or more, which is by far the
+	 * most common). This ensures that each be128_xor() call in the loop
+	 * takes the same amount of time regardless of the value of 'ch', which
+	 * is derived from function parameter 'b', which is commonly used as a
+	 * key, e.g., for GHASH. The odd array elements are all set to zero,
+	 * making each be128_xor() a NOP if its associated bit in 'ch' is not
+	 * set, and this is equivalent to calling be128_xor() conditionally.
+	 * This approach aims to avoid leaking information about such keys
+	 * through execution time invariances.
+	 *
+	 * Unfortunately, __aligned(16) or higher does not work on x86 for
+	 * variables on the stack so we need to perform the alignment by hand.
+	 */
+	be128 array[16 + 3] = {};
+	be128 *p = PTR_ALIGN(&array[0], 2 * sizeof(be128));
 	int i;
 
 	p[0] = *r;
 	for (i = 0; i < 7; ++i)
-		gf128mul_x_lle(&p[i + 1], &p[i]);
+		gf128mul_x_lle(&p[2 * i + 2], &p[2 * i]);
 
 	memset(r, 0, sizeof(*r));
 	for (i = 0;;) {
 		u8 ch = ((u8 *)b)[15 - i];
 
-		if (ch & 0x80)
-			be128_xor(r, r, &p[0]);
-		if (ch & 0x40)
-			be128_xor(r, r, &p[1]);
-		if (ch & 0x20)
-			be128_xor(r, r, &p[2]);
-		if (ch & 0x10)
-			be128_xor(r, r, &p[3]);
-		if (ch & 0x08)
-			be128_xor(r, r, &p[4]);
-		if (ch & 0x04)
-			be128_xor(r, r, &p[5]);
-		if (ch & 0x02)
-			be128_xor(r, r, &p[6]);
-		if (ch & 0x01)
-			be128_xor(r, r, &p[7]);
+		be128_xor(r, r, &p[ 0 + !(ch & 0x80)]);
+		be128_xor(r, r, &p[ 2 + !(ch & 0x40)]);
+		be128_xor(r, r, &p[ 4 + !(ch & 0x20)]);
+		be128_xor(r, r, &p[ 6 + !(ch & 0x10)]);
+		be128_xor(r, r, &p[ 8 + !(ch & 0x08)]);
+		be128_xor(r, r, &p[10 + !(ch & 0x04)]);
+		be128_xor(r, r, &p[12 + !(ch & 0x02)]);
+		be128_xor(r, r, &p[14 + !(ch & 0x01)]);
 
 		if (++i >= 16)
 			break;
 
-		gf128mul_x8_lle(r);
+		gf128mul_x8_lle_ti(r); /* use the time invariant version */
 	}
 }
 EXPORT_SYMBOL(gf128mul_lle);
Signature · 1 line
2.35.1
author maintainer
#3 lore raw

PATCH v3 3/3 crypto: gcmaes - Provide minimal library implementation

In reply to Ard Biesheuvel

Implement a minimal library version of GCM based on the existing library implementations of AES and multiplication in GF(2^128). Using these primitives, GCM can be implemented in a straight-forward manner.

GCM has a couple of sharp edges, i.e., the amount of input data processed with the same initialization vector (IV) should be capped to protect the counter from 32-bit rollover (or carry), and the size of the authentication tag should be fixed for a given key. [0]

The former concern is addressed trivially, given that the function call API uses 32-bit signed types for the input lengths. It is still up to the caller to avoid IV reuse in general, but this is not something we can police at the implementation level.

As for the latter concern, let's make the authentication tag size part of the key schedule, and only permit it to be configured as part of the key expansion routine.

Note that table based AES implementations are susceptible to known plaintext timing attacks on the encryption key. The AES library already attempts to mitigate this to some extent, but given that the counter mode encryption used by GCM operates exclusively on known plaintext by construction (the IV and therefore the initial counter value are known to an attacker), let's take some extra care to mitigate this, by calling the AES library with interrupts disabled.

[0] https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38d.pdf

---
 arch/x86/crypto/aesni-intel_glue.c |  24 +-
 include/crypto/gcm.h               |  22 +
 lib/crypto/Kconfig                 |   6 +
 lib/crypto/Makefile                |   3 +
 lib/crypto/gcmaes.c                | 720 ++++++++++++++++++++
 5 files changed, 763 insertions(+), 12 deletions(-)
arch/x86/crypto/aesni-intel_glue.c +12 -12
index a5b0cb3efeba..0733f218783e 100644
@@ -778,8 +778,8 @@ static int gcmaes_crypt_by_sg(bool enc, struct aead_request *req,
 	return 0;
 }
 
-static int gcmaes_encrypt(struct aead_request *req, unsigned int assoclen,
-			  u8 *hash_subkey, u8 *iv, void *aes_ctx)
+static int gcmaesni_encrypt(struct aead_request *req, unsigned int assoclen,
+			    u8 *hash_subkey, u8 *iv, void *aes_ctx)
 {
 	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
 	unsigned long auth_tag_len = crypto_aead_authsize(tfm);
@@ -797,8 +797,8 @@ static int gcmaes_encrypt(struct aead_request *req, unsigned int assoclen,
 	return 0;
 }
 
-static int gcmaes_decrypt(struct aead_request *req, unsigned int assoclen,
-			  u8 *hash_subkey, u8 *iv, void *aes_ctx)
+static int gcmaesni_decrypt(struct aead_request *req, unsigned int assoclen,
+			    u8 *hash_subkey, u8 *iv, void *aes_ctx)
 {
 	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
 	unsigned long auth_tag_len = crypto_aead_authsize(tfm);
@@ -847,8 +847,8 @@ static int helper_rfc4106_encrypt(struct aead_request *req)
 		*(iv+4+i) = req->iv[i];
 	*((__be32 *)(iv+12)) = counter;
 
-	return gcmaes_encrypt(req, req->assoclen - 8, ctx->hash_subkey, iv,
-			      aes_ctx);
+	return gcmaesni_encrypt(req, req->assoclen - 8, ctx->hash_subkey, iv,
+				aes_ctx);
 }
 
 static int helper_rfc4106_decrypt(struct aead_request *req)
@@ -875,8 +875,8 @@ static int helper_rfc4106_decrypt(struct aead_request *req)
 		*(iv+4+i) = req->iv[i];
 	*((__be32 *)(iv+12)) = counter;
 
-	return gcmaes_decrypt(req, req->assoclen - 8, ctx->hash_subkey, iv,
-			      aes_ctx);
+	return gcmaesni_decrypt(req, req->assoclen - 8, ctx->hash_subkey, iv,
+				aes_ctx);
 }
 #endif
 
@@ -1167,8 +1167,8 @@ static int generic_gcmaes_encrypt(struct aead_request *req)
 	memcpy(iv, req->iv, 12);
 	*((__be32 *)(iv+12)) = counter;
 
-	return gcmaes_encrypt(req, req->assoclen, ctx->hash_subkey, iv,
-			      aes_ctx);
+	return gcmaesni_encrypt(req, req->assoclen, ctx->hash_subkey, iv,
+				aes_ctx);
 }
 
 static int generic_gcmaes_decrypt(struct aead_request *req)
@@ -1183,8 +1183,8 @@ static int generic_gcmaes_decrypt(struct aead_request *req)
 	memcpy(iv, req->iv, 12);
 	*((__be32 *)(iv+12)) = counter;
 
-	return gcmaes_decrypt(req, req->assoclen, ctx->hash_subkey, iv,
-			      aes_ctx);
+	return gcmaesni_decrypt(req, req->assoclen, ctx->hash_subkey, iv,
+				aes_ctx);
 }
 
 static struct aead_alg aesni_aeads[] = { {
include/crypto/gcm.h +22 -0
index 9d7eff04f224..afe70370a865 100644
@@ -3,6 +3,9 @@
 
 #include <linux/errno.h>
 
+#include <crypto/aes.h>
+#include <crypto/gf128mul.h>
+
 #define GCM_AES_IV_SIZE 12
 #define GCM_RFC4106_IV_SIZE 8
 #define GCM_RFC4543_IV_SIZE 8
@@ -60,4 +63,23 @@ static inline int crypto_ipsec_check_assoclen(unsigned int assoclen)
 
 	return 0;
 }
+
+struct gcmaes_ctx {
+	be128			ghash_key;
+	struct crypto_aes_ctx	aes_ctx;
+	unsigned int		authsize;
+};
+
+int gcmaes_expandkey(struct gcmaes_ctx *ctx, const u8 *key,
+		     unsigned int keysize, unsigned int authsize);
+
+void gcmaes_encrypt(const struct gcmaes_ctx *ctx, u8 *dst, const u8 *src,
+		    int crypt_len, const u8 *assoc, int assoc_len,
+		    const u8 iv[GCM_AES_IV_SIZE], u8 *authtag);
+
+int __must_check gcmaes_decrypt(const struct gcmaes_ctx *ctx, u8 *dst,
+				const u8 *src, int crypt_len, const u8 *assoc,
+				int assoc_len, const u8 iv[GCM_AES_IV_SIZE],
+				const u8 *authtag);
+
 #endif
lib/crypto/Kconfig +6 -0
index 2a4b57779fd7..4290967dd322 100644
@@ -11,6 +11,12 @@ config CRYPTO_LIB_AES
 config CRYPTO_GF128MUL
 	tristate
 
+config CRYPTO_LIB_GCMAES
+	tristate
+	select CRYPTO_GF128MUL
+	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_UTILS
+
 config CRYPTO_LIB_ARC4
 	tristate
 
lib/crypto/Makefile +3 -0
index 60bb566eed78..3c9738accda7 100644
@@ -12,6 +12,9 @@ libaes-y					:= aes.o
 
 obj-$(CONFIG_CRYPTO_GF128MUL)			+= gf128mul.o
 
+obj-$(CONFIG_CRYPTO_LIB_GCMAES)			+= libgcmaes.o
+libgcmaes-y					:= gcmaes.o
+
 obj-$(CONFIG_CRYPTO_LIB_ARC4)			+= libarc4.o
 libarc4-y					:= arc4.o
 
lib/crypto/gcmaes.c new file +720 -0

720 lines not on this page · raw message

Signature · 1 line
2.35.1
#4 lore raw
In reply to Ard Biesheuvel
Quoted 2 lines · Ard Biesheuvel

Provide a generic library implementation of GCM-AES which can be used

Every place else in the world, this is called AES-GCM. Can we stick with the convention?

author maintainer
#5 lore raw
Quoted 7 lines · Jason A. Donenfeld
Quoted 2 lines · Ard Biesheuvel

Provide a generic library implementation of GCM-AES which can be used

Every place else in the world, this is called AES-GCM. Can we stick with the convention?

Good point, I'll change that next time around.