Fix null pointer dereference in mbedtls_mpi_exp_mod

Fix a null pointer dereference in mbedtls_mpi_exp_mod(X, A, N, E, _RR) when
A is the value 0 represented with 0 limbs.

Make the code a little more robust against similar bugs.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine
2021-06-08 23:17:42 +02:00
parent bc781eab47
commit c559eac574
3 changed files with 15 additions and 4 deletions

View File

@@ -0,0 +1,6 @@
Bugfix
* Fix a null pointer dereference when mbedtls_mpi_exp_mod() was called with
A=0 represented with 0 limbs. This bug could not be triggered by code
that constructed A with one of the mbedtls_mpi_read_xxx functions
(including in particular TLS code) since those always built an mpi object
with at least one limb. Credit to OSS-Fuzz. Fixes #4641.

View File

@@ -2080,6 +2080,11 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
#endif
j = N->n + 1;
/* All W[i] and X must have at least N->n limbs for the mpi_montmul()
* and mpi_montred() calls later. Here we ensure that W[1] and X are
* large enough, and later we'll grow other W[i] to the same length.
* They must not be shrunk midway through this function!
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
@@ -2117,6 +2122,10 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &W[1], A, N ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) );
/* Re-grow W[1] if necessary. This should be only necessary in one corner
* case: when A == 0 represented with A.n == 0, mbedtls_mpi_copy shrinks
* W[1] to 0 limbs. */
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], N->n +1 ) );
mpi_montmul( &W[1], &RR, N, mm, &T );

View File

@@ -1073,19 +1073,15 @@ Base test mbedtls_mpi_exp_mod #6 (Negative base + exponent)
mbedtls_mpi_exp_mod:10:"-23":10:"-13":10:"29":10:"0":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
Test mbedtls_mpi_exp_mod: 0 (null) ^ 0 (null) mod 9
depends_on:TEST_TEMPORARILY_DISABLED_BECAUSE_IT_CAUSES_A_CRASH
mbedtls_mpi_exp_mod:16:"":16:"":16:"09":16:"1":0
Test mbedtls_mpi_exp_mod: 0 (null) ^ 0 (1 limb) mod 9
depends_on:TEST_TEMPORARILY_DISABLED_BECAUSE_IT_CAUSES_A_CRASH
mbedtls_mpi_exp_mod:16:"":16:"00":16:"09":16:"1":0
Test mbedtls_mpi_exp_mod: 0 (null) ^ 1 mod 9
depends_on:TEST_TEMPORARILY_DISABLED_BECAUSE_IT_CAUSES_A_CRASH
mbedtls_mpi_exp_mod:16:"":16:"01":16:"09":16:"":0
Test mbedtls_mpi_exp_mod: 0 (null) ^ 2 mod 9
depends_on:TEST_TEMPORARILY_DISABLED_BECAUSE_IT_CAUSES_A_CRASH
mbedtls_mpi_exp_mod:16:"":16:"02":16:"09":16:"":0
Test mbedtls_mpi_exp_mod: 0 (1 limb) ^ 0 (null) mod 9