From 552e8f2d6a28bdd664f01da2564ea261dcf56477 Mon Sep 17 00:00:00 2001
From: Jarno Lamsa <jarno.lamsa@arm.com>
Date: Thu, 14 Nov 2019 10:05:36 +0200
Subject: [PATCH] Add double check to entropy-loop

To prevent glitching and going through without strong source
---
 library/entropy.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/library/entropy.c b/library/entropy.c
index 75421cfb2..fdb2e152f 100644
--- a/library/entropy.c
+++ b/library/entropy.c
@@ -258,7 +258,8 @@ int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
  */
 static int entropy_gather_internal( mbedtls_entropy_context *ctx )
 {
-    int ret, i, have_one_strong = 0;
+    int ret, i;
+    volatile int have_one_strong_fi = 0;
     unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER];
     size_t olen;
 
@@ -271,7 +272,7 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
     for( i = 0; i < ctx->source_count; i++ )
     {
         if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )
-            have_one_strong = 1;
+            have_one_strong_fi = 1;
 
         olen = 0;
         if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,
@@ -292,8 +293,14 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
         }
     }
 
-    if( have_one_strong == 0 )
-        ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
+    if( have_one_strong_fi == 0 )
+    {
+        mbedtls_platform_enforce_volatile_reads();
+        if( have_one_strong_fi == 0)
+        {
+            ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
+        }
+    }
 
 cleanup:
     mbedtls_platform_zeroize( buf, sizeof( buf ) );