From feb0396d20593ea557835657d04f449bc52d4557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Thu, 20 Aug 2020 09:59:33 +0200 Subject: [PATCH] Fix memory leak in test_suite_x509write with PSA crypto MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The documentation of mbedtls_pk_wrap_as_opaque is quite clear: * \param handle Output: a PSA key handle. * It's the caller's responsibility to call * psa_destroy_key() on that handle after calling * mbedtls_pk_free() on the PK context. But the test failed to call psa_destroy_key(). While at it, also use PSA_DONE(): it ensures that if we fail to destroy the key, we'll get an explicit error message about it without the need for valgrind. This is a preliminary to adding a valgrind-based test for constant-flow code: we need to make sure the rest of the tests are fully valgrind-clean, which they weren't. Signed-off-by: Manuel Pégourié-Gonnard --- tests/suites/test_suite_x509write.function | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/tests/suites/test_suite_x509write.function b/tests/suites/test_suite_x509write.function index be9e0ae52..b205b74d7 100644 --- a/tests/suites/test_suite_x509write.function +++ b/tests/suites/test_suite_x509write.function @@ -5,12 +5,20 @@ #include "mbedtls/pem.h" #include "mbedtls/oid.h" #include "mbedtls/rsa.h" + #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #include "mbedtls/psa_util.h" +#include "test/psa_crypto_helpers.h" +#define PSA_INIT( ) PSA_ASSERT( psa_crypto_init( ) ) +#else +/* Define empty macros so that we can use them in the preamble and teardown + * of every test function that uses PSA conditionally based on + * MBEDTLS_USE_PSA_CRYPTO. */ +#define PSA_INIT( ) ( (void) 0 ) +#define PSA_DONE( ) ( (void) 0 ) #endif - #if defined(MBEDTLS_RSA_C) int mbedtls_rsa_decrypt_func( void *ctx, int mode, size_t *olen, const unsigned char *input, unsigned char *output, @@ -156,7 +164,7 @@ void x509_csr_check_opaque( char *key_file, int md_type, int key_usage, const char *subject_name = "C=NL,O=PolarSSL,CN=PolarSSL Server 1"; mbedtls_test_rnd_pseudo_info rnd_info; - psa_crypto_init(); + PSA_INIT( ); memset( &rnd_info, 0x2a, sizeof( mbedtls_test_rnd_pseudo_info ) ); md_alg_psa = mbedtls_psa_translate_md( (mbedtls_md_type_t) md_type ); @@ -184,9 +192,12 @@ void x509_csr_check_opaque( char *key_file, int md_type, int key_usage, buf[pem_len] = '\0'; TEST_ASSERT( x509_crt_verifycsr( buf, pem_len + 1 ) == 0 ); + exit: mbedtls_x509write_csr_free( &req ); mbedtls_pk_free( &key ); + psa_destroy_key( slot ); + PSA_DONE( ); } /* END_CASE */