From e9aebd220ca8cac7112c3407820e68ab91b2bf89 Mon Sep 17 00:00:00 2001 From: David Garske Date: Fri, 10 Jul 2026 14:07:04 -0700 Subject: [PATCH] Fix STM32 DHUK AES-CBC in-place decrypt chaining IV and correct stale CTR comment --- wolfcrypt/src/aes.c | 6 +++--- wolfcrypt/src/port/st/stm32.c | 18 ++++++++++++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/wolfcrypt/src/aes.c b/wolfcrypt/src/aes.c index 420d3f0d78..8e10c7936c 100644 --- a/wolfcrypt/src/aes.c +++ b/wolfcrypt/src/aes.c @@ -7358,9 +7358,9 @@ int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz) xorbufout(out, in, ks, WC_AES_BLOCK_SIZE); } else { - /* The XTRANSFORM_AESCTRBLOCK macro discards this return; zero - * the block so a failed HW ECB does not leave stale/prior - * plaintext in the output. */ + /* The CTR loop breaks on this non-zero return; zero the block + * so a failed HW ECB does not leave stale/prior plaintext in + * the output. */ ForceZero(out, WC_AES_BLOCK_SIZE); } ForceZero(ks, sizeof(ks)); diff --git a/wolfcrypt/src/port/st/stm32.c b/wolfcrypt/src/port/st/stm32.c index 3ebd614861..6902039b6a 100644 --- a/wolfcrypt/src/port/st/stm32.c +++ b/wolfcrypt/src/port/st/stm32.c @@ -3729,6 +3729,21 @@ static int Stm32Dhuk_Cipher(struct wc_CryptoInfo* info) if (ret != 0) { return ret; } + /* CBC requires a non-zero, block-multiple length. Validate before the + * pre-decrypt last-block copy below so an invalid sz cannot read past + * the input buffer (mirrors the bare backend wc_Stm32_Aes_Cbc). */ + if (info->cipher.aescbc.sz == 0 || + (info->cipher.aescbc.sz % WC_AES_BLOCK_SIZE) != 0) { + return BAD_FUNC_ARG; + } + if (!info->cipher.enc) { + /* In-place decrypt overwrites the last ciphertext block, so + * capture it for the next chaining IV before the decrypt (mirrors + * the non-DHUK bare backend wc_Stm32_Aes_Cbc). */ + XMEMCPY(info->cipher.aescbc.aes->tmp, + info->cipher.aescbc.in + info->cipher.aescbc.sz + - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); + } ret = Stm32Dhuk_Aes(NULL, WC_DHUK_MODE_CBC, info->cipher.enc, info->cipher.aescbc.in, info->cipher.aescbc.sz, info->cipher.aescbc.out, @@ -3743,8 +3758,7 @@ static int Stm32Dhuk_Cipher(struct wc_CryptoInfo* info) } else { XMEMCPY(info->cipher.aescbc.aes->reg, - info->cipher.aescbc.in + info->cipher.aescbc.sz - - WC_AES_BLOCK_SIZE, WC_AES_BLOCK_SIZE); + info->cipher.aescbc.aes->tmp, WC_AES_BLOCK_SIZE); } } return ret;