Merge pull request #3395 from AndrzejKurek/sha-flow_ctrl

Add flow control to sha256
diff --git a/include/mbedtls/error.h b/include/mbedtls/error.h
index a52f9f5..9696f17 100644
--- a/include/mbedtls/error.h
+++ b/include/mbedtls/error.h
@@ -86,7 +86,7 @@
  * CHACHA20  3                  0x0051-0x0055
  * POLY1305  3                  0x0057-0x005B
  * CHACHAPOLY 2 0x0054-0x0056
- * PLATFORM  3  0x0070-0x0072   0x0071-0x0071
+ * PLATFORM  4  0x0070-0x0072   0x0071-0x0071 0x0076-0x0076
  *
  * High-level module nr (3 bits - 0x0...-0x7...)
  * Name      ID  Nr of Errors
diff --git a/include/mbedtls/nist_kw.h b/include/mbedtls/nist_kw.h
index 3b67b59..c94c15a 100644
--- a/include/mbedtls/nist_kw.h
+++ b/include/mbedtls/nist_kw.h
@@ -133,6 +133,7 @@
  *
  * \return          \c 0 on success.
  * \return          \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.
+ * \return          \c MBEDTLS_ERR_PLATFORM_ALLOC_FAILED in case of a memory allocation failure.
  * \return          cipher-specific error code on failure of the underlying cipher.
  */
 int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,
diff --git a/include/mbedtls/platform.h b/include/mbedtls/platform.h
index ec1df15..8a88ce7 100644
--- a/include/mbedtls/platform.h
+++ b/include/mbedtls/platform.h
@@ -42,6 +42,7 @@
 #define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED     -0x0070 /**< Hardware accelerator failed */
 #define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */
 #define MBEDTLS_ERR_PLATFORM_FAULT_DETECTED      -0x0071 /**< A hardware fault was detected in a critical path. As a security precaution this should be treated as a potential physical attack */
+#define MBEDTLS_ERR_PLATFORM_ALLOC_FAILED        -0x0076 /**< Memory allocation failed */
 
 #if defined(MBEDTLS_PLATFORM_C)
 
diff --git a/include/mbedtls/platform_util.h b/include/mbedtls/platform_util.h
index fa9f326..4e0f989 100644
--- a/include/mbedtls/platform_util.h
+++ b/include/mbedtls/platform_util.h
@@ -199,6 +199,22 @@
 void *mbedtls_platform_memcpy( void *dst, const void *src, size_t num );
 
 /**
+ * \brief       Secure memmove
+ *
+ *              This is a constant-time version of memmove(). It is based on
+ *              the double use of the mbedtls_platform_memcpy() function secured
+ *              against side-channel attacks.
+ *
+ * \param dst   Destination buffer where the data is being moved to.
+ * \param src   Source buffer where the data is being moved from.
+ * \param num   The length of the buffers in bytes.
+ *
+ * \return      0 if the operation was successful
+ * \return      #MBEDTLS_ERR_PLATFORM_ALLOC_FAILED if a memory allocation failed
+ */
+int mbedtls_platform_memmove( void *dst, const void *src, size_t num );
+
+/**
  * \brief       Secure memcmp
  *
  *              This is a constant-time version of memcmp(). If
diff --git a/include/tinycrypt/ecc.h b/include/tinycrypt/ecc.h
index 6a85a55..57aa508 100644
--- a/include/tinycrypt/ecc.h
+++ b/include/tinycrypt/ecc.h
@@ -155,7 +155,8 @@
  * @param random OUT -- random integer in the range 0 < random < top
  * @param top IN -- upper limit
  * @param num_words IN -- number of words
- * @return a random integer in the range 0 < random < top
+ * @return UECC_SUCCESS in case of success
+ * @return UECC_FAILURE upon failure
  */
 int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top,
 			     wordcount_t num_words);
