Merge remote-tracking branch 'upstream-public/pr/1401' into mbedtls-2.7-proposed
diff --git a/ChangeLog b/ChangeLog
index ee9b669..2c14930 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -50,6 +50,9 @@
      Alex Hixon.
    * Allow configuring the shared library extension by setting the DLEXT
      environment variable when using the project makefiles.
+   * Verify that when (f_send, f_recv and f_recv_timeout) send or receive
+     more than the required length an error is returned. Raised by
+     Sam O'Connor in #1245.
 
 = mbed TLS 2.7.2 branch released 2018-03-16
 
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 236e52d..28905c9 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -2434,6 +2434,14 @@
             if( ret < 0 )
                 return( ret );
 
+            if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
+            {
+                MBEDTLS_SSL_DEBUG_MSG( 1,
+                    ( "f_recv returned %d bytes but only %lu were requested",
+                    ret, (unsigned long)len ) );
+                return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+            }
+
             ssl->in_left += ret;
         }
     }
@@ -2481,6 +2489,14 @@
         if( ret <= 0 )
             return( ret );
 
+        if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1,
+                ( "f_send returned %d bytes but only %lu bytes were sent",
+                ret, (unsigned long)ssl->out_left ) );
+            return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+        }
+
         ssl->out_left -= ret;
     }