Test mbedtls_mpi_fill_random

Positive tests: test that the RNG has the expected size, given that we
know how many leading zeros it has because we know how the function
consumes bytes and when the test RNG produces null bytes.

Negative tests: test that if the RNG is willing to emit less than the
number of wanted bytes, the function fails.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine 2020-11-25 15:37:20 +01:00
parent 401ba5e9b7
commit 2f78062e75
2 changed files with 90 additions and 0 deletions

View file

@ -1,5 +1,6 @@
/* BEGIN_HEADER */
#include "mbedtls/bignum.h"
#include "mbedtls/entropy.h"
typedef struct mbedtls_test_mpi_random
{
@ -43,6 +44,22 @@ int mbedtls_test_mpi_miller_rabin_determinizer( void* state,
return( 0 );
}
/* Random generator that is told how many bytes to return. */
static int f_rng_bytes_left( void *state, unsigned char *buf, size_t len )
{
size_t *bytes_left = state;
size_t i;
for( i = 0; i < len; i++ )
{
if( *bytes_left == 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
buf[i] = *bytes_left & 0xff;
--( *bytes_left );
}
return( 0 );
}
/* END_HEADER */
/* BEGIN_DEPENDENCIES
@ -1251,6 +1268,37 @@ exit:
}
/* END_CASE */
/* BEGIN_CASE */
void mpi_fill_random( int wanted_bytes, int rng_bytes, int expected_ret )
{
mbedtls_mpi X;
int ret;
size_t bytes_left = rng_bytes;
mbedtls_mpi_init( &X );
ret = mbedtls_mpi_fill_random( &X, wanted_bytes,
f_rng_bytes_left, &bytes_left );
TEST_ASSERT( ret == expected_ret );
if( expected_ret == 0 )
{
/* mbedtls_mpi_fill_random is documented to use bytes from the RNG
* as a big-endian representation of the number. We know when
* our RNG function returns null bytes, so we know how many
* leading zero bytes the number has. */
size_t leading_zeros = 0;
if( wanted_bytes > 0 && rng_bytes % 256 == 0 )
leading_zeros = 1;
TEST_ASSERT( mbedtls_mpi_size( &X ) + leading_zeros ==
(size_t) wanted_bytes );
TEST_ASSERT( (int) bytes_left == rng_bytes - wanted_bytes );
}
exit:
mbedtls_mpi_free( &X );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_SELF_TEST */
void mpi_selftest( )
{