You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ab...@apache.org on 2026/02/20 05:59:05 UTC

(httpcomponents-core) branch master updated: HTTP/2: fix frame header parsing and validate SETTINGS ACK length (#628)

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

abernal pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git


The following commit(s) were added to refs/heads/master by this push:
     new 999a1e91a HTTP/2: fix frame header parsing and validate SETTINGS ACK length (#628)
999a1e91a is described below

commit 999a1e91aef6cbcd619ff9a7c57e1005c3e015a9
Author: Arturo Bernal <ab...@apache.org>
AuthorDate: Fri Feb 20 05:59:00 2026 +0000

    HTTP/2: fix frame header parsing and validate SETTINGS ACK length (#628)
    
    Parse the 24-bit Length field as an unsigned value, treat flags as an
    unsigned byte, and mask out the reserved bit from the Stream Identifier.
    
    Also enforce RFC 9113 ยง6.5: SETTINGS frames with ACK set MUST have an
    empty payload (Length = 0); otherwise raise FRAME_SIZE_ERROR.
---
 .../hc/core5/http2/impl/io/FrameInputBuffer.java   |   5 +-
 .../impl/nio/AbstractH2StreamMultiplexer.java      |   5 +
 .../hc/core5/http2/impl/nio/FrameInputBuffer.java  |  10 +-
 .../core5/http2/impl/io/TestFrameInputBuffer.java  |  54 ++++++++++
 .../impl/nio/TestAbstractH2StreamMultiplexer.java  |  31 ++++++
 .../core5/http2/impl/nio/TestFrameInputBuffer.java | 109 +++++++++++++++++++++
 6 files changed, 209 insertions(+), 5 deletions(-)

diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/io/FrameInputBuffer.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/io/FrameInputBuffer.java
index e390805b0..376f26d1a 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/io/FrameInputBuffer.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/io/FrameInputBuffer.java
@@ -103,11 +103,12 @@ public RawFrame read(final InputStream inStream) throws IOException {
         final int payloadLen = (buffer[off] & 0xff) << 16 | (buffer[off + 1] & 0xff) << 8 | (buffer[off + 2] & 0xff);
         final int type = buffer[off + 3] & 0xff;
         final int flags = buffer[off + 4] & 0xff;
-        final int streamId = Math.abs(buffer[off + 5] & 0xff) << 24 | (buffer[off + 6] & 0xff << 16) | (buffer[off + 7] & 0xff) << 8 | (buffer[off + 8] & 0xff);
+        // HTTP/2 stream id is 31-bit; ignore the reserved (MSB) bit.
+        // Note: mask before shift; `b & 0xff << 16` would drop the byte due to operator precedence.
+        final int streamId = ((buffer[off + 5] & 0x7f) << 24) | ((buffer[off + 6] & 0xff) << 16) | ((buffer[off + 7] & 0xff) << 8) | (buffer[off + 8] & 0xff);
         if (payloadLen > maxFramePayloadSize) {
             throw new H2ConnectionException(H2Error.FRAME_SIZE_ERROR, "Frame size exceeds maximum");
         }
-
         final int frameLen = payloadOff + payloadLen;
         fillBuffer(inStream, frameLen);
 
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java
index 2bdfc6c92..b0e1abb80 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java
@@ -946,6 +946,11 @@ private void consumeFrame(final RawFrame frame) throws HttpException, IOExceptio
                     throw new H2ConnectionException(H2Error.PROTOCOL_ERROR, "Illegal stream id");
                 }
                 if (frame.isFlagSet(FrameFlag.ACK)) {
+                    // RFC 9113, Section 6.5: SETTINGS with ACK set MUST have an empty payload.
+                    final ByteBuffer payload = frame.getPayload();
+                    if (payload != null && payload.hasRemaining()) {
+                        throw new H2ConnectionException(H2Error.FRAME_SIZE_ERROR, "Invalid SETTINGS ACK payload");
+                    }
                     if (localSettingState == SettingsHandshake.TRANSMITTED) {
                         localSettingState = SettingsHandshake.ACKED;
                         ioSession.setEvent(SelectionKey.OP_WRITE);
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/FrameInputBuffer.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/FrameInputBuffer.java
index fb1c8f280..009f75d3d 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/FrameInputBuffer.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/FrameInputBuffer.java
@@ -133,13 +133,17 @@ public RawFrame read(final ByteBuffer src, final ReadableByteChannel channel) th
                 case HEAD_EXPECTED:
                     if (buffer.remaining() >= FrameConsts.HEAD_LEN) {
                         final int lengthAndType = buffer.getInt();
-                        payloadLen = lengthAndType >> 8;
+                        // HTTP/2 Length field is 24-bit unsigned (RFC 9113, Section 4.1).
+                        // Use unsigned shift + mask to avoid negative lengths when the high bit is set.
+                        payloadLen = (lengthAndType >>> 8) & 0x00ffffff;
                         if (payloadLen > maxFramePayloadSize) {
                             throw new H2ConnectionException(H2Error.FRAME_SIZE_ERROR, "Frame size exceeds maximum");
                         }
                         type = lengthAndType & 0xff;
-                        flags = buffer.get();
-                        streamId = Math.abs(buffer.getInt());
+                        // Flags are an octet on the wire; keep them in the 0..255 range.
+                        flags = buffer.get() & 0xff;
+                        // Stream Identifier is 31-bit; mask out the reserved (MSB) bit (RFC 9113, Section 4.1).
+                        streamId = buffer.getInt() & 0x7fffffff;
                         state = State.PAYLOAD_EXPECTED;
                     } else {
                         break;
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInputBuffer.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInputBuffer.java
new file mode 100644
index 000000000..2fe43f836
--- /dev/null
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/io/TestFrameInputBuffer.java
@@ -0,0 +1,54 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.http2.impl.io;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.ByteArrayInputStream;
+
+import org.apache.hc.core5.http2.frame.RawFrame;
+import org.junit.jupiter.api.Test;
+
+class TestFrameInputBuffer {
+
+
+    @Test
+    void reservedBitInStreamIdIsIgnored() throws Exception {
+        final byte[] frame = new byte[]{
+                0x00, 0x00, 0x00,   // length = 0
+                0x00,               // type = DATA
+                0x00,               // flags
+                (byte) 0x8A, 0x12, 0x34, 0x56 // streamId with reserved bit set
+        };
+
+        final FrameInputBuffer inBuf = new FrameInputBuffer(16384);
+        final RawFrame rawFrame = inBuf.read(new ByteArrayInputStream(frame));
+
+        assertEquals(0x0A123456, rawFrame.getStreamId());
+    }
+
+}
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java
index d832608f8..5590ededc 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java
@@ -1574,5 +1574,36 @@ void testHpackExceptionInHeadersMappedToConnectionCompressionError() throws Exce
                 .failed(ArgumentMatchers.any(Exception.class));
     }
 
+
+    @Test
+    void testInputSettingsAckWithNonEmptyPayloadRejected() throws Exception {
+        final AbstractH2StreamMultiplexer mux = new H2StreamMultiplexerImpl(
+                protocolIOSession,
+                FRAME_FACTORY,
+                StreamIdGenerator.ODD,
+                httpProcessor,
+                CharCodingConfig.DEFAULT,
+                H2Config.custom().build(),
+                h2StreamListener,
+                () -> streamHandler);
+
+        // SETTINGS (0x04), ACK (0x01), streamId=0, length=6 (INVALID for ACK)
+        // payload is one dummy setting (content irrelevant)
+        final byte[] bytes = new byte[] {
+                0x00, 0x00, 0x06,       // length = 6
+                0x04,                   // type = SETTINGS
+                0x01,                   // flags = ACK
+                0x00, 0x00, 0x00, 0x00, // stream id = 0
+                0x00, 0x01,             // setting id
+                0x00, 0x00, 0x00, 0x01  // setting value
+        };
+
+        final H2ConnectionException ex = Assertions.assertThrows(
+                H2ConnectionException.class,
+                () -> mux.onInput(ByteBuffer.wrap(bytes)));
+
+        Assertions.assertEquals(H2Error.FRAME_SIZE_ERROR, H2Error.getByCode(ex.getCode()));
+    }
+
 }
 
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInputBuffer.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInputBuffer.java
new file mode 100644
index 000000000..88f07e240
--- /dev/null
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestFrameInputBuffer.java
@@ -0,0 +1,109 @@
+/*
+ * ====================================================================
+ * 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+package org.apache.hc.core5.http2.impl.nio;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.ByteArrayInputStream;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+
+import org.apache.hc.core5.http2.H2ConnectionException;
+import org.apache.hc.core5.http2.H2Error;
+import org.apache.hc.core5.http2.frame.RawFrame;
+import org.junit.jupiter.api.Test;
+
+class TestFrameInputBuffer {
+
+    @Test
+    void payloadLengthWithHighBitMustTriggerFrameSizeError() throws Exception {
+        // length = 0x800000 (top bit set in the 24-bit length)
+        // type = 0x00 (DATA), flags = 0x00, streamId = 0
+        //
+        // With the OLD code:
+        //   payloadLen = (lengthAndType >> 8) becomes NEGATIVE -> bypasses "payloadLen > max"
+        //   then PAYLOAD_EXPECTED sees remaining >= negative -> attempts wrap with negative length -> runtime failure
+        //
+        // With the FIX:
+        //   payloadLen = (lengthAndType >>> 8) & 0x00ffffff == 0x800000 -> throws FRAME_SIZE_ERROR
+
+        final byte[] frame = new byte[]{
+                (byte) 0x80, 0x00, 0x00, 0x00, // 24-bit length (0x800000) + type (0x00)
+                0x00,                          // flags
+                0x00, 0x00, 0x00, 0x00         // streamId
+                // no payload
+        };
+
+        final FrameInputBuffer inBuf = new FrameInputBuffer(16 * 1024);
+        final ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(frame));
+
+        final H2ConnectionException ex = assertThrows(H2ConnectionException.class, () -> inBuf.read(ch));
+        assertEquals(H2Error.FRAME_SIZE_ERROR.getCode(), ex.getCode());
+    }
+
+    @Test
+    void flagsMustBeTreatedAsUnsignedByte() throws Exception {
+        // flags on the wire are 1 byte (0..255). If you read into a signed byte and store as int,
+        // values >= 0x80 become negative without & 0xff.
+        final byte[] frame = new byte[]{
+                0x00, 0x00, 0x00, 0x00, // length=0 + type=0
+                (byte) 0x80,            // flags = 0x80
+                0x00, 0x00, 0x00, 0x00  // streamId = 0
+        };
+
+        final FrameInputBuffer inBuf = new FrameInputBuffer(16 * 1024);
+        final ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(frame));
+
+        final RawFrame rawFrame = inBuf.read(ch);
+        assertNotNull(rawFrame);
+        assertEquals(0x80, rawFrame.getFlags());
+    }
+
+    @Test
+    void streamIdReservedBitMustBeIgnored() throws Exception {
+        // On the wire stream-id is 32 bits; top bit is reserved and MUST be ignored.
+        // streamId = 0x80000001 should be treated as 0x00000001.
+        //
+        // OLD code: Math.abs(0x80000001 as int) = 2147483647 (wrong)
+        // FIX: streamId = getInt() & 0x7fffffff = 1
+
+        final byte[] frame = new byte[]{
+                0x00, 0x00, 0x00, 0x00, // length=0 + type=0
+                0x00,                   // flags
+                (byte) 0x80, 0x00, 0x00, 0x01 // streamId = 0x80000001
+        };
+
+        final FrameInputBuffer inBuf = new FrameInputBuffer(16 * 1024);
+        final ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(frame));
+
+        final RawFrame rawFrame = inBuf.read(ch);
+        assertNotNull(rawFrame);
+        assertEquals(1, rawFrame.getStreamId());
+    }
+}