From 8c7698b62a4c33b226d0f4da9ea831593578e7ce Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Fri, 12 May 2017 07:26:01 +0100 Subject: [PATCH] Fix potential stack underflow in mpi_read_file. When provided with an empty line, mpi_read_file causes a numeric underflow resulting in a stack underflow. This commit fixes this and adds some documentation to mpi_read_file. --- ChangeLog | 6 ++++++ include/polarssl/bignum.h | 10 +++++++++- library/bignum.c | 6 +++--- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/ChangeLog b/ChangeLog index b46c72879..cedfc1870 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,11 @@ mbed TLS ChangeLog (Sorted per branch, date) += mbed TLS x.x.x branch released xxxx-xx-xx + +Bugfix + * Fix potential stack underflow in mpi_read_file. + Found by Guido Vranken. + = mbed TLS 1.3.19 branch released 2017-03-08 Security diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h index 2db29d5ae..3b55151a0 100644 --- a/include/polarssl/bignum.h +++ b/include/polarssl/bignum.h @@ -377,7 +377,7 @@ int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen ); #if defined(POLARSSL_FS_IO) /** - * \brief Read X from an opened file + * \brief Read MPI from a line in an opened file * * \param X Destination MPI * \param radix Input numeric base @@ -386,6 +386,14 @@ int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen ); * \return 0 if successful, POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if * the file read buffer is too small or a * POLARSSL_ERR_MPI_XXX error code + * + * \note On success, this function advances the file stream + * to the end of the current line or to EOF. + * + * The function returns 0 on an empty line. + * + * Leading whitespaces are ignored, as is a + * '0x' prefix for radix 16. */ int mpi_read_file( mpi *X, int radix, FILE *fin ); diff --git a/library/bignum.c b/library/bignum.c index afde19bd5..5873b6630 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -620,11 +620,11 @@ int mpi_read_file( mpi *X, int radix, FILE *fin ) if( slen == sizeof( s ) - 2 ) return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL ); - if( s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; } - if( s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; } + if( slen > 0 && s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; } + if( slen > 0 && s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; } p = s + slen; - while( --p >= s ) + while( p-- > s ) if( mpi_get_digit( &d, radix, *p ) != 0 ) break;