From b5e56ec5fd0f07ef398527f66b49bc0f2f0cef03 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Wed, 9 Jun 2021 13:26:43 +0200 Subject: [PATCH] mbedtls_mpi_gcd: fix the case B==0 Signed-off-by: Gilles Peskine --- ChangeLog.d/mpi_gcd-0.txt | 4 ++++ library/bignum.c | 10 ++++++++++ 2 files changed, 14 insertions(+) create mode 100644 ChangeLog.d/mpi_gcd-0.txt diff --git a/ChangeLog.d/mpi_gcd-0.txt b/ChangeLog.d/mpi_gcd-0.txt new file mode 100644 index 000000000..41e11e1f6 --- /dev/null +++ b/ChangeLog.d/mpi_gcd-0.txt @@ -0,0 +1,4 @@ +Bugfix + * Fix mbedtls_mpi_gcd(G,A,B) when the value of B is zero. This had no + effect on Mbed TLS's internal use of mbedtls_mpi_gcd(), but may affect + applications that call mbedtls_mpi_gcd() directly. Fixes #4642. diff --git a/library/bignum.c b/library/bignum.c index 4aa25a4c6..9f6873dbc 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -2391,6 +2391,16 @@ int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B lz = mbedtls_mpi_lsb( &TA ); lzt = mbedtls_mpi_lsb( &TB ); + /* The loop below gives the correct result when A==0 but not when B==0. + * So have a special case for B==0. Leverage the fact that we just + * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test + * slightly more efficient than cmp_int(). */ + if( lzt == 0 && mbedtls_mpi_get_bit( &TB, 0 ) == 0 ) + { + ret = mbedtls_mpi_copy( G, A ); + goto cleanup; + } + if( lzt < lz ) lz = lzt;