Merge branch 'mbedtls-1.3' into mbedtls-1.3-restricted

* mbedtls-1.3:
  Fix spurious #endif from previous cherry-pick
  Fix macroization of inline in C++
  Add missing warning in doc
  Fix compile error in net.c with musl libc
diff --git a/ChangeLog b/ChangeLog
index 8dac7a4..284cd48 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -2,11 +2,42 @@
 
 = mbed TLS 1.3.14 released 2015-10-xx
 
+Security
+   * Added fix for CVE-2015-5291 to prevent heap corruption due to buffer
+     overflow of the hostname or session ticket. Found by Guido Vranken,
+     Intelworks.
+   * Fix stack buffer overflow in pkcs12 decryption (used by
+     mbedtls_pk_parse_key(file)() when the password is > 129 bytes. Found by
+     Guido Vranken, Intelworks. Not triggerable remotely.
+   * Fix potential buffer overflow in mbedtls_mpi_read_string().
+     Found by Guido Vranken, Intelworks. Not exploitable remotely in the context
+     of TLS, but might be in other uses. On 32 bit machines, requires reading a
+     string of close to or larger than 1GB to exploit; on 64 bit machines, would
+     require reading a string of close to or larger than 2^62 bytes.
+   * Fix potential random memory allocation in mbedtls_pem_read_buffer()
+     on crafted PEM input data. Found and fix provided by Guido Vranken,
+     Intelworks. Not triggerable remotely in TLS. Triggerable remotely if you
+     accept PEM data from an untrusted source.
+   * Fix potential double-free if ssl_set_psk() is called repeatedly on
+     the same ssl_context object and some memory allocations fail. Found by
+     Guido Vranken, Intelworks. Can not be forced remotely.
+   * Fix possible heap buffer overflow in base64_encode() when the input
+     buffer is 512MB or larger on 32-bit platforms. Found by Guido Vranken,
+     Intelworks. Found by Guido Vranken. Not trigerrable remotely in TLS.
+   * Fix potential heap buffer overflow in servers that perform client
+     authentication against a crafted CA cert. Cannot be triggered remotely
+     unless you allow third parties to pick trust CAs for client auth. Found by
+     Guido Vranken, Intelworks.
+
 Bugfix
    * Fix compile error in net.c with musl libc. Found and patch provided by
      zhasha (#278).
    * Fix macroization of 'inline' keywork when building as C++. (#279)
 
+Changes
+   * Added checking of hostname length in ssl_set_hostname() to ensure domain
+     names are compliant with RFC 1035.
+
 = mbed TLS 1.3.13 released 2015-09-17
 
 Security
diff --git a/include/polarssl/base64.h b/include/polarssl/base64.h
index 0f1e854..bdd0c41 100644
--- a/include/polarssl/base64.h
+++ b/include/polarssl/base64.h
@@ -44,6 +44,8 @@
  * \return         0 if successful, or POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL.
  *                 *dlen is always updated to reflect the amount
  *                 of data that has (or would have) been written.
+ *                 If that length cannot be represented, then no data is
+ *                 written to the buffer and *dlen is set to SIZE_T_MAX.
  *
  * \note           Call this function with *dlen = 0 to obtain the
  *                 required buffer size in *dlen
diff --git a/include/polarssl/ssl.h b/include/polarssl/ssl.h
index 3b67d38..c7cd541 100644
--- a/include/polarssl/ssl.h
+++ b/include/polarssl/ssl.h
@@ -195,6 +195,8 @@
 #endif /* POLARSSL_SSL_PROTO_TLS1_1 */
 #endif /* POLARSSL_SSL_PROTO_TLS1_2 */
 
+#define SSL_MAX_HOST_NAME_LEN           255 /*!< Maximum host name defined in RFC 1035 */
+
 /* RFC 6066 section 4, see also mfl_code_to_length in ssl_tls.c
  * NONE must be zero so that memset()ing structure to zero works */
 #define SSL_MAX_FRAG_LEN_NONE           0   /*!< don't use this extension   */
diff --git a/library/base64.c b/library/base64.c
index ac922a4..7de87e5 100644
--- a/library/base64.c
+++ b/library/base64.c
@@ -75,6 +75,8 @@
      49,  50,  51, 127, 127, 127, 127, 127
 };
 
+#define BASE64_SIZE_T_MAX   ( (size_t) -1 ) /* SIZE_T_MAX is not standard */
+
 /*
  * Encode a buffer into base64 format
  */
@@ -91,15 +93,16 @@
         return( 0 );
     }
 
-    n = ( slen << 3 ) / 6;
+    n = slen / 3 + ( slen % 3 != 0 );
 
-    switch( ( slen << 3 ) - ( n * 6 ) )
+    if( n > ( BASE64_SIZE_T_MAX - 1 ) / 4 )
     {
-        case  2: n += 3; break;
-        case  4: n += 2; break;
-        default: break;
+        *dlen = BASE64_SIZE_T_MAX;
+        return( POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL );
     }
 
+    n *= 4;
+
     if( *dlen < n + 1 )
     {
         *dlen = n + 1;
@@ -190,7 +193,10 @@
     }
 
     if( n == 0 )
+    {
+        *dlen = 0;
         return( 0 );
+    }
 
     n = ( ( n * 6 ) + 7 ) >> 3;
     n -= j;
diff --git a/library/bignum.c b/library/bignum.c
index f479bc9..c97f16d 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -59,11 +59,14 @@
 #define biL    (ciL << 3)               /* bits  in limb  */
 #define biH    (ciL << 2)               /* half limb size */
 
+#define MPI_SIZE_T_MAX  ( (size_t) -1 ) /* SIZE_T_MAX is not standard */
+
 /*
  * Convert between bits/chars and number of limbs
+ * Divide first in order to avoid potential overflows
  */
-#define BITS_TO_LIMBS(i)  (((i) + biL - 1) / biL)
-#define CHARS_TO_LIMBS(i) (((i) + ciL - 1) / ciL)
+#define BITS_TO_LIMBS(i)  ( (i) / biL + ( (i) % biL != 0 ) )
+#define CHARS_TO_LIMBS(i) ( (i) / ciL + ( (i) % ciL != 0 ) )
 
 /*
  * Initialize one MPI
@@ -414,6 +417,9 @@
 
     if( radix == 16 )
     {
+        if( slen > MPI_SIZE_T_MAX >> 2 )
+            return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
         n = BITS_TO_LIMBS( slen << 2 );
 
         MPI_CHK( mpi_grow( X, n ) );
diff --git a/library/pem.c b/library/pem.c
index 5060484..054fcff 100644
--- a/library/pem.c
+++ b/library/pem.c
@@ -317,6 +317,9 @@
           ( POLARSSL_AES_C || POLARSSL_DES_C ) */
     }
 
