From 0e810b9648c3bc240d08ecfd01564f725e35ff2d Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Thu, 3 Jan 2019 17:13:11 +0000 Subject: [PATCH] Don't call memcpy with NULL pointer in mbedtls_mpi_read_binary() mbedtls_mpi_read_binary() calls memcpy() with the source pointer being the source pointer passed to mbedtls_mpi_read_binary(), the latter may be NULL if the buffer length is 0 (and this happens e.g. in the ECJPAKE test suite). The behavior of memcpy(), in contrast, is undefined when called with NULL source buffer, even if the length of the copy operation is 0. This commit fixes this by explicitly checking that the source pointer is not NULL before calling memcpy(), and skipping the call otherwise. --- library/bignum.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index bdd6af85c..d3d02b1a0 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -823,10 +823,15 @@ int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t bu } MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) ); - Xp = (unsigned char*) X->p; - memcpy( Xp + overhead, buf, buflen ); + /* Avoid calling `memcpy` with NULL source argument, + * even if buflen is 0. */ + if( buf != NULL ) + { + Xp = (unsigned char*) X->p; + memcpy( Xp + overhead, buf, buflen ); - mpi_bigendian_to_host( X->p, limbs ); + mpi_bigendian_to_host( X->p, limbs ); + } cleanup: