Merge branch 'mbedtls-2.16' into baremetal-2.16-20190909

* mbedtls-2.16: (28 commits)
  Bump version to Mbed TLS 2.16.3
  Changelog entry
  Check for zero length and NULL buffer pointer
  ssl-opt.sh: wait for proxy to start before running the script further
  Fix uninitialized variable in x509_crt
  HMAC DRBG: Split entropy-gathering requests to reduce request sizes
  Fix the license header of hkdf
  Add a change log entry
  Add a test for mlaformed ECJPAKE context
  Fix handling of md failure
  Add a test for signing content with a long ECDSA key
  Add documentation notes about the required size of the signature buffers
  Add missing MBEDTLS_ECP_C dependencies in check_config.h
  Change size of preallocated buffer for pk_sign() calls
  Adapt ChangeLog
  Fix mpi_bigendian_to_host() on bigendian systems
  Add ChangeLog entry for new function
  Add ChangeLog entry
  Correct deterministic ECDSA behavior
  Add warning for alternative ECDSA implementations
  ...
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index 461843b..6572280 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -167,15 +167,15 @@
 
 if(USE_SHARED_MBEDTLS_LIBRARY)
     add_library(mbedcrypto SHARED ${src_crypto})
-    set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.2 SOVERSION 3)
+    set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.3 SOVERSION 3)
     target_link_libraries(mbedcrypto ${libs})
 
     add_library(mbedx509 SHARED ${src_x509})
-    set_target_properties(mbedx509 PROPERTIES VERSION 2.16.2 SOVERSION 0)
+    set_target_properties(mbedx509 PROPERTIES VERSION 2.16.3 SOVERSION 0)
     target_link_libraries(mbedx509 ${libs} mbedcrypto)
 
     add_library(mbedtls SHARED ${src_tls})
-    set_target_properties(mbedtls PROPERTIES VERSION 2.16.2 SOVERSION 12)
+    set_target_properties(mbedtls PROPERTIES VERSION 2.16.3 SOVERSION 12)
     target_link_libraries(mbedtls ${libs} mbedx509)
 
     install(TARGETS mbedtls mbedx509 mbedcrypto
diff --git a/library/bignum.c b/library/bignum.c
index d94754a..e45426c 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -742,10 +742,15 @@
 static mbedtls_mpi_uint mpi_uint_bigendian_to_host_c( mbedtls_mpi_uint x )
 {
     uint8_t i;
+    unsigned char *x_ptr;
     mbedtls_mpi_uint tmp = 0;
-    /* This works regardless of the endianness. */
-    for( i = 0; i < ciL; i++, x >>= 8 )
-        tmp |= ( x & 0xFF ) << ( ( ciL - 1 - i ) << 3 );
+
+    for( i = 0, x_ptr = (unsigned char*) &x; i < ciL; i++, x_ptr++ )
+    {
+        tmp <<= CHAR_BIT;
+        tmp |= (mbedtls_mpi_uint) *x_ptr;
+    }
+
     return( tmp );
 }
 
@@ -2351,7 +2356,8 @@
             }
 
             if (count++ > 30) {
-                return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
+                ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
+                goto cleanup;
             }
 
         } while ( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ||
diff --git a/library/ecdsa.c b/library/ecdsa.c
index 58e1a5f..2b48006 100644
--- a/library/ecdsa.c
+++ b/library/ecdsa.c
@@ -254,6 +254,8 @@
                 mbedtls_mpi *r, mbedtls_mpi *s,
                 const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
+                int (*f_rng_blind)(void *, unsigned char *, size_t),
+                void *p_rng_blind,
                 mbedtls_ecdsa_restart_ctx *rs_ctx )
 {
     int ret, key_tries, sign_tries;
@@ -323,7 +325,9 @@
 mul:
 #endif
             MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
-                                                  f_rng, p_rng, ECDSA_RS_ECP ) );
+                                                          f_rng_blind,
+                                                          p_rng_blind,
+                                                          ECDSA_RS_ECP ) );
             MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
         }
         while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
@@ -349,7 +353,8 @@
          * Generate a random value to blind inv_mod in next step,
          * avoiding a potential timing leak.
          */
