Fix buffer overflow with hashes larger than key size.
Truncate input hashes to curve private key size as that is all that is required
for the internal implementation.
Signed-off-by: Paul Elliott <paul.elliott@arm.com>
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index 6e0d06b..5013c5d 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -3524,6 +3524,7 @@
const uint8_t *hash, size_t hash_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ size_t required_hash_length;
if (!PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
return PSA_ERROR_NOT_SUPPORTED;
@@ -3561,8 +3562,13 @@
operation->md_alg = mbedtls_hash_info_md_from_psa(hash_alg);
operation->alg = alg;
- memcpy(operation->hash, hash, hash_length);
- operation->hash_length = hash_length;
+ /* We only need to store the same length of hash as the private key size
+ * here, it would be truncated by the internal implementation anyway. */
+ required_hash_length = (hash_length < operation->coordinate_bytes ?
+ hash_length : operation->coordinate_bytes);
+
+ memcpy(operation->hash, hash, required_hash_length);
+ operation->hash_length = required_hash_length;
return PSA_SUCCESS;
@@ -3574,6 +3580,7 @@
(void) hash;
(void) hash_length;
(void) status;
+ (void) required_hash_length;
return PSA_ERROR_NOT_SUPPORTED;
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
@@ -3722,6 +3729,7 @@
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t coordinate_bytes = 0;
+ size_t required_hash_length = 0;
if (!PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
return PSA_ERROR_NOT_SUPPORTED;
@@ -3785,8 +3793,13 @@
mbedtls_ecdsa_restart_init(&operation->restart_ctx);
- memcpy(operation->hash, hash, hash_length);
- operation->hash_length = hash_length;
+ /* We only need to store the same length of hash as the private key size
+ * here, it would be truncated by the internal implementation anyway. */
+ required_hash_length = (hash_length < coordinate_bytes ? hash_length :
+ coordinate_bytes);
+
+ memcpy(operation->hash, hash, required_hash_length);
+ operation->hash_length = required_hash_length;
return PSA_SUCCESS;
#else
@@ -3800,6 +3813,7 @@
(void) signature_length;
(void) status;
(void) coordinate_bytes;
+ (void) required_hash_length;
return PSA_ERROR_NOT_SUPPORTED;
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||