From b3129ba11930c81fb47b58d81e4c4651a24aaec6 Mon Sep 17 00:00:00 2001 From: Victor Krasnoshchok Date: Sat, 29 Aug 2020 22:54:37 +0300 Subject: [PATCH] Refactoring after CR and new unit test #3175 Signed-off-by: Victor Krasnoshchok --- library/entropy.c | 25 +++++++++++++++--------- tests/suites/test_suite_entropy.data | 3 +++ tests/suites/test_suite_entropy.function | 15 ++++++++++++++ 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/library/entropy.c b/library/entropy.c index 519c3aef3..fd2c207f0 100644 --- a/library/entropy.c +++ b/library/entropy.c @@ -466,25 +466,32 @@ int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx ) #if defined(MBEDTLS_FS_IO) int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path ) { - int ret; + int ret = 0; FILE *f = NULL; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) - goto exit; - - ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; - if( ( f = fopen( path, "wb" ) ) != NULL ) { - if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE ) - goto exit; - ret = 0; + ret = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; + goto exit; + } + + if( ( f = fopen( path, "wb" ) ) == NULL ) + { + ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; + goto exit; + } + + if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE ) + { + ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; + goto exit; } exit: mbedtls_platform_zeroize( buf, sizeof( buf ) ); - if( f ) + if( f != NULL ) fclose( f ); return( ret ); diff --git a/tests/suites/test_suite_entropy.data b/tests/suites/test_suite_entropy.data index b2d20b472..bc077f815 100644 --- a/tests/suites/test_suite_entropy.data +++ b/tests/suites/test_suite_entropy.data @@ -7,6 +7,9 @@ entropy_seed_file:"data_files/entropy_seed":0 Entropy write/update seed file: nonexistent entropy_seed_file:"no_such_dir/file":MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR +Entropy write/update seed file: base NV seed file +entropy_write_base_seed_file:0 + Entropy no sources entropy_no_sources: diff --git a/tests/suites/test_suite_entropy.function b/tests/suites/test_suite_entropy.function index d9ea44149..a453aadf3 100644 --- a/tests/suites/test_suite_entropy.function +++ b/tests/suites/test_suite_entropy.function @@ -149,6 +149,21 @@ exit: } /* END_CASE */ +/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */ +void entropy_write_base_seed_file( int ret ) +{ + mbedtls_entropy_context ctx; + + 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 ); + +exit: + mbedtls_entropy_free( &ctx ); +} +/* END_CASE */ + /* BEGIN_CASE */ void entropy_no_sources( ) {