psa_import_key: fix memory leak on error
Free the content of the pk object if an error occurs after the import.
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index de2bf40..dbeeef6 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -487,6 +487,7 @@
{
int ret;
mbedtls_pk_context pk;
+ psa_status_t status = PSA_SUCCESS;
mbedtls_pk_init( &pk );
if( PSA_KEY_TYPE_IS_KEYPAIR( type ) )
ret = mbedtls_pk_parse_key( &pk, data, data_length, NULL, 0 );
@@ -502,7 +503,7 @@
type == PSA_KEY_TYPE_RSA_KEYPAIR )
slot->data.rsa = mbedtls_pk_rsa( pk );
else
- return( PSA_ERROR_INVALID_ARGUMENT );
+ status = PSA_ERROR_INVALID_ARGUMENT;
break;
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
@@ -515,15 +516,26 @@
psa_ecc_curve_t expected_curve =
PSA_KEY_TYPE_GET_CURVE( type );
if( actual_curve != expected_curve )
- return( PSA_ERROR_INVALID_ARGUMENT );
+ {
+ status = PSA_ERROR_INVALID_ARGUMENT;
+ break;
+ }
slot->data.ecp = ecp;
}
else
- return( PSA_ERROR_INVALID_ARGUMENT );
+ status = PSA_ERROR_INVALID_ARGUMENT;
break;
#endif /* MBEDTLS_ECP_C */
default:
- return( PSA_ERROR_INVALID_ARGUMENT );
+ status = PSA_ERROR_INVALID_ARGUMENT;
+ break;
+ }
+ /* Free the content of the pk object only on error. On success,
+ * the content of the object has been stored in the slot. */
+ if( status != PSA_SUCCESS )
+ {
+ mbedtls_pk_free( &pk );
+ return( status );
}
}
else