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
diff --git a/library/psa_crypto_storage.h b/library/psa_crypto_storage.h
index 8fe20ac..938cc4f 100644
--- a/library/psa_crypto_storage.h
+++ b/library/psa_crypto_storage.h
@@ -35,9 +35,14 @@
#include <stdint.h>
#include <string.h>
-/* Limit the maximum key size to 30kB (just in case someone tries to
- * inadvertently store an obscene amount of data) */
-#define PSA_CRYPTO_MAX_STORAGE_SIZE ( 30 * 1024 )
+/* Limit the maximum key size in storage. This should have no effect
+ * since the key size is limited in memory. */
+#define PSA_CRYPTO_MAX_STORAGE_SIZE ( PSA_BITS_TO_BYTES( PSA_MAX_KEY_BITS ) )
+/* Sanity check: a file size must fit in 32 bits. Allow a generous
+ * 64kB of metadata. */
+#if PSA_CRYPTO_MAX_STORAGE_SIZE > 0xffff0000
+#error PSA_CRYPTO_MAX_STORAGE_SIZE > 0xffff0000
+#endif
/** The maximum permitted persistent slot number.
*