Merge branch 'mbedtls-2.1-iotssl-1071-ca-flags'

Fixes a regression introduced by an earlier commit that modified
x509_crt_verify_top() to ensure that valid certificates that are after past or
future valid in the chain are processed. However the change introduced a change
in behaviour that caused the verification flags MBEDTLS_X509_BADCERT_EXPIRED and
MBEDTLS_BADCERT_FUTURE to always be set whenever there is a failure in the
verification regardless of the cause.

The fix maintains both behaviours:

 * Ensure that valid certificates after future and past are verified
 * Ensure that the correct verification flags are set.
diff --git a/ChangeLog b/ChangeLog
index 4008783..73804ec 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,6 +1,18 @@
 mbed TLS ChangeLog (Sorted per branch, date)
 
-= mbed TLS x.x.x branch released xxxx-xx-xx
+= mbed TLS 2.1.x branch released xxxx-xx-xx
+
+Security
+   * Add checks to prevent signature forgeries for very large messages while
+     using RSA through the PK module in 64-bit systems. The issue was caused by
+     some data loss when casting a size_t to an unsigned int value in the
+     functions rsa_verify_wrap(), rsa_sign_wrap(), rsa_alt_sign_wrap() and
+     mbedtls_pk_sign(). Found by Jean-Philippe Aumasson.
+   * Fixed potential livelock during the parsing of a CRL in PEM format in
+     mbedtls_x509_crl_parse(). A string containing a CRL followed by trailing
+     characters after the footer could result in the execution of an infinite
+     loop. The issue can be triggered remotely. Found by Greg Zaverucha,
+     Microsoft.
 
 Bugfix
    * Fix output certificate verification flags set by x509_crt_verify_top() when
@@ -8,6 +20,28 @@
      MBEDTLS_X509_BADCERT_NOT_TRUSTED and MBEDTLS_X509_BADCERT_EXPIRED, to be
      set when the verification conditions are not met regardless of the cause.
      Found by Harm Verhagen and inestlerode. #665 #561
+   * Fix the redefinition of macro ssl_set_bio to an undefined symbol
+     mbedtls_ssl_set_bio_timeout in compat-1.3.h, by removing it.
+     Found by omlib-lin. #673
+   * Fix unused variable/function compilation warnings in pem.c and x509_csr.c
+     that are reported when building mbed TLS with a config.h that does not
+     define MBEDTLS_PEM_PARSE_C. Found by omnium21. #562
+   * Fix incorrect renegotiation condition in ssl_check_ctr_renegotiate() that
+     would compare 64 bits of the record counter instead of 48 bits as indicated
+     in RFC 6347 Section 4.3.1. This could cause the execution of the
+     renegotiation routines at unexpected times when the protocol is DTLS. Found
+     by wariua. #687
+   * Fixed multiple buffer overreads in mbedtls_pem_read_buffer() when parsing
+     the input string in PEM format to extract the different components. Found
+     by Eyal Itkin.
+   * Fixed potential arithmetic overflow in mbedtls_ctr_drbg_reseed() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed potential arithmetic overflows in mbedtls_cipher_update() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed potential arithmetic overflow in mbedtls_md2_update() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed potential arithmetic overflow in mbedtls_base64_decode() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
 
 = mbed TLS 2.1.6 branch released 2016-10-17
 
diff --git a/include/mbedtls/compat-1.3.h b/include/mbedtls/compat-1.3.h
index 27abbd9..af51b5f 100644
--- a/include/mbedtls/compat-1.3.h
+++ b/include/mbedtls/compat-1.3.h
@@ -2453,7 +2453,6 @@
 #define ssl_set_arc4_support mbedtls_ssl_conf_arc4_support
 #define ssl_set_authmode mbedtls_ssl_conf_authmode
 #define ssl_set_bio mbedtls_ssl_set_bio
-#define ssl_set_bio mbedtls_ssl_set_bio_timeout
 #define ssl_set_ca_chain mbedtls_ssl_conf_ca_chain
 #define ssl_set_cbc_record_splitting mbedtls_ssl_conf_cbc_record_splitting
 #define ssl_set_ciphersuites mbedtls_ssl_conf_ciphersuites
diff --git a/include/mbedtls/rsa.h b/include/mbedtls/rsa.h
index 9c8645d..a324b69 100644
--- a/include/mbedtls/rsa.h
+++ b/include/mbedtls/rsa.h
@@ -206,7 +206,7 @@
  * \return         0 if successful, or an MBEDTLS_ERR_RSA_XXX error code
  *
  * \note           This function does NOT take care of message
