From ce37e6269ed709ad08da0924cb5e6635ebf36860 Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Tue, 27 Jun 2017 08:24:34 +0100 Subject: [PATCH] Reliably zeroize sensitive data in AES sample application The AES sample application programs/aes/aescrypt2 could miss zeroizing the stack-based key buffer in case of an error during operation. This commit fixes this and also clears another temporary buffer as well as all command line arguments (one of which might be the key) before exit. --- programs/aes/aescrypt2.c | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/programs/aes/aescrypt2.c b/programs/aes/aescrypt2.c index c77d77f5f..7cd3349fe 100644 --- a/programs/aes/aescrypt2.c +++ b/programs/aes/aescrypt2.c @@ -79,7 +79,9 @@ int main( int argc, char *argv[] ) FILE *fkey, *fin = NULL, *fout = NULL; char *p; + unsigned char IV[16]; + unsigned char tmp[16]; unsigned char key[512]; unsigned char digest[32]; unsigned char buffer[1024]; @@ -123,10 +125,10 @@ int main( int argc, char *argv[] ) } mode = atoi( argv[1] ); - memset(IV, 0, sizeof(IV)); - memset(key, 0, sizeof(key)); - memset(digest, 0, sizeof(digest)); - memset(buffer, 0, sizeof(buffer)); + memset( IV, 0, sizeof( IV ) ); + memset( key, 0, sizeof( key ) ); + memset( digest, 0, sizeof( digest ) ); + memset( buffer, 0, sizeof( buffer ) ); if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT ) { @@ -185,8 +187,6 @@ int main( int argc, char *argv[] ) } } - memset( argv[4], 0, strlen( argv[4] ) ); - #if defined(_WIN32_WCE) filesize = fseek( fin, 0L, SEEK_END ); #else @@ -272,7 +272,6 @@ int main( int argc, char *argv[] ) mbedtls_md_finish( &sha_ctx, digest ); } - memset( key, 0, sizeof( key ) ); mbedtls_aes_setkey_enc( &aes_ctx, digest, 256 ); mbedtls_md_hmac_starts( &sha_ctx, digest, 32 ); @@ -319,7 +318,6 @@ int main( int argc, char *argv[] ) if( mode == MODE_DECRYPT ) { - unsigned char tmp[16]; /* * The encrypted file must be structured as follows: @@ -374,7 +372,6 @@ int main( int argc, char *argv[] ) mbedtls_md_finish( &sha_ctx, digest ); } - memset( key, 0, sizeof( key ) ); mbedtls_aes_setkey_dec( &aes_ctx, digest, 256 ); mbedtls_md_hmac_starts( &sha_ctx, digest, 32 ); @@ -441,6 +438,15 @@ exit: if( fout ) fclose( fout ); + /* Zeroize all command line arguments to also cover + the case when the user has missed or reordered some, + in which case the key might not be in argv[4]. */ + for( i = 0; i < (unsigned int) argc; i++ ) + memset( argv[i], 0, strlen( argv[i] ) ); + + memset( IV, 0, sizeof( IV ) ); + memset( key, 0, sizeof( key ) ); + memset( tmp, 0, sizeof( tmp ) ); memset( buffer, 0, sizeof( buffer ) ); memset( digest, 0, sizeof( digest ) );