Skip to content

Commit e76aeb7

Browse files
Andres AGsimonbutcher
Andres AG
authored andcommitted
Fix buffer overflow in mbedtls_mpi_write_string()
Fix a buffer overflow when writting a string representation of an MPI number to a buffer in hexadecimal. The problem occurs because hex digits are written in pairs and this is not accounted for in the calculation of the required buffer size when the number of digits is odd.
1 parent 9b3b6dc commit e76aeb7

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

ChangeLog

+3
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ Bugfix
6161
generated in Visual Studio 2015. Reported by Steve Valliere. #742
6262
* Fix a resource leak in ssl_cookie, when using MBEDTLS_THREADING_C.
6363
Raised and fix suggested by Alan Gillingham in the mbed TLS forum. #771
64+
* Fix 1 byte buffer overflow in mbedtls_mpi_write_string() when the MPI
65+
number to write in hexadecimal is negative and requires an odd number of
66+
digits. Found and fixed by Guido Vranken.
6467

6568
= mbed TLS 2.4.1 branch released 2016-12-13
6669

library/bignum.c

+6-1
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,12 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
534534
n = mbedtls_mpi_bitlen( X );
535535
if( radix >= 4 ) n >>= 1;
536536
if( radix >= 16 ) n >>= 1;
537-
n += 3;
537+
/*
538+
* Round up the buffer length to an even value to ensure that there is
539+
* enough room for hexadecimal values that can be represented in an odd
540+
* number of digits.
541+
*/
542+
n += 3 + ( ( n + 1 ) & 1 );
538543

539544
if( buflen < n )
540545
{

tests/suites/test_suite_mpi.data

+3
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ mpi_read_write_string:16:"":16:"00":4:0:0
4646
Test mpi_read_write_string #9 (Empty MPI -> dec)
4747
mpi_read_write_string:16:"":10:"0":4:0:0
4848

49+
Test mpi_write_string #10 (Negative hex with odd number of digits)
50+
mpi_read_write_string:16:"-1":16:"":3:0:MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL
51+
4952
Base test mbedtls_mpi_read_binary #1
5053
mbedtls_mpi_read_binary:"0941379d00fed1491fe15df284dfde4a142f68aa8d412023195cee66883e6290ffe703f4ea5963bf212713cee46b107c09182b5edcd955adac418bf4918e2889af48e1099d513830cec85c26ac1e158b52620e33ba8692f893efbb2f958b4424":10:"56125680981752282334141896320372489490613963693556392520816017892111350604111697682705498319512049040516698827829292076808006940873974979584527073481012636016353913462376755556720019831187364993587901952757307830896531678727717924"
5154

0 commit comments

Comments
 (0)