From d7bb35257b7279696a445a03d48579f58a53e5d3 Mon Sep 17 00:00:00 2001 From: Janos Follath Date: Sat, 26 Nov 2022 14:59:27 +0000 Subject: [PATCH] mbedtls_mpi_mod_read/write: restrict pre-conditions Require equality for the number of limbs in the modulus and the residue. This makes these functions consistent with residue_setup(). Signed-off-by: Janos Follath --- library/bignum_mod.c | 4 ++-- tests/suites/test_suite_bignum_mod.function | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/library/bignum_mod.c b/library/bignum_mod.c index f07307ce5..7f7c71512 100644 --- a/library/bignum_mod.c +++ b/library/bignum_mod.c @@ -207,7 +207,7 @@ int mbedtls_mpi_mod_read( mbedtls_mpi_mod_residue *r, /* Do our best to check if r and m have been set up */ if ( r->limbs == 0 || m->limbs == 0 ) goto cleanup; - if ( r->limbs > m->limbs ) + if ( r->limbs != m->limbs ) goto cleanup; ret = mbedtls_mpi_mod_raw_read( r->p, m, buf, buflen, ext_rep ); @@ -235,7 +235,7 @@ int mbedtls_mpi_mod_write( const mbedtls_mpi_mod_residue *r, /* Do our best to check if r and m have been set up */ if ( r->limbs == 0 || m->limbs == 0 ) goto cleanup; - if ( r->limbs > m->limbs ) + if ( r->limbs != m->limbs ) goto cleanup; if ( m->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY) diff --git a/tests/suites/test_suite_bignum_mod.function b/tests/suites/test_suite_bignum_mod.function index 8945968d7..7042ed3d2 100644 --- a/tests/suites/test_suite_bignum_mod.function +++ b/tests/suites/test_suite_bignum_mod.function @@ -148,13 +148,23 @@ void mpi_mod_io_neg( char * input_N, data_t * buf, int ret ) TEST_EQUAL( MBEDTLS_ERR_MPI_BAD_INPUT_DATA, mbedtls_mpi_mod_write( &rn, &m, buf->x, buf->len, endian ) ); - /* Fail for r_limbs > m->limbs */ - r.limbs = m.limbs + 1; + /* Fail for r_limbs < m->limbs */ + r.limbs--; + TEST_ASSERT( r.limbs < m.limbs ); TEST_EQUAL( MBEDTLS_ERR_MPI_BAD_INPUT_DATA, mbedtls_mpi_mod_read( &r, &m, buf->x, buf->len, endian ) ); TEST_EQUAL( MBEDTLS_ERR_MPI_BAD_INPUT_DATA, mbedtls_mpi_mod_write( &r, &m, buf->x, buf->len, endian ) ); - r.limbs = r_limbs; + r.limbs++; + + /* Fail for r_limbs > m->limbs */ + m.limbs--; + TEST_ASSERT( r.limbs > m.limbs ); + TEST_EQUAL( MBEDTLS_ERR_MPI_BAD_INPUT_DATA, + mbedtls_mpi_mod_read( &r, &m, buf->x, buf->len, endian ) ); + TEST_EQUAL( MBEDTLS_ERR_MPI_BAD_INPUT_DATA, + mbedtls_mpi_mod_write( &r, &m, buf->x, buf->len, endian ) ); + m.limbs++; /* Test the read */ TEST_EQUAL( ret, mbedtls_mpi_mod_read( &r, &m, buf->x, buf->len, endian ) ); @@ -163,7 +173,9 @@ void mpi_mod_io_neg( char * input_N, data_t * buf, int ret ) if ( r.limbs > 1 && ret == 0 ) TEST_EQUAL( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL, mbedtls_mpi_mod_write( &r, &m, buf->x, 1, endian ) ); + exit: + mbedtls_mpi_mod_residue_release( &r ); mbedtls_mpi_mod_modulus_free( &m ); mbedtls_free( N ); mbedtls_free( R );