-        MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) );
+        MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng_blind,
+                                                  p_rng_blind ) );
 
         /*
          * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
@@ -392,8 +397,9 @@
     ECDSA_VALIDATE_RET( f_rng != NULL );
     ECDSA_VALIDATE_RET( buf   != NULL || blen == 0 );
 
+    /* Use the same RNG for both blinding and ephemeral key generation */
     return( ecdsa_sign_restartable( grp, r, s, d, buf, blen,
-                                    f_rng, p_rng, NULL ) );
+                                    f_rng, p_rng, f_rng, p_rng, NULL ) );
 }
 #endif /* !MBEDTLS_ECDSA_SIGN_ALT */
 
@@ -405,6 +411,8 @@
                     mbedtls_mpi *r, mbedtls_mpi *s,
                     const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
                     mbedtls_md_type_t md_alg,
+                    int (*f_rng_blind)(void *, unsigned char *, size_t),
+                    void *p_rng_blind,
                     mbedtls_ecdsa_restart_ctx *rs_ctx )
 {
     int ret;
@@ -451,8 +459,70 @@
     ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,
                               mbedtls_hmac_drbg_random, p_rng );
 #else
-    ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
-                      mbedtls_hmac_drbg_random, p_rng, rs_ctx );
+    if( f_rng_blind != NULL )
+        ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
+                                      mbedtls_hmac_drbg_random, p_rng,
+                                      f_rng_blind, p_rng_blind, rs_ctx );
+    else
+    {
+        mbedtls_hmac_drbg_context *p_rng_blind_det;
+
+#if !defined(MBEDTLS_ECP_RESTARTABLE)
+        /*
+         * To avoid reusing rng_ctx and risking incorrect behavior we seed a
+         * second HMAC-DRBG with the same seed. We also apply a label to avoid
+         * reusing the bits of the ephemeral key for blinding and eliminate the
+         * risk that they leak this way.
+         */
+        const char* blind_label = "BLINDING CONTEXT";
+        mbedtls_hmac_drbg_context rng_ctx_blind;
+
+        mbedtls_hmac_drbg_init( &rng_ctx_blind );
+        p_rng_blind_det = &rng_ctx_blind;
+
+        mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info,
+                                    data, 2 * grp_len );
+        ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det,
+                                            (const unsigned char*) blind_label,
+                                            strlen( blind_label ) );
+        if( ret != 0 )
+        {
+            mbedtls_hmac_drbg_free( &rng_ctx_blind );
+            goto cleanup;
+        }
+#else
+        /*
+         * In the case of restartable computations we would either need to store
+         * the second RNG in the restart context too or set it up at every
+         * restart. The first option would penalize the correct application of
+         * the function and the second would defeat the purpose of the
+         * restartable feature.
+         *
+         * Therefore in this case we reuse the original RNG. This comes with the
+         * price that the resulting signature might not be a valid deterministic
+         * ECDSA signature with a very low probability (same magnitude as
+         * successfully guessing the private key). However even then it is still
+         * a valid ECDSA signature.
+         */
+        p_rng_blind_det = p_rng;
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+        /*
+         * Since the output of the RNGs is always the same for the same key and
+         * message, this limits the efficiency of blinding and leaks information
+         * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL
+         * won't be a valid value for f_rng_blind anymore. Therefore it should
+         * be checked by the caller and this branch and check can be removed.
+         */
+        ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
+                                      mbedtls_hmac_drbg_random, p_rng,
+                                      mbedtls_hmac_drbg_random, p_rng_blind_det,
+                                      rs_ctx );
+
+#if !defined(MBEDTLS_ECP_RESTARTABLE)
+        mbedtls_hmac_drbg_free( &rng_ctx_blind );
+#endif
+    }
 #endif /* MBEDTLS_ECDSA_SIGN_ALT */
 
 cleanup:
@@ -465,11 +535,12 @@
 }
 
 /*
- * Deterministic signature wrapper
+ * Deterministic signature wrappers
  */
