From c15e31d3556ce15b96b5d5148edb47ced3050b49 Mon Sep 17 00:00:00 2001 From: Nick Child Date: Tue, 25 May 2021 15:31:21 -0400 Subject: [PATCH] pk.c: Ensure min hash_len in pk_hashlen_helper The function `pk_hashlen_helper` exists to ensure a valid hash_len is used in pk_verify and pk_sign functions. This function has been used to adjust to the corrsponding hash_len if the user passes in 0 for the hash_len argument based on the md algorithm given. If the user does not pass in 0 as the hash_len, then it is not adjusted. This is problematic if the user gives a hash_len and hash buffer that is less than the associated length of the md algorithm. This error would go unchecked and eventually lead to buffer overread when given to specific pk_sign/verify functions, since they both ignore the hash_len argument if md_alg is not MBEDTLS_MD_NONE. This commit, adds a conditional to `pk_hashlen_helper` so that an error is thrown if the user specifies a hash_length (not 0) and it is less than the expected for the associated message digest algorithm. This aligns better with the api documentation where it states "If hash_len is 0, then the length associated with md_alg is used instead, or an error returned if it is invalid" Signed-off-by: Nick Child Signed-off-by: Nayna Jain --- ChangeLog.d/ensure_hash_len_is_valid.txt | 5 +++++ library/pk.c | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 ChangeLog.d/ensure_hash_len_is_valid.txt diff --git a/ChangeLog.d/ensure_hash_len_is_valid.txt b/ChangeLog.d/ensure_hash_len_is_valid.txt new file mode 100644 index 0000000000..2059249e19 --- /dev/null +++ b/ChangeLog.d/ensure_hash_len_is_valid.txt @@ -0,0 +1,5 @@ +Bugfix + * mbedtls_pk_sign() and mbedtls_pk_verify() and their extended and + restartable variants now require at least the specified hash length if + nonzero. Before, for RSA, hash_len was ignored in favor of the length of + the specified hash algorithm. diff --git a/library/pk.c b/library/pk.c index 81cfdbfe80..8998271b97 100644 --- a/library/pk.c +++ b/library/pk.c @@ -225,12 +225,15 @@ static inline int pk_hashlen_helper( mbedtls_md_type_t md_alg, size_t *hash_len { const mbedtls_md_info_t *md_info; - if( *hash_len != 0 ) + if( *hash_len != 0 && md_alg == MBEDTLS_MD_NONE ) return( 0 ); if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( -1 ); + if ( *hash_len != 0 && *hash_len < mbedtls_md_get_size( md_info ) ) + return ( -1 ); + *hash_len = mbedtls_md_get_size( md_info ); return( 0 ); }