From 3fed5f90f234aedcd22a1605612eb040ebeb042a Mon Sep 17 00:00:00 2001 From: Daniele Lacamera Date: Fri, 10 Jul 2026 12:13:41 +0200 Subject: [PATCH] rsa: zero wc_MakeRsaKey stack temporaries for mem-zero check wc_MakeRsaKey()'s non-small-stack path declares p/q/tmp1..3 as stack mp_ints and only mp_init's them after the argument and size checks. An early 'goto out' from those checks reaches the WOLFSSL_CHECK_MEM_ZERO cleanup, which calls mp_memzero_check() on the still-uninitialized structs; the garbage size field makes the check scan an arbitrary stack range and can false-abort on unrelated registered memory. Zero the temporaries up front (under WOLFSSL_CHECK_MEM_ZERO) so the early-out cleanup is safe. --- wolfcrypt/src/rsa.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/wolfcrypt/src/rsa.c b/wolfcrypt/src/rsa.c index cd66eab2ef..80b33c2075 100644 --- a/wolfcrypt/src/rsa.c +++ b/wolfcrypt/src/rsa.c @@ -5402,6 +5402,23 @@ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) #endif /* !WOLFSSL_CRYPTOCELL && !WOLFSSL_SE050 */ int err; +#if !defined(WOLFSSL_CRYPTOCELL) && \ + (!defined(WOLFSSL_SE050) || defined(WOLFSSL_SE050_NO_RSA)) && \ + !defined(WOLF_CRYPTO_CB_ONLY_RSA) && \ + !defined(WOLFSSL_MICROCHIP_TA100) && \ + !defined(WOLFSSL_SMALL_STACK) && defined(WOLFSSL_CHECK_MEM_ZERO) + /* Zero the stack temporaries so the mp_memzero_check() in the 'out' + * cleanup is safe even when an early argument/size check leaves via + * 'goto out' before these are mp_init'd - an uninitialized mp_int's size + * field would otherwise make the check scan an arbitrary stack range. + * Done here, after all declarations, to satisfy C89. */ + XMEMSET(&p_buf, 0, sizeof(p_buf)); + XMEMSET(&q_buf, 0, sizeof(q_buf)); + XMEMSET(&tmp1_buf, 0, sizeof(tmp1_buf)); + XMEMSET(&tmp2_buf, 0, sizeof(tmp2_buf)); + XMEMSET(&tmp3_buf, 0, sizeof(tmp3_buf)); +#endif + if (key == NULL || rng == NULL) { err = BAD_FUNC_ARG; goto out;