Merging iotssl-457-badtail with development branch
diff --git a/library/debug.c b/library/debug.c
index 2220e33..f9b8229 100644
--- a/library/debug.c
+++ b/library/debug.c
@@ -43,6 +43,10 @@
 #define mbedtls_snprintf    snprintf
 #endif
 
+#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && !defined(inline)
+#define inline __inline
+#endif
+
 #define DEBUG_BUF_SIZE      512
 
 static int debug_threshold = 0;
@@ -52,6 +56,27 @@
     debug_threshold = threshold;
 }
 
+/*
+ * All calls to f_dbg must be made via this function
+ */
+static inline void debug_send_line( const mbedtls_ssl_context *ssl, int level,
+                                    const char *file, int line,
+                                    const char *str )
+{
+    /*
+     * If in a threaded environment, we need a thread identifier.
+     * Since there is no portable way to get one, use the address of the ssl
+     * context instead, as it shouldn't be shared between threads.
+     */
+#if defined(MBEDTLS_THREADING_C)
+    char idstr[20 + DEBUG_BUF_SIZE]; /* 0x + 16 nibbles + ': ' */
+    mbedtls_snprintf( idstr, sizeof( idstr ), "%p: %s", ssl, str );
+    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, idstr );
+#else
+    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+#endif
+}
+
 void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,
                               const char *file, int line,
                               const char *format, ... )
@@ -86,7 +111,7 @@
         str[ret + 1] = '\0';
     }
 
-    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+    debug_send_line( ssl, level, file, line, str );
 }
 
 void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level,
@@ -109,7 +134,7 @@
     mbedtls_snprintf( str, sizeof( str ), "%s() returned %d (-0x%04x)\n",
               text, ret, -ret );
 
-    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+    debug_send_line( ssl, level, file, line, str );
 }
 
 void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
@@ -126,7 +151,7 @@
     mbedtls_snprintf( str + idx, sizeof( str ) - idx, "dumping '%s' (%u bytes)\n",
               text, (unsigned int) len );
 
-    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+    debug_send_line( ssl, level, file, line, str );
 
     idx = 0;
     memset( txt, 0, sizeof( txt ) );
@@ -140,7 +165,7 @@
             if( i > 0 )
             {
                 mbedtls_snprintf( str + idx, sizeof( str ) - idx, "  %s\n", txt );
-                ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+                debug_send_line( ssl, level, file, line, str );
 
                 idx = 0;
                 memset( txt, 0, sizeof( txt ) );
@@ -162,7 +187,7 @@
             idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, "   " );
 
         mbedtls_snprintf( str + idx, sizeof( str ) - idx, "  %s\n", txt );
-        ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+        debug_send_line( ssl, level, file, line, str );
     }
 }
 
@@ -207,7 +232,7 @@
     mbedtls_snprintf( str + idx, sizeof( str ) - idx, "value of '%s' (%d bits) is:\n",
               text, (int) ( ( n * ( sizeof(mbedtls_mpi_uint) << 3 ) ) + j + 1 ) );
 
-    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+    debug_send_line( ssl, level, file, line, str );
 
     idx = 0;
     for( i = n + 1, j = 0; i > 0; i-- )
@@ -227,7 +252,7 @@
                 if( j > 0 )
                 {
                     mbedtls_snprintf( str + idx, sizeof( str ) - idx, "\n" );
-                    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+                    debug_send_line( ssl, level, file, line, str );
                     idx = 0;
                 }
             }
@@ -244,7 +269,7 @@
         idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, " 00" );
 
     mbedtls_snprintf( str + idx, sizeof( str ) - idx, "\n" );
-    ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+    debug_send_line( ssl, level, file, line, str );
 }
 #endif /* MBEDTLS_BIGNUM_C */
 
@@ -261,7 +286,7 @@
 
     if( mbedtls_pk_debug( pk, items ) != 0 )
     {
-        ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line,
+        debug_send_line( ssl, level, file, line,
                           "invalid PK context\n" );
         return;
     }
