Reject non-byte-aligned RSA keys
On key import and key generation, for RSA, reject key sizes that are
not a multiple of 8. Such keys are not well-supported in Mbed TLS and
are hardly ever used in practice.
The previous commit removed support for non-byte-aligned keys at the
PSA level. This commit actively rejects such keys and adds
corresponding tests (test keys generated with "openssl genrsa").
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index dc6f2da..4584f6b 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -571,6 +571,28 @@
}
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C)
+/* Mbed TLS doesn't support non-byte-aligned key sizes (i.e. key sizes
+ * that are not a multiple of 8) well. For example, there is only
+ * mbedtls_rsa_get_len(), which returns a number of bytes, and no
+ * way to return the exact bit size of a key.
+ * To keep things simple, reject non-byte-aligned key sizes. */
+static psa_status_t psa_check_rsa_key_byte_aligned(
+ const mbedtls_rsa_context *rsa )
+{
+ mbedtls_mpi n;
+ psa_status_t status;
+ mbedtls_mpi_init( &n );
+ status = mbedtls_to_psa_error(
+ mbedtls_rsa_export( rsa, &n, NULL, NULL, NULL, NULL ) );
+ if( status == PSA_SUCCESS )
+ {
+ if( mbedtls_mpi_bitlen( &n ) % 8 != 0 )
+ status = PSA_ERROR_NOT_SUPPORTED;
+ }
+ mbedtls_mpi_free( &n );
+ return( status );
+}
+
static psa_status_t psa_import_rsa_key( mbedtls_pk_context *pk,
mbedtls_rsa_context **p_rsa )
{
@@ -584,8 +606,12 @@
* For example, mbedtls_rsa_get_len() returns the key size in
* bytes, not in bits. */
size_t bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( rsa ) );
+ psa_status_t status;
if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
return( PSA_ERROR_NOT_SUPPORTED );
+ status = psa_check_rsa_key_byte_aligned( rsa );
+ if( status != PSA_SUCCESS )
+ return( status );
*p_rsa = rsa;
return( PSA_SUCCESS );
}
@@ -3556,6 +3582,10 @@
int exponent = 65537;
if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
return( PSA_ERROR_NOT_SUPPORTED );
+ /* Accept only byte-aligned keys, for the same reasons as
+ * in psa_import_rsa_key(). */
+ if( bits % 8 != 0 )
+ return( PSA_ERROR_NOT_SUPPORTED );
if( extra != NULL )
{
const psa_generate_key_extra_rsa *p = extra;