@@ -163,9 +164,9 @@
 
 /* uECC_RNG_Function type
  * The RNG function should fill 'size' random bytes into 'dest'. It should
- * return 1 if 'dest' was filled with random data, or 0 if the random data could
- * not be generated. The filled-in values should be either truly random, or from
- * a cryptographically-secure PRNG.
+ * return 'size' if 'dest' was filled with random data of 'size' length, or 0
+ * if the random data could not be generated. The filled-in values should be
+ * either truly random, or from a cryptographically-secure PRNG.
  *
  * A correctly functioning RNG function must be set (using uECC_set_rng())
  * before calling uECC_make_key() or uECC_sign().
@@ -181,8 +182,8 @@
 
 /*
  * @brief Set the function that will be used to generate random bytes. The RNG
- * function should return 1 if the random data was generated, or 0 if the random
- * data could not be generated.
+ * function should return 'size' if the random data of length 'size' was
+ * generated, or 0 if the random data could not be generated.
  *
  * @note On platforms where there is no predefined RNG function, this must be
  * called before uECC_make_key() or uECC_sign() are used.
diff --git a/library/bignum.c b/library/bignum.c
index 00df10d..f4ab0db 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -558,7 +558,7 @@
         length++;
     } while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
 
-    memmove( *p, p_end, length );
+    MBEDTLS_MPI_CHK( mbedtls_platform_memmove( *p, p_end, length ) );
     *p += length;
 
 cleanup:
diff --git a/library/ccm.c b/library/ccm.c
index 9911e0f..750ec9e 100644
--- a/library/ccm.c
+++ b/library/ccm.c
@@ -37,6 +37,7 @@
 #if defined(MBEDTLS_CCM_C)
 
 #include "mbedtls/ccm.h"
+#include "mbedtls/platform.h"
 #include "mbedtls/platform_util.h"
 
 #include <string.h>
@@ -74,7 +75,7 @@
                         const unsigned char *key,
                         unsigned int keybits )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     const mbedtls_cipher_info_t *cipher_info;
 
     CCM_VALIDATE_RET( ctx != NULL );
@@ -98,7 +99,7 @@
         return( ret );
     }
 
-    return( 0 );
+    return( ret );
 }
 
 /*
@@ -155,7 +156,7 @@
                            const unsigned char *input, unsigned char *output,
                            unsigned char *tag, size_t tag_len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     unsigned char i;
     unsigned char q;
     size_t len_left, olen;
@@ -315,7 +316,7 @@
     CTR_CRYPT( y, y, 16 );
     mbedtls_platform_memcpy( tag, y, tag_len );
 
-    return( 0 );
+    return( ret );
 }
 
 /*
@@ -365,7 +366,7 @@
                       const unsigned char *input, unsigned char *output,
                       const unsigned char *tag, size_t tag_len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     unsigned char check_tag[16];
     unsigned char i;
     int diff;
@@ -394,7 +395,7 @@
         return( MBEDTLS_ERR_CCM_AUTH_FAILED );
     }
 
-    return( 0 );
+    return( ret );
 }
 
 int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
diff --git a/library/entropy.c b/library/entropy.c
index 6656ee8..f5d7d40 100644
--- a/library/entropy.c
+++ b/library/entropy.c
@@ -142,7 +142,7 @@
                         mbedtls_entropy_f_source_ptr f_source, void *p_source,
                         size_t threshold, int strong )
 {
-    int idx, ret = 0;
+    int idx, ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
 #if defined(MBEDTLS_THREADING_C)
     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
@@ -162,6 +162,7 @@
     ctx->source[idx].strong    = strong;
 
     ctx->source_count++;
+    ret = 0;
 
 exit:
 #if defined(MBEDTLS_THREADING_C)
@@ -182,7 +183,7 @@
     unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];
     size_t use_len = len;
     const unsigned char *p = data;
-    int ret = 0;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )
     {
@@ -234,7 +235,7 @@
 int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
                            const unsigned char *data, size_t len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
 #if defined(MBEDTLS_THREADING_C)
     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
@@ -325,7 +326,7 @@
  */
 int mbedtls_entropy_gather( mbedtls_entropy_context *ctx )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
 #if defined(MBEDTLS_THREADING_C)
     if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
