SSLBuffer::EnsureCap: ensure `new_cap` can never cause `offset_` overflow.

Note that, as all users of `SSLBuffer` implement their own cap way below
32k even, there is non way to actually cause this overflow in BoringSSL
as it is now; making this change merely to ensure no future surprises.

Change-Id: Ia8245a1d25e57c17f750fa2580208c4d6a6a6964
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/97867
Reviewed-by: David Benjamin <davidben@google.com>
Commit-Queue: Rudolf Polzer <rpolzer@google.com>
diff --git a/ssl/ssl_buffer.cc b/ssl/ssl_buffer.cc
index bb39afa..e6a2b04 100644
--- a/ssl/ssl_buffer.cc
+++ b/ssl/ssl_buffer.cc
@@ -47,7 +47,7 @@
 }
 
 bool SSLBuffer::EnsureCap(size_t header_len, size_t new_cap) {
-  if (new_cap > 0xffff) {
+  if (new_cap > 0xffff - (SSL3_ALIGN_PAYLOAD - 1)) {
     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
     return false;
   }
diff --git a/ssl/ssl_internal_test.cc b/ssl/ssl_internal_test.cc
index 7f23839..bfbf211 100644
--- a/ssl/ssl_internal_test.cc
+++ b/ssl/ssl_internal_test.cc
@@ -17,6 +17,7 @@
 #include <openssl/aead.h>
 #include <openssl/ssl.h>
 
+#include "../crypto/test/test_util.h"
 #include "internal.h"
 
 
@@ -543,6 +544,16 @@
   }
 }
 
+TEST(SSLBufferTest, EnsureCapBoundary) {
+  SSLBuffer buf;
+  // The maximum safe capacity is 0xffff - (SSL3_ALIGN_PAYLOAD - 1) = 65528.
+  EXPECT_TRUE(buf.EnsureCap(0, 65528));
+
+  // Anything larger should be rejected to prevent uint16_t overflow.
+  EXPECT_FALSE(buf.EnsureCap(0, 65529));
+  EXPECT_TRUE(ErrorEquals(ERR_get_error(), ERR_LIB_SSL, ERR_R_INTERNAL_ERROR));
+}
+
 TEST(SSLTest, ECHPublicName) {
   EXPECT_FALSE(ssl_is_valid_ech_public_name(StringAsBytes("")));
   EXPECT_TRUE(ssl_is_valid_ech_public_name(StringAsBytes("example.com")));