+    if( s1 == s2 )
+        return( POLARSSL_ERR_PEM_INVALID_DATA );
+
     len = 0;
     ret = base64_decode( NULL, &len, s1, s2 - s1 );
 
diff --git a/library/pkcs12.c b/library/pkcs12.c
index f84fd52..dff01a7 100644
--- a/library/pkcs12.c
+++ b/library/pkcs12.c
@@ -87,6 +87,8 @@
     return( 0 );
 }
 
+#define PKCS12_MAX_PWDLEN 128
+
 static int pkcs12_pbe_derive_key_iv( asn1_buf *pbe_params, md_type_t md_type,
                                      const unsigned char *pwd,  size_t pwdlen,
                                      unsigned char *key, size_t keylen,
@@ -95,7 +97,10 @@
     int ret, iterations;
     asn1_buf salt;
     size_t i;
-    unsigned char unipwd[258];
+    unsigned char unipwd[PKCS12_MAX_PWDLEN * 2 + 2];
+
+    if( pwdlen > PKCS12_MAX_PWDLEN )
+        return( POLARSSL_ERR_PKCS12_BAD_INPUT_DATA );
 
     memset( &salt, 0, sizeof(asn1_buf) );
     memset( &unipwd, 0, sizeof(unipwd) );
@@ -126,6 +131,8 @@
     return( 0 );
 }
 
+#undef PKCS12_MAX_PWDLEN
+
 int pkcs12_pbe_sha1_rc4_128( asn1_buf *pbe_params, int mode,
                              const unsigned char *pwd,  size_t pwdlen,
                              const unsigned char *data, size_t len,
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index f603cff..39dc02e 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -65,6 +65,7 @@
                                     size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
 
     *olen = 0;
 
@@ -74,6 +75,12 @@
     SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
                    ssl->hostname ) );
 