@@ -344,7 +345,8 @@
 
 int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
 {
-    int ret, count = 0, i, done;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
+    int count = 0, i, done;
     mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data;
     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
 
diff --git a/library/error.c b/library/error.c
index ecdec78..893de7f 100644
--- a/library/error.c
+++ b/library/error.c
@@ -843,6 +843,8 @@
         mbedtls_snprintf( buf, buflen, "PLATFORM - The requested feature is not supported by the platform" );
     if( use_ret == -(MBEDTLS_ERR_PLATFORM_FAULT_DETECTED) )
         mbedtls_snprintf( buf, buflen, "PLATFORM - A hardware fault was detected in a critical path. As a security precaution this should be treated as a potential physical attack" );
+    if( use_ret == -(MBEDTLS_ERR_PLATFORM_ALLOC_FAILED) )
+        mbedtls_snprintf( buf, buflen, "PLATFORM - Memory allocation failed" );
 #endif /* MBEDTLS_PLATFORM_C */
 
 #if defined(MBEDTLS_POLY1305_C)
diff --git a/library/hmac_drbg.c b/library/hmac_drbg.c
index dd895be..d197f24 100644
--- a/library/hmac_drbg.c
+++ b/library/hmac_drbg.c
@@ -199,7 +199,7 @@
     unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];
     size_t seedlen = 0;
     size_t total_entropy_len;
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     if( use_nonce == HMAC_NONCE_NO )
         total_entropy_len = ctx->entropy_len;
@@ -298,7 +298,7 @@
                     const unsigned char *custom,
                     size_t len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     size_t md_size;
 
     if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
@@ -375,7 +375,7 @@
                                unsigned char *output, size_t out_len,
                                const unsigned char *additional, size_t add_len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     volatile unsigned char *output_fi = output;
     volatile size_t out_len_fi = out_len;
     mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;
@@ -461,7 +461,7 @@
  */
 int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;
 
 #if defined(MBEDTLS_THREADING_C)
diff --git a/library/nist_kw.c b/library/nist_kw.c
index 0ad270a..2f7f082 100644
--- a/library/nist_kw.c
+++ b/library/nist_kw.c
@@ -222,7 +222,11 @@
         }
 
         mbedtls_platform_memcpy( output, NIST_KW_ICV1, KW_SEMIBLOCK_LENGTH );
-        memmove( output + KW_SEMIBLOCK_LENGTH, input, in_len );
+        ret = mbedtls_platform_memmove( output + KW_SEMIBLOCK_LENGTH, input, in_len );
+        if( ret != 0 )
+        {
+            return ret;
+        }
     }
     else
     {
@@ -343,7 +347,12 @@
     }
 
     mbedtls_platform_memcpy( A, input, KW_SEMIBLOCK_LENGTH );
