From 581f773c998e38545cc831a3a56c0a13ef97a5d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Fri, 10 Apr 2026 10:11:43 +0200 Subject: [PATCH] ecp: avoid heap usage in mbedtls_ecp_mod_p448_raw() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With 64-bit limbs, we're using two 64-byte arrays on the stack. With 32-bit limbs, that's two 60-byte arrays. This is entirely acceptable, and much better than allocating all the time in a performance-critical function. Signed-off-by: Manuel Pégourié-Gonnard --- library/ecp_curves.c | 35 ++++++----------------------------- library/ecp_invasive.h | 2 -- 2 files changed, 6 insertions(+), 31 deletions(-) diff --git a/library/ecp_curves.c b/library/ecp_curves.c index 34f87df167..d64a6120a2 100644 --- a/library/ecp_curves.c +++ b/library/ecp_curves.c @@ -5533,32 +5533,15 @@ static void ecp_shift_l_224(mbedtls_mpi_uint *X) MBEDTLS_STATIC_TESTABLE int mbedtls_ecp_mod_p448_raw(mbedtls_mpi_uint *X, size_t X_limbs) { - size_t round; - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - if (X_limbs != BITS_TO_LIMBS(448) * 2) { return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; } /* Both M and Q require an extra limb to catch carries. */ - size_t M_limbs = BITS_TO_LIMBS(448) + 1; - - const size_t Q_limbs = M_limbs; - mbedtls_mpi_uint *M = NULL; - mbedtls_mpi_uint *Q = NULL; - - M = mbedtls_calloc(M_limbs, ciL); - - if (M == NULL) { - return MBEDTLS_ERR_ECP_ALLOC_FAILED; - } - - Q = mbedtls_calloc(Q_limbs, ciL); - - if (Q == NULL) { - ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; - goto cleanup; - } + mbedtls_mpi_uint M[P448_WIDTH + 1]; + mbedtls_mpi_uint Q[P448_WIDTH + 1]; + const size_t M_limbs = P448_WIDTH + 1; + const size_t Q_limbs = P448_WIDTH + 1; /* M = A1 */ memset(M, 0, (M_limbs * ciL)); @@ -5602,7 +5585,7 @@ int mbedtls_ecp_mod_p448_raw(mbedtls_mpi_uint *X, size_t X_limbs) * B1=0. * Using this we need to calculate: * A0 + A1 + B1 + (B0 + B1) * 2^224 = A0 + A1 + B0 * 2^224. */ - for (round = 0; round < 2; ++round) { + for (size_t round = 0; round < 2; ++round) { /* M = A1 */ memset(M, 0, (M_limbs * ciL)); @@ -5626,13 +5609,7 @@ int mbedtls_ecp_mod_p448_raw(mbedtls_mpi_uint *X, size_t X_limbs) (void) mbedtls_mpi_core_add(X, X, M, M_limbs); } - ret = 0; - -cleanup: - mbedtls_free(M); - mbedtls_free(Q); - - return ret; + return 0; } #endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ diff --git a/library/ecp_invasive.h b/library/ecp_invasive.h index 8e5e25f86a..839119b517 100644 --- a/library/ecp_invasive.h +++ b/library/ecp_invasive.h @@ -277,8 +277,6 @@ int mbedtls_ecp_mod_p255_raw(mbedtls_mpi_uint *X, size_t X_limbs); * \return \c 0 on Success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if \p X does not have * twice as many limbs as the modulus. - * \return #MBEDTLS_ERR_ECP_ALLOC_FAILED if memory allocation - * failed. */ MBEDTLS_STATIC_TESTABLE int mbedtls_ecp_mod_p448_raw(mbedtls_mpi_uint *X, size_t X_limbs);