Skip to contentSkip to conversation

Library APIs for AES encryption modes

PATCH Superseded Eric Biggers 5 participants 57 messages Jul 7 – Jul 15

Subsystems (25)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Eric Biggers

author maintainer
#0 lore raw

cover Library APIs for AES encryption modes

This series applies to v7.2-rc2. It can also be retrieved from:

git fetch https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git aes-modes-v1

This series adds library APIs for all the AES encryption modes that are used in the kernel, both authenticated and unauthenticated: AES-ECB, AES-CBC, AES-CBC-CTS, AES-CTR, AES-XCTR, AES-XTS, AES-GCM, and AES-CCM.

Patches 2-7 add the library APIs, and patches 8-13 wire them up to the traditional crypto API (with just priority 110 for now). These are intended to be taken through libcrypto-next for 7.3.

The remaining patches (14-33) convert users of the traditional crypto API to use the new library APIs instead. Most of these will be for 7.4 or later. For now please consider these to be proof-of-concept patches for helping inform the API design. Most of them I haven't tested, and their performance also won't be optimal yet (since the arch-optimized code for these AES modes needs to be migrated into the library first). Nevertheless I think they do make it very clear that (as usual) the library is much easier to use than the traditional crypto API, and we can expect performance improvements once everything is wired up as well.

Apologies for the large patch series, but it ended up being easiest to handle all the AES modes at once rather than try to do them one by one. This ensures a consistent design for them, which is really important. Additionally, the arch-optimized AES code tends to intermingle different modes, and many depend on each other anyway.

But as a result, to keep this series manageable it doesn't include the usual KUnit tests or the integration of the architecture-optimized code. Those will be sent separately in follow-up series.

Feedback is appreciated, especially on patches 2-7 and the library APIs they add.

Eric Biggers (33):
crypto: xts - Split out __xts_verify_key() helper lib/crypto: aes: Add ECB support
lib/crypto: aes: Add CBC and CBC-CTS support lib/crypto: aes: Add CTR and XCTR support
lib/crypto: aes: Add XTS support
lib/crypto: aes: Add GCM support
lib/crypto: aes: Add CCM support
crypto: aes - Add ECB support using library
crypto: aes - Add CBC and CBC-CTS support using library
crypto: aes - Add CTR and XCTR support using library
crypto: aes - Add XTS support using library
crypto: aes - Add GCM support using library
crypto: aes - Add CCM support using library
x86/sev: Use new AES-GCM library
lib/crypto: aesgcm: Remove old AES-GCM library
crypto: aes - Remove AES-CBC-MAC support
lib/crypto: aes: Remove aes_cbcmac_* functions
fscrypt: Use aes_ecb_encrypt() for v1 key derivation
KEYS: encrypted: Use AES-CBC library instead of crypto_skcipher
KEYS: trusted: dcp: Use AES-GCM library instead of crypto_aead
libceph: Use AES-CBC library in ceph_aes_crypt()
libceph: Reimplement messenger v2 encryption using AES-GCM library
wifi: mac80211: Use AES-CTR library in fils_aead.c
wifi: mac80211: Use AES-GCM library for GMAC suite
wifi: mac80211: Use crypto libraries for GCMP and CCMP suites
macsec: Use AES-GCM library instead of crypto_aead
wifi: ipw2x00: Use AES-CCM library
mac802154: Use AES-CCM and AES-CTR libraries
bpf: crypto: Use AES-CBC and AES-ECB libraries
bpf: crypto: Add AES-GCM support
smb: client: Use AES-GCM and AES-CCM libraries
ksmbd: Use AES-GCM and AES-CCM libraries
net: tipc: Use AES-GCM library instead of crypto_aead

 .../crypto/libcrypto-auth-encryption.rst      |   20 +
 .../crypto/libcrypto-unauth-encryption.rst    |   49 +
 Documentation/crypto/libcrypto.rst            |    2 +
 MAINTAINERS                                   |    2 -
 arch/x86/Kconfig                              |    2 +-
 arch/x86/coco/sev/core.c                      |   44 +-
 arch/x86/include/asm/sev.h                    |    2 +-
 crypto/Kconfig                                |   15 +-
 crypto/Makefile                               |    3 -
 crypto/aes.c                                  |  937 +++++++++++++-
 crypto/bpf_crypto_skcipher.c                  |   83 --
 crypto/testmgr.c                              |    6 +-
 drivers/crypto/starfive/jh7110-aes.c          |    2 +-
 drivers/net/Kconfig                           |    4 +-
 drivers/net/macsec.c                          |  327 ++---
 drivers/net/wireless/intel/ipw2x00/Kconfig    |    2 +-
 .../intel/ipw2x00/libipw_crypto_ccmp.c        |  117 +-
 drivers/virt/coco/sev-guest/sev-guest.c       |    7 +-
 fs/crypto/Kconfig                             |    2 +-
 fs/crypto/keysetup_v1.c                       |    5 +-
 fs/smb/client/Kconfig                         |    7 +-
 fs/smb/client/cifsencrypt.c                   |   14 -
 fs/smb/client/cifsfs.c                        |    4 -
 fs/smb/client/cifsglob.h                      |    8 -
 fs/smb/client/cifsproto.h                     |   89 --
 fs/smb/client/connect.c                       |   14 +-
 fs/smb/client/smb2ops.c                       |  275 ++--
 fs/smb/client/smb2pdu.c                       |    2 -
 fs/smb/client/smb2proto.h                     |    1 -
 fs/smb/client/smb2transport.c                 |   39 -
 fs/smb/server/Kconfig                         |    6 +-
 fs/smb/server/Makefile                        |    2 +-
 fs/smb/server/auth.c                          |  227 ----
 fs/smb/server/auth.h                          |    2 -
 fs/smb/server/crypto_ctx.c                    |  176 ---
 fs/smb/server/crypto_ctx.h                    |   32 -
 fs/smb/server/server.c                        |   14 +-
 fs/smb/server/smb2pdu.c                       |  133 +-
 include/crypto/aes-cbc-macs.h                 |   22 +-
 include/crypto/aes-cbc.h                      |   77 ++
 include/crypto/aes-ccm.h                      |  244 ++++
 include/crypto/aes-ctr.h                      |   56 +
 include/crypto/aes-ecb.h                      |   49 +
 include/crypto/aes-gcm.h                      |  249 ++++
 include/crypto/aes-xts.h                      |   87 ++
 include/crypto/gcm.h                          |   23 +-
 include/crypto/xts.h                          |   18 +-
 include/linux/bpf_crypto.h                    |   24 -
 include/linux/ceph/messenger.h                |   22 +-
 include/net/macsec.h                          |    5 +-
 kernel/bpf/Kconfig                            |   14 +
 kernel/bpf/Makefile                           |    4 +-
 kernel/bpf/crypto.c                           |  302 ++---
 lib/crypto/Kconfig                            |   41 +-
 lib/crypto/Makefile                           |    3 -
 lib/crypto/aes.c                              | 1146 ++++++++++++++++-
 lib/crypto/aesgcm.c                           |  721 -----------
 lib/crypto/tests/Kconfig                      |    6 +
 lib/crypto/tests/aes_cbc_macs_kunit.c         |   68 +-
 net/ceph/Kconfig                              |    5 +-
 net/ceph/crypto.c                             |   66 +-
 net/ceph/crypto.h                             |    3 +-
 net/ceph/messenger_v2.c                       |  963 +++++---------
 net/mac80211/Kconfig                          |    7 +-
 net/mac80211/Makefile                         |    1 -
 net/mac80211/aead_api.c                       |  113 --
 net/mac80211/aead_api.h                       |   23 -
 net/mac80211/aes_ccm.h                        |   39 +-
 net/mac80211/aes_gcm.h                        |   38 +-
 net/mac80211/aes_gmac.c                       |   85 +-
 net/mac80211/aes_gmac.h                       |   10 +-
 net/mac80211/fils_aead.c                      |   90 +-
 net/mac80211/key.c                            |   42 +-
 net/mac80211/key.h                            |    8 +-
 net/mac80211/wpa.c                            |   23 +-
 net/mac802154/Kconfig                         |    6 +-
 net/mac802154/llsec.c                         |  158 +--
 net/mac802154/llsec.h                         |    8 +-
 net/tipc/Kconfig                              |    4 +-
 net/tipc/crypto.c                             |  467 ++-----
 net/tipc/msg.h                                |    3 -
 net/tipc/sysctl.c                             |    6 +
 security/keys/Kconfig                         |    4 +-
 security/keys/encrypted-keys/encrypted.c      |  194 +--
 security/keys/trusted-keys/Kconfig            |    1 +
 security/keys/trusted-keys/trusted_dcp.c      |   69 +-
 86 files changed, 4167 insertions(+), 4126 deletions(-)
 create mode 100644 Documentation/crypto/libcrypto-auth-encryption.rst
 create mode 100644 Documentation/crypto/libcrypto-unauth-encryption.rst
 delete mode 100644 crypto/bpf_crypto_skcipher.c
 delete mode 100644 fs/smb/server/crypto_ctx.c
 delete mode 100644 fs/smb/server/crypto_ctx.h
 create mode 100644 include/crypto/aes-cbc.h
 create mode 100644 include/crypto/aes-ccm.h
 create mode 100644 include/crypto/aes-ctr.h
 create mode 100644 include/crypto/aes-ecb.h
 create mode 100644 include/crypto/aes-gcm.h
 create mode 100644 include/crypto/aes-xts.h
 delete mode 100644 include/linux/bpf_crypto.h
 delete mode 100644 lib/crypto/aesgcm.c
 delete mode 100644 net/mac80211/aead_api.c
 delete mode 100644 net/mac80211/aead_api.h

base-commit: 8cdeaa50eae8dad34885515f62559ee83e7e8dda

Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH 1/33 crypto: xts - Split out __xts_verify_key() helper

Make the AES-XTS key verification code callable by the crypto library by splitting out a helper function that doesn't use crypto_skcipher.

---
 include/crypto/xts.h | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)
include/crypto/xts.h +14 -4
index 15b16c4853d8..16aef89f021f 100644
@@ -7,9 +7,9 @@
 #include <linux/fips.h>
 
 #define XTS_BLOCK_SIZE 16
+#define XTS_FORBID_WEAK_KEYS (1 << 0)
 
-static inline int xts_verify_key(struct crypto_skcipher *tfm,
-				 const u8 *key, unsigned int keylen)
+static inline int __xts_verify_key(const u8 *key, size_t keylen, int flags)
 {
 	/*
 	 * key consists of keys of equal size concatenated, therefore
@@ -29,12 +29,22 @@ static inline int xts_verify_key(struct crypto_skcipher *tfm,
 	 * Ensure that the AES and tweak key are not identical when
 	 * in FIPS mode or the FORBID_WEAK_KEYS flag is set.
 	 */
-	if ((fips_enabled || (crypto_skcipher_get_flags(tfm) &
-			      CRYPTO_TFM_REQ_FORBID_WEAK_KEYS)) &&
+	if ((fips_enabled || (flags & XTS_FORBID_WEAK_KEYS)) &&
 	    !crypto_memneq(key, key + (keylen / 2), keylen / 2))
 		return -EINVAL;
 
 	return 0;
 }
 
+static inline int xts_verify_key(struct crypto_skcipher *tfm, const u8 *key,
+				 unsigned int keylen)
+{
+	int flags = (crypto_skcipher_get_flags(tfm) &
+		     CRYPTO_TFM_REQ_FORBID_WEAK_KEYS) ?
+			    XTS_FORBID_WEAK_KEYS :
+			    0;
+
+	return __xts_verify_key(key, keylen, flags);
+}
+
 #endif  /* _CRYPTO_XTS_H */
Signature · 1 line
2.54.0
Reviewed-by on v1 1/33
#2 lore raw

Re: [PATCH 01/33] crypto: xts - Split out __xts_verify_key() helper

Quoted 7 lines · Eric Biggers

Make the AES-XTS key verification code callable by the crypto library by splitting out a helper function that doesn't use crypto_skcipher.

---
  include/crypto/xts.h | 18 ++++++++++++++----
  1 file changed, 14 insertions(+), 4 deletions(-)
author maintainer
#3 lore raw

PATCH 2/33 lib/crypto: aes: Add ECB support

In reply to Eric Biggers

Add support for AES-ECB to the crypto library.

This will be used to provide a streamlined implementation of the "ecb(aes)" crypto_skcipher algorithm. fs/crypto/keysetup_v1.c will also use aes_ecb_encrypt() directly.

As usual, the architecture-optimized AES-ECB code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

ECB is obsolete of course, but we need this for parity with the traditional API and to support some odd users of ECB in the kernel.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

Create a documentation file libcrypto-unauth-encryption.rst to hold the documentation for this and other unauthenticated encryption modes.

---
 .../crypto/libcrypto-unauth-encryption.rst    | 28 ++++++++++
 Documentation/crypto/libcrypto.rst            |  1 +
 include/crypto/aes-ecb.h                      | 49 ++++++++++++++++
 lib/crypto/Kconfig                            |  9 ++-
 lib/crypto/aes.c                              | 56 +++++++++++++++++++
 lib/crypto/tests/Kconfig                      |  1 +
 6 files changed, 142 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/crypto/libcrypto-unauth-encryption.rst
 create mode 100644 include/crypto/aes-ecb.h
Documentation/crypto/libcrypto-unauth-encryption.rst new file +28 -0
new file mode 100644
index 000000000000..891c15279749
@@ -0,0 +1,28 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Unauthenticated encryption
+==========================
+
+Support for unauthenticated encryption and decryption, including bare stream
+ciphers and other length-preserving algorithms such as block ciphers in XTS
+mode.  The legitimate use cases for these algorithms are:
+
+- Support for legacy protocols that really should have chosen an authenticated
+  mode (or even another primitive entirely) but didn't.
+
+- Internal components of authenticated modes.  For example, AES-CTR is used by
+  AES-GCM and AES-CCM internally.
+
+- Storage encryption that cannot accommodate ciphertext expansion.  Usually
+  AES-XTS is used for this.
+
+- Stream ciphers for key derivation and random number generation.
+
+Besides the above, these shouldn't be used.
+
+AES-ECB
+-------
+
+Support for AES in the ECB mode of operation.
+
+.. kernel-doc:: include/crypto/aes-ecb.h
Documentation/crypto/libcrypto.rst +1 -0
index a1557d45b0e5..bbf5ca137910 100644
@@ -161,5 +161,6 @@ API documentation
    libcrypto-blockcipher
    libcrypto-hash
    libcrypto-signature
+   libcrypto-unauth-encryption
    libcrypto-utils
    sha3
include/crypto/aes-ecb.h new file +49 -0

49 lines not on this page · raw message

lib/crypto/Kconfig +7 -2
index 591c1c2a7fb3..26514c181a7f 100644
@@ -8,8 +8,7 @@ config CRYPTO_LIB_UTILS
 
 config CRYPTO_LIB_AES
 	tristate
-	# Select dependencies of modes that are part of libaes.
-	select CRYPTO_LIB_UTILS if CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_UTILS
 
 config CRYPTO_LIB_AES_ARCH
 	bool
@@ -36,6 +35,12 @@ config CRYPTO_LIB_AES_CBC_MACS
 	  this if your module uses any of the functions from
 	  <crypto/aes-cbc-macs.h>.
 
+config CRYPTO_LIB_AES_ECB
+	tristate
+	select CRYPTO_LIB_AES
+	help
+	  The AES-ECB library functions.
+
 config CRYPTO_LIB_AESGCM
 	tristate
 	select CRYPTO_LIB_AES
lib/crypto/aes.c +56 -0

68 lines not on this page · raw message

lib/crypto/tests/Kconfig +1 -0
index 9409c1a935c3..a57e87dbb1b1 100644
@@ -145,6 +145,7 @@ config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
 	tristate "Enable all crypto library code for KUnit tests"
 	depends on KUNIT
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_ECB
 	select CRYPTO_LIB_BLAKE2B
 	select CRYPTO_LIB_CHACHA20POLY1305
 	select CRYPTO_LIB_CURVE25519
Signature · 1 line
2.54.0
#4 lore raw

Re: [PATCH 02/33] lib/crypto: aes: Add ECB support

Quoted 37 lines · Eric Biggers

Add support for AES-ECB to the crypto library.

This will be used to provide a streamlined implementation of the "ecb(aes)" crypto_skcipher algorithm. fs/crypto/keysetup_v1.c will also use aes_ecb_encrypt() directly.

As usual, the architecture-optimized AES-ECB code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

ECB is obsolete of course, but we need this for parity with the traditional API and to support some odd users of ECB in the kernel.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

Create a documentation file libcrypto-unauth-encryption.rst to hold the documentation for this and other unauthenticated encryption modes.

---
  .../crypto/libcrypto-unauth-encryption.rst    | 28 ++++++++++
  Documentation/crypto/libcrypto.rst            |  1 +
  include/crypto/aes-ecb.h                      | 49 ++++++++++++++++
  lib/crypto/Kconfig                            |  9 ++-
  lib/crypto/aes.c                              | 56 +++++++++++++++++++
  lib/crypto/tests/Kconfig                      |  1 +
  6 files changed, 142 insertions(+), 2 deletions(-)

create mode 100644 Documentation/crypto/libcrypto-unauth-encryption.rst create mode 100644 include/crypto/aes-ecb.h

Documentation/crypto/libcrypto-unauth-encryption.rst new file +0 -0
new file mode 100644
index 000000000000..891c15279749

Documentation/crypto/libcrypto-unauth-encryption.rst line 8

Quoted 8 lines
Documentation/crypto/libcrypto-unauth-encryption.rst new file +8 -0
@@ -0,0 +1,28 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Unauthenticated encryption
+==========================
+
+Support for unauthenticated encryption and decryption, including bare stream
+ciphers and other length-preserving algorithms such as block ciphers in XTS
+mode.

This sentence no verb?

Quoted 55 lines
Documentation/crypto/libcrypto-unauth-encryption.rst new file +20 -0
+
+- Support for legacy protocols that really should have chosen an authenticated
+  mode (or even another primitive entirely) but didn't.
+
+- Internal components of authenticated modes.  For example, AES-CTR is used by
+  AES-GCM and AES-CCM internally.
+
+- Storage encryption that cannot accommodate ciphertext expansion.  Usually
+  AES-XTS is used for this.
+
+- Stream ciphers for key derivation and random number generation.
+
+Besides the above, these shouldn't be used.
+
+AES-ECB
+-------
+
+Support for AES in the ECB mode of operation.
+
+.. kernel-doc:: include/crypto/aes-ecb.h
Documentation/crypto/libcrypto.rst +1 -0
index a1557d45b0e5..bbf5ca137910 100644
@@ -161,5 +161,6 @@ API documentation
     libcrypto-blockcipher
     libcrypto-hash
     libcrypto-signature
+   libcrypto-unauth-encryption
     libcrypto-utils
     sha3
include/crypto/aes-ecb.h new file +18 -0
new file mode 100644
index 000000000000..bfc56bdb082c
@@ -0,0 +1,49 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * AES-ECB unauthenticated encryption and decryption
+ *
+ * Copyright 2026 Google LLC
+ */
+#ifndef _CRYPTO_AES_ECB_H
+#define _CRYPTO_AES_ECB_H
+
+#include <crypto/aes.h>
+
+/**
+ * aes_ecb_encrypt() - Encrypt data using AES-ECB
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.
+ * @src: The source data
+ * @len: Number of bytes to encrypt.  Must be a multiple of AES_BLOCK_SIZE.
+ * @key: The key

include/crypto/aes-ecb.h line 28

Quoted 10 lines
include/crypto/aes-ecb.h new file +10 -0
+ *
+ * ECB mode is insecure by itself.  This function exists only for compatibility
+ * with legacy protocols and for internal use by other modes.
+ *
+ * This supports incremental encryption, but the length of each chunk must be a
+ * multiple of AES_BLOCK_SIZE.
+ *
+ * Context: Any context.
+ */
+void aes_ecb_encrypt(u8 *dst, const u8 *src, size_t len, aes_encrypt_arg key);

Other similar functions like aes_encrypt() use the key as first argument ... so maybe do the same here, too, for consistency?

Quoted 8 lines
include/crypto/aes-ecb.h new file +8 -0
+/**
+ * aes_ecb_decrypt() - Decrypt data using AES-ECB
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.
+ * @src: The source data
+ * @len: Number of bytes to decrypt.  Must be a multiple of AES_BLOCK_SIZE.
+ * @key: The key
+ *

include/crypto/aes-ecb.h line 47

Quoted 10 lines
include/crypto/aes-ecb.h new file +10 -0
+ * ECB mode is insecure by itself.  This function exists only for compatibility
+ * with legacy protocols and for internal use by other modes.
+ *
+ * This supports incremental decryption, but the length of each chunk must be a
+ * multiple of AES_BLOCK_SIZE.
+ *
+ * Context: Any context.
+ */
+void aes_ecb_decrypt(u8 *dst, const u8 *src, size_t len,
+		     const struct aes_key *key);

dito

Apart from that, patch looks fine to me.

Thomas

author maintainer
#5 lore raw

Re: [PATCH 02/33] lib/crypto: aes: Add ECB support

Quoted 8 lines · Thomas Huth

Documentation/crypto/libcrypto-unauth-encryption.rst

Quoted 6 lines
Documentation/crypto/libcrypto-unauth-encryption.rst new file +6 -0
+Unauthenticated encryption
+==========================
+
+Support for unauthenticated encryption and decryption, including bare stream
+ciphers and other length-preserving algorithms such as block ciphers in XTS
+mode.

This sentence no verb?

It's a noun phrase that introduces what the section contains, before transitioning into full sentences.

I used this in all existing Documentation/crypto/libcrypto-*.rst. It's also fairly common in the help text for kconfig symbols (across the kernel, not just the kconfig help text I've written).

I guess it's a bad practice. But if we go with something else here, like "These functions provide support for ...", I should update the existing libcrypto-*.rst too.

Quoted 4 lines
Quoted 1 line

+void aes_ecb_encrypt(u8 *dst, const u8 *src, size_t len, aes_encrypt_arg key);

Other similar functions like aes_encrypt() use the key as first argument ... so maybe do the same here, too, for consistency?

For single-block AES, there's indeed already aes_encrypt(key, dst, src) and aes_decrypt(key, dst, src). But for actual AEAD encryption there's already:

chacha20poly1305_encrypt(dst, src, src_len, ad, ad_len, nonce, key) chacha20poly1305_decrypt(dst, src, src_len, ad, ad_len, nonce, key) xchacha20poly1305_encrypt(dst, src, src_len, ad, ad_len, nonce, key) xchacha20poly1305_decrypt(dst, src, src_len, ad, ad_len, nonce, key) chacha20poly1305_encrypt_sg_inplace(src, src_len, ad, ad_len, nonce, key) chacha20poly1305_decrypt_sg_inplace(src, src_len, ad, ad_len, nonce, key)

Those follow the convention described by Jason here:
https://lore.kernel.org/linux-crypto/[email protected]/

This series prioritizes consistency with those (and other functions taking [dst, src, len]] such as memcpy() and crypto_xor()), adding:

    aes_ecb_encrypt(dst, src, len, key);
    aes_ecb_decrypt(dst, src, len, key);
    aes_cbc_encrypt(dst, src, len, iv, key);
    aes_cbc_decrypt(dst, src, len, iv, key);
    aes_cbc_cts_encrypt(dst, src, len, iv, key);
    aes_cbc_cts_decrypt(dst, src, len, iv, key);
    aes_ctr(dst, src, len, ctr, key);
    aes_xctr(dst, src, len, ctr, iv, key);
    aes_xts_encrypt(dst, src, len, tweak, key, cont);
    aes_xts_decrypt(dst, src, len, tweak, key, cont);
    aes_gcm_encrypt(dst, authtag, src, data_len, ad, ad_len, nonce, key)
    aes_gcm_decrypt(dst, src, authtag, data_len, ad, ad_len, nonce, key)
    aes_ccm_encrypt(dst, authtag, src, data_len, ad, ad_len, nonce, nonce_len, key)
    aes_ccm_decrypt(dst, src, authtag, data_len, ad, ad_len, nonce, nonce_len, key)

