From 053022fe24c35fe082f4296ac9c2ac5428b499bf Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Thu, 29 Jun 2023 19:26:48 +0200 Subject: [PATCH] Reduce the size of mbedtls_mpi Reduce the size of mbedtls_mpi from 3 words to 2 on most architectures. This also reduces the code size significantly in bignum.o and ecp_curves.o, with negligible variations in other modules. This removes the ability to set MBEDTLS_MPI_MAX_LIMBS to a value >=65536, but we don't support customizing this value anyway (it's always 10000). Signed-off-by: Gilles Peskine --- include/mbedtls/bignum.h | 7 +++++-- library/bignum.c | 12 ++++++++---- library/ecp_curves.c | 5 +++-- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h index e7f3131740..96cc656913 100644 --- a/include/mbedtls/bignum.h +++ b/include/mbedtls/bignum.h @@ -214,10 +214,13 @@ typedef struct mbedtls_mpi { * Note that this implies that calloc() or `... = {0}` does not create * a valid MPI representation. You must call mbedtls_mpi_init(). */ - int MBEDTLS_PRIVATE(s); + signed short MBEDTLS_PRIVATE(s); /** Total number of limbs in \c p. */ - size_t MBEDTLS_PRIVATE(n); + unsigned short MBEDTLS_PRIVATE(n); +#if MBEDTLS_MPI_MAX_LIMBS > 65535 +#error "MBEDTLS_MPI_MAX_LIMBS > 65535 is not supported" +#endif /** Pointer to limbs. * diff --git a/library/bignum.c b/library/bignum.c index 36effaf8da..5b9293293e 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -114,7 +114,9 @@ int mbedtls_mpi_grow(mbedtls_mpi *X, size_t nblimbs) mbedtls_free(X->p); } - X->n = nblimbs; + /* nblimbs fits in n because we ensure that MBEDTLS_MPI_MAX_LIMBS + * fits, and we've checked that nblimbs <= MBEDTLS_MPI_MAX_LIMBS. */ + X->n = (unsigned short) nblimbs; X->p = p; } @@ -162,7 +164,9 @@ int mbedtls_mpi_shrink(mbedtls_mpi *X, size_t nblimbs) mbedtls_free(X->p); } - X->n = i; + /* i fits in n because we ensure that MBEDTLS_MPI_MAX_LIMBS + * fits, and we've checked that i <= nblimbs <= MBEDTLS_MPI_MAX_LIMBS. */ + X->n = (unsigned short) i; X->p = p; return 0; @@ -1574,8 +1578,8 @@ static void mpi_montred(mbedtls_mpi *A, const mbedtls_mpi *N, { mbedtls_mpi_uint z = 1; mbedtls_mpi U; - - U.n = U.s = (int) z; + U.n = 1; + U.s = 1; U.p = &z; mpi_montmul(A, &U, N, mm, T); diff --git a/library/ecp_curves.c b/library/ecp_curves.c index a4fa663a56..9acf778aee 100644 --- a/library/ecp_curves.c +++ b/library/ecp_curves.c @@ -4512,12 +4512,13 @@ static const mbedtls_ecp_point brainpoolP512r1_T[32] = { defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) /* * Create an MPI from embedded constants - * (assumes len is an exact multiple of sizeof(mbedtls_mpi_uint)) + * (assumes len is an exact multiple of sizeof(mbedtls_mpi_uint) and + * len < 1048576) */ static inline void ecp_mpi_load(mbedtls_mpi *X, const mbedtls_mpi_uint *p, size_t len) { X->s = 1; - X->n = len / sizeof(mbedtls_mpi_uint); + X->n = (unsigned short) (len / sizeof(mbedtls_mpi_uint)); X->p = (mbedtls_mpi_uint *) p; } #endif