Hello,
A TLS session uses one key pair in each direction. Each block is
encrypted and authenticated with a separate IV, but with the same key.
When MBEDTLS_USE_PSA_CRYPTO is enabled, each encryption/decryption
operation performs the key expansion. When MBEDTLS_USE_PSA_CRYPTO is
disabled, encryption/decryption reuses a context which contains the
expanded key, so there are fewer calls to key expansion. In all cases,
there are at least two calls to key expansion either near the end of the
handshake or for the first application data exchange.
By default, on x86, Mbed TLS will use AESNI (via aesni.c) if present. If
AESNI is enabled at compile time and present at runtime, it is always used.
If GDB isn't breaking on any aesni_setkey_enc_128 calls from the TLS
code, I can think of two explanations. One is that the compiler has
inlined several copies of this function and GDB is only breaking on one
of the copies. Another is that TLS might not be using AES-128 after all
— maybe it's using AES-256 or Chacha-Poly? Please double-check which
cipher suite is used, e.g. with debugging traces or Wireshark.
Best regards,
--
Gilles Peskine
Mbed TLS developer
On 12/02/2023 20:37, Mbed TLS via mbed-tls wrote:
> Hi,
>
> I'm using AES 128 GCM with TLS 1.2 and trying to understand the AES key expansion code for decrypting received SSL records.
>
> I'm not an expert on AES but as I understand it, we use the IV (4 byte salt + 8 byte explicit nonce in the received message), pad to 16 bytes, increment and use this as input to the AES key expansion for the first block of ciphertext. This produces a round key per AES round (10 rounds for AES 128). We then increment our IV as input to the key expansion and generate the rounding keys for the next block.
>
> I noticed aesni_setkey_enc_128 in aesni.c contains the Intel AES-NI instruction AESKEYGENASSIST which helps with key expansion.
>
> However, what's confusing me is when I add a breakpoint in GDB, this function is only called once, via mbedtls_ctr_drbg_seed in ctr_drbg.c. I thought we need to do the key expansion on every block, to generate the round keys?
>
> I kept looking at the code and I noticed mbedtls_aesni_crypt_ecb, which contains the Intel AES-NI instructions for performing decryption.
>
> This loads the round key via ctx->buf + ctx->rk_offset but I do not see any code updating this round key per block.
>
> Could someone please explain where the round keys are generated for each round, per block?
>
> Thanks,