From a16fa297f79c122aa861284ab221a05c62780444 Mon Sep 17 00:00:00 2001 From: Ron Eldor Date: Tue, 20 Nov 2018 14:07:01 +0200 Subject: [PATCH 1/2] Refactor mpi_write_hlp to not be recursive Refactor `mpi_write_hlp()` to not be recursive, to fix stack overflows. Iterate over the `mbedtls_mpi` division of the radix requested, until it is zero. Each iteration, put the residue in the next LSB of the output buffer. Fixes #2190 --- library/bignum.c | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index ae5e7cfa0..593229ecd 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -499,26 +499,38 @@ cleanup: } /* - * Helper to write the digits high-order first + * Helper to write the digits high-order first. */ -static int mpi_write_hlp( mbedtls_mpi *X, int radix, char **p ) +static int mpi_write_hlp( mbedtls_mpi *X, int radix, + char **p, const size_t buflen ) { int ret; mbedtls_mpi_uint r; + size_t length = 0; + char *p_end = *p + buflen; - if( radix < 2 || radix > 16 ) - return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); + do + { + if( length >= buflen ) + { + return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL ); + } - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) ); + /* + * Write the residue in the current position, as an ASCII character. + */ + if( r < 0xA ) + *(--p_end) = (char)( '0' + r ); + else + *(--p_end) = (char)( 'A' + ( r - 0xA ) ); - if( mbedtls_mpi_cmp_int( X, 0 ) != 0 ) - MBEDTLS_MPI_CHK( mpi_write_hlp( X, radix, p ) ); + length++; + } while( mbedtls_mpi_cmp_int( X, 0 ) != 0 ); - if( r < 10 ) - *(*p)++ = (char)( r + 0x30 ); - else - *(*p)++ = (char)( r + 0x37 ); + memmove( *p, p_end, length ); + *p += length; cleanup: @@ -588,7 +600,7 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix, if( T.s == -1 ) T.s = 1; - MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p ) ); + MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p, buflen ) ); } *p++ = '\0'; From 8a6917dc67ecb8d98421909402cdbe0c0a973d20 Mon Sep 17 00:00:00 2001 From: Ron Eldor Date: Tue, 27 Nov 2018 10:33:38 +0200 Subject: [PATCH 2/2] Update ChangeLog Update the ChangeLog with the fix. --- ChangeLog | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ChangeLog b/ChangeLog index 8f0e8c1c7..292df8334 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,11 @@ mbed TLS ChangeLog (Sorted per branch, date) += mbed TLS x.xx.x branch released xxxx-xx-xx + +Bugfix + * Reduce stack usage of `mpi_write_hlp()` by eliminating recursion. + Fixes #2190. + = mbed TLS 2.14.0 branch released 2018-11-19 Security