Fix length checking for AEAD ciphersuites
diff --git a/ChangeLog b/ChangeLog
index c1df109..563aa54 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -5,6 +5,11 @@
 (and various x509 structures got a new member)
 
 = PolarSSL 1.3 branch
+Security
+   * Fix length checking for AEAD ciphersuites (found by Codenomicon).
+     It was possible to crash the server (and client) using crafted messages
+     when a GCM suite was chosen.
+
 Features
    * Add CCM module and cipher mode to Cipher Layer
    * Support for CCM and CCM_8 ciphersuites
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index ce6730d..e3b0a17 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -1327,10 +1327,18 @@
         unsigned char add_data[13];
         unsigned char taglen = ssl->transform_in->ciphersuite_info->flags &
                                POLARSSL_CIPHERSUITE_SHORT_TAG ? 8 : 16;
+        unsigned char explicit_iv_len =  ssl->transform_in->ivlen -
+                                         ssl->transform_in->fixed_ivlen;
 
-        dec_msglen = ssl->in_msglen - ( ssl->transform_in->ivlen -
-                                        ssl->transform_in->fixed_ivlen );
-        dec_msglen -= taglen;
+        if( ssl->in_msglen < explicit_iv_len + taglen )
+        {
+            SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
+                                "+ taglen (%d)", ssl->in_msglen,
+                                explicit_iv_len, taglen ) );
+            return( POLARSSL_ERR_SSL_INVALID_MAC );
+        }
+        dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
+
         dec_msg = ssl->in_msg;
         dec_msg_result = ssl->in_msg;
         ssl->in_msglen = dec_msglen;