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.
diff --git a/library/bignum.c b/library/bignum.c
index 4c99e04..8b9082c 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -534,7 +534,12 @@
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 )
{