Streamline mbedtls_xxx_drbg_update_seed_file

Refactor mbedtls_ctr_drbg_update_seed_file and
mbedtls_hmac_drbg_update_seed_file to make the error logic clearer.

The new code does not use fseek, so it works with non-seekable files.
This commit is contained in:
Gilles Peskine 2018-09-11 18:43:09 +02:00
parent b7f71c8bc1
commit 8220466297
2 changed files with 32 additions and 30 deletions

View file

@ -568,35 +568,36 @@ exit:
int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path )
{
int ret = 0;
FILE *f;
FILE *f = NULL;
size_t n;
unsigned char buf[ MBEDTLS_CTR_DRBG_MAX_INPUT ];
unsigned char c;
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR );
fseek( f, 0, SEEK_END );
n = (size_t) ftell( f );
fseek( f, 0, SEEK_SET );
if( n > MBEDTLS_CTR_DRBG_MAX_INPUT )
n = fread( buf, 1, sizeof( buf ), f );
if( fread( &c, 1, 1, f ) != 0 )
{
fclose( f );
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
ret = MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG;
goto exit;
}
if( fread( buf, 1, n, f ) != n )
if( n == 0 || ferror( f ) )
{
ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;
else
ret = mbedtls_ctr_drbg_update_ret( ctx, buf, n );
goto exit;
}
fclose( f );
f = NULL;
ret = mbedtls_ctr_drbg_update_ret( ctx, buf, n );
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
if( f != NULL )
fclose( f );
if( ret != 0 )
return( ret );
return( mbedtls_ctr_drbg_write_seed_file( ctx, path ) );
}
#endif /* MBEDTLS_FS_IO */

View file

@ -417,35 +417,36 @@ exit:
int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )
{
int ret = 0;
FILE *f;
FILE *f = NULL;
size_t n;
unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];
unsigned char c;
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR );
fseek( f, 0, SEEK_END );
n = (size_t) ftell( f );
fseek( f, 0, SEEK_SET );
if( n > MBEDTLS_HMAC_DRBG_MAX_INPUT )
n = fread( buf, 1, sizeof( buf ), f );
if( fread( &c, 1, 1, f ) != 0 )
{
fclose( f );
return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );
ret = MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG;
goto exit;
}
if( fread( buf, 1, n, f ) != n )
if( n == 0 || ferror( f ) )
{
ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;
else
ret = mbedtls_hmac_drbg_update_ret( ctx, buf, n );
goto exit;
}
fclose( f );
f = NULL;
ret = mbedtls_hmac_drbg_update_ret( ctx, buf, n );
exit:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
if( f != NULL )
fclose( f );
if( ret != 0 )
return( ret );
return( mbedtls_hmac_drbg_write_seed_file( ctx, path ) );
}
#endif /* MBEDTLS_FS_IO */