diff --git a/ChangeLog b/ChangeLog index 81cbeb092..5c2386af6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -17,6 +17,13 @@ Security being leaked to memory after release. * Fix dhm_check_range() failing to detect trivial subgroups and potentially leaking 1 bit of the private key. Reported by prashantkspatil. + * Make mpi_read_binary constant-time with respect to + the input data. Previously, trailing zero bytes were detected + and omitted for the sake of saving memory, but potentially + leading to slight timing differences. + Reported by Marco Macchetti, Kudelski Group. + * Wipe stack buffer temporarily holding EC private exponent + after keypair generation. Bugfix * Fix memory leak in ssl_set_hostname() when called multiple times. diff --git a/library/bignum.c b/library/bignum.c index e4a8dece5..0a9560734 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -678,16 +678,20 @@ cleanup: int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen ) { int ret; - size_t i, j, n; + size_t i, j; + size_t const limbs = CHARS_TO_LIMBS( buflen ); - for( n = 0; n < buflen; n++ ) - if( buf[n] != 0 ) - break; + /* Ensure that target MPI has exactly the necessary number of limbs */ + if( X->n != limbs ) + { + mpi_free( X ); + mpi_init( X ); + MPI_CHK( mpi_grow( X, limbs ) ); + } - MPI_CHK( mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) ); MPI_CHK( mpi_lset( X, 0 ) ); - for( i = buflen, j = 0; i > n; i--, j++ ) + for( i = buflen, j = 0; i > 0; i--, j++ ) X->p[j / ciL] |= ((t_uint) buf[i - 1]) << ((j % ciL) << 3); cleanup: @@ -1881,7 +1885,6 @@ int mpi_fill_random( mpi *X, size_t size, cleanup: polarssl_zeroize( buf, sizeof( buf ) ); - return( ret ); } diff --git a/library/ecp.c b/library/ecp.c index 79066dc91..f39e7ebe8 100644 --- a/library/ecp.c +++ b/library/ecp.c @@ -1854,7 +1854,6 @@ int ecp_gen_keypair( ecp_group *grp, mpi *d, ecp_point *Q, { /* SEC1 3.2.1: Generate d such that 1 <= n < N */ int count = 0; - unsigned char rnd[POLARSSL_ECP_MAX_BYTES]; /* * Match the procedure given in RFC 6979 (deterministic ECDSA): @@ -1865,8 +1864,7 @@ int ecp_gen_keypair( ecp_group *grp, mpi *d, ecp_point *Q, */ do { - MPI_CHK( f_rng( p_rng, rnd, n_size ) ); - MPI_CHK( mpi_read_binary( d, rnd, n_size ) ); + MPI_CHK( mpi_fill_random( d, n_size, f_rng, p_rng ) ); MPI_CHK( mpi_shift_r( d, 8 * n_size - grp->nbits ) ); /*