-    memmove( output, input + KW_SEMIBLOCK_LENGTH, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
+    ret = mbedtls_platform_memmove( output, input + KW_SEMIBLOCK_LENGTH,
+                                       ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
+    if( ret != 0 )
+    {
+        return ret;
+    }
 
     /* Calculate intermediate values */
     for( t = s; t >= 1; t-- )
diff --git a/library/pk.c b/library/pk.c
index caa5e17..b92eb14 100644
--- a/library/pk.c
+++ b/library/pk.c
@@ -46,10 +46,9 @@
 #endif /* MBEDTLS_USE_TINYCRYPT */
 
 #include "mbedtls/platform_util.h"
-
-#if defined(MBEDTLS_PLATFORM_C)
 #include "mbedtls/platform.h"
-#else
+
+#if !defined(MBEDTLS_PLATFORM_C)
 #include <stdlib.h>
 #define mbedtls_calloc    calloc
 #define mbedtls_free       free
@@ -576,8 +575,8 @@
                        const unsigned char *hash, size_t hash_len,
                        const unsigned char *sig, size_t sig_len )
 {
-    int ret;
-    volatile int ret_fi;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
+    volatile int ret_fi = UECC_FAULT_DETECTED;
     uint8_t signature[2*NUM_ECC_BYTES];
     unsigned char *p;
     const mbedtls_uecc_keypair *keypair = (const mbedtls_uecc_keypair *) ctx;
@@ -623,13 +622,18 @@
                               size_t n_len )
 {
     size_t len = 0;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     if( (size_t)( *p - start ) < n_len )
         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
 
     len = n_len;
     *p -= len;
-    memmove( *p, start, len );
+    ret = mbedtls_platform_memmove( *p, start, len );
+    if( ret != 0 )
+    {
+        return( ret );
+    }
 
     /* ASN.1 DER encoding requires minimal length, so skip leading 0s.
      * Neither r nor s should be 0, but as a failsafe measure, still detect
@@ -677,7 +681,7 @@
 static int pk_ecdsa_sig_asn1_from_uecc( unsigned char *sig, size_t *sig_len,
                                         size_t buf_len )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     size_t len = 0;
     const size_t rs_len = *sig_len / 2;
     unsigned char *p = sig + buf_len;
@@ -691,10 +695,14 @@
     *--p = MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE;
     len += 2;
 
-    memmove( sig, p, len );
+    ret = mbedtls_platform_memmove( sig, p, len );
+    if( ret != 0 )
+    {
+        return( ret );
+    }
     *sig_len = len;
 
-    return( 0 );
+    return( ret );
 }
 
 static int uecc_eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
@@ -1560,7 +1568,7 @@
         }
         else
         {
-            verify_ret = MBEDTLS_ERR_PK_HW_ACCEL_FAILED;
+            verify_ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
         }
     }
 
diff --git a/library/platform_util.c b/library/platform_util.c
index 3869f30..de2fa2b 100644
--- a/library/platform_util.c
+++ b/library/platform_util.c
@@ -38,6 +38,12 @@
 #include "mbedtls/platform.h"
 #include "mbedtls/threading.h"
 
+#if !defined(MBEDTLS_PLATFORM_C)
+#include <stdlib.h>
+#define mbedtls_calloc    calloc
+#define mbedtls_free       free
+#endif
+
 #if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
 #include "mbedtls/entropy_poll.h"
 #endif
@@ -121,6 +127,23 @@
     return( memcpy( (void *) dst, (void *) src, start_offset ) );
 }
 
+int mbedtls_platform_memmove( void *dst, const void *src, size_t num )
+{
+    /* The buffers can have a common part, so we cannot do a copy from a random
+     * location. By using a temporary buffer we can do so, but the cost of it
+     * is using more memory and longer transfer time. */
+    void *tmp = mbedtls_calloc( 1, num );
+    if( tmp != NULL )
+    {
+        mbedtls_platform_memcpy( tmp, src, num );
+        mbedtls_platform_memcpy( dst, tmp, num );
+        mbedtls_free( tmp );
+        return 0;
+    }
+
+    return MBEDTLS_ERR_PLATFORM_ALLOC_FAILED;
+}
+
 int mbedtls_platform_memcmp( const void *buf1, const void *buf2, size_t num )
 {
     volatile const unsigned char *A = (volatile const unsigned char *) buf1;
@@ -190,6 +213,9 @@
     do
     {
         i++;
+        /* Dummy calculations to increase the time between iterations and
+         * make side channel attack more difficult by reducing predictability
+         * of its behaviour */
         shift = rn_2 & 0x07;
         if ( i % 2 )
             rn_2 = (uint32_t)( rn_2 >> shift | rn_2 << ( 32 - shift ) );
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index ffd0554..5c74386 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -27,9 +27,9 @@
 
 #if defined(MBEDTLS_SSL_CLI_C)
 
-#if defined(MBEDTLS_PLATFORM_C)
 #include "mbedtls/platform.h"
-#else
+
+#if !defined(MBEDTLS_PLATFORM_C)
 #include <stdlib.h>
 #define mbedtls_calloc    calloc
 #define mbedtls_free      free
@@ -47,6 +47,7 @@
 #include "mbedtls/platform_time.h"
 #endif
 
+#include "mbedtls/platform.h"
 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
 #include "mbedtls/platform_util.h"
 #endif
@@ -682,7 +683,7 @@
  */
 static int ssl_generate_random( mbedtls_ssl_context *ssl )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     unsigned char *p = ssl->handshake->randbytes;
 #if defined(MBEDTLS_HAVE_TIME)
     mbedtls_time_t t;
@@ -723,6 +724,10 @@
             ssl->handshake->hello_random_set = MBEDTLS_SSL_FI_FLAG_SET;
             return( 0 );
         }
+        else
+        {
+            ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
+        }
     }
 
     return( ret );
@@ -2354,7 +2359,7 @@
                                          unsigned char* out,
                                          unsigned add_length_tag )
 {
-    volatile int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+    volatile int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     /*
      * Generate (part of) the pre-master secret as
@@ -2387,6 +2392,10 @@
             ssl->handshake->premaster_generated = MBEDTLS_SSL_FI_FLAG_SET;
             return( 0 );
         }
+        else
+        {
+            ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
+        }
     }
 
     MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
@@ -2402,7 +2411,7 @@
                                         unsigned char *out, size_t buflen,
                                         size_t *olen )
 {
-    volatile int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+    volatile int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     size_t len_bytes = mbedtls_ssl_get_minor_ver( ssl ) ==
         MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
     mbedtls_pk_context *peer_pk = NULL;
@@ -2459,6 +2468,12 @@
         {
             ssl->handshake->premaster_generated = MBEDTLS_SSL_FI_FLAG_SET;
         }
+        else
+        {
+            ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
+            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
+            goto cleanup;
+        }
     }
     else
     {
@@ -3100,7 +3115,7 @@
             }
             else
             {
-                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+                return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
             }
         }
 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
@@ -3133,7 +3148,7 @@
 
 static int ssl_process_in_server_key_exchange( mbedtls_ssl_context *ssl )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
 
     /* Preparation:
@@ -3374,7 +3389,7 @@
 
 static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
 
@@ -3408,7 +3423,7 @@
 
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
 
-    return( 0 );
+    return( ret );
 }
 
 /*
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index bab8f00..2cd34b2 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -27,9 +27,9 @@
 
 #if defined(MBEDTLS_SSL_SRV_C)
 
-#if defined(MBEDTLS_PLATFORM_C)
 #include "mbedtls/platform.h"
-#else
+
+#if !defined(MBEDTLS_PLATFORM_C)
 #include <stdlib.h>
 #define mbedtls_calloc    calloc
 #define mbedtls_free      free
@@ -38,6 +38,7 @@
 #include "mbedtls/debug.h"
 #include "mbedtls/ssl.h"
 #include "mbedtls/ssl_internal.h"
+#include "mbedtls/platform.h"
 #include "mbedtls/platform_util.h"
 
 #include <string.h>
@@ -3424,7 +3425,7 @@
 
 #if defined(MBEDTLS_USE_TINYCRYPT)
         {
-            int ret;
+            int ret = UECC_FAULT_DETECTED;
             static const unsigned char ecdh_param_hdr[] = {
                 MBEDTLS_SSL_EC_TLS_NAMED_CURVE,
                 0  /* high bits of secp256r1 TLS ID  */,
@@ -4213,7 +4214,7 @@
                                           unsigned char *buf,
                                           size_t buflen )
 {
-    int ret;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     mbedtls_ssl_ciphersuite_handle_t ciphersuite_info =
         mbedtls_ssl_handshake_get_ciphersuite( ssl->handshake );
     unsigned char *p, *end;
@@ -4249,8 +4250,7 @@
         mbedtls_ssl_suite_get_key_exchange( ciphersuite_info )
         == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
     {
-        ((void) ret);
-        if( mbedtls_ssl_ecdh_read_peerkey( ssl, &p, end ) != 0 )
+        if( ( ret = mbedtls_ssl_ecdh_read_peerkey( ssl, &p, end ) ) != 0 )
             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
     }
     else
@@ -4272,7 +4272,6 @@
         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
                                       p, end - p) ) != 0 )
         {
-            ((void) ret);
             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
         }
