From 60d8b98d4844475884b4a585cf38ac8a26184d91 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Mon, 29 Mar 2021 22:28:21 +0200 Subject: [PATCH] Preserve MBEDTLS_ERR_ECP_RANDOM_FAILED in case of a hostile RNG Signed-off-by: Gilles Peskine --- library/ecp.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/library/ecp.c b/library/ecp.c index 3e5cebc29..30d4d1923 100644 --- a/library/ecp.c +++ b/library/ecp.c @@ -3091,6 +3091,22 @@ cleanup: } #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) +static int mbedtls_ecp_gen_privkey_sw( + const mbedtls_mpi *N, mbedtls_mpi *d, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) +{ + int ret = mbedtls_mpi_random( d, 1, N, f_rng, p_rng ); + switch( ret ) + { + case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: + return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); + default: + return( ret ); + } +} +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ + /* * Generate a private key */ @@ -3110,7 +3126,7 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) - return( mbedtls_mpi_random( d, 1, &grp->N, f_rng, p_rng ) ); + return( mbedtls_ecp_gen_privkey_sw( &grp->N, d, f_rng, p_rng ) ); #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );