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>
This commit is contained in:
Gilles Peskine 2023-07-26 18:43:39 +02:00
parent 5fd88b7f75
commit 6b9017045f

View File

@ -166,11 +166,10 @@ void entropy_init_free(int reinit)
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 @@ exit:
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 @@ void entropy_func_len(int len, int ret)
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 @@ void entropy_source_fail(char *path)
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 @@ void entropy_threshold(int threshold, int chunk_size, int result)
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 @@ void entropy_calls(int strength1, int strength2,
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 @@ void entropy_nv_seed(data_t *read_seed)
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 @@ void entropy_nv_seed(data_t *read_seed)
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);