Forbid sequence number wrapping
diff --git a/library/error.c b/library/error.c
index 64dc0f5..4aa167f 100644
--- a/library/error.c
+++ b/library/error.c
@@ -433,6 +433,8 @@
             snprintf( buf, buflen, "SSL - Unkown identity received (eg, PSK identity)" );
         if( use_ret == -(POLARSSL_ERR_SSL_INTERNAL_ERROR) )
             snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
+        if( use_ret == -(POLARSSL_ERR_SSL_COUNTER_WRAPPING) )
+            snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
 #endif /* POLARSSL_SSL_TLS_C */
 
 #if defined(POLARSSL_X509_USE_C) || defined(POLARSSL_X509_CREATE_C)
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 4f3095c..20cb9bd 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -1309,6 +1309,13 @@
         if( ++ssl->out_ctr[i - 1] != 0 )
             break;
 
+    /* The loops goes to its end iff the counter is wrapping */
+    if( i == 0 )
+    {
+        SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
+        return( POLARSSL_ERR_SSL_COUNTER_WRAPPING );
+    }
+
     SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
 
     return( 0 );
@@ -1775,6 +1782,13 @@
         if( ++ssl->in_ctr[i - 1] != 0 )
             break;
 
+    /* The loops goes to its end iff the counter is wrapping */
+    if( i == 0 )
+    {
+        SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
+        return( POLARSSL_ERR_SSL_COUNTER_WRAPPING );
+    }
+
     SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
 
     return( 0 );