- *                 padding. Also, be sure to set input[0] = 0 or assure that
+ *                 padding. Also, be sure to set input[0] = 0 or ensure that
  *                 input is smaller than N.
  *
  * \note           The input and output buffers must be large
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
index fa7fbda..1f885ee 100644
--- a/include/mbedtls/ssl.h
+++ b/include/mbedtls/ssl.h
@@ -1946,7 +1946,7 @@
 
 /**
  * \brief          Set record counter threshold for periodic renegotiation.
- *                 (Default: 2^64 - 256.)
+ *                 (Default: 2^48 - 1)
  *
  *                 Renegotiation is automatically triggered when a record
  *                 counter (outgoing or ingoing) crosses the defined
@@ -1957,9 +1957,17 @@
  *                 Lower values can be used to enforce policies such as "keys
  *                 must be refreshed every N packets with cipher X".
  *
+ *                 The renegotiation period can be disabled by setting
+ *                 conf->disable_renegotiation to
+ *                 MBEDTLS_SSL_RENEGOTIATION_DISABLED.
+ *
+ * \note           When the configured transport is
+ *                 MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation
+ *                 period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM,
+ *                 the maximum renegotiation period is 2^64 - 1.
+ *
  * \param conf     SSL configuration
  * \param period   The threshold value: a big-endian 64-bit number.
- *                 Set to 2^64 - 1 to disable periodic renegotiation
  */
 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
                                    const unsigned char period[8] );
diff --git a/include/mbedtls/x509.h b/include/mbedtls/x509.h
index 54dac16..f219bf1 100644
--- a/include/mbedtls/x509.h
+++ b/include/mbedtls/x509.h
@@ -157,7 +157,7 @@
 #define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY          (1 << 13)
 #define MBEDTLS_X509_EXT_FRESHEST_CRL                (1 << 14)
 
-#define MBEDTLS_X509_EXT_NS_CERT_TYPE                (1 << 16)   /* Parsed (and then ?) */
+#define MBEDTLS_X509_EXT_NS_CERT_TYPE                (1 << 16)
 
 /*
  * Storage format identifiers
diff --git a/library/base64.c b/library/base64.c
index 3432e5f..4ed6b31 100644
--- a/library/base64.c
+++ b/library/base64.c
@@ -192,7 +192,11 @@
         return( 0 );
     }
 
-    n = ( ( n * 6 ) + 7 ) >> 3;
+    /* The following expression is to calculate the following formula without
+     * risk of integer overflow in n:
+     *     n = ( ( n * 6 ) + 7 ) >> 3;
+     */
+    n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 );
     n -= j;
 
     if( dst == NULL || dlen < n )
diff --git a/library/cipher.c b/library/cipher.c
index ccc0685..1523b07 100644
--- a/library/cipher.c
+++ b/library/cipher.c
@@ -300,9 +300,9 @@
          * If there is not enough data for a full block, cache it.
          */
         if( ( ctx->operation == MBEDTLS_DECRYPT &&
-                ilen + ctx->unprocessed_len <= mbedtls_cipher_get_block_size( ctx ) ) ||
+                ilen <= mbedtls_cipher_get_block_size( ctx ) - ctx->unprocessed_len ) ||
              ( ctx->operation == MBEDTLS_ENCRYPT &&
-                ilen + ctx->unprocessed_len < mbedtls_cipher_get_block_size( ctx ) ) )
+                ilen < mbedtls_cipher_get_block_size( ctx ) - ctx->unprocessed_len ) )
         {
             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
                     ilen );
diff --git a/library/ctr_drbg.c b/library/ctr_drbg.c
index aefddfa..646196e 100644
--- a/library/ctr_drbg.c
+++ b/library/ctr_drbg.c
@@ -290,7 +290,8 @@
     unsigned char seed[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT];
     size_t seedlen = 0;
 
-    if( ctx->entropy_len + len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
+    if( ctx->entropy_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT ||
+        len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len )
         return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
 
     memset( seed, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );
diff --git a/library/md2.c b/library/md2.c
index 8976701..95cbcce 100644
--- a/library/md2.c
+++ b/library/md2.c
@@ -158,7 +158,7 @@
 
     while( ilen > 0 )
     {
-        if( ctx->left + ilen > 16 )
+        if( ilen > 16 - ctx->left )
             fill = 16 - ctx->left;
         else
             fill = ilen;
diff --git a/library/net.c b/library/net.c
index a77268c..b6b08ed 100644
--- a/library/net.c
+++ b/library/net.c
@@ -228,7 +228,7 @@
             }
         }
 
-        /* I we ever get there, it's a success */
+        /* Bind was successful */
         ret = 0;
         break;
     }
diff --git a/library/pem.c b/library/pem.c
index 1ee3966..8dd86a4 100644
--- a/library/pem.c
+++ b/library/pem.c
@@ -44,12 +44,12 @@
 #define mbedtls_free       free
 #endif
 
