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>
diff --git a/ChangeLog.d/mpi_exp_mod-zero.txt b/ChangeLog.d/mpi_exp_mod-zero.txt
new file mode 100644
index 0000000..50a0c1c
--- /dev/null
+++ b/ChangeLog.d/mpi_exp_mod-zero.txt
@@ -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.
diff --git a/library/bignum.c b/library/bignum.c
index bd352e1..e6258fd 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -2080,6 +2080,11 @@
#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 @@
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 );
diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data
index d34164c..499fd37 100644
--- a/tests/suites/test_suite_mpi.data
+++ b/tests/suites/test_suite_mpi.data
@@ -1073,19 +1073,15 @@
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