mbedtls_ecp_gen_privkey_mx: make bit manipulations unconditional

Don't calculate the bit-size of the initially generated random number.
This is not necessary to reach the desired distribution of private
keys, and creates a (tiny) side channel opportunity.

This changes the way the result is derived from the random number, but
does not affect the resulting distribution.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine 2021-03-24 12:25:59 +01:00
parent 6acfc9cb4c
commit 4f7767445b
2 changed files with 5 additions and 13 deletions

View file

@ -3048,17 +3048,13 @@ int mbedtls_ecp_gen_privkey_mx( size_t high_bit,
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t b;
size_t n_bytes = ( high_bit + 7 ) / 8;
/* [Curve25519] page 5 */
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_bytes, f_rng, p_rng ) );
/* Make sure the most significant bit is high_bit */
b = mbedtls_mpi_bitlen( d ); /* mbedtls_mpi_bitlen is one-based */
if( b > high_bit + 1 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - 1 - high_bit ) );
else
/* Make sure the most significant bit is exactly at high_bit */
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_bytes - high_bit - 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, high_bit, 1 ) );
/* Make sure the last two bits are unset for Curve448, three bits for

View file

@ -277,17 +277,13 @@ depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED
mbedtls_ecp_gen_key:MBEDTLS_ECP_DP_SECP192R1
ECP generate Montgomery key: Curve25519, random in range
genkey_mx_known_answer:254:"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
ECP generate Montgomery key: Curve25519, set high bit
genkey_mx_known_answer:254:"0f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
genkey_mx_known_answer:254:"9e020406080a0c0e10121416181a1c1e20222426282a2c2e30323436383a3df0":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
ECP generate Montgomery key: Curve25519, clear higher bit
## If the bit 255 is set, the library shifts the random number right.
genkey_mx_known_answer:254:"ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"7f808101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f78"
ECP generate Montgomery key: Curve25519, clear low bits
genkey_mx_known_answer:254:"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1eff":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
genkey_mx_known_answer:254:"9e020406080a0c0e10121416181a1c1e20222426282a2c2e30323436383a3dff":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
ECP generate Montgomery key: Curve25519, random = all-bits-zero
genkey_mx_known_answer:254:"0000000000000000000000000000000000000000000000000000000000000000":"4000000000000000000000000000000000000000000000000000000000000000"