@@ -282,7 +307,7 @@
             mbedtls_debug_print_ecp( ssl, level, file, line, name, items[i].value );
         else
 #endif
-            ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line,
+            debug_send_line( ssl, level, file, line,
                               "should not happen\n" );
     }
 }
@@ -305,7 +330,7 @@
             memcpy( str, start, len );
             str[len] = '\0';
 
-            ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+            debug_send_line( ssl, level, file, line, str );
 
             start = cur + 1;
         }
@@ -327,7 +352,7 @@
         char buf[1024];
 
         mbedtls_snprintf( str, sizeof( str ), "%s #%d:\n", text, ++i );
-        ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
+        debug_send_line( ssl, level, file, line, str );
 
         mbedtls_x509_crt_info( buf, sizeof( buf ) - 1, "", crt );
         debug_print_line_by_line( ssl, level, file, line, buf );
diff --git a/library/entropy_poll.c b/library/entropy_poll.c
index 42b02e7..6b3ad35 100644
--- a/library/entropy_poll.c
+++ b/library/entropy_poll.c
@@ -140,7 +140,7 @@
                            unsigned char *output, size_t len, size_t *olen )
 {
     FILE *file;
-    size_t ret;
+    size_t read_len;
     ((void) data);
 
 #if defined(HAVE_GETRANDOM)
@@ -165,8 +165,8 @@
     if( file == NULL )
         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
 
-    ret = fread( output, 1, len, file );
-    if( ret != len )
+    read_len = fread( output, 1, len, file );
+    if( read_len != len )
     {
         fclose( file );
         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
diff --git a/library/md2.c b/library/md2.c
index 3263a22..88d679f 100644
--- a/library/md2.c
+++ b/library/md2.c
@@ -47,13 +47,13 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
+#if !defined(MBEDTLS_MD2_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
 }
 
-#if !defined(MBEDTLS_MD2_ALT)
-
 static const unsigned char PI_SUBST[256] =
 {
     0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36,
diff --git a/library/md4.c b/library/md4.c
index 563c653..dcd9313 100644
--- a/library/md4.c
+++ b/library/md4.c
@@ -47,13 +47,13 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
+#if !defined(MBEDTLS_MD4_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
 }
 
-#if !defined(MBEDTLS_MD4_ALT)
-
 /*
  * 32-bit integer manipulation macros (little endian)
  */
diff --git a/library/md5.c b/library/md5.c
index d8f2163..42c7c34 100644
--- a/library/md5.c
+++ b/library/md5.c
@@ -46,13 +46,13 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
+#if !defined(MBEDTLS_MD5_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
 }
 
-#if !defined(MBEDTLS_MD5_ALT)
-
 /*
  * 32-bit integer manipulation macros (little endian)
  */
diff --git a/library/sha1.c b/library/sha1.c
index 14331b3..ffad228 100644
--- a/library/sha1.c
+++ b/library/sha1.c
@@ -46,13 +46,13 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
+#if !defined(MBEDTLS_SHA1_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
 }
 
-#if !defined(MBEDTLS_SHA1_ALT)
-
 /*
  * 32-bit integer manipulation macros (big endian)
  */
diff --git a/library/sha256.c b/library/sha256.c
index 28f09e5..4d8c868 100644
--- a/library/sha256.c
+++ b/library/sha256.c
@@ -46,13 +46,13 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
+#if !defined(MBEDTLS_SHA256_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
 }
 
-#if !defined(MBEDTLS_SHA256_ALT)
-
 /*
  * 32-bit integer manipulation macros (big endian)
  */
diff --git a/library/sha512.c b/library/sha512.c
index 9e3e0e0..d1dc8fa 100644
--- a/library/sha512.c
+++ b/library/sha512.c
@@ -52,13 +52,13 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST */
 
+#if !defined(MBEDTLS_SHA512_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
 }
 
