From e0545c30ddc0dc5ee03705e31d5f6ebb0a8452b4 Mon Sep 17 00:00:00 2001 From: Andres AG Date: Fri, 6 Jan 2017 13:17:35 +0000 Subject: [PATCH] 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. --- ChangeLog | 3 +++ library/bignum.c | 7 ++++++- tests/suites/test_suite_mpi.data | 3 +++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 32d76df95..a298738fa 100644 --- a/ChangeLog +++ b/ChangeLog @@ -58,6 +58,9 @@ Bugfix generated in Visual Studio 2015. Reported by Steve Valliere. #742 * Fix a resource leak in ssl_cookie, when using MBEDTLS_THREADING_C. Raised and fix suggested by Alan Gillingham in the mbed TLS forum. #771 + * Fix 1 byte buffer overflow in mbedtls_mpi_write_string() when the MPI + number to write in hexadecimal is negative and requires an odd number of + digits. Found and fixed by Guido Vranken. = mbed TLS 2.1.6 branch released 2016-10-17 diff --git a/library/bignum.c b/library/bignum.c index 7841bea43..199b4f2ee 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -534,7 +534,12 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix, n = mbedtls_mpi_bitlen( X ); if( radix >= 4 ) n >>= 1; if( radix >= 16 ) n >>= 1; - n += 3; + /* + * Round up the buffer length to an even value to ensure that there is + * enough room for hexadecimal values that can be represented in an odd + * number of digits. + */ + n += 3 + ( ( n + 1 ) & 1 ); if( buflen < n ) { diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data index 3fd7f2d1b..0d4ee4490 100644 --- a/tests/suites/test_suite_mpi.data +++ b/tests/suites/test_suite_mpi.data @@ -46,6 +46,9 @@ mpi_read_write_string:16:"":16:"00":4:0:0 Test mpi_read_write_string #9 (Empty MPI -> dec) mpi_read_write_string:16:"":10:"0":4:0:0 +Test mpi_write_string #10 (Negative hex with odd number of digits) +mpi_read_write_string:16:"-1":16:"":3:0:MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL + Base test mbedtls_mpi_read_binary #1 mbedtls_mpi_read_binary:"0941379d00fed1491fe15df284dfde4a142f68aa8d412023195cee66883e6290ffe703f4ea5963bf212713cee46b107c09182b5edcd955adac418bf4918e2889af48e1099d513830cec85c26ac1e158b52620e33ba8692f893efbb2f958b4424":10:"56125680981752282334141896320372489490613963693556392520816017892111350604111697682705498319512049040516698827829292076808006940873974979584527073481012636016353913462376755556720019831187364993587901952757307830896531678727717924"