+    if( end < p || (size_t)( end - p ) < ssl->hostname_len + 9 )
+    {
+         SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+         return;
+    }
+
     /*
      * struct {
      *     NameType name_type;
@@ -117,6 +124,7 @@
                                          size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
 
     *olen = 0;
 
@@ -125,6 +133,12 @@
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
 
+    if( end < p || (size_t)(end - p) < 5 + ssl->verify_data_len )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     /*
      * Secure renegotiation
      */
@@ -151,6 +165,7 @@
                                                 size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
     size_t sig_alg_len = 0;
 #if defined(POLARSSL_RSA_C) || defined(POLARSSL_ECDSA_C)
     unsigned char *sig_alg_list = buf + 6;
@@ -163,9 +178,54 @@
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
 
+#if defined(POLARSSL_RSA_C)
+#if defined(POLARSSL_SHA512_C)
+    /* SHA512 + RSA signature, SHA384 + RSA signature */
+    sig_alg_len += 4;
+#endif
+#if defined(POLARSSL_SHA256_C)
+    /* SHA256 + RSA signature, SHA224 + RSA signature */
+    sig_alg_len += 4;
+#endif
+#if defined(POLARSSL_SHA1_C)
+    /* SHA1 + RSA signature */
+    sig_alg_len += 2;
+#endif
+#if defined(POLARSSL_MD5_C)
+    /* MD5 + RSA signature */
+    sig_alg_len += 2;
+#endif
+#endif /* POLARSSL_RSA_C */
+#if defined(POLARSSL_ECDSA_C)
+#if defined(POLARSSL_SHA512_C)
+    /* SHA512 + ECDSA signature, SHA384 + ECDSA signature */
+    sig_alg_len += 4;
+#endif
+#if defined(POLARSSL_SHA256_C)
+    /* SHA256 + ECDSA signature, SHA224 + ECDSA signature */
+    sig_alg_len += 4;
+#endif
+#if defined(POLARSSL_SHA1_C)
+    /* SHA1 + ECDSA signature */
+    sig_alg_len += 2;
+#endif
+#if defined(POLARSSL_MD5_C)
+    /* MD5 + ECDSA signature */
+    sig_alg_len += 2;
+#endif
+#endif /* POLARSSL_ECDSA_C */
+
+    if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     /*
      * Prepare signature_algorithms extension (TLS 1.2)
      */
+    sig_alg_len = 0;
+
 #if defined(POLARSSL_RSA_C)
 #if defined(POLARSSL_SHA512_C)
     sig_alg_list[sig_alg_len++] = SSL_HASH_SHA512;
@@ -248,6 +308,7 @@
                                                      size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
     unsigned char *elliptic_curve_list = p + 6;
     size_t elliptic_curve_len = 0;
     const ecp_curve_info *info;
@@ -269,6 +330,25 @@
     for( info = ecp_curve_list(); info->grp_id != POLARSSL_ECP_DP_NONE; info++ )
     {
 #endif
+        elliptic_curve_len += 2;
+    }
+
+    if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
+    elliptic_curve_len = 0;
+
+#if defined(POLARSSL_SSL_SET_CURVES)
+    for( grp_id = ssl->curve_list; *grp_id != POLARSSL_ECP_DP_NONE; grp_id++ )
+    {
+       info = ecp_curve_info_from_grp_id( *grp_id );
+#else
+    for( info = ecp_curve_list(); info->grp_id != POLARSSL_ECP_DP_NONE; info++ )
+    {
+#endif
 
         elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
         elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
@@ -294,12 +374,18 @@
                                                    size_t *olen )
 {
     unsigned char *p = buf;
-    ((void) ssl);
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
 
     *olen = 0;
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
 
+    if( end < p || (size_t)( end - p ) < 6 )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );
 
@@ -319,14 +405,21 @@
                                                size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
 
-    if( ssl->mfl_code == SSL_MAX_FRAG_LEN_NONE ) {
-        *olen = 0;
+    *olen = 0;
+
+    if( ssl->mfl_code == SSL_MAX_FRAG_LEN_NONE )
         return;
-    }
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
 
+    if( end < p || (size_t)( end - p ) < 5 )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );
 
@@ -344,15 +437,21 @@
                                           unsigned char *buf, size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
+
+    *olen = 0;
 
     if( ssl->trunc_hmac == SSL_TRUNC_HMAC_DISABLED )
-    {
-        *olen = 0;
         return;
-    }
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
 
