From db14a9d180069e8a6cb63455e75463aad9f68889 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Tue, 15 Nov 2022 22:59:00 +0100 Subject: [PATCH] Fix NULL+0 in addition 0 + 0 Fix undefined behavior (typically harmless in practice) of mbedtls_mpi_add_mpi(), mbedtls_mpi_add_abs() and mbedtls_mpi_add_int() when both operands are 0 and the left operand is represented with 0 limbs. Signed-off-by: Gilles Peskine --- ChangeLog.d/mpi-add-0-ub.txt | 4 ++++ library/bignum.c | 5 +++++ 2 files changed, 9 insertions(+) create mode 100644 ChangeLog.d/mpi-add-0-ub.txt diff --git a/ChangeLog.d/mpi-add-0-ub.txt b/ChangeLog.d/mpi-add-0-ub.txt new file mode 100644 index 0000000000..9f131a4300 --- /dev/null +++ b/ChangeLog.d/mpi-add-0-ub.txt @@ -0,0 +1,4 @@ +Bugfix + * Fix undefined behavior (typically harmless in practice) of + mbedtls_mpi_add_mpi(), mbedtls_mpi_add_abs() and mbedtls_mpi_add_int() + when both operands are 0 and the left operand is represented with 0 limbs. diff --git a/library/bignum.c b/library/bignum.c index 521787d749..497ccbc817 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -889,6 +889,11 @@ int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi if( B->p[j - 1] != 0 ) break; + /* Exit early to avoid undefined behavior on NULL+0 when X->n == 0 + * and B is 0 (of any size). */ + if( j == 0 ) + return( 0 ); + MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) ); /* j is the number of non-zero limbs of B. Add those to X. */