-int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
-                    const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
-                    mbedtls_md_type_t md_alg )
+int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r,
+                            mbedtls_mpi *s, const mbedtls_mpi *d,
+                            const unsigned char *buf, size_t blen,
+                            mbedtls_md_type_t md_alg )
 {
     ECDSA_VALIDATE_RET( grp   != NULL );
     ECDSA_VALIDATE_RET( r     != NULL );
@@ -477,7 +548,27 @@
     ECDSA_VALIDATE_RET( d     != NULL );
     ECDSA_VALIDATE_RET( buf   != NULL || blen == 0 );
 
-    return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL ) );
+    return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg,
+                                        NULL, NULL, NULL ) );
+}
+
+int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r,
+                                mbedtls_mpi *s, const mbedtls_mpi *d,
+                                const unsigned char *buf, size_t blen,
+                                mbedtls_md_type_t md_alg,
+                                int (*f_rng_blind)(void *, unsigned char *,
+                                                   size_t),
+                                void *p_rng_blind )
+{
+    ECDSA_VALIDATE_RET( grp   != NULL );
+    ECDSA_VALIDATE_RET( r     != NULL );
+    ECDSA_VALIDATE_RET( s     != NULL );
+    ECDSA_VALIDATE_RET( d     != NULL );
+    ECDSA_VALIDATE_RET( buf   != NULL || blen == 0 );
+    ECDSA_VALIDATE_RET( f_rng_blind != NULL );
+
+    return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg,
+                                        f_rng_blind, p_rng_blind, NULL ) );
 }
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
@@ -656,11 +747,9 @@
     mbedtls_mpi_init( &s );
 
 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
-    (void) f_rng;
-    (void) p_rng;
-
     MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
-                             hash, hlen, md_alg, rs_ctx ) );
+                                                 hash, hlen, md_alg, f_rng,
+                                                 p_rng, rs_ctx ) );
 #else
     (void) md_alg;
 
@@ -668,8 +757,10 @@
     MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
                          hash, hlen, f_rng, p_rng ) );
 #else
+    /* Use the same RNG for both blinding and ephemeral key generation */
     MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
-                         hash, hlen, f_rng, p_rng, rs_ctx ) );
+                                             hash, hlen, f_rng, p_rng, f_rng,
+                                             p_rng, rs_ctx ) );
 #endif /* MBEDTLS_ECDSA_SIGN_ALT */
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
diff --git a/library/ecjpake.c b/library/ecjpake.c
index b276514..1845c93 100644
--- a/library/ecjpake.c
+++ b/library/ecjpake.c
@@ -226,7 +226,7 @@
     p += id_len;
 
     /* Compute hash */
-    mbedtls_md( md_info, buf, p - buf, hash );
+    MBEDTLS_MPI_CHK( mbedtls_md( md_info, buf, p - buf, hash ) );
 
     /* Turn it into an integer mod n */
     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( h, hash,
diff --git a/library/pkwrite.c b/library/pkwrite.c
index bf4ce73..76f0a34 100644
--- a/library/pkwrite.c
+++ b/library/pkwrite.c
@@ -38,7 +38,9 @@
 #include "mbedtls/rsa.h"
 #endif
 #if defined(MBEDTLS_ECP_C)
+#include "mbedtls/bignum.h"
 #include "mbedtls/ecp.h"
+#include "mbedtls/platform_util.h"
 #endif
 #if defined(MBEDTLS_ECDSA_C)
 #include "mbedtls/ecdsa.h"
@@ -209,6 +211,26 @@
 
     return( (int) len );
 }
+
+/*
+ * privateKey  OCTET STRING -- always of length ceil(log2(n)/8)
+ */
+static int pk_write_ec_private( unsigned char **p, unsigned char *start,
+                                mbedtls_ecp_keypair *ec )
+{
+    int ret;
+    size_t byte_length = ( ec->grp.pbits + 7 ) / 8;
+    unsigned char tmp[MBEDTLS_ECP_MAX_BYTES];
+
+    ret = mbedtls_mpi_write_binary( &ec->d, tmp, byte_length );
+    if( ret != 0 )
+        goto exit;
+    ret = mbedtls_asn1_write_octet_string( p, start, tmp, byte_length );
+
+exit:
+    mbedtls_platform_zeroize( tmp, byte_length );
+    return( ret );
+}
 #endif /* MBEDTLS_ECP_C */
 #endif /* MBEDTLS_USE_TINYCRYPT */
 
