From 770b5e1e9e043a00f79276d588c8c7437c0b774c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Wed, 29 Apr 2015 17:02:01 +0200 Subject: [PATCH] Fix missing NULL check in MPI --- ChangeLog | 2 ++ include/polarssl/bignum.h | 4 +++- library/bignum.c | 3 +++ tests/suites/test_suite_mpi.data | 3 +++ tests/suites/test_suite_mpi.function | 19 +++++++++++++++++++ 5 files changed, 30 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 19382bc87..75ddfdb15 100644 --- a/ChangeLog +++ b/ChangeLog @@ -28,6 +28,8 @@ Features errors on use of deprecated functions. Bugfix + * mpi_size() and mpi_msb() would segfault when called on an mpi that is + initialized but not set (found by pravic). * Fix detection of support for getrandom() on Linux (reported by syzzer) by doing it at runtime (using uname) rather that compile time. * Fix handling of symlinks by "make install" (found by Gaƫl PORTAY). diff --git a/include/polarssl/bignum.h b/include/polarssl/bignum.h index df25bd1f1..8e1687b97 100644 --- a/include/polarssl/bignum.h +++ b/include/polarssl/bignum.h @@ -188,7 +188,9 @@ typedef struct mpi; /** - * \brief Initialize one MPI + * \brief Initialize one MPI (make internal references valid) + * This just makes it ready to be set or freed, + * but does not define a value for the MPI. * * \param X One MPI to initialize. */ diff --git a/library/bignum.c b/library/bignum.c index 12c72af3a..f479bc9ed 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -356,6 +356,9 @@ size_t mpi_msb( const mpi *X ) { size_t i, j; + if( X->n == 0 ) + return( 0 ); + for( i = X->n - 1; i > 0; i-- ) if( X->p[i] != 0 ) break; diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data index 7908f9144..56817ccbe 100644 --- a/tests/suites/test_suite_mpi.data +++ b/tests/suites/test_suite_mpi.data @@ -1,3 +1,6 @@ +Arguments with no value +mpi_null: + Base test mpi_read_write_string #1 mpi_read_write_string:10:"128":10:"128":100:0:0 diff --git a/tests/suites/test_suite_mpi.function b/tests/suites/test_suite_mpi.function index ce1a07205..023cab412 100644 --- a/tests/suites/test_suite_mpi.function +++ b/tests/suites/test_suite_mpi.function @@ -7,6 +7,25 @@ * END_DEPENDENCIES */ +/* BEGIN_CASE */ +void mpi_null( ) +{ + mpi X, Y, Z; + + mpi_init( &X ); + mpi_init( &Y ); + mpi_init( &Z ); + + TEST_ASSERT( mpi_get_bit( &X, 42 ) == 0 ); + TEST_ASSERT( mpi_lsb( &X ) == 0 ); + TEST_ASSERT( mpi_msb( &X ) == 0 ); + TEST_ASSERT( mpi_size( &X ) == 0 ); + +exit: + mpi_free( &X ); +} +/* END_CASE */ + /* BEGIN_CASE */ void mpi_read_write_string( int radix_X, char *input_X, int radix_A, char *input_A, int output_size, int result_read,