-#if !defined(MBEDTLS_SHA512_ALT)
-
 /*
  * 64-bit integer manipulation macros (big endian)
  */
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index c6f810c..75983d1 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -1748,6 +1748,12 @@
     size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
     unsigned char *p = ssl->handshake->premaster + pms_offset;
 
+    if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
+    {
+        MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
+        return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
+    }
+
     /*
      * Generate (part of) the pre-master as
      *  struct {
@@ -2522,6 +2528,14 @@
 
         i = 4;
         n = ssl->conf->psk_identity_len;
+
+        if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
+                                        "SSL buffer too short" ) );
+            return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
+        }
+
         ssl->out_msg[i++] = (unsigned char)( n >> 8 );
         ssl->out_msg[i++] = (unsigned char)( n      );
 
@@ -2550,6 +2564,14 @@
              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
              */
             n = ssl->handshake->dhm_ctx.len;
+
+            if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
+            {
+                MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
+                                            " or SSL buffer too short" ) );
+                return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
+            }
+
             ssl->out_msg[i++] = (unsigned char)( n >> 8 );
             ssl->out_msg[i++] = (unsigned char)( n      );
 
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 9007562..bff1b63 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -694,8 +694,6 @@
     }
     else
     {
-        int ret;
-
         /* Initialize HMAC contexts */
         if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
             ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
@@ -1455,7 +1453,7 @@
             /*
              * Generate IV
              */
-            int ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
+            ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
                                   ssl->transform_out->ivlen );
             if( ret != 0 )
                 return( ret );
@@ -3718,6 +3716,9 @@
 {
     int ret;
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
 
     ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
@@ -5459,6 +5460,13 @@
     if( psk_len > MBEDTLS_PSK_MAX_LEN )
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
 
+    /* Identity len will be encoded on two bytes */
+    if( ( psk_identity_len >> 16 ) != 0 ||
+        psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN )
+    {
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+    }
+
     if( conf->psk != NULL || conf->psk_identity != NULL )
     {
         mbedtls_free( conf->psk );
@@ -5862,6 +5870,29 @@
     return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
 }
 
+#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
+{
+    size_t max_len;
+
+    /*
+     * Assume mfl_code is correct since it was checked when set
+     */
+    max_len = mfl_code_to_length[ssl->conf->mfl_code];
+
+    /*
+     * Check if a smaller max length was negotiated
+     */
+    if( ssl->session_out != NULL &&
+        mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
+    {
+        max_len = mfl_code_to_length[ssl->session_out->mfl_code];
+    }
+
+    return max_len;
+}
+#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
+
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
 {
@@ -5894,6 +5925,9 @@
 {
     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
 #if defined(MBEDTLS_SSL_CLI_C)
     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
         ret = mbedtls_ssl_handshake_client_step( ssl );
@@ -5913,6 +5947,9 @@
 {
     int ret = 0;
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
 
     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
@@ -6008,6 +6045,9 @@
 {
     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
 #if defined(MBEDTLS_SSL_SRV_C)
     /* On server, just send the request */
     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
@@ -6085,6 +6125,9 @@
     int ret, record_read = 0;
     size_t n;
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
 
 #if defined(MBEDTLS_SSL_PROTO_DTLS)
@@ -6339,23 +6382,7 @@
 {
     int ret;
 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
-    unsigned int max_len;
-#endif
-
-#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
-    /*
-     * Assume mfl_code is correct since it was checked when set
-     */
-    max_len = mfl_code_to_length[ssl->conf->mfl_code];
-
-    /*
-     * Check if a smaller max length was negotiated
-     */
-    if( ssl->session_out != NULL &&
-        mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
-    {
-        max_len = mfl_code_to_length[ssl->session_out->mfl_code];
-    }
+    size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );
 
     if( len > max_len )
     {
@@ -6444,6 +6471,9 @@
 
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
 #if defined(MBEDTLS_SSL_RENEGOTIATION)
     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
     {
@@ -6479,6 +6509,9 @@
 {
     int ret;
 
+    if( ssl == NULL || ssl->conf == NULL )
+        return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
+
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
 
     if( ssl->out_left != 0 )