Skip to contentSkip to conversation

crypto: Add AES-GCM implementation to lib/crypto

PATCH Superseded Ard Biesheuvel 3 participants 8 messages Oct 24, 2022 – Oct 25, 2022

Subsystems (2)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Ard Biesheuvel

author maintainer
#0 lore raw

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

Provide a generic library implementation of AES-GCM 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 v3:
- rename GCM-AES to AES-GCM

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: aesgcm - Provide minimal library implementation

 crypto/Kconfig                    |   3 -
 crypto/Makefile                   |   1 -
 include/crypto/gcm.h              |  22 +
 lib/crypto/Kconfig                |   9 +
 lib/crypto/Makefile               |   5 +
 lib/crypto/aesgcm.c               | 720 ++++++++++++++++++++
 {crypto => lib/crypto}/gf128mul.c |  58 +-
 7 files changed, 795 insertions(+), 23 deletions(-)
 create mode 100644 lib/crypto/aesgcm.c
 rename {crypto => lib/crypto}/gf128mul.c (87%)
Signature · 1 line
2.35.1
author maintainer
#1 lore raw

PATCH v4 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
#3 lore raw

PATCH v4 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
#4 lore raw

PATCH v4 3/3 crypto: aesgcm - Provide minimal library implementation

In reply to Ard Biesheuvel

Implement a minimal library version of AES-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

---
 include/crypto/gcm.h |  22 +
 lib/crypto/Kconfig   |   6 +
 lib/crypto/Makefile  |   3 +
 lib/crypto/aesgcm.c  | 720 ++++++++++++++++++++
 4 files changed, 751 insertions(+)
include/crypto/gcm.h +22 -0
index 9d7eff04f224..1155d326cb89 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 aesgcm_ctx {
+	be128			ghash_key;
+	struct crypto_aes_ctx	aes_ctx;
+	unsigned int		authsize;
+};
+
+int aesgcm_expandkey(struct aesgcm_ctx *ctx, const u8 *key,
+		     unsigned int keysize, unsigned int authsize);
+
+void aesgcm_encrypt(const struct aesgcm_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 aesgcm_decrypt(const struct aesgcm_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..5355a835428f 100644
@@ -11,6 +11,12 @@ config CRYPTO_LIB_AES
 config CRYPTO_GF128MUL
 	tristate
 
+config CRYPTO_LIB_AESGCM
+	tristate
+	select CRYPTO_GF128MUL
+	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_UTILS
+
 config CRYPTO_LIB_ARC4
 	tristate
 
lib/crypto/Makefile +3 -0
index 60bb566eed78..c5f4502c5e12 100644
@@ -12,6 +12,9 @@ libaes-y					:= aes.o
 
 obj-$(CONFIG_CRYPTO_GF128MUL)			+= gf128mul.o
 
+obj-$(CONFIG_CRYPTO_LIB_AESGCM)			+= libaesgcm.o
+libaesgcm-y					:= aesgcm.o
+
 obj-$(CONFIG_CRYPTO_LIB_ARC4)			+= libarc4.o
 libarc4-y					:= arc4.o
 
lib/crypto/aesgcm.c new file +720 -0

720 lines not on this page · raw message

Signature · 1 line
2.35.1
#5 lore raw

RE: [PATCH v4 3/3] crypto: aesgcm - Provide minimal library implementation

Quoted 2 lines
lib/crypto/aesgcm.c +1 -0
+static int __init libaesgcm_init(void)

...

lib/crypto/aesgcm.c line 686

Quoted 5 lines
lib/crypto/aesgcm.c +5 -0
+		if (aesgcm_expandkey(&ctx, aesgcm_tv[i].key, aesgcm_tv[i].klen,
+				     aesgcm_tv[i].clen - plen)) {
+			WARN(1, "aesgcm_expandkey() failed on vector %d\n", i);
+			return -EINVAL;
+		}

Other self-test errors in lib/crypto (blake2s, chacha20poly1305, and curve25519) are reported with pr_err. Could you add that in addition to the WARNs?

Also, they return -ENODEV rather than -EINVAL on self-test failures, like this:

static int __init blake2s_mod_init(void)

{
        if (!IS_ENABLED(CONFIG_CRYPTO_MANAGER_DISABLE_TESTS) &&
            WARN_ON(!blake2s_selftest()))
                return -ENODEV;
        return 0;
}
maintainer
#2 lore raw

Re: [PATCH v4 1/3] crypto: move gf128mul library into lib/crypto

In reply to Ard Biesheuvel

lib/crypto/Kconfig config CRYPTO_LIB_UTILS · line 12

Quoted 2 lines · Ard Biesheuvel
lib/crypto/Kconfig +2 -0
+config CRYPTO_GF128MUL
+	tristate

This should be renamed to CRYPTO_LIB_GF128MUL, to make it consistent with all the other CRYPTO_LIB_* options. (It could be a separate patch, though.)

- Eric

maintainer
#6 lore raw

Re: [PATCH v4 3/3] crypto: aesgcm - Provide minimal library implementation

In reply to Ard Biesheuvel
Quoted 4 lines · Ard Biesheuvel

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.

This doesn't seem to have been any note left about this in the code itself. Sizes are usually size_t, so if another type is used intentionally, that should be carefully documented.

Also, does it really need to be signed?

include/crypto/gcm.h static inline int crypto_ipsec_check_assoclen(unsigned int assoclen) · line 83

Quoted 4 lines
include/crypto/gcm.h +4 -0
+int __must_check aesgcm_decrypt(const struct aesgcm_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);

This returns 0 or -EBADMSG, which is inconsistent with chacha20poly1305_decrypt() which returns a bool. It would be nice if the different algorithms would use consistent conventions.

- Eric

author maintainer
#7 lore raw

Re: [PATCH v4 3/3] crypto: aesgcm - Provide minimal library implementation

Quoted 7 lines · Eric Biggers
Quoted 4 lines · Ard Biesheuvel

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.

Quoted 6 lines

This doesn't seem to have been any note left about this in the code itself. Sizes are usually size_t, so if another type is used intentionally, that should be carefully documented.

Also, does it really need to be signed?

I'll add a comment in the code where the counter increment occurs.

Using int is easier because I can use signed comparison with 0 to decide whether we are done. We don't need the range so unless someone feels using unsigned int is essential here, I am going to leave it as is.

Quoted 9 lines

include/crypto/gcm.h static inline int crypto_ipsec_check_assoclen(unsigned int assoclen) · line 83

Quoted 4 lines
include/crypto/gcm.h +4 -0
+int __must_check aesgcm_decrypt(const struct aesgcm_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);

This returns 0 or -EBADMSG, which is inconsistent with chacha20poly1305_decrypt() which returns a bool. It would be nice if the different algorithms would use consistent conventions.

I'll change that.