This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch 2.2.X
in repository https://gitbox.apache.org/repos/asf/mina.git


The following commit(s) were added to refs/heads/2.2.X by this push:
     new 63755b435 Protect against unbounded memory allocation
63755b435 is described below

commit 63755b4358ff2282bb8c3c8d9778f3f89c654b21
Author: emmanuel lecharny <[email protected]>
AuthorDate: Mon Nov 16 00:16:12 2026 +0100

    Protect against unbounded memory allocation
---
 .../handlers/http/AbstractHttpLogicHandler.java    |  29 +++++
 .../apache/mina/proxy/utils/IoBufferDecoder.java   |  12 +-
 .../mina/proxy/HttpProxyResponseBodyLimitTest.java | 143 +++++++++++++++++++++
 3 files changed, 183 insertions(+), 1 deletion(-)

diff --git 
a/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
 
b/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
index 4b85f8dd5..b293491f9 100644
--- 
a/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
+++ 
b/mina-core/src/main/java/org/apache/mina/proxy/handlers/http/AbstractHttpLogicHandler.java
@@ -53,6 +53,20 @@ public abstract class AbstractHttpLogicHandler extends 
AbstractProxyLogicHandler
 
     private static final byte[] CRLF_DELIMITER = new byte[] { '\r', '\n' };
 
