Merge remote-tracking branch 'hanno/mpi_read_file_underflow_backport-1.3' into mbedtls-1.3
* hanno/mpi_read_file_underflow_backport-1.3:
Fix potential stack underflow in mpi_read_file.
diff --git a/ChangeLog b/ChangeLog
index dd6a69e..8449329 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -25,6 +25,8 @@
Found by blaufish. Fixes #641.
* Fix incorrect sign computation in modular exponentiation
when dealing with negative MPI. Found by Guido Vranken.
+ * Fix potential stack underflow in mpi_read_file.
+ Found by Guido Vranken.
Changes
* Clarify ECDSA documentation and improve the sample code to avoid
diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h
index dc54af8..c11db96 100644
--- a/include/polarssl/bignum.h
+++ b/include/polarssl/bignum.h
@@ -377,7 +377,7 @@
#if defined(POLARSSL_FS_IO)
/**
- * \brief Read X from an opened file
+ * \brief Read MPI from a line in an opened file
*
* \param X Destination MPI
* \param radix Input numeric base
@@ -386,6 +386,14 @@
* \return 0 if successful, POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if
* the file read buffer is too small or a
* POLARSSL_ERR_MPI_XXX error code
+ *
+ * \note On success, this function advances the file stream
+ * to the end of the current line or to EOF.
+ *
+ * The function returns 0 on an empty line.
+ *
+ * Leading whitespaces are ignored, as is a
+ * '0x' prefix for radix 16.
*/
int mpi_read_file( mpi *X, int radix, FILE *fin );
diff --git a/library/bignum.c b/library/bignum.c
index 9d12a86..4829d91 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -620,11 +620,11 @@
if( slen == sizeof( s ) - 2 )
return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL );
- if( s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; }
- if( s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; }
+ if( slen > 0 && s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; }
+ if( slen > 0 && s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; }
p = s + slen;
- while( --p >= s )
+ while( p-- > s )
if( mpi_get_digit( &d, radix, *p ) != 0 )
break;