Merge remote-tracking branch 'upstream-public/pr/1439' into development-proposed
diff --git a/ChangeLog b/ChangeLog
index ec8cc99..0d079c8 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -19,6 +19,8 @@
      resumption of the session).
    * Verify results of RSA private key operations to defend
      against Bellcore glitch attack.
+   * Fix a buffer overread in ssl_parse_server_key_exchange() that could cause
+     a crash on invalid input.
 
 Features
    * Extend PKCS#8 interface by introducing support for the entire SHA
@@ -55,6 +57,8 @@
    * Log correct number of ciphersuites used in Client Hello message. #918
    * Fix X509 CRT parsing that would potentially accept an invalid tag when
      parsing the subject alternative names.
+   * Fix a possible arithmetic overflow in ssl_parse_server_key_exchange()
+     that could cause a key exchange to fail on valid data.
 
 Changes
    * Fix tag lengths and value ranges in the documentation of CCM encryption.
diff --git a/library/ssl_cli.c b/library/ssl_cli.c
index 5367fdd..fc90f86 100644
--- a/library/ssl_cli.c
+++ b/library/ssl_cli.c
@@ -2479,10 +2479,18 @@
         /*
          * Read signature
          */
+
+        if( p > end - 2 )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
+            mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
+                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
+            return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
+        }
         sig_len = ( p[0] << 8 ) | p[1];
         p += 2;
 
-        if( end != p + sig_len )
+        if( p != end - sig_len )
         {
             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,