From 4bcb4914c520a7ddbb8f361f2b58ef83237e0f69 Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Tue, 18 Apr 2017 15:49:39 +0100 Subject: [PATCH] Abort modular inversion when modulus is one. The modular inversion function hangs when provided with the modulus 1. This commit refuses this modulus with a BAD_INPUT error code. It also adds a test for this case. --- include/mbedtls/bignum.h | 4 ++-- library/bignum.c | 2 +- tests/suites/test_suite_mpi.data | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h index aa51556a5..a7133131b 100644 --- a/include/mbedtls/bignum.h +++ b/include/mbedtls/bignum.h @@ -665,8 +665,8 @@ int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B * * \return 0 if successful, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed, - * MBEDTLS_ERR_MPI_BAD_INPUT_DATA if N is negative or nil - MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N + * MBEDTLS_ERR_MPI_BAD_INPUT_DATA if N is <= 1, + MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N. */ int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N ); diff --git a/library/bignum.c b/library/bignum.c index efc1a51a8..8df2510f5 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -1893,7 +1893,7 @@ int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi int ret; mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2; - if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 ) + if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); mbedtls_mpi_init( &TA ); mbedtls_mpi_init( &TU ); mbedtls_mpi_init( &U1 ); mbedtls_mpi_init( &U2 ); diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data index 84cdc1fa0..17cf350e4 100644 --- a/tests/suites/test_suite_mpi.data +++ b/tests/suites/test_suite_mpi.data @@ -550,6 +550,9 @@ mbedtls_mpi_inv_mod:10:"3":10:"-11":10:"4":MBEDTLS_ERR_MPI_BAD_INPUT_DATA Base test mbedtls_mpi_inv_mod #4 mbedtls_mpi_inv_mod:10:"2":10:"4":10:"0":MBEDTLS_ERR_MPI_NOT_ACCEPTABLE +Base test mbedtls_mpi_inv_mod #5 +mbedtls_mpi_inv_mod:10:"3":10:"1":10:"0":MBEDTLS_ERR_MPI_BAD_INPUT_DATA + Test mbedtls_mpi_inv_mod #1 mbedtls_mpi_inv_mod:16:"aa4df5cb14b4c31237f98bd1faf527c283c2d0f3eec89718664ba33f9762907c":16:"fffbbd660b94412ae61ead9c2906a344116e316a256fd387874c6c675b1d587d":16:"8d6a5c1d7adeae3e94b9bcd2c47e0d46e778bc8804a2cc25c02d775dc3d05b0c":0