+    if( end < p || (size_t)( end - p ) < 4 )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );
 
@@ -368,17 +467,25 @@
                                        unsigned char *buf, size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
+
+    *olen = 0;
 
     if( ssl->encrypt_then_mac == SSL_ETM_DISABLED ||
         ssl->max_minor_ver == SSL_MINOR_VERSION_0 )
     {
-        *olen = 0;
         return;
     }
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
                         "extension" ) );
 
+    if( end < p || (size_t)( end - p ) < 4 )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );
 
@@ -394,17 +501,25 @@
                                        unsigned char *buf, size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
+
+    *olen = 0;
 
     if( ssl->extended_ms == SSL_EXTENDED_MS_DISABLED ||
         ssl->max_minor_ver == SSL_MINOR_VERSION_0 )
     {
-        *olen = 0;
         return;
     }
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
                         "extension" ) );
 
+    if( end < p || (size_t)( end - p ) < 4 )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );
 
@@ -420,16 +535,22 @@
                                           unsigned char *buf, size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
     size_t tlen = ssl->session_negotiate->ticket_len;
 
+    *olen = 0;
+
     if( ssl->session_tickets == SSL_SESSION_TICKETS_DISABLED )
-    {
-        *olen = 0;
         return;
-    }
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
 
+    if( end < p || (size_t)( end - p ) < 4 + tlen )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_SESSION_TICKET      ) & 0xFF );
 
@@ -457,16 +578,26 @@
                                 unsigned char *buf, size_t *olen )
 {
     unsigned char *p = buf;
+    const unsigned char *end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
+    size_t alpnlen = 0;
     const char **cur;
 
+    *olen = 0;
+
     if( ssl->alpn_list == NULL )
-    {
-        *olen = 0;
         return;
-    }
 
     SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
 
+    for( cur = ssl->alpn_list; *cur != NULL; cur++ )
+        alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
+
+    if( end < p || (size_t)( end - p ) < 6 + alpnlen )
+    {
+        SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
+        return;
+    }
+
     *p++ = (unsigned char)( ( TLS_EXT_ALPN >> 8 ) & 0xFF );
     *p++ = (unsigned char)( ( TLS_EXT_ALPN      ) & 0xFF );
 
@@ -746,13 +877,13 @@
     ext_len += olen;
 #endif
 
-#if defined(POLARSSL_SSL_SESSION_TICKETS)
-    ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
+#if defined(POLARSSL_SSL_ALPN)
+    ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
     ext_len += olen;
 #endif
 
-#if defined(POLARSSL_SSL_ALPN)
-    ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
+#if defined(POLARSSL_SSL_SESSION_TICKETS)
+    ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
     ext_len += olen;
 #endif
 
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index 379a3ab..82fa2d4 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -2300,6 +2300,7 @@
     size_t ct_len, sa_len; /* including length bytes */
     unsigned char *buf, *p;
     const x509_crt *crt;
+    const unsigned char * const end = ssl->out_msg + SSL_MAX_CONTENT_LEN;
 
     SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
 
@@ -2406,10 +2407,14 @@
     total_dn_size = 0;
     while( crt != NULL && crt->version != 0 )
     {
-        if( p - buf > 4096 )
-            break;
-
         dn_size = crt->subject_raw.len;
+
+        if( end < p || (size_t)( end - p ) < 2 + dn_size )
+        {
+            SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) );
+            break;
+        }
+
         *p++ = (unsigned char)( dn_size >> 8 );
         *p++ = (unsigned char)( dn_size      );
         memcpy( p, crt->subject_raw.p, dn_size );
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 96e867b..7fc9d99 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -4064,7 +4064,9 @@
         ( ssl->psk_identity = polarssl_malloc( psk_identity_len ) ) == NULL )
     {
         polarssl_free( ssl->psk );
+        polarssl_free( ssl->psk_identity );
         ssl->psk = NULL;
+        ssl->psk_identity = NULL;
         return( POLARSSL_ERR_SSL_MALLOC_FAILED );
     }
 
@@ -4148,6 +4150,9 @@
     if( ssl->hostname_len + 1 == 0 )
         return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
 
+    if( ssl->hostname_len > SSL_MAX_HOST_NAME_LEN )
+        return( POLARSSL_ERR_SSL_BAD_INPUT_DATA );
+
     ssl->hostname = polarssl_malloc( ssl->hostname_len + 1 );
 
     if( ssl->hostname == NULL )