1
0
mirror of https://github.com/Mbed-TLS/mbedtls.git synced 2025-08-05 19:35:48 +03:00

mbedtls_mpi_random: avoid local allocation

Rewrite the minimum bound comparison to avoid a local allocation. This costs
a bit of code size, but saves RAM. This is in preparation for moving the
bulk of the function to the bignum_core module where allocation is not
permitted.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine
2022-09-09 23:19:04 +02:00
parent 6f949ea67b
commit 8a32a75aa2

View File

@@ -1968,10 +1968,9 @@ int mbedtls_mpi_random( mbedtls_mpi *X,
{ {
int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
int count; int count;
unsigned lt_lower = 1, lt_upper = 0; unsigned ge_lower = 1, lt_upper = 0;
size_t n_bits = mbedtls_mpi_bitlen( N ); size_t n_bits = mbedtls_mpi_bitlen( N );
size_t n_bytes = ( n_bits + 7 ) / 8; size_t n_bytes = ( n_bits + 7 ) / 8;
mbedtls_mpi lower_bound;
if( min < 0 ) if( min < 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
@@ -1997,14 +1996,10 @@ int mbedtls_mpi_random( mbedtls_mpi *X,
*/ */
count = ( n_bytes > 4 ? 30 : 250 ); count = ( n_bytes > 4 ? 30 : 250 );
mbedtls_mpi_init( &lower_bound );
/* Ensure that target MPI has exactly the same number of limbs /* Ensure that target MPI has exactly the same number of limbs
* as the upper bound, even if the upper bound has leading zeros. * as the upper bound, even if the upper bound has leading zeros.
* This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */ * This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &lower_bound, N->n ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &lower_bound, min ) );
/* /*
* Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA) * Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
@@ -2027,13 +2022,12 @@ int mbedtls_mpi_random( mbedtls_mpi *X,
goto cleanup; goto cleanup;
} }
MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, &lower_bound, &lt_lower ) ); ge_lower = mbedtls_mpi_core_uint_le_mpi( min, X->p, X->n );
MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, &lt_upper ) ); lt_upper = mbedtls_mpi_core_lt_ct( X->p, N->p, N->n );
} }
while( lt_lower != 0 || lt_upper == 0 ); while( ge_lower == 0 || lt_upper == 0 );
cleanup: cleanup:
mbedtls_mpi_free( &lower_bound );
return( ret ); return( ret );
} }