Don't call psa_crypto_init with uninitialized local contexts (entropy)
psa_crypto_init can fail, and if it does we'll try calling free() on the
local variable, which is uninitialized. This commit fixes memory corruption
when a test fails.
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/tests/suites/test_suite_entropy.function b/tests/suites/test_suite_entropy.function
index 617c875..0e013b7 100644
--- a/tests/suites/test_suite_entropy.function
+++ b/tests/suites/test_suite_entropy.function
@@ -166,11 +166,10 @@
void entropy_seed_file(char *path, int ret)
{
mbedtls_entropy_context ctx;
+ mbedtls_entropy_init(&ctx);
MD_PSA_INIT();
- mbedtls_entropy_init(&ctx);
-
TEST_ASSERT(mbedtls_entropy_write_seed_file(&ctx, path) == ret);
TEST_ASSERT(mbedtls_entropy_update_seed_file(&ctx, path) == ret);
@@ -184,11 +183,10 @@
void entropy_write_base_seed_file(int ret)
{
mbedtls_entropy_context ctx;
+ mbedtls_entropy_init(&ctx);
MD_PSA_INIT();
- mbedtls_entropy_init(&ctx);
-
TEST_ASSERT(mbedtls_entropy_write_seed_file(&ctx, MBEDTLS_PLATFORM_STD_NV_SEED_FILE) == ret);
TEST_ASSERT(mbedtls_entropy_update_seed_file(&ctx, MBEDTLS_PLATFORM_STD_NV_SEED_FILE) == ret);
@@ -249,10 +247,10 @@
unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE + 10] = { 0 };
size_t i, j;
- MD_PSA_INIT();
-
mbedtls_entropy_init(&ctx);
+ MD_PSA_INIT();
+
/*
* See comments in mbedtls_entropy_self_test()
*/
@@ -286,10 +284,10 @@
unsigned char buf[16];
entropy_dummy_context dummy = { DUMMY_FAIL, 0, 0 };
- MD_PSA_INIT();
-
mbedtls_entropy_init(&ctx);
+ MD_PSA_INIT();
+
TEST_ASSERT(mbedtls_entropy_add_source(&ctx, entropy_dummy_source,
&dummy, 16,
MBEDTLS_ENTROPY_SOURCE_WEAK)
@@ -324,11 +322,11 @@
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
int ret;
- MD_PSA_INIT();
-
mbedtls_entropy_init(&ctx);
entropy_clear_sources(&ctx);
+ MD_PSA_INIT();
+
/* Set strong source that reaches its threshold immediately and
* a weak source whose threshold is a test parameter. */
TEST_ASSERT(mbedtls_entropy_add_source(&ctx, entropy_dummy_source,
@@ -374,11 +372,11 @@
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
int ret;
- MD_PSA_INIT();
-
mbedtls_entropy_init(&ctx);
entropy_clear_sources(&ctx);
+ MD_PSA_INIT();
+
TEST_ASSERT(mbedtls_entropy_add_source(&ctx, entropy_dummy_source,
&dummy1, threshold,
strength1) == 0);
@@ -473,8 +471,6 @@
unsigned char check_seed[MBEDTLS_ENTROPY_BLOCK_SIZE];
unsigned char check_entropy[MBEDTLS_ENTROPY_BLOCK_SIZE];
- MD_PSA_INIT();
-
memset(entropy, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
memset(buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
memset(empty, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
@@ -488,6 +484,8 @@
mbedtls_entropy_init(&ctx);
entropy_clear_sources(&ctx);
+ MD_PSA_INIT();
+
TEST_ASSERT(mbedtls_entropy_add_source(&ctx, mbedtls_nv_seed_poll, NULL,
MBEDTLS_ENTROPY_BLOCK_SIZE,
MBEDTLS_ENTROPY_SOURCE_STRONG) == 0);