diff --git a/include/polarssl/entropy.h b/include/polarssl/entropy.h index e334c2247..235b7733c 100644 --- a/include/polarssl/entropy.h +++ b/include/polarssl/entropy.h @@ -41,6 +41,10 @@ #endif #endif +#if defined(POLARSSL_THREADING_C) +#include "threading.h" +#endif + #if defined(POLARSSL_HAVEGE_C) #include "havege.h" #endif @@ -106,6 +110,9 @@ typedef struct #if defined(POLARSSL_HAVEGE_C) havege_state havege_data; #endif +#if defined(POLARSSL_THREADING_C) + threading_mutex_t mutex; /*!< mutex */ +#endif } entropy_context; @@ -149,6 +156,7 @@ int entropy_gather( entropy_context *ctx ); /** * \brief Retrieve entropy from the accumulator (Max ENTROPY_BLOCK_SIZE) + * (Thread-safe if POLARSSL_THREADING_C is enabled) * * \param data Entropy context * \param output Buffer to fill diff --git a/library/entropy.c b/library/entropy.c index d43f9833c..c5fac26e9 100644 --- a/library/entropy.c +++ b/library/entropy.c @@ -40,6 +40,10 @@ void entropy_init( entropy_context *ctx ) { memset( ctx, 0, sizeof(entropy_context) ); +#if defined(POLARSSL_THREADING_C) + polarssl_mutex_init( &ctx->mutex ); +#endif + #if defined(POLARSSL_ENTROPY_SHA512_ACCUMULATOR) sha512_starts( &ctx->accumulator, 0 ); #else @@ -67,6 +71,9 @@ void entropy_init( entropy_context *ctx ) void entropy_free( entropy_context *ctx ) { ((void) ctx); +#if defined(POLARSSL_THREADING_C) + polarssl_mutex_free( &ctx->mutex ); +#endif } int entropy_add_source( entropy_context *ctx, @@ -175,16 +182,24 @@ int entropy_func( void *data, unsigned char *output, size_t len ) if( len > ENTROPY_BLOCK_SIZE ) return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED ); +#if defined(POLARSSL_THREADING_C) + if( ( ret = polarssl_mutex_lock( &ctx->mutex ) ) != 0 ) + return( ret ); +#endif + /* * Always gather extra entropy before a call */ do { if( count++ > ENTROPY_MAX_LOOP ) - return( POLARSSL_ERR_ENTROPY_SOURCE_FAILED ); + { + ret = POLARSSL_ERR_ENTROPY_SOURCE_FAILED; + goto exit; + } if( ( ret = entropy_gather( ctx ) ) != 0 ) - return( ret ); + goto exit; reached = 0; @@ -231,7 +246,15 @@ int entropy_func( void *data, unsigned char *output, size_t len ) memcpy( output, buf, len ); - return( 0 ); + ret = 0; + +exit: +#if defined(POLARSSL_THREADING_C) + if( polarssl_mutex_unlock( &ctx->mutex ) != 0 ) + return( POLARSSL_ERR_THREADING_MUTEX_ERROR ); +#endif + + return( ret ); } #endif