psa_import_key: fix memory leak on error

Free the content of the pk object if an error occurs after the import.
This commit is contained in:
Gilles Peskine 2018-06-28 08:46:13 +02:00 committed by itayzafrir
parent 122b265067
commit c648d6949d

View File

@ -487,6 +487,7 @@ psa_status_t psa_import_key( psa_key_slot_t key,
{ {
int ret; int ret;
mbedtls_pk_context pk; mbedtls_pk_context pk;
psa_status_t status = PSA_SUCCESS;
mbedtls_pk_init( &pk ); mbedtls_pk_init( &pk );
if( PSA_KEY_TYPE_IS_KEYPAIR( type ) ) if( PSA_KEY_TYPE_IS_KEYPAIR( type ) )
ret = mbedtls_pk_parse_key( &pk, data, data_length, NULL, 0 ); 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 ) type == PSA_KEY_TYPE_RSA_KEYPAIR )
slot->data.rsa = mbedtls_pk_rsa( pk ); slot->data.rsa = mbedtls_pk_rsa( pk );
else else
return( PSA_ERROR_INVALID_ARGUMENT ); status = PSA_ERROR_INVALID_ARGUMENT;
break; break;
#endif /* MBEDTLS_RSA_C */ #endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_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_ecc_curve_t expected_curve =
PSA_KEY_TYPE_GET_CURVE( type ); PSA_KEY_TYPE_GET_CURVE( type );
if( actual_curve != expected_curve ) if( actual_curve != expected_curve )
return( PSA_ERROR_INVALID_ARGUMENT ); {
status = PSA_ERROR_INVALID_ARGUMENT;
break;
}
slot->data.ecp = ecp; slot->data.ecp = ecp;
} }
else else
return( PSA_ERROR_INVALID_ARGUMENT ); status = PSA_ERROR_INVALID_ARGUMENT;
break; break;
#endif /* MBEDTLS_ECP_C */ #endif /* MBEDTLS_ECP_C */
default: 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 else