@@ -4414,7 +4413,7 @@
         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
     }
 
-    return( 0 );
+    return( ret );
 }
 
 /* Update the handshake state */
@@ -4660,6 +4659,10 @@
             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
             goto exit;
         }
+        else
+        {
+            ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
+        }
 
     }
 
@@ -4735,7 +4738,7 @@
  */
 int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl )
 {
-    int ret = 0;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 52f56cf..4f41ac9 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -50,13 +50,14 @@
 #include "mbedtls/version.h"
 #include "mbedtls/platform.h"
 
-
 #include <string.h>
 
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
 #include "mbedtls/oid.h"
 #endif
 
+#define PROPER_HS_FRAGMENT 0x75555555
+
 #if defined(MBEDTLS_USE_TINYCRYPT)
 static int uecc_rng_wrapper( uint8_t *dest, unsigned int size )
 {
@@ -175,7 +176,7 @@
                               unsigned char *buf,
                               size_t buflen )
 {
-    int ret = 0;
+    int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     mbedtls_record rec;
     MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) );
     MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen );
@@ -1893,7 +1894,7 @@
 
 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
 {
-    volatile int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+    volatile int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
     ssl->handshake->key_derivation_done = MBEDTLS_SSL_FI_FLAG_UNSET;
@@ -1982,7 +1983,7 @@
 
 int mbedtls_ssl_build_pms( mbedtls_ssl_context *ssl )
 {
-    volatile int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+    volatile int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
     mbedtls_ssl_ciphersuite_handle_t ciphersuite_info =
         mbedtls_ssl_handshake_get_ciphersuite( ssl->handshake );
@@ -2028,8 +2029,9 @@
             }
             else
             {
-                MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
-                return( ret );
+                MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret",
+                                       MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
+                return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
             }
         }
         else
@@ -4736,7 +4738,7 @@
         mbedtls_platform_memcmp( ssl->in_msg + 6, "\0\0\0",        3 ) != 0 ||
         mbedtls_platform_memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
     {
-        return( 1 );
+        return( PROPER_HS_FRAGMENT );
     }
     return( 0 );
 }
@@ -4929,7 +4931,7 @@
          * messages; the commonality is that both handshake fragments and
          * future messages cannot be forwarded immediately to the
          * handshake logic layer. */
-        if( ssl_hs_is_proper_fragment( ssl ) == 1 )
+        if( ssl_hs_is_proper_fragment( ssl ) == PROPER_HS_FRAGMENT )
         {
             MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
@@ -6053,7 +6055,7 @@
                 size_t reassembly_buf_sz;
 
                 hs_buf->is_fragmented =
-                    ( ssl_hs_is_proper_fragment( ssl ) == 1 );
+                    ( ssl_hs_is_proper_fragment( ssl ) == PROPER_HS_FRAGMENT );
 
                 /* We copy the message back into the input buffer
                  * after reassembly, so check that it's not too large.
@@ -7340,7 +7342,7 @@
                                          void *rs_ctx )
 {
     volatile int verify_ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
-    volatile int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+    volatile int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
     volatile int flow_counter = 0;
     mbedtls_ssl_ciphersuite_handle_t ciphersuite_info =
         mbedtls_ssl_handshake_get_ciphersuite( ssl->handshake );
@@ -7966,7 +7968,7 @@
 
 int mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
 {
-    volatile int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+    volatile int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
 
 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
     volatile const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
diff --git a/library/x509_crt.c b/library/x509_crt.c
index 7f689ff..43bb977 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -2936,7 +2936,7 @@
  *
  * Return value:
  *  - 0 on success
- *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
+ *  - MBEDTLS_ERR_ECP_IN_PROGRESS or MBEDTLS_ERR_PLATFORM_FAULT_DETECTED otherwise
  */
 static int x509_crt_find_parent_in(
                         mbedtls_x509_crt_sig_info const *child_sig,
@@ -3051,6 +3051,8 @@
             mbedtls_platform_random_delay();
             if( ret_fi == 0 )
                 signature_is_good = X509_SIGNATURE_IS_GOOD;
+            else
+                return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
         }
 
         if( top && ! signature_is_good )
@@ -3869,6 +3871,8 @@
         mbedtls_platform_random_delay();
         if( flags_fi == 0 )
             return( 0 );
+        else
+            return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
     }
 
     /* Preserve the API by removing internal extra bits - from now on the
diff --git a/tinycrypt/ecc.c b/tinycrypt/ecc.c
index ba36267..ca91e12 100644
--- a/tinycrypt/ecc.c
+++ b/tinycrypt/ecc.c
@@ -1080,7 +1080,7 @@
 	/* If an RNG function was specified, get a random initial Z value to
          * protect against side-channel attacks such as Template SPA */
 	if (g_rng_function) {
-		if (!uECC_generate_random_int(k2[carry], curve_p, num_words)) {
+		if (uECC_generate_random_int(k2[carry], curve_p, num_words) != UECC_SUCCESS) {
 			r = UECC_FAILURE;
 			goto clear_and_out;
 		}
@@ -1165,21 +1165,21 @@
 	bitcount_t num_bits = uECC_vli_numBits(top);
 
 	if (!g_rng_function) {
-		return 0;
+		return UECC_FAILURE;
 	}
 
 	for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
-		if (!g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE)) {
-      			return 0;
+		if (g_rng_function((uint8_t *)random, num_words * uECC_WORD_SIZE) != num_words * uECC_WORD_SIZE) {
+      			return UECC_FAILURE;
     		}
 		random[num_words - 1] &=
         		mask >> ((bitcount_t)(num_words * uECC_WORD_SIZE * 8 - num_bits));
 		if (!uECC_vli_isZero(random) &&
 			uECC_vli_cmp(top, random) == 1) {
-			return 1;
+			return UECC_SUCCESS;
 		}
 	}
-	return 0;
+	return UECC_FAILURE;
 }
 
 