+#if defined(MBEDTLS_PEM_PARSE_C)
 /* 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_PEM_PARSE_C)
 void mbedtls_pem_init( mbedtls_pem_context *ctx )
 {
     memset( ctx, 0, sizeof( mbedtls_pem_context ) );
@@ -249,7 +249,7 @@
 
     enc = 0;
 
-    if( memcmp( s1, "Proc-Type: 4,ENCRYPTED", 22 ) == 0 )
+    if( s2 - s1 >= 22 && memcmp( s1, "Proc-Type: 4,ENCRYPTED", 22 ) == 0 )
     {
 #if defined(MBEDTLS_MD5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) &&         \
     ( defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) )
@@ -262,22 +262,22 @@
 
 
 #if defined(MBEDTLS_DES_C)
-        if( memcmp( s1, "DEK-Info: DES-EDE3-CBC,", 23 ) == 0 )
+        if( s2 - s1 >= 23 && memcmp( s1, "DEK-Info: DES-EDE3-CBC,", 23 ) == 0 )
         {
             enc_alg = MBEDTLS_CIPHER_DES_EDE3_CBC;
 
             s1 += 23;
-            if( pem_get_iv( s1, pem_iv, 8 ) != 0 )
+            if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8 ) != 0 )
                 return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
 
             s1 += 16;
         }
-        else if( memcmp( s1, "DEK-Info: DES-CBC,", 18 ) == 0 )
+        else if( s2 - s1 >= 18 && memcmp( s1, "DEK-Info: DES-CBC,", 18 ) == 0 )
         {
             enc_alg = MBEDTLS_CIPHER_DES_CBC;
 
             s1 += 18;
-            if( pem_get_iv( s1, pem_iv, 8) != 0 )
+            if( s2 - s1 < 16 || pem_get_iv( s1, pem_iv, 8) != 0 )
                 return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
 
             s1 += 16;
@@ -285,9 +285,11 @@
 #endif /* MBEDTLS_DES_C */
 
 #if defined(MBEDTLS_AES_C)
-        if( memcmp( s1, "DEK-Info: AES-", 14 ) == 0 )
+        if( s2 - s1 >= 14 && memcmp( s1, "DEK-Info: AES-", 14 ) == 0 )
         {
-            if( memcmp( s1, "DEK-Info: AES-128-CBC,", 22 ) == 0 )
+            if( s2 - s1 < 22 )
+                return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
+            else if( memcmp( s1, "DEK-Info: AES-128-CBC,", 22 ) == 0 )
                 enc_alg = MBEDTLS_CIPHER_AES_128_CBC;
             else if( memcmp( s1, "DEK-Info: AES-192-CBC,", 22 ) == 0 )
                 enc_alg = MBEDTLS_CIPHER_AES_192_CBC;
@@ -297,7 +299,7 @@
                 return( MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG );
 
             s1 += 22;
-            if( pem_get_iv( s1, pem_iv, 16 ) != 0 )
+            if( s2 - s1 < 32 || pem_get_iv( s1, pem_iv, 16 ) != 0 )
                 return( MBEDTLS_ERR_PEM_INVALID_ENC_IV );
 
             s1 += 32;
@@ -316,7 +318,7 @@
           ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
     }
 
-    if( s1 == s2 )
+    if( s1 >= s2 )
         return( MBEDTLS_ERR_PEM_INVALID_DATA );
 
     ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 );
diff --git a/library/pk.c b/library/pk.c
index 10bd0a5..8d13bc5 100644
--- a/library/pk.c
+++ b/library/pk.c
@@ -29,6 +29,8 @@
 #include "mbedtls/pk.h"
 #include "mbedtls/pk_internal.h"
 
+#include "mbedtls/bignum.h"
+
 #if defined(MBEDTLS_RSA_C)
 #include "mbedtls/rsa.h"
 #endif
@@ -39,6 +41,8 @@
 #include "mbedtls/ecdsa.h"
 #endif
 
+#include <limits.h>
+
 /* 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;
@@ -209,6 +213,11 @@
         int ret;
         const mbedtls_pk_rsassa_pss_options *pss_opts;
 
+#if defined(MBEDTLS_HAVE_INT64)
+        if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
+            return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+#endif /* MBEDTLS_HAVE_INT64 */
+
         if( options == NULL )
             return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
 
@@ -232,7 +241,7 @@
         return( 0 );
 #else
         return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
-#endif
+#endif /* MBEDTLS_RSA_C && MBEDTLS_PKCS1_V21 */
     }
 
     /* General case: no options */
diff --git a/library/pk_wrap.c b/library/pk_wrap.c
index 712ad48..db6274c 100644
--- a/library/pk_wrap.c
+++ b/library/pk_wrap.c
@@ -30,6 +30,7 @@
 
 /* Even if RSA not activated, for the sake of RSA-alt */
 #include "mbedtls/rsa.h"
+#include "mbedtls/bignum.h"
 
 #include <string.h>
 
@@ -49,6 +50,8 @@
 #define mbedtls_free       free
 #endif
 
+#include <limits.h>
+
 #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
