From 9c3e0602535dec9cba6f7d533682fc7f07c17ced Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Tue, 5 Jan 2021 16:03:55 +0100 Subject: [PATCH] Explain the design of mbedtls_psa_get_random better Signed-off-by: Gilles Peskine --- library/psa_crypto.c | 18 ++++++++++++++++-- library/psa_crypto_random_impl.h | 4 ++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/library/psa_crypto.c b/library/psa_crypto.c index c82fecb08..896da3fe2 100644 --- a/library/psa_crypto.c +++ b/library/psa_crypto.c @@ -6412,14 +6412,28 @@ psa_status_t psa_generate_random( uint8_t *output, } /* Wrapper function allowing the classic API to use the PSA RNG. - * In the non-external case, mbedtls_psa_get_random is defined - * as a constant function pointer in psa_crypto_random_impl.h. + * + * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls + * `psa_generate_random(...)`. The state parameter is ignored since the + * PSA API doesn't support passing an explicit state. + * + * In the non-external case, psa_generate_random() calls an + * `mbedtls_xxx_drbg_random` function which has exactly the same signature + * and semantics as mbedtls_psa_get_random(). As an optimization, + * instead of doing this back-and-forth between the PSA API and the + * classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random` + * as a constant function pointer to `mbedtls_xxx_drbg_random`. */ #if defined (MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) int mbedtls_psa_get_random( void *p_rng, unsigned char *output, size_t output_size ) { + /* This function takes a pointer to the RNG state because that's what + * classic mbedtls functions using an RNG expect. The PSA RNG manages + * its own state internally and doesn't let the caller access that state. + * So we just ignore the state parameter, and in practice we'll pass + * NULL. */ (void) p_rng; psa_status_t status = psa_generate_random( output, output_size ); if( status == PSA_SUCCESS ) diff --git a/library/psa_crypto_random_impl.h b/library/psa_crypto_random_impl.h index 07e1d1031..1232186c9 100644 --- a/library/psa_crypto_random_impl.h +++ b/library/psa_crypto_random_impl.h @@ -30,10 +30,12 @@ typedef mbedtls_psa_external_random_context_t mbedtls_psa_random_context_t; +/* Trivial wrapper around psa_generate_random(). */ int mbedtls_psa_get_random( void *p_rng, unsigned char *output, size_t output_size ); +/* The PSA RNG API doesn't need any externally maintained state. */ #define MBEDTLS_PSA_RANDOM_STATE NULL #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */ @@ -163,6 +165,8 @@ static mbedtls_f_rng_t *const mbedtls_psa_get_random = mbedtls_hmac_drbg_random; * This variable is only intended to be used through the macro * #MBEDTLS_PSA_RANDOM_STATE. */ +/* psa_crypto.c sets this variable to a pointer to the DRBG state in the + * global PSA crypto state. */ extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state; /** A pointer to the PSA DRBG state.