(Side note: looking at it again, the last four maybe should all use [dst, src, data_len, authtag]. In this series, the authtag is instead grouped with the src or dst to which it's usually concatenated.)

If key is put at the beginning instead, it then raises the question of why should it be different from nonce/iv/ctr and (ad, ad_len). So would it really be:

aes_gcm_encrypt(key, dst, authtag, src, data_len, ad, ad_len, nonce)

... or would it actually be something like:

aes_gcm_encrypt(key, nonce, ad, ad_len, dst, authtag, src, data_len)

It's conventional to put "the object being operated on" at the beginning, which could be argued to apply to the key. But alternatively the key could just be considered another input. crypto_skcipher was "object-like"; however, with the library the key is a simple struct, or even just a byte array in the case of ChaCha20Poly1305.

There's no single right answer here. But we should consider the full picture including the chacha20poly1305 functions. The (dst, src, len, auxiliary stuff) order also helps for things like the AES_CRYPT_SG macro in crypto/aes.c, as the "auxiliary stuff" is together and at the end.

Note that if we decide we like this order, we could reorder the arguments of aes_encrypt() and aes_decrypt() to match.

Maybe let's see what other people prefer?

- Eric

Reviewed-by
#6 lore raw

Re: [PATCH 02/33] lib/crypto: aes: Add ECB support

Quoted 10 lines · Eric Biggers
Quoted 8 lines · Thomas Huth

Documentation/crypto/libcrypto-unauth-encryption.rst

Quoted 6 lines
Documentation/crypto/libcrypto-unauth-encryption.rst new file +6 -0
+Unauthenticated encryption
+==========================
+
+Support for unauthenticated encryption and decryption, including bare stream
+ciphers and other length-preserving algorithms such as block ciphers in XTS
+mode.

This sentence no verb?

Quoted 6 lines

It's a noun phrase that introduces what the section contains, before transitioning into full sentences.

I used this in all existing Documentation/crypto/libcrypto-*.rst. It's also fairly common in the help text for kconfig symbols (across the kernel, not just the kconfig help text I've written).

Fair point for the help texts (which should be concise), but (as a non-native speaker) I did not expect it in doc file. Anyway, if it's already like this in other files, then it's certainly fine here, too.

Quoted 16 lines
Quoted 4 lines
Quoted 1 line

+void aes_ecb_encrypt(u8 *dst, const u8 *src, size_t len, aes_encrypt_arg key);

Other similar functions like aes_encrypt() use the key as first argument ... so maybe do the same here, too, for consistency?

For single-block AES, there's indeed already aes_encrypt(key, dst, src) and aes_decrypt(key, dst, src). But for actual AEAD encryption there's already:

chacha20poly1305_encrypt(dst, src, src_len, ad, ad_len, nonce, key) chacha20poly1305_decrypt(dst, src, src_len, ad, ad_len, nonce, key) xchacha20poly1305_encrypt(dst, src, src_len, ad, ad_len, nonce, key) xchacha20poly1305_decrypt(dst, src, src_len, ad, ad_len, nonce, key) chacha20poly1305_encrypt_sg_inplace(src, src_len, ad, ad_len, nonce, key) chacha20poly1305_decrypt_sg_inplace(src, src_len, ad, ad_len, nonce, key)

Quoted 2 lines

Those follow the convention described by Jason here:
https://lore.kernel.org/linux-crypto/[email protected]/

Ok, makes sense now, thanks for the explanation! Feel free to add my:

to this patch if you like.

Quoted 2 lines

Note that if we decide we like this order, we could reorder the arguments of aes_encrypt() and aes_decrypt() to match.

Yes, maybe a good idea for more consistency in the code...

Thomas

author maintainer
#7 lore raw

PATCH 3/33 lib/crypto: aes: Add CBC and CBC-CTS support

In reply to Eric Biggers

Add support for AES-CBC and AES-CBC-CTS to the crypto library.

These will be used to provide streamlined implementations of the "cbc(aes)" and "cts(cbc(aes))" crypto_skcipher algorithms. Most users of these crypto_skcipher algorithms will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

- block/blk-crypto-fallback.c (for AES-128-CBC-ESSIV)
- fs/crypto/crypto.c (for AES-128-CBC-ESSIV)
- fs/crypto/fname.c (for AES-256-CTS and AES-128-CBC)
- kernel/bpf/crypto.c
- net/ceph/crypto.c
- security/keys/encrypted-keys/encrypted.c

As usual, the architecture-optimized AES-CBC and AES-CBC-CTS code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
 .../crypto/libcrypto-unauth-encryption.rst    |   7 +
 include/crypto/aes-cbc.h                      |  77 ++++++++
 lib/crypto/Kconfig                            |   6 +
 lib/crypto/aes.c                              | 174 ++++++++++++++++++
 lib/crypto/tests/Kconfig                      |   1 +
 5 files changed, 265 insertions(+)
 create mode 100644 include/crypto/aes-cbc.h
Documentation/crypto/libcrypto-unauth-encryption.rst +7 -0
index 891c15279749..fb8106034089 100644
@@ -20,6 +20,13 @@ mode.  The legitimate use cases for these algorithms are:
 
 Besides the above, these shouldn't be used.
 
+AES-CBC
+-------
+
+Support for AES in the CBC and CBC-CTS modes of operation.
+
+.. kernel-doc:: include/crypto/aes-cbc.h
+
 AES-ECB
 -------
 
include/crypto/aes-cbc.h new file +77 -0

77 lines not on this page · raw message

lib/crypto/Kconfig +6 -0
index 26514c181a7f..c64cc3e12b57 100644
@@ -27,6 +27,12 @@ config CRYPTO_LIB_AESCFB
 	select CRYPTO_LIB_AES
 	select CRYPTO_LIB_UTILS
 
+config CRYPTO_LIB_AES_CBC
+	tristate
+	select CRYPTO_LIB_AES
+	help
+	  The AES-CBC and AES-CBC-CTS library functions.
+
 config CRYPTO_LIB_AES_CBC_MACS
 	tristate
 	select CRYPTO_LIB_AES
lib/crypto/aes.c +174 -0

186 lines not on this page · raw message

lib/crypto/tests/Kconfig +1 -0
index a57e87dbb1b1..e78086f3c954 100644
@@ -144,6 +144,7 @@ config CRYPTO_LIB_SM3_KUNIT_TEST
 config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
 	tristate "Enable all crypto library code for KUnit tests"
 	depends on KUNIT
+	select CRYPTO_LIB_AES_CBC
 	select CRYPTO_LIB_AES_CBC_MACS
 	select CRYPTO_LIB_AES_ECB
 	select CRYPTO_LIB_BLAKE2B
Signature · 1 line
2.54.0
Reviewed-by on v1 3/33
#8 lore raw

Re: [PATCH 03/33] lib/crypto: aes: Add CBC and CBC-CTS support

Quoted 30 lines · Eric Biggers

Add support for AES-CBC and AES-CBC-CTS to the crypto library.

These will be used to provide streamlined implementations of the "cbc(aes)" and "cts(cbc(aes))" crypto_skcipher algorithms. Most users of these crypto_skcipher algorithms will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

- block/blk-crypto-fallback.c (for AES-128-CBC-ESSIV)
- fs/crypto/crypto.c (for AES-128-CBC-ESSIV)
- fs/crypto/fname.c (for AES-256-CTS and AES-128-CBC)
- kernel/bpf/crypto.c
- net/ceph/crypto.c
- security/keys/encrypted-keys/encrypted.c

As usual, the architecture-optimized AES-CBC and AES-CBC-CTS code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
  .../crypto/libcrypto-unauth-encryption.rst    |   7 +
  include/crypto/aes-cbc.h                      |  77 ++++++++
  lib/crypto/Kconfig                            |   6 +
  lib/crypto/aes.c                              | 174 ++++++++++++++++++
  lib/crypto/tests/Kconfig                      |   1 +
  5 files changed, 265 insertions(+)

create mode 100644 include/crypto/aes-cbc.h

...

Quoted 18 lines
lib/crypto/aes.c +18 -0
+void aes_cbc_cts_decrypt(u8 *dst, const u8 *src, size_t len,
+			 u8 iv[AES_BLOCK_SIZE], const struct aes_key *key)
+{
+	/* Offset to P[n] and C[n] (last plaintext and ciphertext block) */
+	size_t pn_offset = round_down(len - 1, AES_BLOCK_SIZE);
+	/* Length of P[n] and C[n], 1 <= pn_len <= AES_BLOCK_SIZE */
+	size_t pn_len = len - pn_offset;
+	u8 *pad;
+
+	if (WARN_ON_ONCE(len < AES_BLOCK_SIZE))
+		return;
+
+	if (len == AES_BLOCK_SIZE) {
+		aes_cbc_decrypt(dst, src, len, iv, key);
+		return;
+	}
+	if (likely(aes_cbc_cts_decrypt_arch(dst, src, len, iv, key)))
+		return;

lib/crypto/aes.c void aes_ecb_decrypt(u8 *dst, const u8 *src, size_t len, · line 963

Quoted 10 lines
lib/crypto/aes.c +10 -0
+
+	/* Compute P[0]..P[n - 2]. */
+	aes_cbc_decrypt(dst, src, pn_offset - AES_BLOCK_SIZE, iv, key);
+
+	/* Compute P[n] and P[n - 1], considering that src may equal dst. */
+	pad = &dst[pn_offset - AES_BLOCK_SIZE];
+	aes_decrypt(key, pad, &src[pn_offset - AES_BLOCK_SIZE]);
+	crypto_xor_cpy(&dst[pn_offset], &src[pn_offset], pad,
+		       pn_len); /* P[n] */
+	crypto_xor(pad, &dst[pn_offset], pn_len);

Took me a while to understand why you'd use the above xor instead of a memcpy(pad, &src[pn_offset], pn_len) here, but that's because src and dst might point to the same buffer, right?

Anyway, patch looks good to me, so:

Quoted 6 lines
lib/crypto/aes.c +6 -0
+	aes_decrypt(key, pad, pad);
+	crypto_xor(pad, iv, AES_BLOCK_SIZE); /* P[n - 1] */
+}
+EXPORT_SYMBOL_GPL(aes_cbc_cts_decrypt);
+#endif /* CONFIG_CRYPTO_LIB_AES_CBC */
+
author maintainer
#9 lore raw

Re: [PATCH 03/33] lib/crypto: aes: Add CBC and CBC-CTS support

Quoted 65 lines · Thomas Huth
Quoted 30 lines · Eric Biggers

Add support for AES-CBC and AES-CBC-CTS to the crypto library.

These will be used to provide streamlined implementations of the "cbc(aes)" and "cts(cbc(aes))" crypto_skcipher algorithms. Most users of these crypto_skcipher algorithms will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

- block/blk-crypto-fallback.c (for AES-128-CBC-ESSIV)
- fs/crypto/crypto.c (for AES-128-CBC-ESSIV)
- fs/crypto/fname.c (for AES-256-CTS and AES-128-CBC)
- kernel/bpf/crypto.c
- net/ceph/crypto.c
- security/keys/encrypted-keys/encrypted.c

As usual, the architecture-optimized AES-CBC and AES-CBC-CTS code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
  .../crypto/libcrypto-unauth-encryption.rst    |   7 +
  include/crypto/aes-cbc.h                      |  77 ++++++++
  lib/crypto/Kconfig                            |   6 +
  lib/crypto/aes.c                              | 174 ++++++++++++++++++
  lib/crypto/tests/Kconfig                      |   1 +
  5 files changed, 265 insertions(+)

create mode 100644 include/crypto/aes-cbc.h

...

Quoted 18 lines
lib/crypto/aes.c +18 -0
+void aes_cbc_cts_decrypt(u8 *dst, const u8 *src, size_t len,
+			 u8 iv[AES_BLOCK_SIZE], const struct aes_key *key)
+{
+	/* Offset to P[n] and C[n] (last plaintext and ciphertext block) */
+	size_t pn_offset = round_down(len - 1, AES_BLOCK_SIZE);
+	/* Length of P[n] and C[n], 1 <= pn_len <= AES_BLOCK_SIZE */
+	size_t pn_len = len - pn_offset;
+	u8 *pad;
+
+	if (WARN_ON_ONCE(len < AES_BLOCK_SIZE))
+		return;
+
+	if (len == AES_BLOCK_SIZE) {
+		aes_cbc_decrypt(dst, src, len, iv, key);
+		return;
+	}
+	if (likely(aes_cbc_cts_decrypt_arch(dst, src, len, iv, key)))
+		return;

lib/crypto/aes.c void aes_ecb_decrypt(u8 *dst, const u8 *src, size_t len, · line 963

Quoted 10 lines
lib/crypto/aes.c +10 -0
+
+	/* Compute P[0]..P[n - 2]. */
+	aes_cbc_decrypt(dst, src, pn_offset - AES_BLOCK_SIZE, iv, key);
+
+	/* Compute P[n] and P[n - 1], considering that src may equal dst. */
+	pad = &dst[pn_offset - AES_BLOCK_SIZE];
+	aes_decrypt(key, pad, &src[pn_offset - AES_BLOCK_SIZE]);
+	crypto_xor_cpy(&dst[pn_offset], &src[pn_offset], pad,
+		       pn_len); /* P[n] */
+	crypto_xor(pad, &dst[pn_offset], pn_len);

Took me a while to understand why you'd use the above xor instead of a memcpy(pad, &src[pn_offset], pn_len) here, but that's because src and dst might point to the same buffer, right?

Quoted 3 lines

Anyway, patch looks good to me, so:

Yes, the write to &dst[pn_offset] can overwrite &src[pn_offset].

- Eric

#10 lore raw

Re: [PATCH 03/33] lib/crypto: aes: Add CBC and CBC-CTS support

In reply to Eric Biggers
Quoted 14 lines · On Mon, 6 Jul 2026 22:34:33 -0700 Eric Biggers <[email protected]> wrote:

Add support for AES-CBC and AES-CBC-CTS to the crypto library.

These will be used to provide streamlined implementations of the "cbc(aes)" and "cts(cbc(aes))" crypto_skcipher algorithms. Most users of these crypto_skcipher algorithms will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

- block/blk-crypto-fallback.c (for AES-128-CBC-ESSIV)
- fs/crypto/crypto.c (for AES-128-CBC-ESSIV)
- fs/crypto/fname.c (for AES-256-CTS and AES-128-CBC)
- kernel/bpf/crypto.c
- net/ceph/crypto.c
- security/keys/encrypted-keys/encrypted.c

...

lib/crypto/aes.c void aes_ecb_decrypt(u8 *dst, const u8 *src, size_t len, · line 821

Quoted 2 lines
lib/crypto/aes.c +2 -0
+void aes_cbc_encrypt(u8 *dst, const u8 *src, size_t len, u8 iv[AES_BLOCK_SIZE],
+		     aes_encrypt_arg key)

Does embedding the 'u8 iv[]' in a structure work? It gives better type-checking for the length of the array.

David

author maintainer
#11 lore raw

Re: [PATCH 03/33] lib/crypto: aes: Add CBC and CBC-CTS support

Quoted 17 lines · David Laight
Quoted 7 lines · On Mon, 6 Jul 2026 22:34:33 -0700 Eric Biggers <[email protected]> wrote:

Add support for AES-CBC and AES-CBC-CTS to the crypto library.

These will be used to provide streamlined implementations of the "cbc(aes)" and "cts(cbc(aes))" crypto_skcipher algorithms. Most users of these crypto_skcipher algorithms will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

Quoted 7 lines

- block/blk-crypto-fallback.c (for AES-128-CBC-ESSIV)
- fs/crypto/crypto.c (for AES-128-CBC-ESSIV)
- fs/crypto/fname.c (for AES-256-CTS and AES-128-CBC)
- kernel/bpf/crypto.c
- net/ceph/crypto.c
- security/keys/encrypted-keys/encrypted.c

Quoted 7 lines

...

lib/crypto/aes.c void aes_ecb_decrypt(u8 *dst, const u8 *src, size_t len, · line 821

Quoted 2 lines
lib/crypto/aes.c +2 -0
+void aes_cbc_encrypt(u8 *dst, const u8 *src, size_t len, u8 iv[AES_BLOCK_SIZE],
+		     aes_encrypt_arg key)

Does embedding the 'u8 iv[]' in a structure work? It gives better type-checking for the length of the array.

It doesn't work very well, since callers tend to just have a u8 array.

- Eric

author maintainer
#12 lore raw

PATCH 4/33 lib/crypto: aes: Add CTR and XCTR support

In reply to Eric Biggers

Add support for AES-CTR and AES-XCTR to the crypto library.

These will be used to provide streamlined implementations of the "ctr(aes)" and "xctr(aes)" crypto_skcipher algorithms. Most users of "ctr(aes)" will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

- net/mac80211/fils_aead.c
- net/mac802154/llsec.c

As usual, the architecture-optimized AES-CTR and AES-XCTR code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

This is also a prerequisite for supporting AES-GCM, AES-CCM, and AES-HCTR2 in the crypto library.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
 .../crypto/libcrypto-unauth-encryption.rst    |  7 ++
 include/crypto/aes-ctr.h                      | 56 +++++++++++
 lib/crypto/Kconfig                            |  6 ++
 lib/crypto/aes.c                              | 93 +++++++++++++++++++
 lib/crypto/tests/Kconfig                      |  1 +
 5 files changed, 163 insertions(+)
 create mode 100644 include/crypto/aes-ctr.h
Documentation/crypto/libcrypto-unauth-encryption.rst +7 -0
index fb8106034089..6aca01d715da 100644
@@ -27,6 +27,13 @@ Support for AES in the CBC and CBC-CTS modes of operation.
 
 .. kernel-doc:: include/crypto/aes-cbc.h
 
+AES-CTR and AES-XCTR
+--------------------
+
+Support for AES in the CTR and XCTR modes of operation.
+
+.. kernel-doc:: include/crypto/aes-ctr.h
+
 AES-ECB
 -------
 
include/crypto/aes-ctr.h new file +56 -0

56 lines not on this page · raw message

lib/crypto/Kconfig +6 -0
index c64cc3e12b57..96febc3df6d6 100644
@@ -47,6 +47,12 @@ config CRYPTO_LIB_AES_ECB
 	help
 	  The AES-ECB library functions.
 
+config CRYPTO_LIB_AES_CTR
+	tristate
+	select CRYPTO_LIB_AES
+	help
+	  The AES-CTR and AES-XCTR library functions.
+
 config CRYPTO_LIB_AESGCM
 	tristate
 	select CRYPTO_LIB_AES
lib/crypto/aes.c +93 -0

105 lines not on this page · raw message

lib/crypto/tests/Kconfig +1 -0
index e78086f3c954..9284d0134d77 100644
@@ -146,6 +146,7 @@ config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
 	depends on KUNIT
 	select CRYPTO_LIB_AES_CBC
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CTR
 	select CRYPTO_LIB_AES_ECB
 	select CRYPTO_LIB_BLAKE2B
 	select CRYPTO_LIB_CHACHA20POLY1305
Signature · 1 line
2.54.0
#13 lore raw

Re: [PATCH 04/33] lib/crypto: aes: Add CTR and XCTR support

Quoted 35 lines · Eric Biggers

Add support for AES-CTR and AES-XCTR to the crypto library.

These will be used to provide streamlined implementations of the "ctr(aes)" and "xctr(aes)" crypto_skcipher algorithms. Most users of "ctr(aes)" will also be able to switch to the library, which as usual will be simpler and faster, e.g.:

- net/mac80211/fils_aead.c
- net/mac802154/llsec.c

As usual, the architecture-optimized AES-CTR and AES-XCTR code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code.

This is also a prerequisite for supporting AES-GCM, AES-CCM, and AES-HCTR2 in the crypto library.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
  .../crypto/libcrypto-unauth-encryption.rst    |  7 ++
  include/crypto/aes-ctr.h                      | 56 +++++++++++
  lib/crypto/Kconfig                            |  6 ++
  lib/crypto/aes.c                              | 93 +++++++++++++++++++
  lib/crypto/tests/Kconfig                      |  1 +
  5 files changed, 163 insertions(+)

create mode 100644 include/crypto/aes-ctr.h

Documentation/crypto/libcrypto-unauth-encryption.rst +0 -0
index fb8106034089..6aca01d715da 100644

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation. · line 33

Quoted 7 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
@@ -27,6 +27,13 @@ Support for AES in the CBC and CBC-CTS modes of operation.
 
  .. kernel-doc:: include/crypto/aes-cbc.h
 
+AES-CTR and AES-XCTR
+--------------------
+
+Support for AES in the CTR and XCTR modes of operation.

I guess you already have this on your radar, but just in case: It would be nice to turn this into a full sentence, too.

Quoted 26 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +2 -0
+.. kernel-doc:: include/crypto/aes-ctr.h
+
  AES-ECB
  -------
 
include/crypto/aes-ctr.h new file +15 -0
new file mode 100644
index 000000000000..fa2b7d303e55
@@ -0,0 +1,56 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * AES-CTR and AES-XCTR stream ciphers
+ *
+ * Copyright 2026 Google LLC
+ */
+#ifndef _CRYPTO_AES_CTR_H
+#define _CRYPTO_AES_CTR_H
+
+#include <crypto/aes.h>
+
+/**
+ * aes_ctr() - AES-CTR en/decryption
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.

include/crypto/aes-ctr.h line 25

Quoted 10 lines
include/crypto/aes-ctr.h new file +10 -0
+ * @src: The source data
+ * @len: Number of bytes to en/decrypt
+ * @ctr: The counter.  It will be incremented by ceil(@len / AES_BLOCK_SIZE).
+ * @key: The key
+ *
+ * This implements AES in counter mode with a 128-bit big endian counter.
+ *
+ * This supports incremental en/decryption.  The length of each non-final chunk
+ * must be a multiple of AES_BLOCK_SIZE, and the updated @ctr must be passed in
+ * each time.

Maybe add some wording that ctr ideally should not be 0 for the first call, i.e. a "nonce" value?

Quoted 80 lines
include/crypto/aes-ctr.h new file +30 -0
+ * Context: Any context.
+ */
+void aes_ctr(u8 *dst, const u8 *src, size_t len,
+	     u8 ctr[at_least AES_BLOCK_SIZE], aes_encrypt_arg key);
+
+/**
+ * aes_xctr() - AES-XCTR en/decryption
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.
+ * @src: The source data
+ * @len: Number of bytes to en/decrypt
+ * @ctr: The block counter.  For the first call, set it to 1.  It will be
+ *	 incremented by ceil(@len / AES_BLOCK_SIZE).
+ * @iv: The initialization vector
+ * @key: The key
+ *
+ * This implements AES in XOR Counter mode, as specified in the paper
+ * "Length-preserving encryption with HCTR2"
+ * (https://eprint.iacr.org/2021/1441.pdf).
+ *
+ * This supports incremental en/decryption.  The length of each non-final chunk
+ * must be a multiple of AES_BLOCK_SIZE, and the updated @ctr must be passed in
+ * each time.
+ *
+ * Context: Any context.
+ */
+void aes_xctr(u8 *dst, const u8 *src, size_t len, u64 *ctr,
+	      const u8 iv[at_least AES_BLOCK_SIZE], aes_encrypt_arg key);
+
+#endif /* _CRYPTO_AES_CTR_H */
lib/crypto/Kconfig +6 -0
index c64cc3e12b57..96febc3df6d6 100644
@@ -47,6 +47,12 @@ config CRYPTO_LIB_AES_ECB
  	help
  	  The AES-ECB library functions.
 
+config CRYPTO_LIB_AES_CTR
+	tristate
+	select CRYPTO_LIB_AES
+	help
+	  The AES-CTR and AES-XCTR library functions.
+
  config CRYPTO_LIB_AESGCM
  	tristate
  	select CRYPTO_LIB_AES
lib/crypto/aes.c +18 -0
index 3635fbe946f3..9da274a72221 100644
@@ -6,6 +6,7 @@
 
  #include <crypto/aes-cbc-macs.h>
  #include <crypto/aes-cbc.h>
+#include <crypto/aes-ctr.h>
  #include <crypto/aes-ecb.h>
  #include <crypto/aes.h>
  #include <crypto/utils.h>
@@ -967,6 +968,98 @@ void aes_cbc_cts_decrypt(u8 *dst, const u8 *src, size_t len,
  EXPORT_SYMBOL_GPL(aes_cbc_cts_decrypt);
  #endif /* CONFIG_CRYPTO_LIB_AES_CBC */
 
+#if IS_ENABLED(CONFIG_CRYPTO_LIB_AES_CTR)
+/*
+ * Hooks for optimized AES-CTR and AES-XCTR implementations, overridable by the
+ * architecture.  They are called with any len >= 0.  Returning false causes the
+ * fallback implementation to be used instead.
+ */
+#ifndef aes_ctr_arch
+static bool aes_ctr_arch(u8 *dst, const u8 *src, size_t len,
+			 u8 ctr[AES_BLOCK_SIZE], const struct aes_enckey *key)
+{
+	return false;
+}
+#endif
+#ifndef aes_xctr_arch
+static bool aes_xctr_arch(u8 *dst, const u8 *src, size_t len, u64 *ctr,
+			  const u8 iv[AES_BLOCK_SIZE],
+			  const struct aes_enckey *key)

lib/crypto/aes.c void aes_cbc_cts_decrypt(u8 *dst, const u8 *src, size_t len, · line 997

Quoted 10 lines
lib/crypto/aes.c +10 -0
+{
+	return false;
+}
+#endif
+
+static __always_inline void inc_be128_ctr(u8 ctr[AES_BLOCK_SIZE])
+{
+	/* Casts to u8 are needed because of the implicit integer promotion. */
+	if (((u8)++ctr[AES_BLOCK_SIZE - 1]) != 0)
+		return;

Why do you handle the first value separately here? The code could be simplified to start with "int i = AES_BLOCK_SIZE -1" in the for-loop instead?

Quoted 37 lines
lib/crypto/aes.c +37 -0
+	for (int i = AES_BLOCK_SIZE - 2; i >= 0; i--) {
+		if ((u8)++ctr[i] != 0)
+			break;
+	}
+}
+
+void aes_ctr(u8 *dst, const u8 *src, size_t len, u8 ctr[AES_BLOCK_SIZE],
+	     aes_encrypt_arg key)
+{
+	u8 keystream[AES_BLOCK_SIZE] __aligned(__alignof__(long));
+
+	if (likely(aes_ctr_arch(dst, src, len, ctr, key.enc_key)))
+		return;
+
+	/* Handle the full blocks. */
+	for (; len >= AES_BLOCK_SIZE; len -= AES_BLOCK_SIZE) {
+		aes_encrypt(key, keystream, ctr);
+		crypto_xor_cpy(dst, src, keystream, AES_BLOCK_SIZE);
+		inc_be128_ctr(ctr);
+		dst += AES_BLOCK_SIZE;
+		src += AES_BLOCK_SIZE;
+	}
+	/* Handle any partial block at the end. */
+	if (len) {
+		aes_encrypt(key, keystream, ctr);
+		crypto_xor_cpy(dst, src, keystream, len);
+		/* Counter is incremented even with just a partial block. */
+		inc_be128_ctr(ctr);
+	}
+	memzero_explicit(keystream, sizeof(keystream));
+}
+EXPORT_SYMBOL_GPL(aes_ctr);
+
+void aes_xctr(u8 *dst, const u8 *src, size_t len, u64 *ctr,
+	      const u8 iv[AES_BLOCK_SIZE], aes_encrypt_arg key)
+{
+	const __le64 iv0 = get_unaligned((const __le64 *)&iv[0]);

lib/crypto/aes.c void aes_cbc_cts_decrypt(u8 *dst, const u8 *src, size_t len, · line 1044

Quoted 10 lines
lib/crypto/aes.c +10 -0
+	__le64 aes_input[2];
+	u8 keystream[AES_BLOCK_SIZE] __aligned(__alignof__(long));
+
+	if (likely(aes_xctr_arch(dst, src, len, ctr, iv, key.enc_key)))
+		return;
+
+	aes_input[1] = get_unaligned((const __le64 *)&iv[8]);
+	/* Handle the full blocks. */
+	for (; len >= AES_BLOCK_SIZE; len -= AES_BLOCK_SIZE) {
+		aes_input[0] = iv0 ^ cpu_to_le64((*ctr)++);

Do we want to have a BUG_ON or WARN_ON_ONCE somewhere to check that ctr does not wrap around (i.e. to make sure that ctr was really 1 for the first call)? Something like:

	WARN_ON_ONCE((s64)(cpu_to_le64(*ctr) + len / AES_BLOCK_SIZE) < 0)

at the beginning of the function?

Quoted 26 lines
lib/crypto/aes.c +18 -0
+		aes_encrypt(key, keystream, (const u8 *)aes_input);
+		crypto_xor_cpy(dst, src, keystream, AES_BLOCK_SIZE);
+		dst += AES_BLOCK_SIZE;
+		src += AES_BLOCK_SIZE;
+	}
+	/* Handle any partial block at the end. */
+	if (len) {
+		/* Counter is incremented even with just a partial block. */
+		aes_input[0] = iv0 ^ cpu_to_le64((*ctr)++);
+		aes_encrypt(key, keystream, (const u8 *)aes_input);
+		crypto_xor_cpy(dst, src, keystream, len);
+	}
+	memzero_explicit(keystream, sizeof(keystream));
+	memzero_explicit(aes_input, sizeof(aes_input));
+}
+EXPORT_SYMBOL_GPL(aes_xctr);
+#endif /* CONFIG_CRYPTO_LIB_AES_CTR */
+
  static int __init aes_mod_init(void)
  {
  #ifdef aes_mod_init_arch
lib/crypto/tests/Kconfig +0 -0
index e78086f3c954..9284d0134d77 100644

lib/crypto/tests/Kconfig config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT · line 152

Quoted 7 lines
lib/crypto/tests/Kconfig +1 -0
@@ -146,6 +146,7 @@ config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
  	depends on KUNIT
  	select CRYPTO_LIB_AES_CBC
  	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CTR
  	select CRYPTO_LIB_AES_ECB
  	select CRYPTO_LIB_BLAKE2B
  	select CRYPTO_LIB_CHACHA20POLY1305

Thomas

author maintainer
#14 lore raw

Re: [PATCH 04/33] lib/crypto: aes: Add CTR and XCTR support

Quoted 5 lines · Thomas Huth
Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +0 -0
index fb8106034089..6aca01d715da 100644
@@ -27,6 +27,13 @@ Support for AES in the CBC and CBC-CTS modes of operation.
Quoted 8 lines

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation. · line 33

Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
  .. kernel-doc:: include/crypto/aes-cbc.h
+AES-CTR and AES-XCTR
+--------------------
+
+Support for AES in the CTR and XCTR modes of operation.

I guess you already have this on your radar, but just in case: It would be nice to turn this into a full sentence, too.

Yes, I'm making all of them full sentences.

Quoted 15 lines
Quoted 4 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
+/**
+ * aes_ctr() - AES-CTR en/decryption
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation.

Quoted 10 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +10 -0
+ * @src: The source data
+ * @len: Number of bytes to en/decrypt
+ * @ctr: The counter.  It will be incremented by ceil(@len / AES_BLOCK_SIZE).
+ * @key: The key
+ *
+ * This implements AES in counter mode with a 128-bit big endian counter.
+ *
+ * This supports incremental en/decryption.  The length of each non-final chunk
+ * must be a multiple of AES_BLOCK_SIZE, and the updated @ctr must be passed in
+ * each time.
Quoted 2 lines

Maybe add some wording that ctr ideally should not be 0 for the first call, i.e. a "nonce" value?

It depends on the usage. If a distinct key is used for each message for example, always starting at 0 is perfectly fine.

I'm not sure how far we should go to document the proper use of each algorithm. Really the AES-CTR support is just for internal use by AES-GCM and AES-CCM, and a few odd users that implement specific other protocols that need AES-CTR. It's not intended to be a place to go to receive an introduction to CTR mode.

Quoted 9 lines

Documentation/crypto/libcrypto-unauth-encryption.rst

Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +5 -0
+static __always_inline void inc_be128_ctr(u8 ctr[AES_BLOCK_SIZE])
+{
+	/* Casts to u8 are needed because of the implicit integer promotion. */
+	if (((u8)++ctr[AES_BLOCK_SIZE - 1]) != 0)
+		return;

Why do you handle the first value separately here? The code could be simplified to start with "int i = AES_BLOCK_SIZE -1" in the for-loop instead?

Just a trick to optimize performance by unrolling the first iteration, since 255 times out of 256 the first iteration is enough.

Quoted 19 lines
Quoted 4 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
+void aes_xctr(u8 *dst, const u8 *src, size_t len, u64 *ctr,
+	      const u8 iv[AES_BLOCK_SIZE], aes_encrypt_arg key)
+{
+	const __le64 iv0 = get_unaligned((const __le64 *)&iv[0]);

Documentation/crypto/libcrypto-unauth-encryption.rst

Quoted 10 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +10 -0
+	__le64 aes_input[2];
+	u8 keystream[AES_BLOCK_SIZE] __aligned(__alignof__(long));
+
+	if (likely(aes_xctr_arch(dst, src, len, ctr, iv, key.enc_key)))
+		return;
+
+	aes_input[1] = get_unaligned((const __le64 *)&iv[8]);
+	/* Handle the full blocks. */
+	for (; len >= AES_BLOCK_SIZE; len -= AES_BLOCK_SIZE) {
+		aes_input[0] = iv0 ^ cpu_to_le64((*ctr)++);

Do we want to have a BUG_ON or WARN_ON_ONCE somewhere to check that ctr does not wrap around (i.e. to make sure that ctr was really 1 for the first call)? Something like:

Quoted 3 lines
	WARN_ON_ONCE((s64)(cpu_to_le64(*ctr) + len / AES_BLOCK_SIZE) < 0)

at the beginning of the function?

Maybe. Since the counter is a u64, and this function isn't going to be called from very many places, I don't think it would be a particularly valuable WARN_ON_ONCE. It shouldn't be BUG_ON.

- Eric

#15 lore raw

Re: [PATCH 04/33] lib/crypto: aes: Add CTR and XCTR support

Quoted 54 lines · Eric Biggers
Quoted 5 lines · Thomas Huth
Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +0 -0
index fb8106034089..6aca01d715da 100644
@@ -27,6 +27,13 @@ Support for AES in the CBC and CBC-CTS modes of operation.
Quoted 8 lines

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation. · line 33

Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
   .. kernel-doc:: include/crypto/aes-cbc.h
+AES-CTR and AES-XCTR
+--------------------
+
+Support for AES in the CTR and XCTR modes of operation.

I guess you already have this on your radar, but just in case: It would be nice to turn this into a full sentence, too.

Yes, I'm making all of them full sentences.

Quoted 15 lines
Quoted 4 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
+/**
+ * aes_ctr() - AES-CTR en/decryption
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation.

Quoted 10 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +10 -0
+ * @src: The source data
+ * @len: Number of bytes to en/decrypt
+ * @ctr: The counter.  It will be incremented by ceil(@len / AES_BLOCK_SIZE).
+ * @key: The key
+ *
+ * This implements AES in counter mode with a 128-bit big endian counter.
+ *
+ * This supports incremental en/decryption.  The length of each non-final chunk
+ * must be a multiple of AES_BLOCK_SIZE, and the updated @ctr must be passed in
+ * each time.
Quoted 2 lines

Maybe add some wording that ctr ideally should not be 0 for the first call, i.e. a "nonce" value?

It depends on the usage. If a distinct key is used for each message for example, always starting at 0 is perfectly fine.

I'm not sure how far we should go to document the proper use of each algorithm. Really the AES-CTR support is just for internal use by AES-GCM and AES-CCM, and a few odd users that implement specific other protocols that need AES-CTR. It's not intended to be a place to go to receive an introduction to CTR mode.

Quoted 9 lines

Documentation/crypto/libcrypto-unauth-encryption.rst

Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +5 -0
+static __always_inline void inc_be128_ctr(u8 ctr[AES_BLOCK_SIZE])
+{
+	/* Casts to u8 are needed because of the implicit integer promotion. */
+	if (((u8)++ctr[AES_BLOCK_SIZE - 1]) != 0)
+		return;

Why do you handle the first value separately here? The code could be simplified to start with "int i = AES_BLOCK_SIZE -1" in the for-loop instead?

Quoted 2 lines

Just a trick to optimize performance by unrolling the first iteration, since 255 times out of 256 the first iteration is enough.

Ok, but then maybe add a comment here. Otherwise people will wonder why it has been done like this when reading the code later.

FWIW, I doubt that this really makes a big difference here. Looking at a function that contains your code, the disassembly currently looks like this (with -O2):

0000000000000000 <inc_be128_ctr>:

   0:   80 47 0f 01             addb   $0x1,0xf(%rdi)
   4:   48 8d 57 0e             lea    0xe(%rdi),%rdx
   8:   74 0a                   je     14 <inc_be128_ctr+0x14>
   a:   c3                      ret
   b:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
  10:   48 83 ea 01             sub    $0x1,%rdx
  14:   80 02 01                addb   $0x1,(%rdx)
  17:   75 05                   jne    1e <inc_be128_ctr+0x1e>
  19:   48 39 d7                cmp    %rdx,%rdi
  1c:   75 f2                   jne    10 <inc_be128_ctr+0x10>
  1e:   c3                      ret

So that's 3 assembly instructions 'til you reach the "ret".

When you drop the optimization, it looks like this:

0000000000000000 <inc_be128_ctr>:

   0:   48 8d 57 0f             lea    0xf(%rdi),%rdx
   4:   eb 0e                   jmp    14 <inc_be128_ctr+0x14>
   6:   66 2e 0f 1f 84 00 00    cs nopw 0x0(%rax,%rax,1)
   d:   00 00 00
  10:   48 83 ea 01             sub    $0x1,%rdx
  14:   80 02 01                addb   $0x1,(%rdx)
  17:   75 05                   jne    1e <inc_be128_ctr+0x1e>
  19:   48 39 d7                cmp    %rdx,%rdi
  1c:   75 f2                   jne    10 <inc_be128_ctr+0x10>
  1e:   c3                      ret

That's 4 assembly instructions 'til you reach the "ret". Not such a big difference...?

And with -O3, both variants end up with the same code.

Thomas

#16 lore raw

Re: [PATCH 04/33] lib/crypto: aes: Add CTR and XCTR support

Quoted 60 lines · On Tue, 14 Jul 2026 06:53:32 +0200 Thomas Huth <[email protected]> wrote:
Quoted 54 lines · Eric Biggers
Quoted 5 lines · Thomas Huth
Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +0 -0
index fb8106034089..6aca01d715da 100644
@@ -27,6 +27,13 @@ Support for AES in the CBC and CBC-CTS modes of operation.
Quoted 8 lines

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation. · line 33

Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
   .. kernel-doc:: include/crypto/aes-cbc.h
+AES-CTR and AES-XCTR
+--------------------
+
+Support for AES in the CTR and XCTR modes of operation.  

I guess you already have this on your radar, but just in case: It would be nice to turn this into a full sentence, too.

Yes, I'm making all of them full sentences.

Quoted 15 lines
Quoted 4 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +4 -0
+/**
+ * aes_ctr() - AES-CTR en/decryption
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.

Documentation/crypto/libcrypto-unauth-encryption.rst Support for AES in the CBC and CBC-CTS modes of operation.

Quoted 10 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +10 -0
+ * @src: The source data
+ * @len: Number of bytes to en/decrypt
+ * @ctr: The counter.  It will be incremented by ceil(@len / AES_BLOCK_SIZE).
+ * @key: The key
+ *
+ * This implements AES in counter mode with a 128-bit big endian counter.
+ *
+ * This supports incremental en/decryption.  The length of each non-final chunk
+ * must be a multiple of AES_BLOCK_SIZE, and the updated @ctr must be passed in
+ * each time.  
Quoted 2 lines

Maybe add some wording that ctr ideally should not be 0 for the first call, i.e. a "nonce" value?

It depends on the usage. If a distinct key is used for each message for example, always starting at 0 is perfectly fine.

I'm not sure how far we should go to document the proper use of each algorithm. Really the AES-CTR support is just for internal use by AES-GCM and AES-CCM, and a few odd users that implement specific other protocols that need AES-CTR. It's not intended to be a place to go to receive an introduction to CTR mode.

Quoted 9 lines

Documentation/crypto/libcrypto-unauth-encryption.rst

Quoted 5 lines
Documentation/crypto/libcrypto-unauth-encryption.rst +5 -0
+static __always_inline void inc_be128_ctr(u8 ctr[AES_BLOCK_SIZE])
+{
+	/* Casts to u8 are needed because of the implicit integer promotion. */
+	if (((u8)++ctr[AES_BLOCK_SIZE - 1]) != 0)
+		return;  

Why do you handle the first value separately here? The code could be simplified to start with "int i = AES_BLOCK_SIZE -1" in the for-loop instead?

Quoted 2 lines

Just a trick to optimize performance by unrolling the first iteration, since 255 times out of 256 the first iteration is enough.

Ok, but then maybe add a comment here. Otherwise people will wonder why it has been done like this when reading the code later.

Quoted 7 lines

FWIW, I doubt that this really makes a big difference here. Looking at a function that contains your code, the disassembly currently looks like this (with -O2):

0000000000000000 <inc_be128_ctr>:

    0:   80 47 0f 01             addb   $0x1,0xf(%rdi)
    4:   48 8d 57 0e             lea    0xe(%rdi),%rdx

Those two run in the same clock.

Quoted 1 line
    8:   74 0a                   je     14 <inc_be128_ctr+0x14>

Depends on the 'addb', hopefully/likely predicted non-taken.

Quoted 1 line

a: c3 ret

Predicted taken using the RSB.
Execution continues speculatively after the call even before the memory read for 0xf(%rdi) has completed.

Quoted 12 lines
    b:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
   10:   48 83 ea 01             sub    $0x1,%rdx
   14:   80 02 01                addb   $0x1,(%rdx)
   17:   75 05                   jne    1e <inc_be128_ctr+0x1e>
   19:   48 39 d7                cmp    %rdx,%rdi
   1c:   75 f2                   jne    10 <inc_be128_ctr+0x10>
   1e:   c3                      ret

So that's 3 assembly instructions 'til you reach the "ret".

When you drop the optimization, it looks like this:

Quoted 7 lines

0000000000000000 <inc_be128_ctr>:

    0:   48 8d 57 0f             lea    0xf(%rdi),%rdx
    4:   eb 0e                   jmp    14 <inc_be128_ctr+0x14>
    6:   66 2e 0f 1f 84 00 00    cs nopw 0x0(%rax,%rax,1)
    d:   00 00 00
   10:   48 83 ea 01             sub    $0x1,%rdx
   14:   80 02 01                addb   $0x1,(%rdx)

That depends on the 'sub'

Quoted 1 line
   17:   75 05                   jne    1e <inc_be128_ctr+0x1e>

That is likely predicted not taken - so you get a misprediction penalty

Quoted 6 lines
   19:   48 39 d7                cmp    %rdx,%rdi
   1c:   75 f2                   jne    10 <inc_be128_ctr+0x10>
   1e:   c3                      ret

That's 4 assembly instructions 'til you reach the "ret". Not such a big difference...?

There is an extra 'jmp' - that will cost in the fetch-decode part. The alignment pad (not there in the kernel) might also force another i-cache line be accessed.
The first conditional branch is mispredicted - say 20 clocks.

In any case the instruction count doesn't really matter. What matters is the length of the register dependency chain and how the branches get predicted.
I've gone back and annotated the asm.

Quoted 2 lines

And with -O3, both variants end up with the same code.

No one sane would compile the kernel (or much else) with -O3. It bloats things too much.
gcc isn't that good at optimising loops for modern cpu.

-- David

Quoted 4 lines

Thomas

author maintainer
#17 lore raw

PATCH 5/33 lib/crypto: aes: Add XTS support

In reply to Eric Biggers

Add support for AES-XTS to the crypto library.

This will be used to provide a streamlined implementation of the "xts(aes)" crypto_skcipher algorithm. I'm also planning to use this directly in fscrypt and blk-crypto-fallback.

As usual, the architecture-optimized AES-XTS code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code. Compared to direct implementation of "xts(aes)", I've also eliminated the requirement for architectures to implement ciphertext stealing, as the library just handles it portably instead. That will simplify things considerably.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
 .../crypto/libcrypto-unauth-encryption.rst    |   7 +
 include/crypto/aes-xts.h                      |  87 +++++++
 lib/crypto/Kconfig                            |   6 +
 lib/crypto/aes.c                              | 224 ++++++++++++++++++
 lib/crypto/tests/Kconfig                      |   1 +
 5 files changed, 325 insertions(+)
 create mode 100644 include/crypto/aes-xts.h
Documentation/crypto/libcrypto-unauth-encryption.rst +7 -0
index 6aca01d715da..15deba7e53e8 100644
@@ -40,3 +40,10 @@ AES-ECB
 Support for AES in the ECB mode of operation.
 
 .. kernel-doc:: include/crypto/aes-ecb.h
+
+AES-XTS
+-------
+
+Support for AES in the XTS mode of operation.
+
+.. kernel-doc:: include/crypto/aes-xts.h
include/crypto/aes-xts.h new file +87 -0

87 lines not on this page · raw message

lib/crypto/Kconfig +6 -0
index 96febc3df6d6..9af44cf743a7 100644
@@ -53,6 +53,12 @@ config CRYPTO_LIB_AES_CTR
 	help
 	  The AES-CTR and AES-XCTR library functions.
 
+config CRYPTO_LIB_AES_XTS
+	tristate
+	select CRYPTO_LIB_AES
+	help
+	  The AES-XTS library functions.
+
 config CRYPTO_LIB_AESGCM
 	tristate
 	select CRYPTO_LIB_AES
lib/crypto/aes.c +224 -0

237 lines not on this page · raw message

lib/crypto/tests/Kconfig +1 -0
index 9284d0134d77..b559e7c79e76 100644
@@ -148,6 +148,7 @@ config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
 	select CRYPTO_LIB_AES_CBC_MACS
 	select CRYPTO_LIB_AES_CTR
 	select CRYPTO_LIB_AES_ECB
+	select CRYPTO_LIB_AES_XTS
 	select CRYPTO_LIB_BLAKE2B
 	select CRYPTO_LIB_CHACHA20POLY1305
 	select CRYPTO_LIB_CURVE25519
Signature · 1 line
2.54.0
#18 lore raw

Re: [PATCH 05/33] lib/crypto: aes: Add XTS support

Quoted 347 lines · Eric Biggers

Add support for AES-XTS to the crypto library.

This will be used to provide a streamlined implementation of the "xts(aes)" crypto_skcipher algorithm. I'm also planning to use this directly in fscrypt and blk-crypto-fallback.

As usual, the architecture-optimized AES-XTS code will be migrated into the library as well (using the hooks provided in this commit), eliminating lots of repetitive boilerplate code. Compared to direct implementation of "xts(aes)", I've also eliminated the requirement for architectures to implement ciphertext stealing, as the library just handles it portably instead. That will simplify things considerably.

Initial test coverage is provided by the crypto_skcipher support added in a later commit. I'm planning a KUnit test suite as well.

---
  .../crypto/libcrypto-unauth-encryption.rst    |   7 +
  include/crypto/aes-xts.h                      |  87 +++++++
  lib/crypto/Kconfig                            |   6 +
  lib/crypto/aes.c                              | 224 ++++++++++++++++++
  lib/crypto/tests/Kconfig                      |   1 +
  5 files changed, 325 insertions(+)

create mode 100644 include/crypto/aes-xts.h

Documentation/crypto/libcrypto-unauth-encryption.rst +7 -0
index 6aca01d715da..15deba7e53e8 100644
@@ -40,3 +40,10 @@ AES-ECB
  Support for AES in the ECB mode of operation.
 
  .. kernel-doc:: include/crypto/aes-ecb.h
+
+AES-XTS
+-------
+
+Support for AES in the XTS mode of operation.
+
+.. kernel-doc:: include/crypto/aes-xts.h
include/crypto/aes-xts.h new file +87 -0
new file mode 100644
index 000000000000..226ac38d54ac
@@ -0,0 +1,87 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * AES-XTS unauthenticated encryption and decryption
+ *
+ * Copyright 2026 Google LLC
+ */
+#ifndef _CRYPTO_AES_XTS_H
+#define _CRYPTO_AES_XTS_H
+
+#include <crypto/aes.h>
+#include <crypto/xts.h>
+
+/**
+ * struct aes_xts_key - A key prepared for AES-XTS encryption and decryption
+ *
+ * Note that (depending on the architecture) this typically is around 768 bytes,
+ * which makes it a bit too large to allocate on the stack in most cases.
+ */
+struct aes_xts_key {
+	/* private: */
+	struct aes_key main_key;
+	struct aes_enckey tweak_key;
+};
+
+/**
+ * aes_xts_preparekey() - Prepare an AES-XTS key
+ * @key: (output) The key structure to initialize
+ * @in_key: The raw AES-XTS key
+ * @key_len: Length of the raw key in bytes
+ * @flags: Optional flag XTS_FORBID_WEAK_KEYS to forbid keys whose two halves
+ *	   are the same.
+ *
+ * Context: Any context.
+ * Return:
+ * * 0 on success
+ * * -EINVAL if the key is rejected because its length isn't 32, 64, or (when
+ *   FIPS mode isn't enabled) 48; or because its two halves are the same and
+ *   either XTS_FORBID_WEAK_KEYS is given or FIPS mode is enabled.
+ */
+int __must_check aes_xts_preparekey(struct aes_xts_key *key, const u8 *in_key,
+				    size_t key_len, int flags);
+
+/**
+ * aes_xts_encrypt() - Encrypt data using AES-XTS
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.
+ * @src: The source data
+ * @len: Number of bytes to encrypt.  Must be >= AES_BLOCK_SIZE.  On non-last
+ *	 calls it also must be a multiple of AES_BLOCK_SIZE.
+ * @tweak: The tweak.  It is updated with the next value, unless @len isn't a
+ *	   multiple of AES_BLOCK_SIZE in which case the value is unspecified.
+ * @key: The key
+ * @cont: %true to continue same message (skip tweak encryption)
+ *
+ * This supports both one-shot and incremental encryption.  For incremental
+ * encryption, all non-last calls require @len aligned to AES_BLOCK_SIZE, and
+ * all non-first calls require @cont = %true.
+ *
+ * Context: Any context.
+ */
+void aes_xts_encrypt(u8 *dst, const u8 *src, size_t len,
+		     u8 tweak[at_least AES_BLOCK_SIZE],
+		     const struct aes_xts_key *key, bool cont);
+
+/**
+ * aes_xts_decrypt() - Decrypt data using AES-XTS
+ * @dst: The destination buffer.  Can be in-place or out-of-place.  For other
+ *	 overlaps the behavior is unspecified.
+ * @src: The source data
+ * @len: Number of bytes to decrypt.  Must be >= AES_BLOCK_SIZE.  On non-last
+ *	 calls it also must be a multiple of AES_BLOCK_SIZE.
+ * @tweak: The tweak.  It is updated with the next value, unless @len isn't a
+ *	   multiple of AES_BLOCK_SIZE in which case the value is unspecified.
+ * @key: The key
+ * @cont: %true to continue same message (skip tweak encryption)
+ *
+ * This supports both one-shot and incremental decryption.  For incremental
+ * decryption, all non-last calls require @len aligned to AES_BLOCK_SIZE, and
+ * all non-first calls require @cont = %true.
+ *
+ * Context: Any context.
+ */
+void aes_xts_decrypt(u8 *dst, const u8 *src, size_t len,
+		     u8 tweak[at_least AES_BLOCK_SIZE],
+		     const struct aes_xts_key *key, bool cont);
+
+#endif /* _CRYPTO_AES_XTS_H */
lib/crypto/Kconfig +6 -0
index 96febc3df6d6..9af44cf743a7 100644
@@ -53,6 +53,12 @@ config CRYPTO_LIB_AES_CTR
  	help
  	  The AES-CTR and AES-XCTR library functions.
 
+config CRYPTO_LIB_AES_XTS
+	tristate
+	select CRYPTO_LIB_AES
+	help
+	  The AES-XTS library functions.
+
  config CRYPTO_LIB_AESGCM
  	tristate
  	select CRYPTO_LIB_AES
lib/crypto/aes.c +180 -0
index 9da274a72221..630702a4228c 100644
@@ -8,7 +8,9 @@
  #include <crypto/aes-cbc.h>
  #include <crypto/aes-ctr.h>
  #include <crypto/aes-ecb.h>
+#include <crypto/aes-xts.h>
  #include <crypto/aes.h>
+#include <crypto/gf128mul.h>
  #include <crypto/utils.h>
  #include <linux/cache.h>
  #include <linux/crypto.h>
@@ -1060,6 +1062,228 @@ void aes_xctr(u8 *dst, const u8 *src, size_t len, u64 *ctr,
  EXPORT_SYMBOL_GPL(aes_xctr);
  #endif /* CONFIG_CRYPTO_LIB_AES_CTR */
 
+#if IS_ENABLED(CONFIG_CRYPTO_LIB_AES_XTS)
+int aes_xts_preparekey(struct aes_xts_key *key, const u8 *in_key,
+		       size_t key_len, int flags)
+{
+	int err;
+
+	err = __xts_verify_key(in_key, key_len, flags);
+	if (err)
+		return err;
+	/* First half of XTS key is the main key */
+	err = aes_preparekey(&key->main_key, in_key, key_len / 2);
+	if (err)
+		return err;
+	/* Second half of XTS key is the tweak key */
+	return aes_prepareenckey(&key->tweak_key, &in_key[key_len / 2],
+				 key_len / 2);
+}
+EXPORT_SYMBOL_GPL(aes_xts_preparekey);
+
+/*
+ * Hooks for optimized AES-XTS implementations, overridable by the architecture.
+ * They are called with len > 0 && len % AES_BLOCK_SIZE == 0.  In other words,
+ * they aren't expected to handle ciphertext stealing or empty inputs.
+ * Returning false causes the fallback implementation to be used instead.
+ *
+ * (Currently, all users of AES-XTS in the kernel seem to en/decrypt whole
+ * numbers of blocks anyway, with len >= 512.  So there's no need to heavily
+ * optimize ciphertext stealing for short messages.)
+ */
+#ifndef aes_xts_encrypt_arch
+static bool aes_xts_encrypt_arch(u8 *dst, const u8 *src, size_t len,
+				 u8 tweak[AES_BLOCK_SIZE],
+				 const struct aes_xts_key *key, bool cont)
+{
+	return false;
+}
+#endif
+#ifndef aes_xts_decrypt_arch
+static bool aes_xts_decrypt_arch(u8 *dst, const u8 *src, size_t len,
+				 u8 tweak[AES_BLOCK_SIZE],
+				 const struct aes_xts_key *key, bool cont)
+{
+	return false;
+}
+#endif
+
+static noinline void aes_xts_crypt_nocts_blockbyblock(
+	u8 *dst, const u8 *src, size_t len, u8 tweak[AES_BLOCK_SIZE],
+	const struct aes_xts_key *key, bool cont, bool enc)
+{
+	le128 t;
+
+	if (cont)
+		memcpy(&t, tweak, sizeof(t));
+	else
+		aes_encrypt(&key->tweak_key, (u8 *)&t, tweak);
+	do {
+		crypto_xor_cpy(dst, src, (const u8 *)&t, AES_BLOCK_SIZE);
+		if (enc)
+			aes_encrypt(&key->main_key, dst, dst);
+		else
+			aes_decrypt(&key->main_key, dst, dst);
+		crypto_xor(dst, (const u8 *)&t, AES_BLOCK_SIZE);
+		gf128mul_x_ble(&t, &t);
+		dst += AES_BLOCK_SIZE;
+		src += AES_BLOCK_SIZE;
+		len -= AES_BLOCK_SIZE;
+	} while (len);
+	memcpy(tweak, &t, sizeof(t));
+	memzero_explicit(&t, sizeof(t));
+}
+
+/* Requires len > 0 && len % AES_BLOCK_SIZE == 0 */
+static __always_inline void aes_xts_encrypt_nocts(u8 *dst, const u8 *src,
+						  size_t len,
+						  u8 tweak[AES_BLOCK_SIZE],
+						  const struct aes_xts_key *key,
+						  bool cont)
+{
+	if (likely(aes_xts_encrypt_arch(dst, src, len, tweak, key, cont)))
+		return;
+
+	/*
+	 * For the fallback, just go block-by-block.  It could be implemented on
+	 * top of AES-ECB, which could be significantly faster than this if the
+	 * arch has optimized AES-ECB code but not AES-XTS.  However, AES-XTS
+	 * performance is important enough that it needs to be (and has been)
+	 * implemented directly by every non-obsolete arch anyway.
+	 */
+	aes_xts_crypt_nocts_blockbyblock(dst, src, len, tweak, key, cont,
+					 /* enc= */ true);
+}
+
+/* Requires len > 0 && len % AES_BLOCK_SIZE == 0 */
+static __always_inline void aes_xts_decrypt_nocts(u8 *dst, const u8 *src,
+						  size_t len,
+						  u8 tweak[AES_BLOCK_SIZE],
+						  const struct aes_xts_key *key,
+						  bool cont)
+{
+	if (likely(aes_xts_decrypt_arch(dst, src, len, tweak, key, cont)))
+		return;
+
+	/* Just go block-by-block.  See comment in aes_xts_encrypt_nocts(). */
+	aes_xts_crypt_nocts_blockbyblock(dst, src, len, tweak, key, cont,
+					 /* enc= */ false);
+}
+
+static noinline void aes_xts_encrypt_cts(u8 *dst, const u8 *src, size_t len,
+					 u8 tweak[AES_BLOCK_SIZE],
+					 const struct aes_xts_key *key,
+					 bool cont)
+{
+	size_t partial_len = len % AES_BLOCK_SIZE; /* Length of partial block */
+	size_t nocts_len = round_down(len, AES_BLOCK_SIZE);
+	u8 tmp_block[AES_BLOCK_SIZE] __aligned(__alignof__(long));
+
+	/* Encrypt all full blocks. */
+	aes_xts_encrypt_nocts(dst, src, nocts_len, tweak, key, cont);
+	dst += nocts_len - AES_BLOCK_SIZE;
+	src += nocts_len - AES_BLOCK_SIZE;
+
+	/*
+	 * Swap the partial block with the first 'partial_len' bytes of the
+	 * encrypted last full block.  Note that a temporary buffer is needed to
+	 * support in-place encryption.
+	 */
+	memcpy(tmp_block, src + AES_BLOCK_SIZE, partial_len);
+	memcpy(dst + AES_BLOCK_SIZE, dst, partial_len);
+	memcpy(dst, tmp_block, partial_len);
+
+	/* Encrypt the last full block again. */
+	crypto_xor(dst, tweak, AES_BLOCK_SIZE);
+	aes_encrypt(&key->main_key, dst, dst);
+	crypto_xor(dst, tweak, AES_BLOCK_SIZE);
+	memzero_explicit(tmp_block, sizeof(tmp_block));
+}
+
+static noinline void aes_xts_decrypt_cts(u8 *dst, const u8 *src, size_t len,
+					 u8 tweak[AES_BLOCK_SIZE],
+					 const struct aes_xts_key *key,
+					 bool cont)
+{
+	size_t partial_len = len % AES_BLOCK_SIZE; /* Length of partial block */
+	size_t nocts_len = round_down(len, AES_BLOCK_SIZE) - AES_BLOCK_SIZE;
+	union {
+		u8 block[AES_BLOCK_SIZE];
+		le128 tweak;
+	} tmp __aligned(__alignof__(long));
+
+	/*
+	 * Decrypt all blocks except the last full block and the partial block.
+	 * The last full block has to be handled specially because decryption
+	 * ciphertext stealing uses the last two tweaks in reverse order.
+	 *
+	 * nocts_len == 0 is possible here, which aes_xts_decrypt_nocts()
+	 * doesn't handle (so that the length doesn't get checked redundantly in
+	 * the fast path).  So handle that case specially as well.
+	 */
+	if (nocts_len)
+		aes_xts_decrypt_nocts(dst, src, nocts_len, tweak, key, cont);
+	else if (!cont)
+		aes_encrypt(&key->tweak_key, tweak, tweak);
+	dst += nocts_len;
+	src += nocts_len;
+
+	/* Copy the tweak, advance it again, then decrypt last full block. */
+	memcpy(&tmp.tweak, tweak, AES_BLOCK_SIZE);
+	gf128mul_x_ble(&tmp.tweak, &tmp.tweak);
+	crypto_xor_cpy(dst, src, tmp.block, AES_BLOCK_SIZE);
+	aes_decrypt(&key->main_key, dst, dst);
+	crypto_xor(dst, tmp.block, AES_BLOCK_SIZE);
+
+	/*
+	 * Swap the partial block with the first 'partial_len' bytes of the
+	 * decrypted last full block.  Note that a temporary buffer is needed to
+	 * support in-place decryption.
+	 */

lib/crypto/aes.c void aes_xctr(u8 *dst, const u8 *src, size_t len, u64 *ctr, · line 1252

Quoted 10 lines
lib/crypto/aes.c +10 -0
+	memcpy(tmp.block, src + AES_BLOCK_SIZE, partial_len);
+	memcpy(dst + AES_BLOCK_SIZE, dst, partial_len);
+	memcpy(dst, tmp.block, partial_len);
+
+	/* Decrypt the last full block again. */
+	crypto_xor(dst, tweak, AES_BLOCK_SIZE);
+	aes_decrypt(&key->main_key, dst, dst);
+	crypto_xor(dst, tweak, AES_BLOCK_SIZE);
+	memzero_explicit(&tmp, sizeof(tmp));
+}

So in aes_xts_decrypt_cts, you're using a union to get a u8* pointer to the tweak, but in aes_xts_crypt_nocts_blockbyblock() you're casting it instead? ... looks a little bit inconsisten, I'd maybe use the same way in both functions (IMHO casting in aes_xts_decrypt_cts should be fine, too, since you never seem to access the individual bytes of the tweak).

Apart from that, patch looks fine to me.

Thanks,
Thomas

author maintainer
#19 lore raw

Re: [PATCH 05/33] lib/crypto: aes: Add XTS support

Quoted 5 lines · Thomas Huth

So in aes_xts_decrypt_cts, you're using a union to get a u8* pointer to the tweak, but in aes_xts_crypt_nocts_blockbyblock() you're casting it instead? ... looks a little bit inconsisten, I'd maybe use the same way in both functions (IMHO casting in aes_xts_decrypt_cts should be fine, too, since you never seem to access the individual bytes of the tweak).

In aes_xts_decrypt_cts() the buffer is first used to hold a le128 tweak, and then it's used to hold a temporary array of length partial_len. So it's two different purposes, and the union makes more sense there.

- Eric

author maintainer
#20 lore raw

PATCH 6/33 lib/crypto: aes: Add GCM support

In reply to Eric Biggers

Add support for AES-GCM to the crypto library.

This will be used to provide streamlined implementations of the "gcm(aes)" and "rfc4106(gcm(aes))" crypto_aead algorithms. Most users of these will also be able to switch to the library, which as usual will be faster and simpler, e.g.:

- drivers/net/macsec.c
- fs/smb/client/
- fs/smb/server/
- net/ceph/messenger_v2.c
- net/mac80211/ (for both GMAC and GCMP)
- net/tipc/crypto.c
- security/keys/trusted-keys/trusted_dcp.c

(I've already written proof-of-concept patches for all the above, and they helped inform the API design.)

As usual, the architecture-optimized AES-GCM code will be migrated into the library as well (using the hooks provided in this commit as well as the GHASH ones), eliminating lots of repetitive boilerplate code.

Incremental en/decryption is supported. Incremental operation is a bit controversial in AEAD APIs because users have to be careful not to consume any decrypted data that hasn't been authenticated yet. But I do think it's the right choice here. It's not fundamentally different from the existing incremental MAC APIs, and it's the only approach that's general enough to work well for all users in the kernel:

- An array of virtually-addressed buffers (like that used by BoringSSL's EVP_AEAD_CTX_sealv() and EVP_AEAD_CTX_openv()) doesn't work in the kernel in general, since in some cases the data for a single AES-GCM message is contained in a large number of highmem pages that each need to be mapped into memory individually. That can be done efficiently only by using CPU-local mappings, but there is a limited number of those.

Ceph messenger v2 is a great example, as it can send or receive up to 32 MiB in a single AES-GCM message. And it needs the en/decrypted data to go into a (potentially large) number of bvecs provided by a custom iterator, as well as into four virtually-addressed buffers, two of which can be large buffers in the vmalloc region.

Even just allocating an array big enough to store all the pointers can be problematic in the kernel. There are cases in which decryption runs in GFP_NOIO context or even in softirq context, where memory allocations are not as reliable as they normally are.

- Meanwhile, 'struct scatterlist' (the choice of crypto_aead) has turned out to be really inconvenient for anyone who *does* just have virtually-addressed buffers. This is especially true if they can be in the vmalloc region, including the stack, as in that case the conversion to a scatterlist has to be done page-by-page.

And even for users who have all of their data in bare 'struct page', none of them actually use 'struct scatterlist' as their native data structure anyway. They actually use skbs, bvecs, or other formats.

- iov_iter is attractive, but ultimately not general enough either (considering the Ceph case for example), but also too general in some ways (like having support for userspace addresses). Additional iter types like ITER_SKB would help a bit, but bloating iov_iter with more types would reduce performance elsewhere in the kernel.

Initial test coverage is provided by the crypto_aead support added in a later commit. I'm planning a KUnit test suite as well.

---
 .../crypto/libcrypto-auth-encryption.rst      |  13 +
 Documentation/crypto/libcrypto.rst            |   1 +
 include/crypto/aes-gcm.h                      | 249 ++++++++++++++++
 include/crypto/gcm.h                          |   2 +-
 lib/crypto/Kconfig                            |   8 +
 lib/crypto/aes.c                              | 269 ++++++++++++++++++
 lib/crypto/tests/Kconfig                      |   1 +
 7 files changed, 542 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/crypto/libcrypto-auth-encryption.rst
 create mode 100644 include/crypto/aes-gcm.h
Documentation/crypto/libcrypto-auth-encryption.rst new file +13 -0
new file mode 100644
index 000000000000..17412b7bd7bb
@@ -0,0 +1,13 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Authenticated encryption
+========================
+
+Support for authenticated encryption and decryption.
+
+AES-GCM
+-------
+
+Support for AES in the GCM mode of operation.
+
+.. kernel-doc:: include/crypto/aes-gcm.h
Documentation/crypto/libcrypto.rst +1 -0
index bbf5ca137910..b8a57e62f0fa 100644
@@ -158,6 +158,7 @@ API documentation
 .. toctree::
    :maxdepth: 2
 
+   libcrypto-auth-encryption
    libcrypto-blockcipher
    libcrypto-hash
    libcrypto-signature
include/crypto/aes-gcm.h new file +249 -0

249 lines not on this page · raw message

include/crypto/gcm.h +1 -1
index 1d5f39ff1dc4..eb91d5603b74 100644
@@ -13,7 +13,7 @@
 /*
  * validate authentication tag for GCM
  */
-static inline int crypto_gcm_check_authsize(unsigned int authsize)
+static inline int crypto_gcm_check_authsize(size_t authsize)
 {
 	switch (authsize) {
 	case 4:
lib/crypto/Kconfig +8 -0
index 9af44cf743a7..5d313c78b9fa 100644
@@ -53,6 +53,14 @@ config CRYPTO_LIB_AES_CTR
 	help
 	  The AES-CTR and AES-XCTR library functions.
 
+config CRYPTO_LIB_AES_GCM
+	tristate
+	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_AES_CTR
+	select CRYPTO_LIB_GF128HASH
+	help
+	  The AES-GCM library functions.
+
 config CRYPTO_LIB_AES_XTS
 	tristate
 	select CRYPTO_LIB_AES
lib/crypto/aes.c +269 -0

281 lines not on this page · raw message

lib/crypto/tests/Kconfig +1 -0
index b559e7c79e76..51183ffabbef 100644
@@ -148,6 +148,7 @@ config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
 	select CRYPTO_LIB_AES_CBC_MACS
 	select CRYPTO_LIB_AES_CTR
 	select CRYPTO_LIB_AES_ECB
+	select CRYPTO_LIB_AES_GCM
 	select CRYPTO_LIB_AES_XTS
 	select CRYPTO_LIB_BLAKE2B
 	select CRYPTO_LIB_CHACHA20POLY1305
Signature · 1 line
2.54.0
author maintainer
#21 lore raw

PATCH 7/33 lib/crypto: aes: Add CCM support

In reply to Eric Biggers

Add support for AES-CCM to the crypto library.

This will be used to provide a streamlined implementation of the "ccm(aes)" crypto_aead algorithm. Most users of "ccm(aes)" will also be able to switch to the library, which as usual will be faster and simpler, e.g.:

- fs/smb/client/
- fs/smb/server/
- net/mac80211/
- net/mac802154/

(I've already written proof-of-concept patches for all the above, and they helped inform the API design.)

As in the AES-GCM API, incremental operation is supported. It has to be used carefully, especially when decrypting, but it makes the API general enough to work well for all users.

The AES-CCM library code calls aes_cbcmac_blocks() directly, bypassing the higher-level aes_cbcmac_init(), aes_cbcmac_update(), and aes_cbcmac_final(). The latter set of functions is useful only for AES-CCM, so they don't make sense to keep around and will be removed once the "ccm(aes)" crypto_aead starts using the AES-CCM library.

Initial test coverage is provided by the crypto_aead support added in a later commit. I'm planning a KUnit test suite as well.

---
 .../crypto/libcrypto-auth-encryption.rst      |   7 +
 include/crypto/aes-ccm.h                      | 244 +++++++++++++++
 lib/crypto/Kconfig                            |   8 +
 lib/crypto/aes.c                              | 287 ++++++++++++++++++
 lib/crypto/tests/Kconfig                      |   1 +
 5 files changed, 547 insertions(+)
 create mode 100644 include/crypto/aes-ccm.h
Documentation/crypto/libcrypto-auth-encryption.rst +7 -0
index 17412b7bd7bb..f3fa5b5305eb 100644
@@ -5,6 +5,13 @@ Authenticated encryption
 
 Support for authenticated encryption and decryption.
 
+AES-CCM
+-------
+
+Support for AES in the CCM mode of operation.
+
+.. kernel-doc:: include/crypto/aes-ccm.h
+
 AES-GCM
 -------
 
include/crypto/aes-ccm.h new file +244 -0

244 lines not on this page · raw message

lib/crypto/Kconfig +8 -0
index 5d313c78b9fa..4066427017bc 100644
@@ -47,6 +47,14 @@ config CRYPTO_LIB_AES_ECB
 	help
 	  The AES-ECB library functions.
 
+config CRYPTO_LIB_AES_CCM
+	tristate
+	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CTR
+	help
+	  The AES-CCM library functions.
+
 config CRYPTO_LIB_AES_CTR
 	tristate
 	select CRYPTO_LIB_AES
lib/crypto/aes.c +287 -0

299 lines not on this page · raw message

lib/crypto/tests/Kconfig +1 -0
index 51183ffabbef..bc084dde424f 100644
@@ -146,6 +146,7 @@ config CRYPTO_LIB_ENABLE_ALL_FOR_KUNIT
 	depends on KUNIT
 	select CRYPTO_LIB_AES_CBC
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CCM
 	select CRYPTO_LIB_AES_CTR
 	select CRYPTO_LIB_AES_ECB
 	select CRYPTO_LIB_AES_GCM
Signature · 1 line
2.54.0
author maintainer
#22 lore raw

PATCH 8/33 crypto: aes - Add ECB support using library

In reply to Eric Biggers

Implement the "ecb(aes)" crypto_skcipher algorithm using the corresponding library functions.

Among other benefits, this allows the architecture-optimized AES-ECB code to be migrated into the library while still leaving it accessible via crypto_skcipher, eliminating lots of boilerplate code.

For now the cra_priority is set to just 110, since the architecture-optimized implementations of this algorithm haven't yet been migrated into the library. It will be boosted once that happens.

---
 crypto/Kconfig |   5 ++
 crypto/aes.c   | 165 ++++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 169 insertions(+), 1 deletion(-)
crypto/Kconfig +5 -0
index f1e372195273..093508d13b8c 100644
@@ -359,7 +359,12 @@ config CRYPTO_AES
 	select CRYPTO_ALGAPI
 	select CRYPTO_LIB_AES
 	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
+	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
 	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
+	# CRYPTO_SKCIPHER should be selected only if a mode that needs it is
+	# enabled, but that doesn't work due to a recursive dependency caused by
+	# CRYPTO_SKCIPHER selecting CRYPTO_ECB.  So just always select it.
+	select CRYPTO_SKCIPHER
 	help
 	  AES cipher algorithms (Rijndael)(FIPS-197, ISO/IEC 18033-3)
 
crypto/aes.c +164 -1

206 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#23 lore raw

PATCH 9/33 crypto: aes - Add CBC and CBC-CTS support using library

In reply to Eric Biggers

Implement the "cbc(aes)" and "cts(cbc(aes))" crypto_skcipher algorithms using the corresponding library functions.

Among other benefits, this allows the architecture-optimized AES-CBC and AES-CBC-CTS code to be migrated into the library while still leaving it accessible via crypto_skcipher, eliminating lots of boilerplate code.

For now the cra_priority is set to just 110, since the architecture-optimized implementations of these algorithms haven't yet been migrated into the library. It will be boosted once that happens.

---
 crypto/Kconfig |   1 +
 crypto/aes.c   | 163 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 164 insertions(+)
crypto/Kconfig +1 -0
index 093508d13b8c..3d30d79878c2 100644
@@ -358,6 +358,7 @@ config CRYPTO_AES
 	tristate "AES (Advanced Encryption Standard)"
 	select CRYPTO_ALGAPI
 	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_AES_CBC if CRYPTO_CBC || CRYPTO_CTS
 	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
 	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
crypto/aes.c +163 -0

184 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#24 lore raw

PATCH 10/33 crypto: aes - Add CTR and XCTR support using library

In reply to Eric Biggers

Implement the "ctr(aes)" and "xctr(aes)" crypto_skcipher algorithms using the corresponding library functions.

Among other benefits, this allows the architecture-optimized AES-CTR and AES-XCTR code to be migrated into the library while still leaving it accessible via crypto_skcipher, eliminating lots of boilerplate code.

For now the cra_priority is set to just 110, since the architecture-optimized implementations of these algorithms haven't yet been migrated into the library. It will be boosted once that happens.

---
 crypto/Kconfig |  1 +
 crypto/aes.c   | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 69 insertions(+)
crypto/Kconfig +1 -0
index 3d30d79878c2..dd6785c68620 100644
@@ -360,6 +360,7 @@ config CRYPTO_AES
 	select CRYPTO_LIB_AES
 	select CRYPTO_LIB_AES_CBC if CRYPTO_CBC || CRYPTO_CTS
 	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
+	select CRYPTO_LIB_AES_CTR if CRYPTO_CTR || CRYPTO_XCTR
 	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
 	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	# CRYPTO_SKCIPHER should be selected only if a mode that needs it is
crypto/aes.c +68 -0

89 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#25 lore raw

PATCH 11/33 crypto: aes - Add XTS support using library

In reply to Eric Biggers

Implement the "xts(aes)" crypto_skcipher algorithm using the corresponding library functions.

Among other benefits, this allows the architecture-optimized AES-XTS code to be migrated into the library while still leaving it accessible via crypto_skcipher, eliminating lots of boilerplate code.

Fast paths similar to what x86_64 uses (to eliminate the scatterlist walking overhead) are included. So we'll get that optimization for all architectures.

For now the cra_priority is set to just 110, since the architecture-optimized implementations of this algorithm haven't yet been migrated into the library. It will be boosted once that happens.

---
 crypto/Kconfig |   1 +
 crypto/aes.c   | 120 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 121 insertions(+)
crypto/Kconfig +1 -0
index dd6785c68620..5e573051c903 100644
@@ -362,6 +362,7 @@ config CRYPTO_AES
 	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	select CRYPTO_LIB_AES_CTR if CRYPTO_CTR || CRYPTO_XCTR
 	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
+	select CRYPTO_LIB_AES_XTS if CRYPTO_XTS
 	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	# CRYPTO_SKCIPHER should be selected only if a mode that needs it is
 	# enabled, but that doesn't work due to a recursive dependency caused by
crypto/aes.c +120 -0

141 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#26 lore raw

PATCH 12/33 crypto: aes - Add GCM support using library

In reply to Eric Biggers

Implement the "gcm(aes)" and "rfc4106(gcm(aes))" crypto_aead algorithms using the corresponding library functions.

Among other benefits, this allows the architecture-optimized AES-GCM code to be migrated into the library while still leaving it accessible via crypto_aead, eliminating lots of boilerplate code.

For now the cra_priority is set to just 110, since the architecture-optimized implementations of these algorithms haven't yet been migrated into the library. It will be boosted once that happens.

---
 crypto/Kconfig |   2 +
 crypto/aes.c   | 237 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 239 insertions(+)
crypto/Kconfig +2 -0
index 5e573051c903..74dfe969216d 100644
@@ -362,7 +362,9 @@ config CRYPTO_AES
 	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	select CRYPTO_LIB_AES_CTR if CRYPTO_CTR || CRYPTO_XCTR
 	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
+	select CRYPTO_LIB_AES_GCM if CRYPTO_GCM
 	select CRYPTO_LIB_AES_XTS if CRYPTO_XTS
+	select CRYPTO_AEAD if CRYPTO_GCM
 	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	# CRYPTO_SKCIPHER should be selected only if a mode that needs it is
 	# enabled, but that doesn't work due to a recursive dependency caused by
crypto/aes.c +237 -0

275 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#27 lore raw

PATCH 13/33 crypto: aes - Add CCM support using library

In reply to Eric Biggers

Implement the "ccm(aes)" crypto_aead algorithm using the corresponding library functions.

Among other benefits, this allows the architecture-optimized AES-CCM code to be migrated into the library while still leaving it accessible via crypto_aead, eliminating lots of boilerplate code.

For now the cra_priority is set to just 110, since the architecture-optimized implementations of this algorithm haven't yet been migrated into the library. It will be boosted once that happens.

---
 crypto/Kconfig |   3 +-
 crypto/aes.c   | 138 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 140 insertions(+), 1 deletion(-)
crypto/Kconfig +2 -1
index 74dfe969216d..e6b894dc784a 100644
@@ -360,11 +360,12 @@ config CRYPTO_AES
 	select CRYPTO_LIB_AES
 	select CRYPTO_LIB_AES_CBC if CRYPTO_CBC || CRYPTO_CTS
 	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
+	select CRYPTO_LIB_AES_CCM if CRYPTO_CCM
 	select CRYPTO_LIB_AES_CTR if CRYPTO_CTR || CRYPTO_XCTR
 	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
 	select CRYPTO_LIB_AES_GCM if CRYPTO_GCM
 	select CRYPTO_LIB_AES_XTS if CRYPTO_XTS
-	select CRYPTO_AEAD if CRYPTO_GCM
+	select CRYPTO_AEAD if CRYPTO_GCM || CRYPTO_CCM
 	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
 	# CRYPTO_SKCIPHER should be selected only if a mode that needs it is
 	# enabled, but that doesn't work due to a recursive dependency caused by
crypto/aes.c +138 -0

159 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#28 lore raw

PATCH 14/33 x86/sev: Use new AES-GCM library

In reply to Eric Biggers

The old AES-GCM library code is being replaced as part of an overhaul that is adding support for all the common AES encryption modes with consistent conventions. The SEV code is the only client of the old AES-GCM code, so update it to the new API.

Besides some slight adjustments to the calling convention, the only notable change is replacing the direct accesses to the auth tag length field (which should be considered private until/unless someone truly needs it) with the AUTHTAG_LEN constant.

---
 arch/x86/Kconfig                        |  2 +-
 arch/x86/coco/sev/core.c                | 44 ++++++++++++-------------
 arch/x86/include/asm/sev.h              |  2 +-
 drivers/virt/coco/sev-guest/sev-guest.c |  7 ++--
 4 files changed, 26 insertions(+), 29 deletions(-)
arch/x86/Kconfig +1 -1
index bdad90f210e4..0b89641cac16 100644
@@ -1495,7 +1495,7 @@ config AMD_MEM_ENCRYPT
 	select ARCH_HAS_CC_PLATFORM
 	select X86_MEM_ENCRYPT
 	select UNACCEPTED_MEMORY
-	select CRYPTO_LIB_AESGCM
+	select CRYPTO_LIB_AES_GCM
 	help
 	  Say yes to enable support for the encryption of system memory.
 	  This requires an AMD processor that supports Secure Memory
arch/x86/coco/sev/core.c +21 -23

106 lines not on this page · raw message

arch/x86/include/asm/sev.h +1 -1
index 594cfa19cbd4..9e7a077c445d 100644
@@ -314,7 +314,7 @@ struct snp_msg_desc {
 
 	struct snp_secrets_page *secrets;
 
-	struct aesgcm_ctx *ctx;
+	struct aes_gcm_key *gcm_key;
 
 	u32 *os_area_msg_seqno;
 	u8 *vmpck;
drivers/virt/coco/sev-guest/sev-guest.c +3 -4
index d186ae55cf63..935537a41469 100644
@@ -17,7 +17,6 @@
 #include <linux/set_memory.h>
 #include <linux/fs.h>
 #include <linux/tsm.h>
-#include <crypto/gcm.h>
 #include <linux/psp-sev.h>
 #include <linux/sockptr.h>
 #include <linux/cleanup.h>
@@ -87,7 +86,7 @@ static int get_report(struct snp_guest_dev *snp_dev, struct snp_guest_request_io
 	 * response payload. Make sure that it has enough space to cover the
 	 * authtag.
 	 */
-	resp_len = sizeof(report_resp->data) + mdesc->ctx->authsize;
+	resp_len = sizeof(report_resp->data) + AUTHTAG_LEN;
 	report_resp = kzalloc(resp_len, GFP_KERNEL_ACCOUNT);
 	if (!report_resp)
 		return -ENOMEM;
@@ -130,7 +129,7 @@ static int get_derived_key(struct snp_guest_dev *snp_dev, struct snp_guest_reque
 	 * response payload. Make sure that it has enough space to cover the
 	 * authtag.
 	 */
-	resp_len = sizeof(derived_key_resp->data) + mdesc->ctx->authsize;
+	resp_len = sizeof(derived_key_resp->data) + AUTHTAG_LEN;
 	derived_key_resp = kzalloc(resp_len, GFP_KERNEL_ACCOUNT);
 	if (!derived_key_resp)
 		return -ENOMEM;
@@ -230,7 +229,7 @@ static int get_ext_report(struct snp_guest_dev *snp_dev, struct snp_guest_reques
 	 * response payload. Make sure that it has enough space to cover the
 	 * authtag.
 	 */
-	resp_len = sizeof(report_resp->data) + mdesc->ctx->authsize;
+	resp_len = sizeof(report_resp->data) + AUTHTAG_LEN;
 	report_resp = kzalloc(resp_len, GFP_KERNEL_ACCOUNT);
 	if (!report_resp) {
 		ret = -ENOMEM;
Signature · 1 line
2.54.0
author maintainer
#29 lore raw

PATCH 15/33 lib/crypto: aesgcm: Remove old AES-GCM library

In reply to Eric Biggers

The old AES-GCM library code is no longer used, so remove it.

---
 include/crypto/gcm.h |  21 --
 lib/crypto/Kconfig   |   6 -
 lib/crypto/Makefile  |   3 -
 lib/crypto/aesgcm.c  | 721 -------------------------------------------
 4 files changed, 751 deletions(-)
 delete mode 100644 lib/crypto/aesgcm.c
include/crypto/gcm.h +0 -21
index eb91d5603b74..1f4457608e4c 100644
@@ -3,9 +3,6 @@
 
 #include <linux/errno.h>
 
-#include <crypto/aes.h>
-#include <crypto/gf128hash.h>
-
 #define GCM_AES_IV_SIZE 12
 #define GCM_RFC4106_IV_SIZE 8
 #define GCM_RFC4543_IV_SIZE 8
@@ -64,22 +61,4 @@ static inline int crypto_ipsec_check_assoclen(unsigned int assoclen)
 	return 0;
 }
 
-struct aesgcm_ctx {
-	struct ghash_key	ghash_key;
-	struct aes_enckey	aes_key;
-	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);
-
-bool __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 +0 -6
index 4066427017bc..f21b45854cc6 100644
@@ -75,12 +75,6 @@ config CRYPTO_LIB_AES_XTS
 	help
 	  The AES-XTS library functions.
 
-config CRYPTO_LIB_AESGCM
-	tristate
-	select CRYPTO_LIB_AES
-	select CRYPTO_LIB_GF128HASH
-	select CRYPTO_LIB_UTILS
-
 config CRYPTO_LIB_ARC4
 	tristate
 
lib/crypto/Makefile +0 -3
index f1e9bf89785f..ca068df1f71f 100644
@@ -63,9 +63,6 @@ clean-files += powerpc/aesp8-ppc.S
 obj-$(CONFIG_CRYPTO_LIB_AESCFB)			+= libaescfb.o
 libaescfb-y					:= aescfb.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 deleted +0 -721

721 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#30 lore raw

PATCH 16/33 crypto: aes - Remove AES-CBC-MAC support

In reply to Eric Biggers

"cbcmac(aes)" is used only by the "ccm" template when instantiated as "ccm(aes)". Since native "ccm(aes)" support has been added to crypto/aes.c, the "cbcmac(aes)" crypto_shash is no longer needed.

Note that "cmac(aes)" and "xcbc(aes)" remain supported.

---
 crypto/Kconfig                       |  4 +-
 crypto/aes.c                         | 62 ----------------------------
 crypto/testmgr.c                     |  6 +--
 drivers/crypto/starfive/jh7110-aes.c |  2 +-
 4 files changed, 6 insertions(+), 68 deletions(-)
crypto/Kconfig +2 -2
index e6b894dc784a..83adbd54d725 100644
@@ -359,14 +359,14 @@ config CRYPTO_AES
 	select CRYPTO_ALGAPI
 	select CRYPTO_LIB_AES
 	select CRYPTO_LIB_AES_CBC if CRYPTO_CBC || CRYPTO_CTS
-	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
+	select CRYPTO_LIB_AES_CBC_MACS if CRYPTO_CMAC || CRYPTO_XCBC
 	select CRYPTO_LIB_AES_CCM if CRYPTO_CCM
 	select CRYPTO_LIB_AES_CTR if CRYPTO_CTR || CRYPTO_XCTR
 	select CRYPTO_LIB_AES_ECB if CRYPTO_ECB
 	select CRYPTO_LIB_AES_GCM if CRYPTO_GCM
 	select CRYPTO_LIB_AES_XTS if CRYPTO_XTS
 	select CRYPTO_AEAD if CRYPTO_GCM || CRYPTO_CCM
-	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC || CRYPTO_CCM
+	select CRYPTO_HASH if CRYPTO_CMAC || CRYPTO_XCBC
 	# CRYPTO_SKCIPHER should be selected only if a mode that needs it is
 	# enabled, but that doesn't work due to a recursive dependency caused by
 	# CRYPTO_SKCIPHER selecting CRYPTO_ECB.  So just always select it.
crypto/aes.c +0 -62

80 lines not on this page · raw message

crypto/testmgr.c +3 -3
index 4958211fbfa9..b25c15173c76 100644
@@ -4421,7 +4421,7 @@ static const struct alg_test_desc alg_test_descs[] = {
 	}, {
 #endif
 		.alg = "cbcmac(aes)",
-		.generic_driver = "cbcmac-aes-lib",
+		.generic_driver = "cbcmac(aes-lib)",
 		.test = alg_test_hash,
 		.suite = {
 			.hash = __VECS(aes_cbcmac_tv_template)
@@ -4434,7 +4434,7 @@ static const struct alg_test_desc alg_test_descs[] = {
 		}
 	}, {
 		.alg = "ccm(aes)",
-		.generic_driver = "ccm_base(ctr(aes-lib),cbcmac-aes-lib)",
+		.generic_driver = "ccm_base(ctr(aes-lib),cbcmac(aes-lib))",
 		.test = alg_test_aead,
 		.fips_allowed = 1,
 		.suite = {
@@ -5239,7 +5239,7 @@ static const struct alg_test_desc alg_test_descs[] = {
 		}
 	}, {
 		.alg = "rfc4309(ccm(aes))",
-		.generic_driver = "rfc4309(ccm_base(ctr(aes-lib),cbcmac-aes-lib))",
+		.generic_driver = "rfc4309(ccm_base(ctr(aes-lib),cbcmac(aes-lib)))",
 		.test = alg_test_aead,
 		.fips_allowed = 1,
 		.suite = {
drivers/crypto/starfive/jh7110-aes.c +1 -1
index a0713aa21250..c591a850f093 100644
@@ -1003,7 +1003,7 @@ static int starfive_aes_ctr_init_tfm(struct crypto_skcipher *tfm)
 
 static int starfive_aes_ccm_init_tfm(struct crypto_aead *tfm)
 {
-	return starfive_aes_aead_init_tfm(tfm, "ccm_base(ctr(aes-lib),cbcmac-aes-lib)");
+	return starfive_aes_aead_init_tfm(tfm, "ccm_base(ctr(aes-lib),cbcmac(aes-lib))");
 }
 
 static int starfive_aes_gcm_init_tfm(struct crypto_aead *tfm)
Signature · 1 line
2.54.0
author maintainer
#31 lore raw

PATCH 17/33 lib/crypto: aes: Remove aes_cbcmac_* functions

In reply to Eric Biggers

The aes_cbcmac_* functions are no longer used, except by their KUnit test, since their functionality was folded directly into the AES-CCM library code. Remove them.

Note that the aes_cmac_* and aes_xcbcmac_* functions remain unchanged.

---
 include/crypto/aes-cbc-macs.h         | 22 +--------
 lib/crypto/aes.c                      | 43 -----------------
 lib/crypto/tests/aes_cbc_macs_kunit.c | 68 +--------------------------
 3 files changed, 2 insertions(+), 131 deletions(-)
include/crypto/aes-cbc-macs.h +1 -21
index e61df108b926..95bbb8603420 100644
@@ -1,6 +1,6 @@
 /* SPDX-License-Identifier: GPL-2.0 */
 /*
- * Support for AES-CMAC, AES-XCBC-MAC, and AES-CBC-MAC
+ * Support for AES-CMAC and AES-XCBC-MAC
  *
  * Copyright 2026 Google LLC
  */
@@ -131,24 +131,4 @@ static inline void aes_cmac(const struct aes_cmac_key *key, const u8 *data,
 	aes_cmac_final(&ctx, out);
 }
 
-/*
- * AES-CBC-MAC support.  This is provided only for use by the implementation of
- * AES-CCM.  It should have no other users.  Warning: unlike AES-CMAC and
- * AES-XCBC-MAC, AES-CBC-MAC isn't a secure MAC for variable-length messages.
- */
-struct aes_cbcmac_ctx {
-	const struct aes_enckey *key;
-	size_t partial_len;
-	u8 h[AES_BLOCK_SIZE];
-};
-static inline void aes_cbcmac_init(struct aes_cbcmac_ctx *ctx,
-				   const struct aes_enckey *key)
-{
-	*ctx = (struct aes_cbcmac_ctx){ .key = key };
-}
-void aes_cbcmac_update(struct aes_cbcmac_ctx *ctx, const u8 *data,
-		       size_t data_len);
-void aes_cbcmac_final(struct aes_cbcmac_ctx *ctx,
-		      u8 out[at_least AES_BLOCK_SIZE]);
-
 #endif /* _CRYPTO_AES_CBC_MACS_H */
lib/crypto/aes.c +0 -43

49 lines not on this page · raw message

lib/crypto/tests/aes_cbc_macs_kunit.c +1 -67

83 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#32 lore raw

PATCH 18/33 fscrypt: Use aes_ecb_encrypt() for v1 key derivation

In reply to Eric Biggers

Now that there's a library function aes_ecb_encrypt(), use it instead of a loop of aes_encrypt() calls.

Note that the use of AES-ECB here is purely for the key derivation function used by the deprecated v1 encryption policies. v2 encryption policies use HKDF-SHA512 instead. Nevertheless, the original version has to continue to be supported for backwards compatibility.

---
 fs/crypto/Kconfig       | 2 +-
 fs/crypto/keysetup_v1.c | 5 ++---
 2 files changed, 3 insertions(+), 4 deletions(-)
fs/crypto/Kconfig +1 -1
index 983d8ad1f417..7662d8c45f07 100644
@@ -3,7 +3,7 @@ config FS_ENCRYPTION
 	bool "FS Encryption (Per-file encryption)"
 	select CRYPTO
 	select CRYPTO_SKCIPHER
-	select CRYPTO_LIB_AES
+	select CRYPTO_LIB_AES_ECB # for deprecated v1 key derivation function
 	select CRYPTO_LIB_SHA256
 	select CRYPTO_LIB_SHA512
 	select KEYS
fs/crypto/keysetup_v1.c +2 -3
index e6e527c73f16..70385d82fa73 100644
@@ -20,7 +20,7 @@
  *    managed alongside the master keys in the filesystem-level keyring)
  */
 
-#include <crypto/aes.h>
+#include <crypto/aes-ecb.h>
 #include <crypto/utils.h>
 #include <keys/user-type.h>
 #include <linux/hashtable.h>
@@ -240,8 +240,7 @@ static int setup_v1_file_key_derived(struct fscrypt_inode_info *ci,
 
 	static_assert(FSCRYPT_FILE_NONCE_SIZE == AES_KEYSIZE_128);
 	aes_prepareenckey(&aes, ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE);
-	for (unsigned int i = 0; i < derived_keysize; i += AES_BLOCK_SIZE)
-		aes_encrypt(&aes, &derived_key[i], &raw_master_key[i]);
+	aes_ecb_encrypt(derived_key, raw_master_key, derived_keysize, &aes);
 
 	err = fscrypt_set_per_file_enc_key(ci, derived_key);
 
Signature · 1 line
2.54.0
author maintainer
#33 lore raw

PATCH 19/33 KEYS: encrypted: Use AES-CBC library instead of crypto_skcipher

In reply to Eric Biggers

Now that there's a library API for AES-CBC, use it instead of a "cbc(aes)" crypto_skcipher. This significantly simplifies the code.

Note that this use of AES-CBC remains questionable (an AEAD should be used instead), but it remains for backwards compatibility.

---
 security/keys/Kconfig                    |   4 +-
 security/keys/encrypted-keys/encrypted.c | 194 +++++++----------------
 2 files changed, 62 insertions(+), 136 deletions(-)
security/keys/Kconfig +1 -3
index f4510d8cb485..d482f632791a 100644
@@ -83,9 +83,7 @@ endif
 
 config ENCRYPTED_KEYS
 	tristate "ENCRYPTED KEYS"
-	select CRYPTO
-	select CRYPTO_AES
-	select CRYPTO_CBC
+	select CRYPTO_LIB_AES_CBC
 	select CRYPTO_LIB_SHA256
 	help
 	  This option provides support for create/encrypting/decrypting keys
security/keys/encrypted-keys/encrypted.c +61 -133

305 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#34 lore raw

PATCH 20/33 KEYS: trusted: dcp: Use AES-GCM library instead of crypto_aead

In reply to Eric Biggers

Now that there's a library API for AES-GCM, use it instead of a "gcm(aes)" crypto_aead. This significantly simplifies the code.

Note, I've left unchanged two pre-existing issues with this code:

- trusted_key_unseal() doesn't validate that the decrypted key actually fits in the buffer to which it's written.

- dcp_blob_fmt::nonce is unnecessarily long, at 16 bytes rather than the 12 bytes that are actually used by the AES-GCM operations. Probably unfixable since it's part of the blob format.

---
 security/keys/trusted-keys/Kconfig       |  1 +
 security/keys/trusted-keys/trusted_dcp.c | 69 +++++-------------------
 2 files changed, 15 insertions(+), 55 deletions(-)
security/keys/trusted-keys/Kconfig +1 -0
index e5a4a53aeab2..361882191ff9 100644
@@ -63,6 +63,7 @@ config TRUSTED_KEYS_DCP
 	bool "DCP-based trusted keys"
 	depends on CRYPTO_DEV_MXS_DCP >= TRUSTED_KEYS
 	default y
+	select CRYPTO_LIB_AES_GCM
 	select HAVE_TRUSTED_KEYS_DEBUG
 	select HAVE_TRUSTED_KEYS
 	help
security/keys/trusted-keys/trusted_dcp.c +14 -55

96 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#35 lore raw

PATCH 21/33 libceph: Use AES-CBC library in ceph_aes_crypt()

In reply to Eric Biggers

Now that there's a library API for AES-CBC, use it instead of a "cbc(aes)" crypto_skcipher. This significantly simplifies the code.

Notably, the new ceph_aes_crypt() just operates on the actual buffer directly. It no longer needs to be converted into a scatterlist.

This conversion also eliminates the broken code that intended to allocate crypto_skcipher objects from a GFP_NOIO context. That isn't actually supported: crypto_alloc_skcipher() takes crypto_alg_sem which isn't GFP_NOIO safe, and it can also load kernel modules.

Note that ceph_aes_crypt() verifies only a single padding byte rather than all of them. That's probably a bug. But I've left it unchanged, as fixing it is outside the scope of this commit.

---
 net/ceph/Kconfig  |  3 +--
 net/ceph/crypto.c | 66 ++++++++++-------------------------------------
 net/ceph/crypto.h |  3 ++-
 3 files changed, 16 insertions(+), 56 deletions(-)
net/ceph/Kconfig +1 -2
index 7e2528cde4b9..74aa2817253b 100644
@@ -3,10 +3,9 @@ config CEPH_LIB
 	tristate "Ceph core library"
 	depends on INET
 	select CRC32
-	select CRYPTO_AES
-	select CRYPTO_CBC
 	select CRYPTO_GCM
 	select CRYPTO_KRB5
+	select CRYPTO_LIB_AES_CBC
 	select CRYPTO_LIB_SHA256
 	select CRYPTO
 	select KEYS
net/ceph/crypto.c +13 -53

121 lines not on this page · raw message

net/ceph/crypto.h +2 -1
index 3a2ade15abbc..d4d97565ebfb 100644
@@ -2,6 +2,7 @@
 #ifndef _FS_CEPH_CRYPTO_H
 #define _FS_CEPH_CRYPTO_H
 
+#include <crypto/aes.h>
 #include <crypto/sha2.h>
 #include <linux/ceph/types.h>
 #include <linux/ceph/buffer.h>
@@ -19,7 +20,7 @@ struct ceph_crypto_key {
 	void *key;
 
 	union {
-		struct crypto_sync_skcipher *aes_tfm;
+		struct aes_key aes_key;
 		struct {
 			struct hmac_sha256_key hmac_key;
 			const struct krb5_enctype *krb5_type;
Signature · 1 line
2.54.0
author maintainer
#36 lore raw

PATCH 22/33 libceph: Reimplement messenger v2 encryption using AES-GCM library

In reply to Eric Biggers

Significantly rework the implementation of Ceph messenger v2 to use the new AES-GCM library instead of a "gcm(aes)" crypto_aead.

This especially takes advantage of the library's support for virtual addresses and incremental en/decryption. crypto_aead only supports scatterlists and has no support for incremental operations, which created significant difficulties for the Ceph messenger v2 code.

- For decryption (receive), the new code receives and decrypts the data directly into its destination buffers, or into a bounce page when the existing rxbounce mount option is enabled. This unifies the code significantly with the non-secure case.

Previously, the entire received message tail (potentially tens of megabytes) was buffered in a list of bounce pages. Then two scatterlists were generated: one for all the different destination buffers and one for the bounce pages. Besides being very complex, the memory use was likely problematic as well. All that is removed.

- For encryption (send), similar changes are made. It differs slightly in that a bounce page is still needed unconditionally. But the single page just keeps getting reused, which is much more efficient.

As a bonus, this conversion also eliminates the broken code that intended to allocate crypto_aead objects from a GFP_NOIO context. That isn't actually supported: crypto_alloc_aead() takes crypto_alg_sem which isn't GFP_NOIO safe, and it can also load kernel modules.

Note: incremental GCM decryption is sometimes perceived as dangerous, as it invites users to consume data before the auth tag is verified. It does seem to be safe here though, as success isn't reported up the stack until the very end. (Also, the old code didn't verify the tag until the data had already been written into the destination buffers either.)

---
 include/linux/ceph/messenger.h |  22 +-
 net/ceph/Kconfig               |   2 +-
 net/ceph/messenger_v2.c        | 963 ++++++++++++---------------------
 3 files changed, 357 insertions(+), 630 deletions(-)
include/linux/ceph/messenger.h +8 -14
index 6aa4c6478c9f..eda9729023ef 100644
@@ -2,9 +2,9 @@
 #ifndef __FS_CEPH_MESSENGER_H
 #define __FS_CEPH_MESSENGER_H
 
+#include <crypto/aes-gcm.h>
 #include <crypto/sha2.h>
 #include <linux/bvec.h>
-#include <linux/crypto.h>
 #include <linux/kref.h>
 #include <linux/mutex.h>
 #include <linux/net.h>
@@ -401,8 +401,7 @@ struct ceph_connection_v2_info {
 
 	struct iov_iter out_iter;
 	struct kvec out_kvecs[8];  /* sendmsg */
-	struct bio_vec out_bvec;  /* sendpage (out_cursor, out_zero),
-				     sendmsg (out_enc_pages) */
+	struct bio_vec out_bvec; /* sendpage (out_cursor, out_zero) */
 	int out_kvec_cnt;
 	int out_state;  /* OUT_S_* */
 
@@ -415,20 +414,15 @@ struct ceph_connection_v2_info {
 
 	struct hmac_sha256_key hmac_key;  /* post-auth signature */
 	bool hmac_key_set;
-	struct crypto_aead *gcm_tfm;  /* on-wire encryption */
-	struct aead_request *gcm_req;
-	struct crypto_wait gcm_wait;
+	struct aes_gcm_key gcm_key; /* on-wire encryption */
+	bool gcm_key_set;
 	struct ceph_gcm_nonce in_gcm_nonce;
 	struct ceph_gcm_nonce out_gcm_nonce;
 
-	struct page **in_enc_pages;
-	int in_enc_page_cnt;
-	int in_enc_resid;
-	int in_enc_i;
-	struct page **out_enc_pages;
-	int out_enc_page_cnt;
-	int out_enc_resid;
-	int out_enc_i;
+	struct aes_gcm_ctx in_gcm_ctx;
+	struct aes_gcm_ctx out_gcm_ctx;
+	u8 *out_ciphertext;
+	u8 *out_front_middle_ciphertext;
 
 	int con_mode;  /* CEPH_CON_MODE_* */
 
net/ceph/Kconfig +1 -1
index 74aa2817253b..de9170c44ebb 100644
@@ -3,9 +3,9 @@ config CEPH_LIB
 	tristate "Ceph core library"
 	depends on INET
 	select CRC32
-	select CRYPTO_GCM
 	select CRYPTO_KRB5
 	select CRYPTO_LIB_AES_CBC
+	select CRYPTO_LIB_AES_GCM
 	select CRYPTO_LIB_SHA256
 	select CRYPTO
 	select KEYS
net/ceph/messenger_v2.c +348 -615

1,339 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#37 lore raw

PATCH 23/33 wifi: mac80211: Use AES-CTR library in fils_aead.c

In reply to Eric Biggers

Now that there's a library API for AES-CTR, use it instead of a "ctr(aes)" crypto_skcipher in aes_siv_encrypt() and aes_siv_decrypt(). This significantly simplifies the code.

Further simplify both aes_siv_encrypt() and aes_siv_decrypt() by memmove()ing the source data to the destination buffer (which is offset by 16 bytes from the source), then doing AES-CTR in-place. This eliminates the need for the temporary buffer in aes_siv_encrypt(), or to rely on an unsupported overlapped operation in aes_siv_decrypt(). The latter was technically a bug, though presumably it worked accidentally.

Finally, also fix the auth tag verification to use crypto_memneq().

---
 net/mac80211/Kconfig     |  1 +
 net/mac80211/fils_aead.c | 90 ++++++++++++----------------------------
 2 files changed, 27 insertions(+), 64 deletions(-)
net/mac80211/Kconfig +1 -0
index d6bc295e23a1..8fe97e63ff39 100644
@@ -4,6 +4,7 @@ config MAC80211
 	depends on CFG80211
 	select CRYPTO
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CTR
 	select CRYPTO_LIB_ARC4
 	select CRYPTO_AES
 	select CRYPTO_CCM
net/mac80211/fils_aead.c +26 -64

136 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#38 lore raw

PATCH 24/33 wifi: mac80211: Use AES-GCM library for GMAC suite

In reply to Eric Biggers

Now that there's a library API for AES-GCM (of which AES-GMAC is a special case), for implementing the GMAC cipher suite use it instead of a "gcm(aes)" crypto_aead. This significantly simplifies the code and eliminates per-skb heap allocations.

As a bonus, ieee80211_crypto_aes_gmac_decrypt() no longer needs to allocate 'mic' on the heap, since it no longer needs to be representable as a scatterlist for crypto_aead.

---
 net/mac80211/Kconfig    |  1 +
 net/mac80211/aes_gmac.c | 85 ++++++++---------------------------------
 net/mac80211/aes_gmac.h | 10 ++---
 net/mac80211/key.c      | 11 ++----
 net/mac80211/key.h      |  3 +-
 net/mac80211/wpa.c      | 12 ++----
 6 files changed, 29 insertions(+), 93 deletions(-)
net/mac80211/Kconfig +1 -0
index 8fe97e63ff39..32808c5de0fb 100644
@@ -5,6 +5,7 @@ config MAC80211
 	select CRYPTO
 	select CRYPTO_LIB_AES_CBC_MACS
 	select CRYPTO_LIB_AES_CTR
+	select CRYPTO_LIB_AES_GCM
 	select CRYPTO_LIB_ARC4
 	select CRYPTO_AES
 	select CRYPTO_CCM
net/mac80211/aes_gmac.c +15 -70

104 lines not on this page · raw message

net/mac80211/aes_gmac.h +4 -6
index 206136b60bca..f31bdfbecf3c 100644
@@ -6,15 +6,13 @@
 #ifndef AES_GMAC_H
 #define AES_GMAC_H
 
-#include <linux/crypto.h>
+#include <crypto/aes-gcm.h>
 
 #define GMAC_AAD_LEN	20
 #define GMAC_NONCE_LEN	12
 
-struct crypto_aead *ieee80211_aes_gmac_key_setup(const u8 key[],
-						 size_t key_len);
-int ieee80211_aes_gmac(struct crypto_aead *tfm, const u8 *aad, u8 *nonce,
-		       const u8 *data, size_t data_len, u8 *mic);
-void ieee80211_aes_gmac_key_free(struct crypto_aead *tfm);
+int ieee80211_aes_gmac(const struct aes_gcm_key *key, const u8 *aad,
+		       const u8 *nonce, const u8 *data, size_t data_len,
+		       u8 *mic);
 
 #endif /* AES_GMAC_H */
net/mac80211/key.c +3 -8
index f45e792abede..48404097e4f1 100644
@@ -711,10 +711,9 @@ ieee80211_key_alloc(u32 cipher, int idx, size_t key_len,
 		/* Initialize AES key state here as an optimization so that
 		 * it does not need to be initialized for every packet.
 		 */
-		key->u.aes_gmac.tfm =
-			ieee80211_aes_gmac_key_setup(key_data, key_len);
-		if (IS_ERR(key->u.aes_gmac.tfm)) {
-			err = PTR_ERR(key->u.aes_gmac.tfm);
+		err = aes_gcm_preparekey(&key->u.aes_gmac.key, key_data,
+					 key_len, IEEE80211_GMAC_MIC_LEN);
+		if (err) {
 			kfree(key);
 			return ERR_PTR(err);
 		}
@@ -752,10 +751,6 @@ static void ieee80211_key_free_common(struct ieee80211_key *key)
 	case WLAN_CIPHER_SUITE_CCMP_256:
 		ieee80211_aes_key_free(key->u.ccmp.tfm);
 		break;
-	case WLAN_CIPHER_SUITE_BIP_GMAC_128:
-	case WLAN_CIPHER_SUITE_BIP_GMAC_256:
-		ieee80211_aes_gmac_key_free(key->u.aes_gmac.tfm);
-		break;
 	case WLAN_CIPHER_SUITE_GCMP:
 	case WLAN_CIPHER_SUITE_GCMP_256:
 		ieee80211_aes_gcm_key_free(key->u.gcmp.tfm);
net/mac80211/key.h +2 -1
index 826e4e9387c5..d2dd2a76fa25 100644
@@ -13,6 +13,7 @@
 #include <linux/crypto.h>
 #include <linux/rcupdate.h>
 #include <crypto/aes-cbc-macs.h>
+#include <crypto/aes-gcm.h>
 #include <crypto/arc4.h>
 #include <net/mac80211.h>
 
@@ -100,7 +101,7 @@ struct ieee80211_key {
 		} aes_cmac;
 		struct {
 			u8 rx_pn[IEEE80211_GMAC_PN_LEN];
-			struct crypto_aead *tfm;
+			struct aes_gcm_key key;
 			u32 replays; /* dot11RSNAStatsCMACReplays */
 			u32 icverrors; /* dot11RSNAStatsCMACICVErrors */
 		} aes_gmac;
net/mac80211/wpa.c +4 -8
index be3a2e95303c..eb4a98537395 100644
@@ -1007,7 +1007,7 @@ ieee80211_crypto_aes_gmac_encrypt(struct ieee80211_tx_data *tx)
 	bip_ipn_swap(nonce + ETH_ALEN, mmie->sequence_number);
 
 	/* MIC = AES-GMAC(IGTK, AAD || Management Frame Body || MMIE, 128) */
-	if (ieee80211_aes_gmac(key->u.aes_gmac.tfm, aad, nonce,
+	if (ieee80211_aes_gmac(&key->u.aes_gmac.key, aad, nonce,
 			       skb->data + 24, skb->len - 24, mmie->mic) < 0)
 		return TX_DROP;
 
@@ -1021,7 +1021,8 @@ ieee80211_crypto_aes_gmac_decrypt(struct ieee80211_rx_data *rx)
 	struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
 	struct ieee80211_key *key = rx->key;
 	struct ieee80211_mmie_16 *mmie;
-	u8 aad[GMAC_AAD_LEN], *mic, ipn[6], nonce[GMAC_NONCE_LEN];
+	u8 aad[GMAC_AAD_LEN], ipn[6], nonce[GMAC_NONCE_LEN];
+	u8 mic[IEEE80211_GMAC_MIC_LEN];
 	struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
 
 	if (!ieee80211_is_mgmt(hdr->frame_control))
@@ -1052,18 +1053,13 @@ ieee80211_crypto_aes_gmac_decrypt(struct ieee80211_rx_data *rx)
 		memcpy(nonce, hdr->addr2, ETH_ALEN);
 		memcpy(nonce + ETH_ALEN, ipn, 6);
 
-		mic = kmalloc(IEEE80211_GMAC_MIC_LEN, GFP_ATOMIC);
-		if (!mic)
-			return RX_DROP_U_OOM;
-		if (ieee80211_aes_gmac(key->u.aes_gmac.tfm, aad, nonce,
+		if (ieee80211_aes_gmac(&key->u.aes_gmac.key, aad, nonce,
 				       skb->data + 24, skb->len - 24,
 				       mic) < 0 ||
 		    crypto_memneq(mic, mmie->mic, sizeof(mmie->mic))) {
 			key->u.aes_gmac.icverrors++;
-			kfree(mic);
 			return RX_DROP_U_MIC_FAIL;
 		}
-		kfree(mic);
 	}
 
 	memcpy(key->u.aes_gmac.rx_pn, ipn, 6);
Signature · 1 line
2.54.0
author maintainer
#39 lore raw

PATCH 25/33 wifi: mac80211: Use crypto libraries for GCMP and CCMP suites

In reply to Eric Biggers

Now that there are library APIs for AES-GCM and AES-CCM, for the GCMP and CCMP cipher suites use them instead of "gcm(aes)" and "ccm(aes)" crypto_aeads. This significantly simplifies the code and eliminates per-skb heap allocations.

---
 net/mac80211/Kconfig    |   5 +-
 net/mac80211/Makefile   |   1 -
 net/mac80211/aead_api.c | 113 ----------------------------------------
 net/mac80211/aead_api.h |  23 --------
 net/mac80211/aes_ccm.h  |  39 +++++---------
 net/mac80211/aes_gcm.h  |  38 +++++---------
 net/mac80211/key.c      |  31 ++++-------
 net/mac80211/key.h      |   5 +-
 net/mac80211/wpa.c      |  11 ++--
 9 files changed, 45 insertions(+), 221 deletions(-)
 delete mode 100644 net/mac80211/aead_api.c
 delete mode 100644 net/mac80211/aead_api.h
net/mac80211/Kconfig +1 -4
index 32808c5de0fb..5658f089d915 100644
@@ -2,14 +2,11 @@
 config MAC80211
 	tristate "Generic IEEE 802.11 Networking Stack (mac80211)"
 	depends on CFG80211
-	select CRYPTO
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CCM
 	select CRYPTO_LIB_AES_CTR
 	select CRYPTO_LIB_AES_GCM
 	select CRYPTO_LIB_ARC4
-	select CRYPTO_AES
-	select CRYPTO_CCM
-	select CRYPTO_GCM
 	select CRC32
 	help
 	  This option enables the hardware independent IEEE 802.11
net/mac80211/Makefile +0 -1
index 36f1e3e2222b..2ae7a57565cd 100644
@@ -7,7 +7,6 @@ mac80211-y := \
 	driver-ops.o \
 	sta_info.o \
 	wep.o \
-	aead_api.o \
 	wpa.o \
 	scan.o offchannel.o \
 	ht.o agg-tx.o agg-rx.o \
net/mac80211/aead_api.c deleted +0 -113

113 lines not on this page · raw message

net/mac80211/aead_api.h deleted +0 -23
deleted file mode 100644
index 7d463b80926a..000000000000
@@ -1,23 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-only */
-
-#ifndef _AEAD_API_H
-#define _AEAD_API_H
-
-#include <crypto/aead.h>
-#include <linux/crypto.h>
-
-struct crypto_aead *
-aead_key_setup_encrypt(const char *alg, const u8 key[],
-		       size_t key_len, size_t mic_len);
-
-int aead_encrypt(struct crypto_aead *tfm, u8 *b_0, u8 *aad,
-		 size_t aad_len, u8 *data,
-		 size_t data_len, u8 *mic);
-
-int aead_decrypt(struct crypto_aead *tfm, u8 *b_0, u8 *aad,
-		 size_t aad_len, u8 *data,
-		 size_t data_len, u8 *mic);
-
-void aead_key_free(struct crypto_aead *tfm);
-
-#endif /* _AEAD_API_H */
net/mac80211/aes_ccm.h +13 -26
index 96256193cf49..f8d5e9cbf0dc 100644
@@ -7,39 +7,26 @@
 #ifndef AES_CCM_H
 #define AES_CCM_H
 
-#include "aead_api.h"
+#include <asm/byteorder.h>
+#include <crypto/aes-ccm.h>
 
 #define CCM_AAD_LEN	32
 
-static inline struct crypto_aead *
-ieee80211_aes_key_setup_encrypt(const u8 key[], size_t key_len, size_t mic_len)
+static inline int ieee80211_aes_ccm_encrypt(const struct aes_ccm_key *key,
+					    const u8 *b_0, const u8 *aad,
+					    u8 *data, size_t data_len, u8 *mic)
 {
-	return aead_key_setup_encrypt("ccm(aes)", key, key_len, mic_len);
+	return aes_ccm_encrypt(data, mic, data, data_len, aad + 2,
+			       be16_to_cpup((__be16 *)aad), b_0 + 1, 13, key);
 }
 
-static inline int
-ieee80211_aes_ccm_encrypt(struct crypto_aead *tfm,
-			  u8 *b_0, u8 *aad, u8 *data,
-			  size_t data_len, u8 *mic)
+static inline int ieee80211_aes_ccm_decrypt(const struct aes_ccm_key *key,
+					    const u8 *b_0, const u8 *aad,
+					    u8 *data, size_t data_len,
+					    const u8 *mic)
 {
-	return aead_encrypt(tfm, b_0, aad + 2,
-			    be16_to_cpup((__be16 *)aad),
-			    data, data_len, mic);
-}
-
-static inline int
-ieee80211_aes_ccm_decrypt(struct crypto_aead *tfm,
-			  u8 *b_0, u8 *aad, u8 *data,
-			  size_t data_len, u8 *mic)
-{
-	return aead_decrypt(tfm, b_0, aad + 2,
-			    be16_to_cpup((__be16 *)aad),
-			    data, data_len, mic);
-}
-
-static inline void ieee80211_aes_key_free(struct crypto_aead *tfm)
-{
-	return aead_key_free(tfm);
+	return aes_ccm_decrypt(data, data, mic, data_len, aad + 2,
+			       be16_to_cpup((__be16 *)aad), b_0 + 1, 13, key);
 }
 
 #endif /* AES_CCM_H */
net/mac80211/aes_gcm.h +13 -25
index b14093b2f7a9..ba13617aeb75 100644
@@ -6,38 +6,26 @@
 #ifndef AES_GCM_H
 #define AES_GCM_H
 
-#include "aead_api.h"
+#include <asm/byteorder.h>
+#include <crypto/aes-gcm.h>
 
 #define GCM_AAD_LEN	32
 
-static inline int ieee80211_aes_gcm_encrypt(struct crypto_aead *tfm,
-					    u8 *j_0, u8 *aad,  u8 *data,
-					    size_t data_len, u8 *mic)
+static inline void ieee80211_aes_gcm_encrypt(const struct aes_gcm_key *key,
+					     const u8 *j_0, const u8 *aad,
+					     u8 *data, size_t data_len, u8 *mic)
 {
-	return aead_encrypt(tfm, j_0, aad + 2,
-			    be16_to_cpup((__be16 *)aad),
-			    data, data_len, mic);
+	aes_gcm_encrypt(data, mic, data, data_len, aad + 2,
+			be16_to_cpup((__be16 *)aad), j_0, key);
 }
 
-static inline int ieee80211_aes_gcm_decrypt(struct crypto_aead *tfm,
-					    u8 *j_0, u8 *aad, u8 *data,
-					    size_t data_len, u8 *mic)
+static inline int ieee80211_aes_gcm_decrypt(const struct aes_gcm_key *key,
+					    const u8 *j_0, const u8 *aad,
+					    u8 *data, size_t data_len,
+					    const u8 *mic)
 {
-	return aead_decrypt(tfm, j_0, aad + 2,
-			    be16_to_cpup((__be16 *)aad),
-			    data, data_len, mic);
-}
-
-static inline struct crypto_aead *
-ieee80211_aes_gcm_key_setup_encrypt(const u8 key[], size_t key_len)
-{
-	return aead_key_setup_encrypt("gcm(aes)", key,
-				      key_len, IEEE80211_GCMP_MIC_LEN);
-}
-
-static inline void ieee80211_aes_gcm_key_free(struct crypto_aead *tfm)
-{
-	return aead_key_free(tfm);
+	return aes_gcm_decrypt(data, data, mic, data_len, aad + 2,
+			       be16_to_cpup((__be16 *)aad), j_0, key);
 }
 
 #endif /* AES_GCM_H */
net/mac80211/key.c +9 -22
index 48404097e4f1..8c8a82d91bf2 100644
@@ -652,10 +652,9 @@ ieee80211_key_alloc(u32 cipher, int idx, size_t key_len,
 		 * Initialize AES key state here as an optimization so that
 		 * it does not need to be initialized for every packet.
 		 */
-		key->u.ccmp.tfm = ieee80211_aes_key_setup_encrypt(
-			key_data, key_len, IEEE80211_CCMP_MIC_LEN);
-		if (IS_ERR(key->u.ccmp.tfm)) {
-			err = PTR_ERR(key->u.ccmp.tfm);
+		err = aes_ccm_preparekey(&key->u.ccmp.key, key_data, key_len,
+					 IEEE80211_CCMP_MIC_LEN);
+		if (err) {
 			kfree(key);
 			return ERR_PTR(err);
 		}
@@ -670,10 +669,9 @@ ieee80211_key_alloc(u32 cipher, int idx, size_t key_len,
 		/* Initialize AES key state here as an optimization so that
 		 * it does not need to be initialized for every packet.
 		 */
-		key->u.ccmp.tfm = ieee80211_aes_key_setup_encrypt(
-			key_data, key_len, IEEE80211_CCMP_256_MIC_LEN);
-		if (IS_ERR(key->u.ccmp.tfm)) {
-			err = PTR_ERR(key->u.ccmp.tfm);
+		err = aes_ccm_preparekey(&key->u.ccmp.key, key_data, key_len,
+					 IEEE80211_CCMP_256_MIC_LEN);
+		if (err) {
 			kfree(key);
 			return ERR_PTR(err);
 		}
@@ -729,10 +727,9 @@ ieee80211_key_alloc(u32 cipher, int idx, size_t key_len,
 		/* Initialize AES key state here as an optimization so that
 		 * it does not need to be initialized for every packet.
 		 */
-		key->u.gcmp.tfm = ieee80211_aes_gcm_key_setup_encrypt(key_data,
-								      key_len);
-		if (IS_ERR(key->u.gcmp.tfm)) {
-			err = PTR_ERR(key->u.gcmp.tfm);
+		err = aes_gcm_preparekey(&key->u.gcmp.key, key_data, key_len,
+					 IEEE80211_GCMP_MIC_LEN);
+		if (err) {
 			kfree(key);
 			return ERR_PTR(err);
 		}
@@ -746,16 +743,6 @@ ieee80211_key_alloc(u32 cipher, int idx, size_t key_len,
 
 static void ieee80211_key_free_common(struct ieee80211_key *key)
 {
-	switch (key->conf.cipher) {
-	case WLAN_CIPHER_SUITE_CCMP:
-	case WLAN_CIPHER_SUITE_CCMP_256:
-		ieee80211_aes_key_free(key->u.ccmp.tfm);
-		break;
-	case WLAN_CIPHER_SUITE_GCMP:
-	case WLAN_CIPHER_SUITE_GCMP_256:
-		ieee80211_aes_gcm_key_free(key->u.gcmp.tfm);
-		break;
-	}
 	kfree_sensitive(key);
 }
 
net/mac80211/key.h +3 -2
index d2dd2a76fa25..a43db120f61c 100644
@@ -13,6 +13,7 @@
 #include <linux/crypto.h>
 #include <linux/rcupdate.h>
 #include <crypto/aes-cbc-macs.h>
+#include <crypto/aes-ccm.h>
 #include <crypto/aes-gcm.h>
 #include <crypto/arc4.h>
 #include <net/mac80211.h>
@@ -90,7 +91,7 @@ struct ieee80211_key {
 			 * Management frames.
 			 */
 			u8 rx_pn[IEEE80211_NUM_TIDS + 1][IEEE80211_CCMP_PN_LEN];
-			struct crypto_aead *tfm;
+			struct aes_ccm_key key;
 			u32 replays; /* dot11RSNAStatsCCMPReplays */
 		} ccmp;
 		struct {
@@ -112,7 +113,7 @@ struct ieee80211_key {
 			 * Management frames.
 			 */
 			u8 rx_pn[IEEE80211_NUM_TIDS + 1][IEEE80211_GCMP_PN_LEN];
-			struct crypto_aead *tfm;
+			struct aes_gcm_key key;
 			u32 replays; /* dot11RSNAStatsGCMPReplays */
 		} gcmp;
 		struct {
net/mac80211/wpa.c +6 -5
index eb4a98537395..db57d383606f 100644
@@ -492,7 +492,7 @@ static int ccmp_encrypt_skb(struct ieee80211_tx_data *tx, struct sk_buff *skb,
 	ccmp_special_blocks(skb, pn, b_0, aad,
 			    key->conf.flags & IEEE80211_KEY_FLAG_SPP_AMSDU,
 			    false);
-	return ieee80211_aes_ccm_encrypt(key->u.ccmp.tfm, b_0, aad, pos, len,
+	return ieee80211_aes_ccm_encrypt(&key->u.ccmp.key, b_0, aad, pos, len,
 					 skb_put(skb, mic_len));
 }
 
@@ -587,7 +587,7 @@ ieee80211_crypto_ccmp_decrypt(struct ieee80211_rx_data *rx,
 					    aad_nonce_computed);
 
 			if (ieee80211_aes_ccm_decrypt(
-				    key->u.ccmp.tfm, b_0, aad,
+				    &key->u.ccmp.key, b_0, aad,
 				    skb->data + hdrlen + IEEE80211_CCMP_HDR_LEN,
 				    data_len,
 				    skb->data + skb->len - mic_len))
@@ -709,8 +709,9 @@ static int gcmp_encrypt_skb(struct ieee80211_tx_data *tx, struct sk_buff *skb)
 	gcmp_special_blocks(skb, pn, j_0, aad,
 			    key->conf.flags & IEEE80211_KEY_FLAG_SPP_AMSDU,
 			    false);
-	return ieee80211_aes_gcm_encrypt(key->u.gcmp.tfm, j_0, aad, pos, len,
-					 skb_put(skb, IEEE80211_GCMP_MIC_LEN));
+	ieee80211_aes_gcm_encrypt(&key->u.gcmp.key, j_0, aad, pos, len,
+				  skb_put(skb, IEEE80211_GCMP_MIC_LEN));
+	return 0;
 }
 
 ieee80211_tx_result
@@ -798,7 +799,7 @@ ieee80211_crypto_gcmp_decrypt(struct ieee80211_rx_data *rx)
 					    aad_nonce_computed);
 
 			if (ieee80211_aes_gcm_decrypt(
-				    key->u.gcmp.tfm, j_0, aad,
+				    &key->u.gcmp.key, j_0, aad,
 				    skb->data + hdrlen + IEEE80211_GCMP_HDR_LEN,
 				    data_len,
 				    skb->data + skb->len -
Signature · 1 line
2.54.0
author maintainer
#40 lore raw

PATCH 26/33 macsec: Use AES-GCM library instead of crypto_aead

In reply to Eric Biggers

Now that there's a library API for AES-GCM, use it instead of a "gcm(aes)" crypto_aead. This significantly simplifies the code.

Notably, per-skb dynamic memory allocations and conversions to scatterlists are eliminated. We now just iterate through the skb's data and process it directly.

Asynchronous en/decryption operations are no longer supported, as that execution model has been found to not be beneficial.

---
 drivers/net/Kconfig  |   4 +-
 drivers/net/macsec.c | 327 ++++++++++++++-----------------------------
 include/net/macsec.h |   5 +-
 3 files changed, 106 insertions(+), 230 deletions(-)
drivers/net/Kconfig +1 -3
index ff79c466712d..e7322d5a1164 100644
@@ -317,9 +317,7 @@ config AMT
 
 config MACSEC
 	tristate "IEEE 802.1AE MAC-level encryption (MACsec)"
-	select CRYPTO
-	select CRYPTO_AES
-	select CRYPTO_GCM
+	select CRYPTO_LIB_AES_GCM
 	select GRO_CELLS
 	help
 	   MACsec is an encryption standard for Ethernet.
drivers/net/macsec.c +102 -225

488 lines not on this page · raw message

include/net/macsec.h +3 -2
index d962093ee923..a315a33b3ac3 100644
@@ -7,6 +7,7 @@
 #ifndef _NET_MACSEC_H_
 #define _NET_MACSEC_H_
 
+#include <crypto/aes-gcm.h>
 #include <linux/u64_stats_sync.h>
 #include <linux/if_vlan.h>
 #include <linux/workqueue.h>
@@ -63,12 +64,12 @@ typedef union pn {
 /**
  * struct macsec_key - SA key
  * @id: user-provided key identifier
- * @tfm: crypto struct, key storage
+ * @gcm_key: the AES-GCM key
  * @salt: salt used to generate IV in XPN cipher suites
  */
 struct macsec_key {
 	u8 id[MACSEC_KEYID_LEN];
-	struct crypto_aead *tfm;
+	struct aes_gcm_key gcm_key;
 	salt_t salt;
 };
 
Signature · 1 line
2.54.0
author maintainer
#41 lore raw

PATCH 27/33 wifi: ipw2x00: Use AES-CCM library

In reply to Eric Biggers

Now that there's a library API for AES-CCM, use it instead of a "ccm(aes)" crypto_aead.

This significantly simplifies the code:

- Dynamic memory allocations go away, including ones during Tx and Rx.

- The additional authenticated data is now just constructed on the stack, as it no longer needs to be representable in a scatterlist.

- The AES-CCM library supports variable-length nonces via the self-explanatory nonce_len parameter, so for the needed 13-byte nonce just use that instead of the odd workaround used by "ccm(aes)" where the nonce was prefixed with a byte containing '14 - nonce_len'.

---
 drivers/net/wireless/intel/ipw2x00/Kconfig    |   2 +-
 .../intel/ipw2x00/libipw_crypto_ccmp.c        | 117 +++++-------------
 2 files changed, 29 insertions(+), 90 deletions(-)
drivers/net/wireless/intel/ipw2x00/Kconfig +1 -1
index b508f14542d5..a1073d34f634 100644
@@ -153,8 +153,8 @@ config LIBIPW
 	tristate
 	depends on PCI && CFG80211
 	select WIRELESS_EXT
-	select CRYPTO
 	select CRYPTO_LIB_ARC4
+	select CRYPTO_LIB_AES_CCM
 	select CRC32
 	help
 	This option enables the hardware independent IEEE 802.11
drivers/net/wireless/intel/ipw2x00/libipw_crypto_ccmp.c +28 -89

203 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#42 lore raw

PATCH 28/33 mac802154: Use AES-CCM and AES-CTR libraries

In reply to Eric Biggers

Now that there are library APIs for AES-CCM and AES-CTR, use these instead of "ccm(aes)" crypto_aeads and a "ctr(aes)" crypto_skcipher.

This significantly simplifies the code, especially considering that the existing code already supported only linear skbs anyway.

Note that as before, 'struct mac802154_llsec_key' contains four copies of the same key prepared in different ways: one for AES-CTR, and one for each AES-CCM authentication tag length 4, 8, and 16 bytes. That continues to be wasteful; however, the crypto APIs are very much working as intended in tying the key to the algorithm and authentication tag length. It shows this driver is doing something wrong by reusing the same key for multiple purposes. At some point this driver will need to be fixed to allow keys with only one algorithm and tag length at a time, but that's outside the scope of this cleanup.

---
 net/mac802154/Kconfig |   6 +-
 net/mac802154/llsec.c | 158 +++++++++++++-----------------------------
 net/mac802154/llsec.h |   8 ++-
 3 files changed, 55 insertions(+), 117 deletions(-)
net/mac802154/Kconfig +1 -5
index 901167b1e6f5..5195556670fa 100644
@@ -3,11 +3,7 @@ config MAC802154
 	tristate "Generic IEEE 802.15.4 Soft Networking Stack (mac802154)"
 	depends on IEEE802154
 	select CRC_CCITT
-	select CRYPTO
-	select CRYPTO_AUTHENC
-	select CRYPTO_CCM
-	select CRYPTO_CTR
-	select CRYPTO_AES
+	select CRYPTO_LIB_AES_CCM
 	help
 	  This option enables the hardware independent IEEE 802.15.4
 	  networking stack for SoftMAC devices (the ones implementing
net/mac802154/llsec.c +49 -109

260 lines not on this page · raw message

net/mac802154/llsec.h +5 -3
index ddeb79228204..2b9815dbe38f 100644
@@ -9,6 +9,8 @@
 #ifndef MAC802154_LLSEC_H
 #define MAC802154_LLSEC_H
 
+#include <crypto/aes-ccm.h>
+#include <crypto/aes-ctr.h>
 #include <linux/slab.h>
 #include <linux/hashtable.h>
 #include <linux/kref.h>
@@ -19,9 +21,9 @@
 struct mac802154_llsec_key {
 	struct ieee802154_llsec_key key;
 
-	/* one tfm for each authsize (4/8/16) */
-	struct crypto_aead *tfm[3];
-	struct crypto_sync_skcipher *tfm0;
+	/* one for each authsize (4/8/16) */
+	struct aes_ccm_key ccm_keys[3];
+	struct aes_enckey ctr_key;
 
 	struct kref ref;
 };
Signature · 1 line
2.54.0
author maintainer
#43 lore raw

PATCH 29/33 bpf: crypto: Use AES-CBC and AES-ECB libraries

In reply to Eric Biggers

BPF crypto was implemented using the lskcipher API, which doesn't seem to be going anywhere. It supports only "arc4", "cbc(aes)", "ecb(aes)", and only with unoptimized implementations.

Library APIs also have been found to be a much better approach, for a variety of reasons, including reduced overhead, greater flexibility, and having to be explicit about the crypto algorithms that are supported.

We can safely ignore the theoretical "arc4" support in BPF crypto as unused, which leaves "cbc(aes)" and "ecb(aes)". Why these algorithms were chosen, it's unclear. Regardless, I'll assume that "cbc(aes)" and "ecb(aes)" need to continue to be supported for backwards compatibility.

There are library APIs for these now, which are much easier to use and more efficient. Reimplement BPF crypto on top of them, greatly simplifying the code. As part of this, the bpf_crypto_type abstraction layer is removed, as it's not useful.

---
 MAINTAINERS                  |   2 -
 crypto/Makefile              |   3 -
 crypto/bpf_crypto_skcipher.c |  83 -----------
 include/linux/bpf_crypto.h   |  24 ----
 kernel/bpf/Kconfig           |  12 ++
 kernel/bpf/Makefile          |   4 +-
 kernel/bpf/crypto.c          | 270 ++++++++++++++---------------------
 7 files changed, 124 insertions(+), 274 deletions(-)
 delete mode 100644 crypto/bpf_crypto_skcipher.c
 delete mode 100644 include/linux/bpf_crypto.h
MAINTAINERS +0 -2
index 4a8b0fd665ce..6585b1a26563 100644
@@ -4894,8 +4894,6 @@ BPF [CRYPTO]
 M:	Vadim Fedorenko <[email protected]>
 L:	[email protected]
 S:	Maintained
-F:	crypto/bpf_crypto_skcipher.c
-F:	include/linux/bpf_crypto.h
 F:	kernel/bpf/crypto.c
 
 BPF [DOCUMENTATION] (Related to Standardization)
crypto/Makefile +0 -3
index 8386d55a9755..33bb5ad595e8 100644
@@ -22,9 +22,6 @@ crypto_skcipher-y += lskcipher.o
 crypto_skcipher-y += skcipher.o
 
 obj-$(CONFIG_CRYPTO_SKCIPHER2) += crypto_skcipher.o
-ifeq ($(CONFIG_BPF_SYSCALL),y)
-obj-$(CONFIG_CRYPTO_SKCIPHER2) += bpf_crypto_skcipher.o
-endif
 
 obj-$(CONFIG_CRYPTO_SEQIV) += seqiv.o
 obj-$(CONFIG_CRYPTO_ECHAINIV) += echainiv.o
crypto/bpf_crypto_skcipher.c deleted +0 -83

83 lines not on this page · raw message

include/linux/bpf_crypto.h deleted +0 -24
deleted file mode 100644
index a41e71d4e2d9..000000000000
@@ -1,24 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-only */
-/* Copyright (c) 2024 Meta Platforms, Inc. and affiliates. */
-#ifndef _BPF_CRYPTO_H
-#define _BPF_CRYPTO_H
-
-struct bpf_crypto_type {
-	void *(*alloc_tfm)(const char *algo);
-	void (*free_tfm)(void *tfm);
-	int (*has_algo)(const char *algo);
-	int (*setkey)(void *tfm, const u8 *key, unsigned int keylen);
-	int (*setauthsize)(void *tfm, unsigned int authsize);
-	int (*encrypt)(void *tfm, const u8 *src, u8 *dst, unsigned int len, u8 *iv);
-	int (*decrypt)(void *tfm, const u8 *src, u8 *dst, unsigned int len, u8 *iv);
-	unsigned int (*ivsize)(void *tfm);
-	unsigned int (*statesize)(void *tfm);
-	u32 (*get_flags)(void *tfm);
-	struct module *owner;
-	char name[14];
-};
-
-int bpf_crypto_register_type(const struct bpf_crypto_type *type);
-int bpf_crypto_unregister_type(const struct bpf_crypto_type *type);
-
-#endif /* _BPF_CRYPTO_H */
kernel/bpf/Kconfig +12 -0
index eb3de35734f0..c4f1086b2daf 100644
@@ -87,6 +87,18 @@ config BPF_UNPRIV_DEFAULT_OFF
 
 	  If you are unsure how to answer this question, answer Y.
 
+config BPF_CRYPTO
+	def_bool y
+	depends on BPF_SYSCALL
+	select CRYPTO_LIB_AES_CBC
+	select CRYPTO_LIB_AES_ECB
+	help
+	  Provide the kfuncs needed for BPF programs to encrypt and decrypt
+	  data. The supported algorithms are:
+
+	    - AES-CBC
+	    - AES-ECB
+
 source "kernel/bpf/preload/Kconfig"
 
 config BPF_LSM
kernel/bpf/Makefile +1 -3
index 4dc41bf5780c..42899bfcbd82 100644
@@ -55,9 +55,7 @@ obj-$(CONFIG_BPF_SYSCALL) += cpumask.o
 # semantics within pahole are revisited accordingly.
 obj-${CONFIG_BPF_LSM} += bpf_lsm_proto.o bpf_lsm.o
 endif
-ifneq ($(CONFIG_CRYPTO),)
-obj-$(CONFIG_BPF_SYSCALL) += crypto.o
-endif
+obj-$(CONFIG_BPF_CRYPTO) += crypto.o
 obj-$(CONFIG_BPF_PRELOAD) += preload/
 
 obj-$(CONFIG_BPF_SYSCALL) += relo_core.o
kernel/bpf/crypto.c +111 -159

390 lines not on this page · raw message

Signature · 1 line
2.54.0
maintainer Reviewed-by on v1 29/33
#44 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

cc +bpf

Quoted 4 lines · Eric Biggers

BPF crypto was implemented using the lskcipher API, which doesn't seem to be going anywhere. It supports only "arc4", "cbc(aes)", "ecb(aes)", and only with unoptimized implementations.

Quoted 8 lines

Library APIs also have been found to be a much better approach, for a variety of reasons, including reduced overhead, greater flexibility, and having to be explicit about the crypto algorithms that are supported.

We can safely ignore the theoretical "arc4" support in BPF crypto as unused, which leaves "cbc(aes)" and "ecb(aes)". Why these algorithms were chosen, it's unclear. Regardless, I'll assume that "cbc(aes)" and "ecb(aes)" need to continue to be supported for backwards compatibility.

That was done for single use case of decrypting small blocks in TC layer with "cbc(aes)", with assumption of extending it later.

This change looks great, but it would be great to CC bpf folks just to be aware of the refactoring.

Quoted 7 lines

There are library APIs for these now, which are much easier to use and more efficient. Reimplement BPF crypto on top of them, greatly simplifying the code. As part of this, the bpf_crypto_type abstraction layer is removed, as it's not useful.

author maintainer
#45 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

Quoted 11 lines · Vadim Fedorenko

cc +bpf

Quoted 8 lines · Eric Biggers

BPF crypto was implemented using the lskcipher API, which doesn't seem to be going anywhere. It supports only "arc4", "cbc(aes)", "ecb(aes)", and only with unoptimized implementations.

Library APIs also have been found to be a much better approach, for a variety of reasons, including reduced overhead, greater flexibility, and having to be explicit about the crypto algorithms that are supported.

Quoted 7 lines
Quoted 4 lines

We can safely ignore the theoretical "arc4" support in BPF crypto as unused, which leaves "cbc(aes)" and "ecb(aes)". Why these algorithms were chosen, it's unclear. Regardless, I'll assume that "cbc(aes)" and "ecb(aes)" need to continue to be supported for backwards compatibility.

That was done for single use case of decrypting small blocks in TC layer with "cbc(aes)", with assumption of extending it later.

What protocol is using AES-CBC? And is the kernel encrypting or decrypting the data elsewhere, or it is just routing an encrypted packet and only the BPF program decrypts it?

Does this mean the AES-ECB support is unnecessary and can be dropped?

Quoted 2 lines

This change looks great, but it would be great to CC bpf folks just to be aware of the refactoring.

Sure. I'm only looking to apply patches 1-13 for now; the rest (bpf, fscrypt, keyrings, libceph, mac80211, macsec, mac802154, smb, ksmbd, tipc) are proof of concept, showing how the library APIs can be used in a wide range of kernel subsystems. I didn't want to spam the entire series to 20 mailing lists. I'll resend them individually later.

Thanks!

- Eric

maintainer
#46 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

Quoted 17 lines · Eric Biggers
Quoted 16 lines · Vadim Fedorenko

cc +bpf

Quoted 12 lines · Eric Biggers

BPF crypto was implemented using the lskcipher API, which doesn't seem to be going anywhere. It supports only "arc4", "cbc(aes)", "ecb(aes)", and only with unoptimized implementations.

Library APIs also have been found to be a much better approach, for a variety of reasons, including reduced overhead, greater flexibility, and having to be explicit about the crypto algorithms that are supported.

We can safely ignore the theoretical "arc4" support in BPF crypto as unused, which leaves "cbc(aes)" and "ecb(aes)". Why these algorithms were chosen, it's unclear. Regardless, I'll assume that "cbc(aes)" and "ecb(aes)" need to continue to be supported for backwards compatibility.

Quoted 6 lines
Quoted 2 lines

That was done for single use case of decrypting small blocks in TC layer with "cbc(aes)", with assumption of extending it later.

What protocol is using AES-CBC? And is the kernel encrypting or decrypting the data elsewhere, or it is just routing an encrypted packet and only the BPF program decrypts it?

That's a "home-made" part of UDP encapsulation, the kernel routes it further based on the info collected by BPF decrypt program.

Quoted 1 line

Does this mean the AES-ECB support is unnecessary and can be dropped?

Let's keep it if it doesn't hurt.

Quoted 8 lines
Quoted 2 lines

This change looks great, but it would be great to CC bpf folks just to be aware of the refactoring.

Sure. I'm only looking to apply patches 1-13 for now; the rest (bpf, fscrypt, keyrings, libceph, mac80211, macsec, mac802154, smb, ksmbd, tipc) are proof of concept, showing how the library APIs can be used in a wide range of kernel subsystems. I didn't want to spam the entire series to 20 mailing lists. I'll resend them individually later.

Ok, cool. But you can keep my Rb anyways - I checked the code and run tests.

Quoted 4 lines

Thanks!

- Eric

author maintainer
#47 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

Quoted 3 lines · Vadim Fedorenko
Quoted 1 line

Does this mean the AES-ECB support is unnecessary and can be dropped?

Let's keep it if it doesn't hurt.

It kind of does. It is "bad" crypto that would have to continue to be maintained, and someone might start using it accidentally.

- Eric

maintainer
#48 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

Quoted 7 lines · Eric Biggers
Quoted 3 lines · Vadim Fedorenko
Quoted 1 line

Does this mean the AES-ECB support is unnecessary and can be dropped?

Let's keep it if it doesn't hurt.

It kind of does. It is "bad" crypto that would have to continue to be maintained, and someone might start using it accidentally.

AES-ECB was introduced as a cipher to use in QUIC-LB draft, draft-ietf-quic-load-balancers-21

I know it is expired draft, but it may be worth keeping this cipher as QUIC WG github is still active

author maintainer
#49 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

Quoted 6 lines · Vadim Fedorenko
Quoted 5 lines · Eric Biggers
Quoted 3 lines · Vadim Fedorenko
Quoted 1 line

Does this mean the AES-ECB support is unnecessary and can be dropped?

Let's keep it if it doesn't hurt.

Quoted 8 lines
Quoted 2 lines

It kind of does. It is "bad" crypto that would have to continue to be maintained, and someone might start using it accidentally.

AES-ECB was introduced as a cipher to use in QUIC-LB draft, draft-ietf-quic-load-balancers-21

I know it is expired draft, but it may be worth keeping this cipher as QUIC WG github is still active

Sigh. We shouldn't implement Internet-Drafts that have clear issues with how they use cryptography. They're likely to change when they undergo cryptography review. We went through this same thing with TCP-AO, where I ended up joining the tcpm working group and getting the draft fixed. Do I need to do the same with this one too?

- Eric

maintainer
#50 lore raw

Re: [PATCH 29/33] bpf: crypto: Use AES-CBC and AES-ECB libraries

Quoted 13 lines · Eric Biggers
Quoted 12 lines · Vadim Fedorenko
Quoted 7 lines · Eric Biggers
Quoted 3 lines · Vadim Fedorenko
Quoted 1 line

Does this mean the AES-ECB support is unnecessary and can be dropped?

Let's keep it if it doesn't hurt.

It kind of does. It is "bad" crypto that would have to continue to be maintained, and someone might start using it accidentally.

AES-ECB was introduced as a cipher to use in QUIC-LB draft, draft-ietf-quic-load-balancers-21

Quoted 8 lines
Quoted 2 lines

I know it is expired draft, but it may be worth keeping this cipher as QUIC WG github is still active

Sigh. We shouldn't implement Internet-Drafts that have clear issues with how they use cryptography. They're likely to change when they undergo cryptography review. We went through this same thing with TCP-AO, where I ended up joining the tcpm working group and getting the draft fixed. Do I need to do the same with this one too?

Looks like they need some crypto expert joining WG, but I'm not currently following the group, unfortunately.

author maintainer
#51 lore raw

PATCH 30/33 bpf: crypto: Add AES-GCM support

In reply to Eric Biggers

Add AES-GCM support as requested at
https://lore.kernel.org/r/CAHAB8Wy1APeCcm7_OfrNYeZFcMXfZ5rUSeDX7-c7WO_rGg2Zig@mail.gmail.com/

With the library this is straightforward to do.

The associated data is assumed to be empty. If control over that is needed, support would need to be added for it as well.

---
 kernel/bpf/Kconfig  |  2 ++
 kernel/bpf/crypto.c | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+)
kernel/bpf/Kconfig +2 -0
index c4f1086b2daf..d14dd1788bd4 100644
@@ -92,12 +92,14 @@ config BPF_CRYPTO
 	depends on BPF_SYSCALL
 	select CRYPTO_LIB_AES_CBC
 	select CRYPTO_LIB_AES_ECB
+	select CRYPTO_LIB_AES_GCM
 	help
 	  Provide the kfuncs needed for BPF programs to encrypt and decrypt
 	  data. The supported algorithms are:
 
 	    - AES-CBC
 	    - AES-ECB
+	    - AES-GCM
 
 source "kernel/bpf/preload/Kconfig"
 
kernel/bpf/crypto.c +32 -0
index 17e0d2fd422a..934d049ee91c 100644
@@ -8,6 +8,7 @@
 #include <linux/skbuff.h>
 #include <crypto/aes-cbc.h>
 #include <crypto/aes-ecb.h>
+#include <crypto/aes-gcm.h>
 
 /* BPF crypto initialization parameters struct */
 /**
@@ -33,6 +34,7 @@ struct bpf_crypto_params {
 enum bpf_crypto_algo_id {
 	BPF_ALGO_AES_CBC,
 	BPF_ALGO_AES_ECB,
+	BPF_ALGO_AES_GCM,
 };
 
 static const struct {
@@ -42,6 +44,7 @@ static const struct {
 } bpf_crypto_algos[] = {
 	{ "skcipher", "cbc(aes)", BPF_ALGO_AES_CBC },
 	{ "skcipher", "ecb(aes)", BPF_ALGO_AES_ECB },
+	{ "aead", "gcm(aes)", BPF_ALGO_AES_GCM },
 };
 
 static bool bpf_crypto_find_algo(const struct bpf_crypto_params *params,
@@ -72,6 +75,7 @@ struct bpf_crypto_ctx {
 	enum bpf_crypto_algo_id algo;
 	union {
 		struct aes_key aes;
+		struct aes_gcm_key aes_gcm;
 	} key;
 	struct rcu_head rcu;
 	refcount_t usage;
@@ -127,6 +131,10 @@ bpf_crypto_ctx_create(const struct bpf_crypto_params *params, u32 params__sz,
 			*err = aes_preparekey(&ctx->key.aes, params->key,
 					      params->key_len);
 		break;
+	case BPF_ALGO_AES_GCM:
+		*err = aes_gcm_preparekey(&ctx->key.aes_gcm, params->key,
+					  params->key_len, params->authsize);
+		break;
 	default:
 		WARN_ON(1);
 		*err = -ENOENT;
@@ -217,6 +225,27 @@ static int bpf_aes_ecb_crypt(u8 *dst, u32 dst_len, const u8 *src, u32 src_len,
 	return 0;
 }
 
+static int bpf_aes_gcm_crypt(u8 *dst, u32 dst_len, const u8 *src, u32 src_len,
+			     u8 *iv, u32 iv_len,
+			     const struct bpf_crypto_ctx *ctx, bool decrypt)
+{
+	const struct aes_gcm_key *key = &ctx->key.aes_gcm;
+	u32 authtag_len = key->authtag_len;
+
+	if (iv_len != GCM_AES_IV_SIZE)
+		return -EINVAL;
+	if (decrypt) {
+		if (src_len < authtag_len || dst_len < src_len - authtag_len)
+			return -EINVAL;
+		return aes_gcm_decrypt(dst, src, src + src_len - authtag_len,
+				       src_len - authtag_len, NULL, 0, iv, key);
+	}
+	if (dst_len < authtag_len || dst_len - authtag_len < src_len)
+		return -EINVAL;
+	aes_gcm_encrypt(dst, dst + src_len, src, src_len, NULL, 0, iv, key);
+	return 0;
+}
+
 static int bpf_crypto_crypt(const struct bpf_crypto_ctx *ctx,
 			    const struct bpf_dynptr_kern *src,
 			    const struct bpf_dynptr_kern *dst,
@@ -254,6 +283,9 @@ static int bpf_crypto_crypt(const struct bpf_crypto_ctx *ctx,
 	case BPF_ALGO_AES_ECB:
 		return bpf_aes_ecb_crypt(pdst, dst_len, psrc, src_len, piv,
 					 iv_len, ctx, decrypt);
+	case BPF_ALGO_AES_GCM:
+		return bpf_aes_gcm_crypt(pdst, dst_len, psrc, src_len, piv,
+					 iv_len, ctx, decrypt);
 	default:
 		return -EINVAL;
 	}
Signature · 1 line
2.54.0
maintainer Reviewed-by on v1 30/33
#52 lore raw

Re: [PATCH 30/33] bpf: crypto: Add AES-GCM support

Quoted 9 lines · Eric Biggers

Add AES-GCM support as requested at
https://lore.kernel.org/r/CAHAB8Wy1APeCcm7_OfrNYeZFcMXfZ5rUSeDX7-c7WO_rGg2Zig@mail.gmail.com/

With the library this is straightforward to do.

The associated data is assumed to be empty. If control over that is needed, support would need to be added for it as well.

author maintainer
#53 lore raw

PATCH 31/33 smb: client: Use AES-GCM and AES-CCM libraries

In reply to Eric Biggers

Now that there are library APIs for AES-GCM and AES-CCM, use them instead of "gcm(aes)" and "ccm(aes)" crypto_aeads. This significantly simplifies the code, especially since the need to build scatterlists goes away.

---
 fs/smb/client/Kconfig         |   7 +-
 fs/smb/client/cifsencrypt.c   |  14 --
 fs/smb/client/cifsfs.c        |   4 -
 fs/smb/client/cifsglob.h      |   8 -
 fs/smb/client/cifsproto.h     |  89 -----------
 fs/smb/client/connect.c       |  14 +-
 fs/smb/client/smb2ops.c       | 275 ++++++++++++++++------------------
 fs/smb/client/smb2pdu.c       |   2 -
 fs/smb/client/smb2proto.h     |   1 -
 fs/smb/client/smb2transport.c |  39 -----
 10 files changed, 135 insertions(+), 318 deletions(-)
fs/smb/client/Kconfig +2 -5
index 2b7db5fb0fd9..5d3e4024b6b5 100644
@@ -4,12 +4,9 @@ config CIFS
 	depends on INET
 	select NLS
 	select NLS_UCS2_UTILS
-	select CRYPTO
-	select CRYPTO_AEAD2
-	select CRYPTO_CCM
-	select CRYPTO_GCM
-	select CRYPTO_AES
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CCM
+	select CRYPTO_LIB_AES_GCM
 	select CRYPTO_LIB_ARC4
 	select CRYPTO_LIB_MD5
 	select CRYPTO_LIB_SHA256
fs/smb/client/cifsencrypt.c +0 -14
index 34804e9842a8..5db6d26e933d 100644
@@ -21,7 +21,6 @@
 #include <linux/highmem.h>
 #include <linux/fips.h>
 #include <linux/iov_iter.h>
-#include <crypto/aead.h>
 #include <crypto/aes-cbc-macs.h>
 #include <crypto/arc4.h>
 #include <crypto/md5.h>
@@ -499,16 +498,3 @@ calc_seckey(struct cifs_ses *ses)
 	kfree_sensitive(ctx_arc4);
 	return 0;
 }
-
-void
-cifs_crypto_secmech_release(struct TCP_Server_Info *server)
-{
-	if (server->secmech.enc) {
-		crypto_free_aead(server->secmech.enc);
-		server->secmech.enc = NULL;
-	}
-	if (server->secmech.dec) {
-		crypto_free_aead(server->secmech.dec);
-		server->secmech.dec = NULL;
-	}
-}
fs/smb/client/cifsfs.c +0 -4
index ea4fc0fa68ca..609fd0fb2285 100644
@@ -2198,9 +2198,5 @@ MODULE_DESCRIPTION
 	"also older servers complying with the SNIA CIFS Specification)");
 MODULE_VERSION(CIFS_VERSION);
 MODULE_SOFTDEP("nls");
-MODULE_SOFTDEP("aes");
-MODULE_SOFTDEP("aead2");
-MODULE_SOFTDEP("ccm");
-MODULE_SOFTDEP("gcm");
 module_init(init_cifs)
 module_exit(exit_cifs)
fs/smb/client/cifsglob.h +0 -8
index 99f9e6dca62b..c14b55365770 100644
@@ -13,7 +13,6 @@
 #include <linux/in6.h>
 #include <linux/inet.h>
 #include <linux/slab.h>
-#include <linux/scatterlist.h>
 #include <linux/mm.h>
 #include <linux/mempool.h>
 #include <linux/workqueue.h>
@@ -220,12 +219,6 @@ struct session_key {
 	char *response;
 };
 
-/* encryption related structure/fields, not specific to a sec mech */
-struct cifs_secmech {
-	struct crypto_aead *enc; /* smb3 encryption AEAD TFM (AES-CCM and AES-GCM) */
-	struct crypto_aead *dec; /* smb3 decryption AEAD TFM (AES-CCM and AES-GCM) */
-};
-
 /* per smb session structure/fields */
 struct ntlmssp_auth {
 	bool sesskey_per_smbsess; /* whether session key is per smb session */
@@ -745,7 +738,6 @@ struct TCP_Server_Info {
 	unsigned long lstrp; /* when we got last response from this server */
 	unsigned long neg_start; /* when negotiate started (jiffies) */
 	unsigned long reconn_delay; /* when resched session and tcon reconnect */
-	struct cifs_secmech secmech; /* crypto sec mech functs, descriptors */
 #define	CIFS_NEGFLAVOR_UNENCAP	1	/* wct == 17, but no ext_sec */
 #define	CIFS_NEGFLAVOR_EXTENDED	2	/* wct == 17, ext_sec bit set */
 	char	negflavor;	/* NEGOTIATE response flavor */
fs/smb/client/cifsproto.h +0 -89

101 lines not on this page · raw message

fs/smb/client/connect.c +5 -9
index 85aec302c89e..77454380fe26 100644
@@ -1730,8 +1730,6 @@ cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
 	server->tcpStatus = CifsExiting;
 	spin_unlock(&server->srv_lock);
 
-	cifs_crypto_secmech_release(server);
-
 	kfree_sensitive(server->session_key.response);
 	server->session_key.response = NULL;
 	server->session_key.len = 0;
@@ -1848,7 +1846,7 @@ cifs_get_tcp_session(struct smb3_fs_context *ctx,
 #ifndef CONFIG_CIFS_SMB_DIRECT
 		cifs_dbg(VFS, "CONFIG_CIFS_SMB_DIRECT is not enabled\n");
 		rc = -ENOENT;
-		goto out_err_crypto_release;
+		goto out_err_put_net;
 #endif
 		tcp_ses->smbd_conn = smbd_get_connection(
 			tcp_ses, (struct sockaddr *)&ctx->dstaddr);
@@ -1858,13 +1856,13 @@ cifs_get_tcp_session(struct smb3_fs_context *ctx,
 			goto smbd_connected;
 		} else {
 			rc = -ENOENT;
-			goto out_err_crypto_release;
+			goto out_err_put_net;
 		}
 	}
 	rc = ip_connect(tcp_ses);
 	if (rc < 0) {
 		cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
-		goto out_err_crypto_release;
+		goto out_err_put_net;
 	}
 smbd_connected:
 	/*
@@ -1895,7 +1893,7 @@ cifs_get_tcp_session(struct smb3_fs_context *ctx,
 		rc = PTR_ERR(tcp_ses->tsk);
 		cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
 		module_put(THIS_MODULE);
-		goto out_err_crypto_release;
+		goto out_err_put_net;
 	}
 	/* thread created, put it on the list */
 	spin_lock(&cifs_tcp_ses_lock);
@@ -1913,9 +1911,7 @@ cifs_get_tcp_session(struct smb3_fs_context *ctx,
 
 	return tcp_ses;
 
-out_err_crypto_release:
-	cifs_crypto_secmech_release(tcp_ses);
-
+out_err_put_net:
 	put_net(cifs_net_ns(tcp_ses));
 
 out_err:
fs/smb/client/smb2ops.c +128 -147

348 lines not on this page · raw message

fs/smb/client/smb2pdu.c +0 -2
index 95c0efe9d43b..3eb8bd1e7a6b 100644
@@ -1343,8 +1343,6 @@ SMB2_negotiate(const unsigned int xid,
 			cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
 	}
 
-	if (server->cipher_type && !rc)
-		rc = smb3_crypto_aead_allocate(server);
 neg_exit:
 	free_rsp_buf(resp_buftype, rsp);
 	return rc;
fs/smb/client/smb2proto.h +0 -1
index 78a4e1c340f9..141d8d1336a5 100644
@@ -113,7 +113,6 @@ int smb2_unlock_range(struct cifsFileInfo *cfile, struct file_lock *flock,
 		      const unsigned int xid);
 int smb2_push_mandatory_locks(struct cifsFileInfo *cfile);
 void smb2_reconnect_server(struct work_struct *work);
-int smb3_crypto_aead_allocate(struct TCP_Server_Info *server);
 unsigned long smb_rqst_len(struct TCP_Server_Info *server,
 			   struct smb_rqst *rqst);
 void smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst);
fs/smb/client/smb2transport.c +0 -39
index 1143ee52470a..23884e311939 100644
@@ -18,7 +18,6 @@
 #include <asm/processor.h>
 #include <linux/mempool.h>
 #include <linux/highmem.h>
-#include <crypto/aead.h>
 #include <crypto/aes-cbc-macs.h>
 #include <crypto/sha2.h>
 #include <crypto/utils.h>
@@ -776,41 +775,3 @@ smb2_setup_async_request(struct TCP_Server_Info *server, struct smb_rqst *rqst)
 
 	return mid;
 }
-
-int
-smb3_crypto_aead_allocate(struct TCP_Server_Info *server)
-{
-	struct crypto_aead *tfm;
-
-	if (!server->secmech.enc) {
-		if ((server->cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
-		    (server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
-			tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
-		else
-			tfm = crypto_alloc_aead("ccm(aes)", 0, 0);
-		if (IS_ERR(tfm)) {
-			cifs_server_dbg(VFS, "%s: Failed alloc encrypt aead\n",
-				 __func__);
-			return PTR_ERR(tfm);
-		}
-		server->secmech.enc = tfm;
-	}
-
-	if (!server->secmech.dec) {
-		if ((server->cipher_type == SMB2_ENCRYPTION_AES128_GCM) ||
-		    (server->cipher_type == SMB2_ENCRYPTION_AES256_GCM))
-			tfm = crypto_alloc_aead("gcm(aes)", 0, 0);
-		else
-			tfm = crypto_alloc_aead("ccm(aes)", 0, 0);
-		if (IS_ERR(tfm)) {
-			crypto_free_aead(server->secmech.enc);
-			server->secmech.enc = NULL;
-			cifs_server_dbg(VFS, "%s: Failed to alloc decrypt aead\n",
-				 __func__);
-			return PTR_ERR(tfm);
-		}
-		server->secmech.dec = tfm;
-	}
-
-	return 0;
-}
Signature · 1 line
2.54.0
author maintainer
#54 lore raw

PATCH 32/33 ksmbd: Use AES-GCM and AES-CCM libraries

In reply to Eric Biggers

Now that there are library APIs for AES-GCM and AES-CCM, use them instead of "gcm(aes)" and "ccm(aes)" crypto_aeads. This significantly simplifies the code, especially since the pool of crypto_aead objects and all the scatterlist building code go away.

Move the encryption and decryption code directly into smb3_decrypt_req() and smb3_encrypt_resp() to take advantage of their respective data layouts.

---
 fs/smb/server/Kconfig      |   6 +-
 fs/smb/server/Makefile     |   2 +-
 fs/smb/server/auth.c       | 227 -------------------------------------
 fs/smb/server/auth.h       |   2 -
 fs/smb/server/crypto_ctx.c | 176 ----------------------------
 fs/smb/server/crypto_ctx.h |  32 ------
 fs/smb/server/server.c     |  14 +--
 fs/smb/server/smb2pdu.c    | 133 +++++++++++++++++++---
 8 files changed, 124 insertions(+), 468 deletions(-)
 delete mode 100644 fs/smb/server/crypto_ctx.c
 delete mode 100644 fs/smb/server/crypto_ctx.h
fs/smb/server/Kconfig +2 -4
index 08d8b7a965a6..6b1a23d01acd 100644
@@ -6,17 +6,15 @@ config SMB_SERVER
 	select NLS
 	select NLS_UTF8
 	select NLS_UCS2_UTILS
-	select CRYPTO
 	select CRYPTO_LIB_AES_CBC_MACS
+	select CRYPTO_LIB_AES_CCM
+	select CRYPTO_LIB_AES_GCM
 	select CRYPTO_LIB_ARC4
 	select CRYPTO_LIB_DES
 	select CRYPTO_LIB_MD5
 	select CRYPTO_LIB_SHA256
 	select CRYPTO_LIB_SHA512
 	select CRYPTO_LIB_UTILS
-	select CRYPTO_AEAD2
-	select CRYPTO_CCM
-	select CRYPTO_GCM
 	select ASN1
 	select OID_REGISTRY
 	select CRC32
fs/smb/server/Makefile +1 -1
index a3e9306055e8..da1c972b9042 100644
@@ -5,7 +5,7 @@
 obj-$(CONFIG_SMB_SERVER) += ksmbd.o
 
 ksmbd-y :=	unicode.o auth.o vfs.o vfs_cache.o server.o ndr.o \
-		misc.o oplock.o connection.o ksmbd_work.o crypto_ctx.o \
+		misc.o oplock.o connection.o ksmbd_work.o \
 		mgmt/ksmbd_ida.o mgmt/user_config.o mgmt/share_config.o \
 		mgmt/tree_connect.o mgmt/user_session.o smb_common.o \
 		transport_tcp.o transport_ipc.o smbacl.o smb2pdu.o \
fs/smb/server/auth.c +0 -227

253 lines not on this page · raw message

fs/smb/server/auth.h +0 -2
index 5767aabc63c9..f438167e9cc2 100644
@@ -36,8 +36,6 @@ struct ksmbd_conn;
 struct ksmbd_work;
 struct kvec;
 
-int ksmbd_crypt_message(struct ksmbd_work *work, struct kvec *iov,
-			unsigned int nvec, int enc);
 void ksmbd_copy_gss_neg_header(void *buf);
 int ksmbd_auth_ntlmv2(struct ksmbd_conn *conn, struct ksmbd_session *sess,
 		      struct ntlmv2_resp *ntlmv2, int blen, char *domain_name,
fs/smb/server/crypto_ctx.c deleted +0 -176

176 lines not on this page · raw message

fs/smb/server/crypto_ctx.h deleted +0 -32
deleted file mode 100644
index b22c6e086f03..000000000000
@@ -1,32 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/*
- *   Copyright (C) 2019 Samsung Electronics Co., Ltd.
- */
-
-#ifndef __CRYPTO_CTX_H__
-#define __CRYPTO_CTX_H__
-
-#include <crypto/aead.h>
-
-enum {
-	CRYPTO_AEAD_AES_GCM = 16,
-	CRYPTO_AEAD_AES_CCM,
-	CRYPTO_AEAD_MAX,
-};
-
-struct ksmbd_crypto_ctx {
-	struct list_head		list;
-
-	struct crypto_aead		*ccmaes[CRYPTO_AEAD_MAX];
-};
-
-#define CRYPTO_GCM(c)		((c)->ccmaes[CRYPTO_AEAD_AES_GCM])
-#define CRYPTO_CCM(c)		((c)->ccmaes[CRYPTO_AEAD_AES_CCM])
-
-void ksmbd_release_crypto_ctx(struct ksmbd_crypto_ctx *ctx);
-struct ksmbd_crypto_ctx *ksmbd_crypto_ctx_find_gcm(void);
-struct ksmbd_crypto_ctx *ksmbd_crypto_ctx_find_ccm(void);
-void ksmbd_crypto_destroy(void);
-int ksmbd_crypto_create(void);
-
-#endif /* __CRYPTO_CTX_H__ */
fs/smb/server/server.c +1 -13
index 36a5ea4828ad..dece42e58d66 100644
@@ -19,7 +19,6 @@
 #include "connection.h"
 #include "transport_ipc.h"
 #include "mgmt/user_session.h"
-#include "crypto_ctx.h"
 #include "auth.h"
 #include "stats.h"
 #include "compress.h"
@@ -564,7 +563,6 @@ static int ksmbd_server_shutdown(void)
 	ksmbd_workqueue_destroy();
 	ksmbd_ipc_release();
 	ksmbd_conn_transport_destroy();
-	ksmbd_crypto_destroy();
 	ksmbd_free_global_file_table();
 	destroy_lease_table(NULL);
 	ksmbd_work_pool_destroy();
@@ -612,13 +610,9 @@ static int __init ksmbd_server_init(void)
 	if (ret)
 		goto err_destroy_file_table;
 
-	ret = ksmbd_crypto_create();
-	if (ret)
-		goto err_release_inode_hash;
-
 	ret = ksmbd_workqueue_init();
 	if (ret)
-		goto err_crypto_destroy;
+		goto err_release_inode_hash;
 
 	ret = ksmbd_conn_wq_init();
 	if (ret)
@@ -628,8 +622,6 @@ static int __init ksmbd_server_init(void)
 
 err_workqueue_destroy:
 	ksmbd_workqueue_destroy();
-err_crypto_destroy:
-	ksmbd_crypto_destroy();
 err_release_inode_hash:
 	ksmbd_release_inode_hash();
 err_destroy_file_table:
@@ -666,9 +658,5 @@ MODULE_AUTHOR("Namjae Jeon <[email protected]>");
 MODULE_DESCRIPTION("Linux kernel CIFS/SMB SERVER");
 MODULE_LICENSE("GPL");
 MODULE_SOFTDEP("pre: nls");
-MODULE_SOFTDEP("pre: aes");
-MODULE_SOFTDEP("pre: aead2");
-MODULE_SOFTDEP("pre: ccm");
-MODULE_SOFTDEP("pre: gcm");
 module_init(ksmbd_server_init)
 module_exit(ksmbd_server_exit)
fs/smb/server/smb2pdu.c +120 -13

186 lines not on this page · raw message

Signature · 1 line
2.54.0
maintainer Acked-by on v1 32/33
#55 lore raw

Re: [PATCH 32/33] ksmbd: Use AES-GCM and AES-CCM libraries

Quoted 11 lines · Eric Biggers

Now that there are library APIs for AES-GCM and AES-CCM, use them instead of "gcm(aes)" and "ccm(aes)" crypto_aeads. This significantly simplifies the code, especially since the pool of crypto_aead objects and all the scatterlist building code go away.

Move the encryption and decryption code directly into smb3_decrypt_req() and smb3_encrypt_resp() to take advantage of their respective data layouts.

Thanks!

author maintainer
#56 lore raw

PATCH 33/33 net: tipc: Use AES-GCM library instead of crypto_aead

In reply to Eric Biggers

Now that there's a library API for AES-GCM, use it instead of a "gcm(aes)" crypto_aead. This significantly simplifies the code.

Notably, per-skb dynamic memory allocations and conversions to scatterlists are eliminated. For encryption the skb is linear, so just call the one-shot function aes_gcm_encrypt(). For decryption, just iterate through the skb's data and decrypt it directly.

There was also an unnecessary copy of the key being made (in a crypto_aead object) for every CPU. That is removed as well. The library en/decryption functions treat struct aes_gcm_key as read-only, so it can be used by an unlimited number of threads with no contention.

Asynchronous en/decryption operations are no longer supported, as that execution model for symmetric crypto has been found to be harmful. It generated endless bugs and didn't actually improve performance.

---
 net/tipc/Kconfig  |   4 +-
 net/tipc/crypto.c | 467 ++++++++--------------------------------------
 net/tipc/msg.h    |   3 -
 net/tipc/sysctl.c |   6 +
 4 files changed, 85 insertions(+), 395 deletions(-)
net/tipc/Kconfig +1 -3
index 18f62135e47b..39fa54b04bb9 100644
@@ -38,9 +38,7 @@ config TIPC_MEDIA_UDP
 config TIPC_CRYPTO
 	bool "TIPC encryption support"
 	depends on TIPC
-	select CRYPTO
-	select CRYPTO_AES
-	select CRYPTO_GCM
+	select CRYPTO_LIB_AES_GCM
 	default y
 	help
 	  Saying Y here will enable support for TIPC encryption.
net/tipc/crypto.c +78 -389

670 lines not on this page · raw message

net/tipc/msg.h +0 -3
index c5eec16213d7..c7f0105148bb 100644
@@ -138,9 +138,6 @@ struct tipc_skb_cb {
 		u8 flags;
 	};
 	u8 reserved;
-#ifdef CONFIG_TIPC_CRYPTO
-	void *crypto_ctx;
-#endif
 } __packed;
 
 #define TIPC_SKB_CB(__skb) ((struct tipc_skb_cb *)&((__skb)->cb[0]))
net/tipc/sysctl.c +6 -0
index 30d2e06e3d8c..3e8d9def5674 100644
@@ -67,6 +67,12 @@ static struct ctl_table tipc_table[] = {
 	},
 #ifdef CONFIG_TIPC_CRYPTO
 	{
+		/*
+		 * This sysctl no longer has any effect on the way that TIPC
+		 * uses the crypto subsystem.  However, a special value can
+		 * still be written to this to trigger debug commands.  See
+		 * tipc_crypto_do_cmd().
+		 */
 		.procname	= "max_tfms",
 		.data		= &sysctl_tipc_max_tfms,
 		.maxlen		= sizeof(sysctl_tipc_max_tfms),
Signature · 1 line
2.54.0