@@ -74,6 +77,11 @@
 {
     int ret;
 
+#if defined(MBEDTLS_HAVE_INT64)
+    if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
+        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+#endif /* MBEDTLS_HAVE_INT64 */
+
     if( sig_len < ((mbedtls_rsa_context *) ctx)->len )
         return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
 
@@ -93,6 +101,11 @@
                    unsigned char *sig, size_t *sig_len,
                    int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
 {
+#if defined(MBEDTLS_HAVE_INT64)
+    if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
+        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+#endif /* MBEDTLS_HAVE_INT64 */
+
     *sig_len = ((mbedtls_rsa_context *) ctx)->len;
 
     return( mbedtls_rsa_pkcs1_sign( (mbedtls_rsa_context *) ctx, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,
@@ -402,6 +415,11 @@
 {
     mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx;
 
+#if defined(MBEDTLS_HAVE_INT64)
+    if( UINT_MAX < hash_len )
+        return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+#endif /* MBEDTLS_HAVE_INT64 */
+
     *sig_len = rsa_alt->key_len_func( rsa_alt->key );
 
     return( rsa_alt->sign_func( rsa_alt->key, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,
diff --git a/library/pkparse.c b/library/pkparse.c
index bddcf5d..f0a12f9 100644
--- a/library/pkparse.c
+++ b/library/pkparse.c
@@ -1186,12 +1186,12 @@
 #endif /* MBEDTLS_PEM_PARSE_C */
 
     /*
-    * At this point we only know it's not a PEM formatted key. Could be any
-    * of the known DER encoded private key formats
-    *
-    * We try the different DER format parsers to see if one passes without
-    * error
-    */
+     * At this point we only know it's not a PEM formatted key. Could be any
+     * of the known DER encoded private key formats
+     *
+     * We try the different DER format parsers to see if one passes without
+     * error
+     */
 #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
     if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk, key, keylen,
                                                   pwd, pwdlen ) ) == 0 )
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index d442642..43efe0c 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -3413,7 +3413,7 @@
 
     if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
     {
-        /* Dont check write errors as we can't do anything here.
+        /* Don't check write errors as we can't do anything here.
          * If the error is permanent we'll catch it later,
          * if it's not, then hopefully it'll work next time. */
         (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
@@ -5914,8 +5914,9 @@
     const char **p;
 
     /*
-     * "Empty strings MUST NOT be included and byte strings MUST NOT be
-     * truncated". Check lengths now rather than later.
+     * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
+     * MUST NOT be truncated."
+     * We check lengths now rather than later.
      */
     tot_len = 0;
     for( p = protos; *p != NULL; p++ )
@@ -6379,6 +6380,10 @@
  */
 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
 {
+    size_t ep_len = ssl_ep_len( ssl );
+    int in_ctr_cmp;
+    int out_ctr_cmp;
+
     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
         ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
@@ -6386,8 +6391,12 @@
         return( 0 );
     }
 
-    if( memcmp( ssl->in_ctr,  ssl->conf->renego_period, 8 ) <= 0 &&
-        memcmp( ssl->out_ctr, ssl->conf->renego_period, 8 ) <= 0 )
+    in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
+                        ssl->conf->renego_period + ep_len, 8 - ep_len );
+    out_ctr_cmp = memcmp( ssl->out_ctr + ep_len,
+                          ssl->conf->renego_period + ep_len, 8 - ep_len );
+
+    if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
     {
         return( 0 );
     }
@@ -7119,8 +7128,8 @@
 
 #if defined(MBEDTLS_SSL_RENEGOTIATION)
     conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
-    memset( conf->renego_period, 0xFF, 7 );
-    conf->renego_period[7] = 0x00;
+    memset( conf->renego_period,     0x00, 2 );
+    memset( conf->renego_period + 2, 0xFF, 6 );
 #endif
 
 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
@@ -7472,7 +7481,7 @@
  * and, for DTLS, to/from TLS equivalent.
  *
  * For TLS this is the identity.
- * For DTLS, use one complement (v -> 255 - v, and then map as follows:
+ * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
  * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)
  * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)
  */
diff --git a/library/x509.c b/library/x509.c
index 33bcb9e..b063a19 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -656,7 +656,7 @@
 
 /*
  * X.509 Extensions (No parsing of extensions, pointer should
- * be either manually updated or extensions should be parsed!
+ * be either manually updated or extensions should be parsed!)
  */
 int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,
                   mbedtls_x509_buf *ext, int tag )
diff --git a/library/x509_crl.c b/library/x509_crl.c
index 125a773..dca14cc 100644
--- a/library/x509_crl.c
+++ b/library/x509_crl.c
@@ -529,7 +529,7 @@
 
             mbedtls_pem_free( &pem );
         }
-        else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
+        else if( is_pem )
         {
             mbedtls_pem_free( &pem );
             return( ret );
diff --git a/library/x509_csr.c b/library/x509_csr.c
index dbf659b..60f66b3 100644
--- a/library/x509_csr.c
+++ b/library/x509_csr.c
@@ -259,8 +259,8 @@
  */
 int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen )
 {
-    int ret;
 #if defined(MBEDTLS_PEM_PARSE_C)
+    int ret;
     size_t use_len;
     mbedtls_pem_context pem;
 #endif
diff --git a/programs/ssl/dtls_client.c b/programs/ssl/dtls_client.c
index b37eb83..2527d8d 100644
--- a/programs/ssl/dtls_client.c
+++ b/programs/ssl/dtls_client.c
@@ -37,7 +37,7 @@
     !defined(MBEDTLS_NET_C)  || !defined(MBEDTLS_TIMING_C) ||             \
     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) ||        \
     !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_RSA_C) ||      \
-    !defined(MBEDTLS_CERTS_C)
+    !defined(MBEDTLS_CERTS_C) || !defined(MBEDTLS_PEM_PARSE_C)
 int main( void )
 {
     mbedtls_printf( "MBEDTLS_SSL_CLI_C and/or MBEDTLS_SSL_PROTO_DTLS and/or "
diff --git a/programs/ssl/ssl_mail_client.c b/programs/ssl/ssl_mail_client.c
index 974c170..ef68f24 100644
--- a/programs/ssl/ssl_mail_client.c
+++ b/programs/ssl/ssl_mail_client.c
@@ -491,13 +491,13 @@
         ret = mbedtls_x509_crt_parse_file( &cacert, opt.ca_file );
     else
 #endif
-#if defined(MBEDTLS_CERTS_C)
+#if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_PEM_PARSE_C)
         ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_cas_pem,
                               mbedtls_test_cas_pem_len );
 #else
     {
         ret = 1;
-        mbedtls_printf("MBEDTLS_CERTS_C not defined.");
+        mbedtls_printf("MBEDTLS_CERTS_C and/or MBEDTLS_PEM_PARSE_C not defined.");
     }
 #endif
     if( ret < 0 )
diff --git a/programs/ssl/ssl_server2.c b/programs/ssl/ssl_server2.c
index bd4d1d1..1f6caf2 100644
--- a/programs/ssl/ssl_server2.c
+++ b/programs/ssl/ssl_server2.c
@@ -60,6 +60,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <stdint.h>
+#include <inttypes.h>
 
 #if !defined(_WIN32)
 #include <signal.h>
@@ -109,7 +111,7 @@
 #define DFL_ALLOW_LEGACY        -2
 #define DFL_RENEGOTIATE         0
 #define DFL_RENEGO_DELAY        -2
-#define DFL_RENEGO_PERIOD       -1
+#define DFL_RENEGO_PERIOD       ( (uint64_t)-1 )
 #define DFL_EXCHANGES           1
 #define DFL_MIN_VERSION         -1
 #define DFL_MAX_VERSION         -1
@@ -288,7 +290,7 @@
     "    renegotiation=%%d    default: 0 (disabled)\n"      \
     "    renegotiate=%%d      default: 0 (disabled)\n"      \
     "    renego_delay=%%d     default: -2 (library default)\n" \
-    "    renego_period=%%d    default: (library default)\n"
+    "    renego_period=%%d    default: (2^64 - 1 for TLS, 2^48 - 1 for DTLS)\n"
 #else
 #define USAGE_RENEGO ""
 #endif
@@ -339,6 +341,19 @@
     "    force_ciphersuite=<name>    default: all enabled\n"            \
     " acceptable ciphersuite names:\n"
 
+
+#define PUT_UINT64_BE(out_be,in_le,i)                                   \
+{                                                                       \
+    (out_be)[(i) + 0] = (unsigned char)( ( (in_le) >> 56 ) & 0xFF );    \
+    (out_be)[(i) + 1] = (unsigned char)( ( (in_le) >> 48 ) & 0xFF );    \
+    (out_be)[(i) + 2] = (unsigned char)( ( (in_le) >> 40 ) & 0xFF );    \
+    (out_be)[(i) + 3] = (unsigned char)( ( (in_le) >> 32 ) & 0xFF );    \
+    (out_be)[(i) + 4] = (unsigned char)( ( (in_le) >> 24 ) & 0xFF );    \
+    (out_be)[(i) + 5] = (unsigned char)( ( (in_le) >> 16 ) & 0xFF );    \
+    (out_be)[(i) + 6] = (unsigned char)( ( (in_le) >> 8  ) & 0xFF );    \
+    (out_be)[(i) + 7] = (unsigned char)( ( (in_le) >> 0  ) & 0xFF );    \
+}
+
 /*
  * global options
  */
@@ -364,7 +379,7 @@
     int allow_legacy;           /* allow legacy renegotiation               */
     int renegotiate;            /* attempt renegotiation?                   */
     int renego_delay;           /* delay before enforcing renegotiation     */
-    int renego_period;          /* period for automatic renegotiation       */
+    uint64_t renego_period;     /* period for automatic renegotiation       */
     int exchanges;              /* number of data exchanges                 */
     int min_version;            /* minimum protocol version accepted        */
     int max_version;            /* maximum protocol version accepted        */
@@ -1025,8 +1040,8 @@
         }
         else if( strcmp( p, "renego_period" ) == 0 )
         {
-            opt.renego_period = atoi( q );
-            if( opt.renego_period < 2 || opt.renego_period > 255 )
+            if( sscanf( q, "%" SCNu64, &opt.renego_period ) != 1 ||
+                opt.renego_period < 2 )
                 goto usage;
         }
         else if( strcmp( p, "exchanges" ) == 0 )
@@ -1741,7 +1756,7 @@
 
     if( opt.renego_period != DFL_RENEGO_PERIOD )
     {
-        renego_period[7] = opt.renego_period;
+        PUT_UINT64_BE( renego_period, opt.renego_period, 0 );
         mbedtls_ssl_conf_renegotiation_period( &conf, renego_period );
     }
 #endif
diff --git a/scripts/config.pl b/scripts/config.pl
index d4c32fd..d8d6a20 100755
--- a/scripts/config.pl
+++ b/scripts/config.pl
@@ -5,9 +5,28 @@
 use warnings;
 use strict;
 
+my $config_file = "include/mbedtls/config.h";
 my $usage = <<EOU;
-$0 [-f <file>] unset <name>
-$0 [-f <file>] set <name> [<value>]
+$0 [-f <file>] [set <symbol> <value> | unset <symbol> | full | realfull]
+
+Commands
+    set <symbol> [<value>]  - Uncomments or adds a #define for the <symbol> to
+                              the configuration file, and optionally making it
+                              of <value>.
+                              If the symbol isn't present in the file an error
+                              is returned.
+    unset <symbol>          - Comments out the #define for the given symbol if
+                              present in the configuration file.
+    full                    - Uncomments all #define's in the configuration file
+                              excluding some reserved symbols, until the
+                              'Module configuration options' section
+    realfull                - Uncomments all #define's with no exclusions
+
+Options
+    -f <filename>           - The file or file path for the configuration file
+                              to edit. When omitted, the following default is
+                              used:
+                                $config_file
 EOU
 # for our eyes only:
 # $0 [-f <file>] full|realfull
@@ -40,8 +59,6 @@
 PLATFORM_[A-Z0-9]+_ALT
 );
 
