psa_import_key: fix memory leak on error
Free the content of the pk object if an error occurs after the import.
@@ -487,6 +487,7 @@ psa_status_t psa_import_key( psa_key_slot_t key,
{
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 @@ psa_status_t psa_import_key( psa_key_slot_t key,
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_status_t psa_import_key( psa_key_slot_t key,
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