@@ -1236,7 +1236,7 @@
 
 int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key)
 {
-	int ret;
+	int ret = UECC_FAULT_DETECTED;
 	uECC_word_t _private[NUM_ECC_WORDS];
 	uECC_word_t _public[NUM_ECC_WORDS * 2];
 
@@ -1264,6 +1264,5 @@
 	uECC_vli_nativeToBytes(
 	public_key +
 	NUM_ECC_BYTES, NUM_ECC_BYTES, _public + NUM_ECC_WORDS);
-	return UECC_SUCCESS;
+	return ret;
 }
-
diff --git a/tinycrypt/ecc_dh.c b/tinycrypt/ecc_dh.c
index 1b1ff3f..a63c84b 100644
--- a/tinycrypt/ecc_dh.c
+++ b/tinycrypt/ecc_dh.c
@@ -74,7 +74,7 @@
 int uECC_make_key_with_d(uint8_t *public_key, uint8_t *private_key,
 			 unsigned int *d)
 {
-	int ret;
+	int ret = UECC_FAULT_DETECTED;
 	uECC_word_t _private[NUM_ECC_WORDS];
 	uECC_word_t _public[NUM_ECC_WORDS * 2];
 
@@ -109,7 +109,7 @@
 
 int uECC_make_key(uint8_t *public_key, uint8_t *private_key)
 {
-	int ret;
+	int ret = UECC_FAULT_DETECTED;
 	uECC_word_t _random[NUM_ECC_WORDS * 2];
 	uECC_word_t _private[NUM_ECC_WORDS];
 	uECC_word_t _public[NUM_ECC_WORDS * 2];
@@ -119,7 +119,7 @@
 		/* Generating _private uniformly at random: */
 		uECC_RNG_Function rng_function = uECC_get_rng();
 		if (!rng_function ||
-			!rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS*uECC_WORD_SIZE)) {
+			rng_function((uint8_t *)_random, 2 * NUM_ECC_WORDS*uECC_WORD_SIZE) != 2 * NUM_ECC_WORDS*uECC_WORD_SIZE) {
         		return UECC_FAILURE;
 		}
 
@@ -162,7 +162,7 @@
 	uECC_word_t _private[NUM_ECC_WORDS];
 	wordcount_t num_words = NUM_ECC_WORDS;
 	wordcount_t num_bytes = NUM_ECC_BYTES;
-	int r;
+	int r = UECC_FAULT_DETECTED;
 
 	/* Converting buffers to correct bit order: */
 	uECC_vli_bytesToNative(_private,
diff --git a/tinycrypt/ecc_dsa.c b/tinycrypt/ecc_dsa.c
index e729251..bb3ed81 100644
--- a/tinycrypt/ecc_dsa.c
+++ b/tinycrypt/ecc_dsa.c
@@ -89,7 +89,7 @@
 	uECC_word_t s[NUM_ECC_WORDS];
 	uECC_word_t p[NUM_ECC_WORDS * 2];
 	wordcount_t num_n_words = BITS_TO_WORDS(NUM_ECC_BITS);
-	int r;
+	int r = UECC_FAILURE;
 
 
 	/* Make sure 0 < k < curve_n */
@@ -109,7 +109,7 @@
 		uECC_vli_clear(tmp);
 		tmp[0] = 1;
 	}
-	else if (!uECC_generate_random_int(tmp, curve_n, num_n_words)) {
+	else if (uECC_generate_random_int(tmp, curve_n, num_n_words) != UECC_SUCCESS) {
 		return UECC_FAILURE;
 	}
 
@@ -136,7 +136,7 @@
 	}
 
 	uECC_vli_nativeToBytes(signature + NUM_ECC_BYTES, NUM_ECC_BYTES, s);
-	return UECC_SUCCESS;
+	return r;
 }
 
 int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
@@ -151,7 +151,7 @@
 		/* Generating _random uniformly at random: */
 		uECC_RNG_Function rng_function = uECC_get_rng();
 		if (!rng_function ||
-		    !rng_function((uint8_t *)_random, 2*NUM_ECC_WORDS*uECC_WORD_SIZE)) {
+		    rng_function((uint8_t *)_random, 2*NUM_ECC_WORDS*uECC_WORD_SIZE) != 2*NUM_ECC_WORDS*uECC_WORD_SIZE) {
 			return UECC_FAILURE;
 		}