-my $config_file = "include/mbedtls/config.h";
-
 # get -f option
 if (@ARGV >= 2 && $ARGV[0] eq "-f") {
     shift; # -f
diff --git a/scripts/data_files/rename-1.3-2.0.txt b/scripts/data_files/rename-1.3-2.0.txt
index 397f6be..cb3381a 100644
--- a/scripts/data_files/rename-1.3-2.0.txt
+++ b/scripts/data_files/rename-1.3-2.0.txt
@@ -1996,7 +1996,6 @@
 ssl_set_arc4_support mbedtls_ssl_conf_arc4_support
 ssl_set_authmode mbedtls_ssl_conf_authmode
 ssl_set_bio mbedtls_ssl_set_bio
-ssl_set_bio_timeout mbedtls_ssl_set_bio_timeout
 ssl_set_ca_chain mbedtls_ssl_conf_ca_chain
 ssl_set_cbc_record_splitting mbedtls_ssl_conf_cbc_record_splitting
 ssl_set_ciphersuites mbedtls_ssl_conf_ciphersuites
diff --git a/tests/data_files/crl-malformed-trailing-spaces.pem b/tests/data_files/crl-malformed-trailing-spaces.pem
new file mode 100644
index 0000000..9eae3da
--- /dev/null
+++ b/tests/data_files/crl-malformed-trailing-spaces.pem
@@ -0,0 +1,20 @@
+-----BEGIN X509 CRL-----
+MIIBbzCB9gIBATAJBgcqhkjOPQQBMD4xCzAJBgNVBAYTAk5MMREwDwYDVQQKEwhQ
+b2xhclNTTDEcMBoGA1UEAxMTUG9sYXJzc2wgVGVzdCBFQyBDQRcNMTMwOTI0MTYz
+MTA4WhcNMjMwOTIyMTYzMTA4WjAUMBICAQoXDTEzMDkyNDE2MjgzOFqgcjBwMG4G
+A1UdIwRnMGWAFJ1tICRJAT8ry3i1Gbx+JMnb+zZ8oUKkQDA+MQswCQYDVQQGEwJO
+TDERMA8GA1UEChMIUG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMg
+Q0GCCQDBQ+J+YkPM6DAJBgcqhkjOPQQBA2kAMGYCMQDVG95rrSSl4dJgbJ5vR1GW
+svEuEsAh35EhF1WrcadMuCeMQVX9cUPupFfQUpHyMfoCMQCKf0yv8pN9BAoi3FVm
+56meWPhUekgLKKMAobt2oJJY6feuiFU2YFGs1aF0rV6Bj+U=
+-----END X509 CRL-----
+-----BEGIN X509 CRL-----
+MIIBcTCB9wIBATAKBggqhkjOPQQDBDA+MQswCQYDVQQGEwJOTDERMA8GA1UEChMI
+UG9sYXJTU0wxHDAaBgNVBAMTE1BvbGFyc3NsIFRlc3QgRUMgQ0EXDTEzMDkyNDE2
+MzEwOFoXDTIzMDkyMjE2MzEwOFowFDASAgEKFw0xMzA5MjQxNjI4MzhaoHIwcDBu
+BgNVHSMEZzBlgBSdbSAkSQE/K8t4tRm8fiTJ2/s2fKFCpEAwPjELMAkGA1UEBhMC
+TkwxETAPBgNVBAoTCFBvbGFyU1NMMRwwGgYDVQQDExNQb2xhcnNzbCBUZXN0IEVD
+IENBggkAwUPifmJDzOgwCgYIKoZIzj0EAwQDaQAwZgIxAL/VFrDIYUECsS0rVpAy
+6zt/CqeAZ1sa/l5LTaG1XW286n2Kibipr6EpkYZNYIQILgIxAI0wb3Py1DHPWpYf
+/BFBH7C3KYq+nWTrLeEnhrjU1LzG/CiQ8lnuskya6lw/P3lJ/A==
+-----END X509 CRL-----      
diff --git a/tests/scripts/generate_code.pl b/tests/scripts/generate_code.pl
index 1c7a281..1c9cfc5 100755
--- a/tests/scripts/generate_code.pl
+++ b/tests/scripts/generate_code.pl
@@ -139,7 +139,7 @@
             $param_defs .= "    char *param$i = params[$i];\n";
             $param_checks .= "    if( verify_string( &param$i ) != 0 ) return( 2 );\n";
             push @dispatch_params, "param$i";
-            $mapping_regex .= ":[^:\n]+";
+            $mapping_regex .= ":(?:\\\\.|[^:\n])+";
         }
         else
         {
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index e73d011..24b0fff 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -1534,6 +1534,19 @@
             -s "=> renegotiate" \
             -s "write hello request"
 
+run_test    "Renegotiation: DTLS, renego_period overflow" \
+            "$P_SRV debug_level=3 dtls=1 exchanges=4 renegotiation=1 renego_period=18446462598732840962 auth_mode=optional" \
+            "$P_CLI debug_level=3 dtls=1 exchanges=4 renegotiation=1" \
+            0 \
+            -c "client hello, adding renegotiation extension" \
+            -s "received TLS_EMPTY_RENEGOTIATION_INFO" \
+            -s "found renegotiation extension" \
+            -s "server hello, secure renegotiation extension" \
+            -s "record counter limit reached: renegotiate" \
+            -c "=> renegotiate" \
+            -s "=> renegotiate" \
+            -s "write hello request" \
+
 requires_gnutls
 run_test    "Renegotiation: DTLS, gnutls server, client-initiated" \
             "$G_SRV -u --mtu 4096" \
diff --git a/tests/suites/test_suite_pem.data b/tests/suites/test_suite_pem.data
index 973c923..339b4d3 100644
--- a/tests/suites/test_suite_pem.data
+++ b/tests/suites/test_suite_pem.data
@@ -15,3 +15,12 @@
 
 PEM write (exactly two lines + 1)
 mbedtls_pem_write_buffer:"-----START TEST-----\n":"-----END TEST-----\n":"000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F00":"-----START TEST-----\nAAECAwQFBgcICQoLDA0ODwABAgMEBQYHCAkKCwwNDg8AAQIDBAUGBwgJCgsMDQ4P\nAAECAwQFBgcICQoLDA0ODwABAgMEBQYHCAkKCwwNDg8AAQIDBAUGBwgJCgsMDQ4P\nAA==\n-----END TEST-----\n"
+
+PEM read (DES-EDE3-CBC + invalid iv)
+mbedtls_pem_read_buffer:"^":"$":"^\nProc-Type\: 4,ENCRYPTED\nDEK-Info\: DES-EDE3-CBC,00$":MBEDTLS_ERR_PEM_INVALID_ENC_IV
+
+PEM read (DES-CBC + invalid iv)
+mbedtls_pem_read_buffer:"^":"$":"^\nProc-Type\: 4,ENCRYPTED\nDEK-Info\: DES-CBC,00$":MBEDTLS_ERR_PEM_INVALID_ENC_IV
+
+PEM read (unknown encryption algorithm)
+mbedtls_pem_read_buffer:"^":"$":"^\nProc-Type\: 4,ENCRYPTED\nDEK-Info\: AES-,00$":MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG
diff --git a/tests/suites/test_suite_pem.function b/tests/suites/test_suite_pem.function
index 6a62bfe..5e02210 100644
--- a/tests/suites/test_suite_pem.function
+++ b/tests/suites/test_suite_pem.function
@@ -3,12 +3,7 @@
 #include "mbedtls/pem.h"
 /* END_HEADER */
 
-/* BEGIN_DEPENDENCIES
- * depends_on:MBEDTLS_PEM_WRITE_C
- * END_DEPENDENCIES
- */
-
-/* BEGIN_CASE */
+/* BEGIN_CASE depends_on:MBEDTLS_PEM_WRITE_C */
 void mbedtls_pem_write_buffer( char *start, char *end, char *buf_str, char *result_str )
 {
     unsigned char buf[5000];
@@ -38,3 +33,20 @@
     mbedtls_free( check_buf );
 }
 /* END_CASE */
+
+/* BEGIN_CASE depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_AES_C:MBEDTLS_DES_C:MBEDTLS_MD5_C:MBEDTLS_CIPHER_MODE_CBC */
+void mbedtls_pem_read_buffer( char *header, char *footer, char *data, int ret )
+{
+    mbedtls_pem_context ctx;
+    size_t use_len = 0;
+
+    mbedtls_pem_init( &ctx );
+
+    TEST_ASSERT( mbedtls_pem_read_buffer( &ctx, header, footer,
+                                          (const unsigned char *)data, NULL, 0,
+                                          &use_len ) == ret );
+
+exit:
+    mbedtls_pem_free( &ctx );
+}
+/* END_CASE */
diff --git a/tests/suites/test_suite_pk.data b/tests/suites/test_suite_pk.data
index 22a7fa8..f6ea378 100644
--- a/tests/suites/test_suite_pk.data
+++ b/tests/suites/test_suite_pk.data
@@ -150,3 +150,6 @@
 depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_RSA_C
 mbedtls_pk_check_pair:"data_files/ec_256_pub.pem":"data_files/server1.key":MBEDTLS_ERR_PK_TYPE_MISMATCH
 
+RSA hash_len overflow (size_t vs unsigned int)
+depends_on:MBEDTLS_RSA_C:MBEDTLS_HAVE_INT64
+pk_rsa_overflow:
diff --git a/tests/suites/test_suite_pk.function b/tests/suites/test_suite_pk.function
index 08a2623..5fa8a69 100644
--- a/tests/suites/test_suite_pk.function
+++ b/tests/suites/test_suite_pk.function
@@ -5,6 +5,9 @@
 #include "mbedtls/ecp.h"
 #include "mbedtls/rsa.h"
 
+/* For detecting 64-bit compilation */
+#include "mbedtls/bignum.h"
+
 static int rnd_std_rand( void *rng_state, unsigned char *output, size_t len );
 
 #define RSA_KEY_SIZE 512
@@ -414,6 +417,34 @@
 }
 /* END_CASE */
 
