From 9f4bb319c956dd5acee0421edbca1c6ef8b31718 Mon Sep 17 00:00:00 2001 From: Gabor Mezei Date: Mon, 31 Jan 2022 16:33:47 +0100 Subject: [PATCH] Implement HKDF extract in TLS 1.3 based on PSA HMAC Signed-off-by: Gabor Mezei --- library/ssl_tls13_invasive.h | 5 ++++ library/ssl_tls13_keys.c | 51 ++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/library/ssl_tls13_invasive.h b/library/ssl_tls13_invasive.h index aa35784010..e3b1dc7c59 100644 --- a/library/ssl_tls13_invasive.h +++ b/library/ssl_tls13_invasive.h @@ -28,6 +28,11 @@ #if defined(MBEDTLS_PSA_CRYPTO_C) +int mbedtls_psa_hkdf_extract( psa_algorithm_t alg, + const unsigned char *salt, size_t salt_len, + const unsigned char *ikm, size_t ikm_len, + unsigned char *prk ); + /** * \brief Expand the supplied \p prk into several additional pseudorandom * keys, which is the output of the HKDF. diff --git a/library/ssl_tls13_keys.c b/library/ssl_tls13_keys.c index 885dd16fbf..e63f83afb9 100644 --- a/library/ssl_tls13_keys.c +++ b/library/ssl_tls13_keys.c @@ -138,6 +138,57 @@ static void ssl_tls13_hkdf_encode_label( #if defined( MBEDTLS_TEST_HOOKS ) +MBEDTLS_STATIC_TESTABLE +int mbedtls_psa_hkdf_extract( psa_algorithm_t alg, + const unsigned char *salt, size_t salt_len, + const unsigned char *ikm, size_t ikm_len, + unsigned char *prk ) +{ + unsigned char null_salt[PSA_MAC_MAX_SIZE] = { '\0' }; + mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT; + psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; + size_t prk_len; + int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; + + if( salt == NULL || salt_len == 0 ) + { + size_t hash_len; + + if( salt_len != 0 ) + { + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + } + + //hash_len = mbedtls_md_get_size( md ); + hash_len = PSA_HASH_LENGTH( alg ); + + if( hash_len == 0 ) + { + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + } + + salt = null_salt; + salt_len = hash_len; + } + + psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_MESSAGE ); + psa_set_key_algorithm( &attributes, alg ); + psa_set_key_type( &attributes, PSA_KEY_TYPE_HMAC ); + + ret = psa_import_key( &attributes, salt, salt_len, &key ); + if( PSA_SUCCESS != ret ) + { + goto cleanup; + } + + ret = psa_mac_compute( key, alg, ikm, ikm_len, prk, PSA_HASH_LENGTH( alg ), &prk_len ); + +cleanup: + psa_destroy_key( key ); + + return( ret ); +} + MBEDTLS_STATIC_TESTABLE psa_status_t mbedtls_psa_hkdf_expand( psa_algorithm_t alg, const unsigned char *prk, size_t prk_len,