Skip to content

Commit

Permalink
Refactor mpi_write_hlp to not be recursive
Browse files Browse the repository at this point in the history
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 Mbed-TLS#2190
  • Loading branch information
Ron Eldor authored and Ron Eldor committed Nov 27, 2018
1 parent 556d7d9 commit a16fa29
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions library/bignum.c
Original file line number Diff line number Diff line change
Expand Up @@ -499,26 +499,38 @@ int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s )
}

/*
* 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:

Expand Down Expand Up @@ -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';
Expand Down

0 comments on commit a16fa29

Please sign in to comment.