Limit keys to 65528 bits
65528 bits is more than any reasonable key until we start supporting
post-quantum cryptography.
This limit is chosen to allow bit-sizes to be stored in 16 bits, with
65535 left to indicate an invalid value. It's a whole number of bytes,
which facilitates some calculations, in particular allowing a key of
exactly PSA_CRYPTO_MAX_STORAGE_SIZE to be created but not one bit
more.
As a resource usage limit, this is arguably too large, but that's out
of scope of the current commit.
Test that key import, generation and derivation reject overly large
sizes.
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index 4721f6b..4c93dd0 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -706,11 +706,14 @@
if( key_type_is_raw_bytes( slot->type ) )
{
- /* Ensure that a bytes-to-bit conversion won't overflow. */
+ size_t bit_size = PSA_BYTES_TO_BITS( data_length );
+ /* Ensure that the bytes-to-bit conversion doesn't overflow. */
if( data_length > SIZE_MAX / 8 )
return( PSA_ERROR_NOT_SUPPORTED );
- status = prepare_raw_data_slot( slot->type,
- PSA_BYTES_TO_BITS( data_length ),
+ /* Ensure that the key is not overly large. */
+ if( bit_size > PSA_MAX_KEY_BITS )
+ return( PSA_ERROR_NOT_SUPPORTED );
+ status = prepare_raw_data_slot( slot->type, bit_size,
&slot->data.raw );
if( status != PSA_SUCCESS )
return( status );
@@ -1470,6 +1473,13 @@
}
slot->type = attributes->core.type;
+ /* Refuse to create overly large keys.
+ * Note that this doesn't trigger on import if the attributes don't
+ * explicitly specify a size (so psa_get_key_bits returns 0), so
+ * psa_import_key() needs its own checks. */
+ if( psa_get_key_bits( attributes ) > PSA_MAX_KEY_BITS )
+ return( PSA_ERROR_NOT_SUPPORTED );
+
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* For a key in a secure element, we need to do three things:
* create the key file in internal storage, create the