+/* BEGIN_CASE depends_on:MBEDTLS_RSA_C:MBEDTLS_HAVE_INT64 */
+void pk_rsa_overflow( )
+{
+    mbedtls_pk_context pk;
+    size_t hash_len = (size_t)-1;
+
+    mbedtls_pk_init( &pk );
+
+    TEST_ASSERT( mbedtls_pk_setup( &pk,
+                 mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == 0 );
+
+#if defined(MBEDTLS_PKCS1_V21)
+    TEST_ASSERT( mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, NULL, &pk,
+                    MBEDTLS_MD_NONE, NULL, hash_len, NULL, 0 ) ==
+                 MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+#endif /* MBEDTLS_PKCS1_V21 */
+
+    TEST_ASSERT( mbedtls_pk_verify( &pk, MBEDTLS_MD_NONE, NULL, hash_len,
+                    NULL, 0 ) == MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+
+    TEST_ASSERT( mbedtls_pk_sign( &pk, MBEDTLS_MD_NONE, NULL, hash_len, NULL, 0,
+                    rnd_std_rand, NULL ) == MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+
+exit:
+    mbedtls_pk_free( &pk );
+}
+/* END_CASE */
+
 /* BEGIN_CASE depends_on:MBEDTLS_RSA_C:MBEDTLS_PK_RSA_ALT_SUPPORT */
 void pk_rsa_alt( )
 {
@@ -461,6 +492,11 @@
     /* Test signature */
     TEST_ASSERT( mbedtls_pk_sign( &alt, MBEDTLS_MD_NONE, hash, sizeof hash,
                           sig, &sig_len, rnd_std_rand, NULL ) == 0 );
+#if defined(MBEDTLS_HAVE_INT64)
+    TEST_ASSERT( mbedtls_pk_sign( &alt, MBEDTLS_MD_NONE, hash, (size_t)-1,
+                          NULL, NULL, rnd_std_rand, NULL ) ==
+                 MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+#endif /* MBEDTLS_HAVE_INT64 */
     TEST_ASSERT( sig_len == RSA_KEY_LEN );
     TEST_ASSERT( mbedtls_pk_verify( &rsa, MBEDTLS_MD_NONE,
                             hash, sizeof hash, sig, sig_len ) == 0 );
diff --git a/tests/suites/test_suite_x509parse.data b/tests/suites/test_suite_x509parse.data
index 9a44dbe..edb7457 100644
--- a/tests/suites/test_suite_x509parse.data
+++ b/tests/suites/test_suite_x509parse.data
@@ -198,6 +198,10 @@
 depends_on:MBEDTLS_PEM_PARSE_C
 mbedtls_x509_crl_info:"data_files/crl-ec-sha512.pem":"CRL version   \: 2\nissuer name   \: C=NL, O=PolarSSL, CN=Polarssl Test EC CA\nthis update   \: 2013-09-24 16\:31\:08\nnext update   \: 2023-09-22 16\:31\:08\nRevoked certificates\:\nserial number\: 0A revocation date\: 2013-09-24 16\:28\:38\nsigned using  \: ECDSA with SHA512\n"
 
+X509 CRL Malformed Input (trailing spaces at end of file)
+depends_on:MBEDTLS_PEM_PARSE_C
+mbedtls_x509_crl_parse:"data_files/crl-malformed-trailing-spaces.pem":MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT
+
 X509 CSR Information RSA with MD4
 depends_on:MBEDTLS_PEM_PARSE_C
 mbedtls_x509_csr_info:"data_files/server1.req.md4":"CSR version   \: 1\nsubject name  \: C=NL, O=PolarSSL, CN=PolarSSL Server 1\nsigned using  \: RSA with MD4\nRSA key size  \: 2048 bits\n"
diff --git a/tests/suites/test_suite_x509parse.function b/tests/suites/test_suite_x509parse.function
index 40e653d..a724cd8 100644
--- a/tests/suites/test_suite_x509parse.function
+++ b/tests/suites/test_suite_x509parse.function
@@ -163,6 +163,22 @@
 }
 /* END_CASE */
 
+/* BEGIN_CASE depends_on:MBEDTLS_FS_IO:MBEDTLS_X509_CRL_PARSE_C */
+void mbedtls_x509_crl_parse( char *crl_file, int result )
+{
+    mbedtls_x509_crl   crl;
+    char buf[2000];
+
+    mbedtls_x509_crl_init( &crl );
+    memset( buf, 0, 2000 );
+
+    TEST_ASSERT( mbedtls_x509_crl_parse_file( &crl, crl_file ) == result );
+
+exit:
+    mbedtls_x509_crl_free( &crl );
+}
+/* END_CASE */
+
 /* BEGIN_CASE depends_on:MBEDTLS_FS_IO:MBEDTLS_X509_CSR_PARSE_C */
 void mbedtls_x509_csr_info( char *csr_file, char *result_str )
 {