+    /**
+     * Maximum entity body length (in bytes) accepted from the proxy during the
+     * handshake. The Content-Length and chunk-size values are proxy-supplied
+     * and drive buffer allocation before any body byte arrives, so they must
+     * be bounded: a hostile or compromised proxy answering with
+     * "Content-Length: 2000000000" would otherwise trigger a ~2 GB allocation
+     * for free. Proxy handshake bodies (auth challenges, error pages) are
+     * small; 64 KiB is generous. The bound can be adjusted with the
+     * "org.apache.mina.proxy.http.maxEntityBodyLength" system property.
+     */
+    private static final int MAX_ENTITY_BODY_LENGTH = Integer
+            .getInteger("org.apache.mina.proxy.http.maxEntityBodyLength", 64 * 
1024);
+
+
     // Parsing vars
 
     /**
@@ -160,6 +174,11 @@ public abstract class AbstractHttpLogicHandler extends 
AbstractProxyLogicHandler
                     contentLength = 0;
                 } else {
                     contentLength = 
Integer.parseInt(contentLengthHeader.trim());
+
+                    if (contentLength < 0 || contentLength > 
MAX_ENTITY_BODY_LENGTH) {
+                        throw new ProxyAuthException("Invalid proxy response 
Content-Length: " + contentLength);
+                    }
+
                     decoder.setContentLength(contentLength, true);
                 }
             }
@@ -205,6 +224,11 @@ public abstract class AbstractHttpLogicHandler extends 
AbstractProxyLogicHandler
                             chunkSize = chunkSize.substring(0, 
chunkSize.length() - 2);
                         }
                         contentLength = Integer.decode("0x" + chunkSize);
+
+                        if (contentLength < 0 || contentLength > 
MAX_ENTITY_BODY_LENGTH) {
+                            throw new ProxyAuthException("Invalid proxy 
response chunk size: " + contentLength);
+                        }
+
                         if (contentLength > 0) {
                             contentLength += 2; // also read chunk's trailing 
CRLF
                             decoder.setContentLength(contentLength, true);
@@ -225,6 +249,11 @@ public abstract class AbstractHttpLogicHandler extends 
AbstractProxyLogicHandler
                     contentLength = 0;
                     responseData.put(tmp);
                     buf.position(buf.position());
+
+                    if (responseData.position() - entityBodyStartPosition > 
MAX_ENTITY_BODY_LENGTH) {
+                        throw new ProxyAuthException("Proxy response entity 
body larger than "
+                                + MAX_ENTITY_BODY_LENGTH + " bytes");
+                    }
                 }
 
                 // Read footers
diff --git 
a/mina-core/src/main/java/org/apache/mina/proxy/utils/IoBufferDecoder.java 
b/mina-core/src/main/java/org/apache/mina/proxy/utils/IoBufferDecoder.java
index 2a865d68c..cac9fc268 100644
--- a/mina-core/src/main/java/org/apache/mina/proxy/utils/IoBufferDecoder.java
+++ b/mina-core/src/main/java/org/apache/mina/proxy/utils/IoBufferDecoder.java
@@ -32,6 +32,13 @@ import org.apache.mina.filter.codec.textline.LineDelimiter;
  * @since MINA 2.0.0-M3
  */
 public class IoBufferDecoder {
+    /**
+     * Maximum number of bytes allocated up front in content-length mode. The
+     * content length is peer-supplied, so the buffer starts small and
+     * auto-expands as data actually arrives instead of eagerly allocating
+     * whatever the peer declared.
+     */
+    private static final int INITIAL_CONTENT_BUFFER_SIZE = 4096;
 
     /**
      * The class holding the decoding context.
@@ -224,7 +231,10 @@ public class IoBufferDecoder {
         // Retrieve fixed length content
         if (contentLength > -1) {
             if (decodedBuffer == null) {
-                decodedBuffer = 
IoBuffer.allocate(contentLength).setAutoExpand(true);
+                // Do not trust the peer-declared length for the upfront
+                // allocation: the buffer auto-expands as bytes arrive, so a
+                // huge declared length costs nothing until it is actually 
sent.
+                decodedBuffer = IoBuffer.allocate(Math.min(contentLength, 
INITIAL_CONTENT_BUFFER_SIZE)).setAutoExpand(true);
             }
 
             // If not enough data to complete the decoding
diff --git 
a/mina-core/src/test/java/org/apache/mina/proxy/HttpProxyResponseBodyLimitTest.java
 
b/mina-core/src/test/java/org/apache/mina/proxy/HttpProxyResponseBodyLimitTest.java
new file mode 100644
index 000000000..c5ebaa23c
--- /dev/null
+++ 
b/mina-core/src/test/java/org/apache/mina/proxy/HttpProxyResponseBodyLimitTest.java
@@ -0,0 +1,143 @@
+/*
+ *  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.mina.proxy;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.net.InetSocketAddress;
+
+import org.apache.mina.core.buffer.IoBuffer;
+import org.apache.mina.core.filterchain.IoFilter.NextFilter;
+import org.apache.mina.core.session.DummySession;
+import org.apache.mina.proxy.handlers.http.AbstractHttpLogicHandler;
+import org.apache.mina.proxy.handlers.http.HttpProxyRequest;
+import org.apache.mina.proxy.handlers.http.HttpProxyResponse;
+import org.apache.mina.proxy.session.ProxyIoSession;
+import org.apache.mina.proxy.utils.IoBufferDecoder;
+import org.junit.Test;
+
+/**
+ * Regression tests: sizes declared by the proxy during the HTTP handshake
+ * (Content-Length, chunk sizes) drive buffer allocation before any body byte
+ * arrives, so they must be bounded. A hostile or compromised proxy answering
+ * a CONNECT with "Content-Length: 2000000000" (or a single "7ffffff0" chunk
+ * header) would otherwise trigger a ~2 GB allocation for free, taking down
+ * the client JVM.
+ */
+public class HttpProxyResponseBodyLimitTest {
+
+    /** Minimal concrete handler: only the response decoding path is under 
test. */
+    private static class TestHttpLogicHandler extends AbstractHttpLogicHandler 
{
+        boolean responseHandled;
+
+        TestHttpLogicHandler(ProxyIoSession proxyIoSession) {
+            super(proxyIoSession);
+        }
+
+        @Override
+        public void doHandshake(NextFilter nextFilter) {
+            // Do nothing
+        }
+
+        @Override
+        public void handleResponse(HttpProxyResponse response) {
+            responseHandled = true;
+        }
+    }
+
+    private TestHttpLogicHandler newHandler() {
+        ProxyIoSession proxyIoSession = new ProxyIoSession(new 
InetSocketAddress("localhost", 8080),
+                new HttpProxyRequest("http://localhost/";));
+        proxyIoSession.setSession(new DummySession());
+
+        return new TestHttpLogicHandler(proxyIoSession);
+    }
+
+    private static IoBuffer response(String text) {
+        return IoBuffer.wrap(text.getBytes());
+    }
+
+    @Test
+    public void hugeContentLengthIsRejected() throws Exception {
+        TestHttpLogicHandler handler = newHandler();
+
+        try {
+            handler.messageReceived(null, response("HTTP/1.0 407 Proxy 
Authentication Required\r\n"
+                    + "Proxy-Authenticate: Basic realm=\"test\"\r\n" + 
"Content-Length: 2000000000\r\n" + "\r\n"));
+            fail("expected ProxyAuthException for a 2 GB declared 
Content-Length");
+        } catch (ProxyAuthException expected) {
+            assertTrue(expected.getMessage(), 
expected.getMessage().contains("Content-Length"));
+        }
+    }
+
+    @Test
+    public void hugeChunkSizeIsRejected() throws Exception {
+        TestHttpLogicHandler handler = newHandler();
+
+        try {
+            handler.messageReceived(null, response("HTTP/1.1 407 Proxy 
Authentication Required\r\n"
+                    + "Proxy-Authenticate: Basic realm=\"test\"\r\n" + 
"Transfer-Encoding: chunked\r\n" + "\r\n"
+                    + "7ffffff0\r\n"));
+            fail("expected ProxyAuthException for a ~2 GB declared chunk 
size");
+        } catch (ProxyAuthException expected) {
+            assertTrue(expected.getMessage(), 
expected.getMessage().contains("chunk size"));
+        }
+    }
+
+    @Test
+    public void reasonableBodyIsStillAccepted() throws Exception {
+        TestHttpLogicHandler handler = newHandler();
+
+        handler.messageReceived(null, response("HTTP/1.0 407 Proxy 
Authentication Required\r\n"
+                + "Proxy-Authenticate: Basic realm=\"test\"\r\n" + 
"Content-Length: 5\r\n" + "\r\n" + "hello"));
+
+        assertTrue("small entity bodies must still be decoded and handled", 
handler.responseHandled);
+    }
+
+    @Test
+    public void contentLengthDecodingIsIncremental() {
+        // Guards the lazy-allocation change in IoBufferDecoder: fragmented
+        // content must still be reassembled correctly.
+        IoBufferDecoder decoder = new IoBufferDecoder(10);
+
+        assertNull("partial content must not complete decoding",
+                decoder.decodeFully(IoBuffer.wrap("hello".getBytes())));
+
+        IoBuffer decoded = 
decoder.decodeFully(IoBuffer.wrap("world".getBytes()));
+        assertNotNull(decoded);
+        assertTrue(decoded.hasRemaining());
+
+        byte[] content = new byte[decoded.remaining()];
+        decoded.get(content);
+        assertTrue("reassembled content must match", new 
String(content).equals("helloworld"));
+    }
+
+    @Test
+    public void hugeDeclaredContentLengthDoesNotAllocateUpfront() {
+        // Before the fix this allocated the full declared length before any
+        // body byte arrived. Now allocation grows with the data received.
+        IoBufferDecoder decoder = new IoBufferDecoder(Integer.MAX_VALUE - 8);
+
+        assertNull(decoder.decodeFully(IoBuffer.wrap("tiny".getBytes())));
+    }
+}

Reply via email to