From e79812ed4d9c3186c3e4040217143cd0419a8e4a Mon Sep 17 00:00:00 2001 From: Victor Krasnoshchok Date: Thu, 27 Aug 2020 00:19:55 +0300 Subject: [PATCH] Fix premature fopen() call in mbedtls_entropy_write_seed_file #3175 Signed-off-by: Victor Krasnoshchok --- library/entropy.c | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/library/entropy.c b/library/entropy.c index db61f16d8..519c3aef3 100644 --- a/library/entropy.c +++ b/library/entropy.c @@ -466,28 +466,27 @@ 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 = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; - FILE *f; + int ret; + FILE *f = NULL; unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; - if( ( f = fopen( path, "wb" ) ) == NULL ) - return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR ); - if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 ) goto exit; - if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) != MBEDTLS_ENTROPY_BLOCK_SIZE ) + ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR; + 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 ) + goto exit; + ret = 0; } - ret = 0; - exit: mbedtls_platform_zeroize( buf, sizeof( buf ) ); - fclose( f ); + if( f ) + fclose( f ); + return( ret ); }