This is an automated email from the ASF dual-hosted git repository.
markt-asf pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/main by this push:
new 87b33150aa Fix BZ 70311: Fail TLS reads that cannot make progress on
BUFFER_OVERFLOW (#1157)
87b33150aa is described below
commit 87b33150aaddbf75f9a58b42645bd318ef4d01c1
Author: Pranav <[email protected]>
AuthorDate: Tue Nov 17 23:17:12 2026 +0530
Fix BZ 70311: Fail TLS reads that cannot make progress on BUFFER_OVERFLOW
(#1157)
* Fail TLS reads that cannot make progress on BUFFER_OVERFLOW
When unwrap() returns BUFFER_OVERFLOW, consumes nothing, and expand()
adds no free space to the destination buffer while input remains, the
next unwrap() fails the same way and SecureNioChannel.read(ByteBuffer)
loops forever. Fail the read with an IOException instead, as the
vectored read() overload already does.
https://bz.apache.org/bugzilla/show_bug.cgi?id=70311
Generated-by: Kiro CLI 3.1.0
Co-authored-by: Mark Thomas <[email protected]>
---
.../apache/tomcat/util/net/LocalStrings.properties | 1 +
.../apache/tomcat/util/net/SecureNioChannel.java | 9 ++
.../util/net/TestSecureNioChannelOverflow.java | 179 +++++++++++++++++++++
.../apache/tomcat/util/net/TesterAppBuffer.java | 59 +++++++
.../tomcat/util/net/TesterSslEnginePair.java | 152 +++++++++++++++++
webapps/docs/changelog.xml | 8 +
6 files changed, 408 insertions(+)
diff --git a/java/org/apache/tomcat/util/net/LocalStrings.properties
b/java/org/apache/tomcat/util/net/LocalStrings.properties
index 3fd39fede6..43822458ac 100644
--- a/java/org/apache/tomcat/util/net/LocalStrings.properties
+++ b/java/org/apache/tomcat/util/net/LocalStrings.properties
@@ -42,6 +42,7 @@ channel.nio.ssl.timeoutDuringHandshake=Timeout during
handshake.
channel.nio.ssl.unexpectedStatusDuringUnwrap=Unexpected status [{0}] during
handshake UNWRAP.
channel.nio.ssl.unexpectedStatusDuringWrap=Unexpected status [{0}] during
handshake WRAP.
channel.nio.ssl.unwrapFail=Unable to unwrap data, invalid status [{0}]
+channel.nio.ssl.unwrapFailNoRoom=Unable to unwrap data because the destination
buffer has no free space and could not be expanded, invalid status [{0}]
channel.nio.ssl.unwrapFailResize=Unable to unwrap data because buffer is too
small, invalid status [{0}]
channel.nio.ssl.wrapFail=Unable to wrap data, invalid status [{0}]
channel.nio.ssl.handshakeUnwrapBufferUnderflow=BUFFER_UNDERFLOW during
handshake unwrap, more data needed from the network
diff --git a/java/org/apache/tomcat/util/net/SecureNioChannel.java
b/java/org/apache/tomcat/util/net/SecureNioChannel.java
index b746f54d14..76c3ddd58a 100644
--- a/java/org/apache/tomcat/util/net/SecureNioChannel.java
+++ b/java/org/apache/tomcat/util/net/SecureNioChannel.java
@@ -696,6 +696,7 @@ public class SecureNioChannel extends NioChannel {
} else {
// The SSL session has increased the required buffer size
// since the buffer was created.
+ int roomBefore = dst.remaining();
if (dst == getBufHandler().getReadBuffer()) {
// This is the normal case for this code
getBufHandler().expand(sslEngine.getSession().getApplicationBufferSize());
@@ -708,6 +709,14 @@ public class SecureNioChannel extends NioChannel {
// to the caller that the buffer has been replaced.
throw new
IOException(sm.getString("channel.nio.ssl.unwrapFailResize",
unwrap.getStatus()));
}
+ // If there is still input to unwrap but unwrap() consumed
+ // nothing and expand() made no more room, the next
unwrap()
+ // overflows the same way and this loop never ends. Fail
the
+ // read instead. An empty netInBuffer exits the loop
normally.
+ if (netInBuffer.position() > 0 && unwrap.bytesConsumed()
== 0
+ && dst.remaining() <= roomBefore) {
+ throw new
IOException(sm.getString("channel.nio.ssl.unwrapFailNoRoom",
unwrap.getStatus()));
+ }
}
} else if (unwrap.getStatus() == Status.CLOSED &&
netInBuffer.position() == 0 && read > 0) {
// Clean TLS close on input side but there is application data
diff --git a/test/org/apache/tomcat/util/net/TestSecureNioChannelOverflow.java
b/test/org/apache/tomcat/util/net/TestSecureNioChannelOverflow.java
new file mode 100644
index 0000000000..7c10b4309f
--- /dev/null
+++ b/test/org/apache/tomcat/util/net/TestSecureNioChannelOverflow.java
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.util.net;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Tests {@link SecureNioChannel#read(ByteBuffer)} when {@code unwrap()}
+ * returns {@code BUFFER_OVERFLOW} and {@code expand()} does not make enough
+ * room for the record.
+ * <p>
+ * Each test writes its TLS record straight into the channel's
+ * {@code netInBuffer}. Nothing is sent over the socket, so the tests do not
+ * depend on timing.
+ */
+public class TestSecureNioChannelOverflow {
+
+ /*
+ * Without the fix, the overflow tests loop forever on one core. The
+ * timeout fails the test, but the looping thread keeps running until the
+ * JVM for this test class exits. build.xml forks a JVM per test class.
+ */
+ private static final long TIMEOUT_MS = 10000;
+
+ private TesterSslEnginePair engines;
+ private ServerSocketChannel listener;
+ private SocketChannel clientSock;
+ private SocketChannel serverSock;
+
+
+ @Before
+ public void setUp() throws Exception {
+ engines = new TesterSslEnginePair();
+ listener = ServerSocketChannel.open();
+ listener.bind(new InetSocketAddress("127.0.0.1", 0));
+ clientSock = SocketChannel.open(listener.getLocalAddress());
+ serverSock = listener.accept();
+ // read() reads the socket first. Nothing is sent, so this returns 0.
+ serverSock.configureBlocking(false);
+ }
+
+
+ @After
+ public void tearDown() throws IOException {
+ clientSock.close();
+ serverSock.close();
+ listener.close();
+ }
+
+
+ /*
+ * Regression guard: passes with and without the fix.
+ */
+ @Test
+ public void testNormalRead() throws Exception {
+ int appSize = engines.getApplicationBufferSize();
+ SocketBufferHandler bh = new SocketBufferHandler(appSize, appSize,
false);
+ SecureNioChannel ch = newChannel(bh);
+ byte[] payload = engines.wrapRecord(1000, ch.netInBuffer);
+
+ ByteBuffer dst = bh.getReadBuffer();
+ Assert.assertEquals(payload.length, ch.read(dst));
+ TesterSslEnginePair.assertContent(payload, dst);
+ }
+
+
+ /*
+ * Regression guard: passes with and without the fix. expand() replaces the
+ * socket read buffer with a larger one and the read succeeds.
+ */
+ @Test
+ public void testExpandGrowsSocketBuffer() throws Exception {
+ int appSize = engines.getApplicationBufferSize();
+ SocketBufferHandler bh = new SocketBufferHandler(appSize / 2, appSize
/ 2, false);
+ SecureNioChannel ch = newChannel(bh);
+ byte[] payload = engines.wrapRecord(appSize, ch.netInBuffer);
+ Assert.assertTrue(payload.length > appSize / 2);
+
+ Assert.assertEquals(payload.length, ch.read(bh.getReadBuffer()));
+ ByteBuffer dst = bh.getReadBuffer();
+ Assert.assertTrue(dst.capacity() >= appSize);
+ TesterSslEnginePair.assertContent(payload, dst);
+ }
+
+
+ /*
+ * The socket read buffer is full and already at the application buffer
+ * size, so expand() returns the same buffer.
+ */
+ @Test(timeout = TIMEOUT_MS)
+ public void testNoRoomSocketBuffer() throws Exception {
+ int appSize = engines.getApplicationBufferSize();
+ SocketBufferHandler bh = new SocketBufferHandler(appSize, appSize,
false);
+ SecureNioChannel ch = newChannel(bh);
+ engines.wrapRecord(appSize, ch.netInBuffer);
+
+ ByteBuffer dst = bh.getReadBuffer();
+ dst.position(dst.limit());
+ assertReadFails(ch, dst);
+ }
+
+
+ /*
+ * The application buffer has no room and expand() does nothing.
+ */
+ @Test(timeout = TIMEOUT_MS)
+ public void testNoRoomAppBuffer() throws Exception {
+ int appSize = engines.getApplicationBufferSize();
+ SecureNioChannel ch = newChannel(new SocketBufferHandler(appSize,
appSize, false));
+ engines.wrapRecord(appSize, ch.netInBuffer);
+ TesterAppBuffer app = new TesterAppBuffer(appSize, appSize, appSize,
false);
+ ch.setAppReadBufHandler(app);
+
+ assertReadFails(ch, app.getByteBuffer());
+ }
+
+
+ /*
+ * The application buffer is large enough but has little room left, and
+ * expand() only moves the limit to the capacity, as
+ * Http11InputBuffer.expand() does. The first expand() adds some room, but
+ * not enough for the record, and the second adds none.
+ */
+ @Test(timeout = TIMEOUT_MS)
+ public void testAppBufferExpandOnlyMovesLimit() throws Exception {
+ int appSize = engines.getApplicationBufferSize();
+ SecureNioChannel ch = newChannel(new SocketBufferHandler(appSize,
appSize, false));
+ engines.wrapRecord(appSize, ch.netInBuffer);
+ TesterAppBuffer app = new TesterAppBuffer(appSize, appSize - 100,
appSize - 92, true);
+ ch.setAppReadBufHandler(app);
+
+ assertReadFails(ch, app.getByteBuffer());
+ }
+
+
+ private SecureNioChannel newChannel(SocketBufferHandler bh) {
+ SecureNioChannel ch = new SecureNioChannel(bh, new NioEndpoint());
+ ch.sc = serverSock;
+ ch.sslEngine = engines.getServer();
+ ch.handshakeComplete = true;
+ return ch;
+ }
+
+
+ private static void assertReadFails(SecureNioChannel ch, ByteBuffer dst) {
+ try {
+ ch.read(dst);
+ Assert.fail("Expected IOException");
+ } catch (IOException expected) {
+ // The message must be unwrapFailNoRoom, not another failure such
as
+ // unwrapFailResize, so a stray IOException cannot pass this test.
+ Assert.assertTrue(String.valueOf(expected.getMessage()),
+ expected.getMessage() != null &&
expected.getMessage().contains("no free space"));
+ }
+ }
+}
diff --git a/test/org/apache/tomcat/util/net/TesterAppBuffer.java
b/test/org/apache/tomcat/util/net/TesterAppBuffer.java
new file mode 100644
index 0000000000..32aa2aec22
--- /dev/null
+++ b/test/org/apache/tomcat/util/net/TesterAppBuffer.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.util.net;
+
+import java.nio.ByteBuffer;
+
+/**
+ * An application read buffer for the secure channel tests. Its
+ * {@code expand(size)} either does nothing or moves the limit up to
+ * {@code size}, as {@code Http11InputBuffer.expand()} does when the buffer is
+ * already large enough.
+ */
+public class TesterAppBuffer implements ApplicationBufferHandler {
+
+ private final boolean moveLimit;
+ private ByteBuffer buffer;
+
+
+ public TesterAppBuffer(int capacity, int position, int limit, boolean
moveLimit) {
+ this.buffer = ByteBuffer.allocate(capacity);
+ this.buffer.limit(limit);
+ this.buffer.position(position);
+ this.moveLimit = moveLimit;
+ }
+
+
+ @Override
+ public void setByteBuffer(ByteBuffer buffer) {
+ this.buffer = buffer;
+ }
+
+
+ @Override
+ public ByteBuffer getByteBuffer() {
+ return buffer;
+ }
+
+
+ @Override
+ public void expand(int size) {
+ if (moveLimit) {
+ buffer.limit(Math.min(size, buffer.capacity()));
+ }
+ }
+}
diff --git a/test/org/apache/tomcat/util/net/TesterSslEnginePair.java
b/test/org/apache/tomcat/util/net/TesterSslEnginePair.java
new file mode 100644
index 0000000000..c9009d542d
--- /dev/null
+++ b/test/org/apache/tomcat/util/net/TesterSslEnginePair.java
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tomcat.util.net;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import javax.net.ssl.SSLEngineResult.Status;
+
+import org.junit.Assert;
+
+/**
+ * A client and a server {@link SSLEngine} that have completed a handshake in
+ * memory. Tests use the client to encrypt records that the server side reads.
+ */
+public class TesterSslEnginePair {
+
+ private final SSLEngine client;
+ private final SSLEngine server;
+
+
+ public TesterSslEnginePair() throws Exception {
+ SSLContext serverCtx = SSLContext.getInstance("TLS");
+
serverCtx.init(TesterSupport.getUserKeyManagers(TesterSupport.LOCALHOST_RSA_JKS),
null, null);
+ SSLContext clientCtx = SSLContext.getInstance("TLS");
+ clientCtx.init(null, TesterSupport.getTrustManagers(), null);
+
+ server = serverCtx.createSSLEngine();
+ server.setUseClientMode(false);
+ client = clientCtx.createSSLEngine("localhost", 443);
+ client.setUseClientMode(true);
+ handshake();
+ }
+
+
+ public SSLEngine getServer() {
+ return server;
+ }
+
+
+ public int getApplicationBufferSize() {
+ return server.getSession().getApplicationBufferSize();
+ }
+
+
+ /**
+ * Encrypts one TLS record of up to {@code size} plaintext bytes into
+ * {@code netIn}.
+ *
+ * @param size The number of plaintext bytes to try to send
+ * @param netIn The buffer to write the encrypted record to
+ *
+ * @return the plaintext that the record holds, which may be shorter than
+ * {@code size}
+ *
+ * @throws Exception if the record cannot be encrypted
+ */
+ public byte[] wrapRecord(int size, ByteBuffer netIn) throws Exception {
+ byte[] payload = new byte[size];
+ Arrays.fill(payload, (byte) 'a');
+ SSLEngineResult result = client.wrap(ByteBuffer.wrap(payload), netIn);
+ Assert.assertEquals(Status.OK, result.getStatus());
+ return Arrays.copyOf(payload, result.bytesConsumed());
+ }
+
+
+ /**
+ * Asserts that a read buffer, still in write mode, holds exactly
+ * {@code expected}.
+ *
+ * @param expected The plaintext that was sent
+ * @param dst The buffer the channel read into
+ */
+ public static void assertContent(byte[] expected, ByteBuffer dst) {
+ dst.flip();
+ byte[] actual = new byte[dst.remaining()];
+ dst.get(actual);
+ Assert.assertArrayEquals(expected, actual);
+ }
+
+
+ private void handshake() throws Exception {
+ int pkt = Math.max(client.getSession().getPacketBufferSize(),
server.getSession().getPacketBufferSize());
+ int app = Math.max(client.getSession().getApplicationBufferSize(),
+ server.getSession().getApplicationBufferSize());
+ ByteBuffer c2s = ByteBuffer.allocate(pkt * 4);
+ ByteBuffer s2c = ByteBuffer.allocate(pkt * 4);
+ ByteBuffer clientApp = ByteBuffer.allocate(app);
+ ByteBuffer serverApp = ByteBuffer.allocate(app);
+ client.beginHandshake();
+ server.beginHandshake();
+ for (int i = 0; i < 1000; i++) {
+ boolean clientDone = step(client, c2s, s2c, clientApp);
+ boolean serverDone = step(server, s2c, c2s, serverApp);
+ if (clientDone && serverDone && c2s.position() == 0 &&
s2c.position() == 0) {
+ return;
+ }
+ }
+ Assert.fail("Handshake did not complete");
+ }
+
+
+ private static boolean step(SSLEngine engine, ByteBuffer out, ByteBuffer
in, ByteBuffer app) throws Exception {
+ switch (engine.getHandshakeStatus()) {
+ case NEED_WRAP:
+ engine.wrap(ByteBuffer.allocate(0), out);
+ return false;
+ case NEED_UNWRAP:
+ unwrap(engine, in, app);
+ return false;
+ case NEED_TASK:
+ Runnable task;
+ while ((task = engine.getDelegatedTask()) != null) {
+ task.run();
+ }
+ return false;
+ default:
+ // Finished or not handshaking. Consume any final message,
+ // such as a TLS 1.3 session ticket.
+ if (in.position() > 0) {
+ unwrap(engine, in, app);
+ }
+ return engine.getHandshakeStatus() ==
HandshakeStatus.NOT_HANDSHAKING;
+ }
+ }
+
+
+ private static void unwrap(SSLEngine engine, ByteBuffer in, ByteBuffer
app) throws Exception {
+ in.flip();
+ engine.unwrap(in, app);
+ in.compact();
+ app.clear();
+ }
+}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 67c353e016..757d815987 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -335,6 +335,14 @@
Add HTTP/2 response header filtering similar to that provided for
HTTP/1.1. Pull request <pr>1154</pr> provided by Arturo Bernal. (markt)
</fix>
+ <fix>
+ <bug>70311</bug>: Fix an infinite loop in
+ <code>SecureNioChannel.read(ByteBuffer)</code> when the TLS engine
+ returns <code>BUFFER_OVERFLOW</code> without consuming any input and
+ the destination buffer cannot be expanded. The read now fails with an
+ <code>IOException</code>. Pull request <pr>1157</pr> provided by
+ Pranav N V. (markt)
+ </fix>
</changelog>
</subsection>
<subsection name="Jasper">
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]