diff --git a/library/platform_util.c b/library/platform_util.c
index 756e226..b1f7450 100644
--- a/library/platform_util.c
+++ b/library/platform_util.c
@@ -72,7 +72,10 @@
 
 void mbedtls_platform_zeroize( void *buf, size_t len )
 {
-    memset_func( buf, 0, len );
+    MBEDTLS_INTERNAL_VALIDATE( len == 0 || buf != NULL );
+
+    if( len > 0 )
+        memset_func( buf, 0, len );
 }
 #endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */
 
diff --git a/library/x509_crt.c b/library/x509_crt.c
index 0089ef2..89fea41 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -3071,15 +3071,13 @@
             continue;
         }
 
+        *r_parent = parent_crt;
+        *r_signature_is_good = signature_is_good;
+
         break;
     }
 
-    if( parent_crt != NULL )
-    {
-        *r_parent = parent_crt;
-        *r_signature_is_good = signature_is_good;
-    }
-    else
+    if( parent_crt == NULL )
     {
 #if defined(MBEDTLS_HAVE_TIME_DATE)
         *r_parent = fallback_parent;
diff --git a/library/x509write_crt.c b/library/x509write_crt.c
index 93cd82f..4804d7a 100644
--- a/library/x509write_crt.c
+++ b/library/x509write_crt.c
@@ -46,6 +46,16 @@
 #include "mbedtls/pem.h"
 #endif /* MBEDTLS_PEM_WRITE_C */
 
+/*
+ * For the currently used signature algorithms the buffer to store any signature
+ * must be at least of size MAX(MBEDTLS_ECDSA_MAX_LEN, MBEDTLS_MPI_MAX_SIZE)
+ */
+#if MBEDTLS_ECDSA_MAX_LEN > MBEDTLS_MPI_MAX_SIZE
+#define SIGNATURE_MAX_SIZE MBEDTLS_ECDSA_MAX_LEN
+#else
+#define SIGNATURE_MAX_SIZE MBEDTLS_MPI_MAX_SIZE
+#endif
+
 void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx )
 {
     memset( ctx, 0, sizeof( mbedtls_x509write_cert ) );
@@ -335,7 +345,7 @@
     size_t sig_oid_len = 0;
     unsigned char *c, *c2;
     unsigned char hash[64];
-    unsigned char sig[MBEDTLS_MPI_MAX_SIZE];
+    unsigned char sig[SIGNATURE_MAX_SIZE];
     unsigned char tmp_buf[2048];
     size_t sub_len = 0, pub_len = 0, sig_and_oid_len = 0, sig_len;
     size_t len = 0;
diff --git a/library/x509write_csr.c b/library/x509write_csr.c
index 85331b1..6105f14 100644
--- a/library/x509write_csr.c
+++ b/library/x509write_csr.c
@@ -45,6 +45,16 @@
 #include "mbedtls/pem.h"
 #endif
 
+/*
+ * For the currently used signature algorithms the buffer to store any signature
+ * must be at least of size MAX(MBEDTLS_ECDSA_MAX_LEN, MBEDTLS_MPI_MAX_SIZE)
+ */
+#if MBEDTLS_ECDSA_MAX_LEN > MBEDTLS_MPI_MAX_SIZE
+#define SIGNATURE_MAX_SIZE MBEDTLS_ECDSA_MAX_LEN
+#else
+#define SIGNATURE_MAX_SIZE MBEDTLS_MPI_MAX_SIZE
+#endif
+
 void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx )
 {
     memset( ctx, 0, sizeof( mbedtls_x509write_csr ) );
@@ -160,7 +170,7 @@
     size_t sig_oid_len = 0;
     unsigned char *c, *c2;
     unsigned char hash[64];
-    unsigned char sig[MBEDTLS_MPI_MAX_SIZE];
+    unsigned char sig[SIGNATURE_MAX_SIZE];
     unsigned char tmp_buf[2048];
     size_t pub_len = 0, sig_and_oid_len = 0, sig_len;
     size_t len = 0;