HTTP Request Smuggling and Cache Poisoning
A request to a large site rarely reaches the application directly. It passes a CDN, a load balancer, perhaps a WAF and a reverse proxy, each of which parses HTTP, decides where the request ends, and may cache the response. Two of the most powerful web attacks live in the gaps between those layers. Request smuggling exploits two parsers that disagree about where one request ends and the next begins, so an attacker can hide a request inside another and have it prepended to a different user's request. Web cache poisoning exploits a cache that stores a response under a key that ignores some input the response depends on, so one attacker request changes what every later visitor receives. Both are taught here as concepts with toy parsers and a toy cache in Python: no sockets and no proxies, because the point is the disagreement, and the fixes are configuration and architecture.
Definitions
- Message length in HTTP/1.1 (RFC 9112 §6.1 and §6.3): a body's length comes from
Transfer-Encoding: chunked(chunks ofhex-size CRLF data CRLF, ending with0 CRLF CRLF) or fromContent-Length. If both are present,Transfer-Encodingwins and the message should be treated as an error or theContent-Lengthremoved; a server must not just pick one silently. - CL.TE / TE.CL desync: the front end uses
Content-Lengthand the back endTransfer-Encoding(or the reverse). Bytes one considers part of the body, the other considers the start of the next request on the same reused connection. - H2 downgrade smuggling: a front end speaking HTTP/2 to clients translates to HTTP/1.1 for the back end, and headers that are harmless in HTTP/2 (a
Content-Lengththat contradicts the frames, CRLF in a header value) become smuggling in the translation. - Cache key: the parts of a request a cache uses to decide "same response" (usually method, host, path, query). Unkeyed input: anything else the response depends on, such as
X-Forwarded-Host, other headers, or cookies.
Smuggling: two parsers, one byte stream
The attacker sends one request with both headers. The two functions below are deliberately naive parsers: the front end trusts Content-Length, the back end trusts Transfer-Encoding. Both read the same bytes from a reused connection, and a normal user's request follows right behind.
attack = (b"POST /search HTTP/1.1\r\nHost: shop.lab.test\r\n"
b"Content-Length: 47\r\nTransfer-Encoding: chunked\r\n\r\n"
b"0\r\n\r\n"
b"GET /admin/delete?user=7 HTTP/1.1\r\nX-Pad: ") # the smuggled prefix
victim = b"GET /account HTTP/1.1\r\nHost: shop.lab.test\r\nCookie: sid=victim-session\r\n\r\n"
def split_head(stream):
head, _, rest = stream.partition(b"\r\n\r\n")
lines = head.split(b"\r\n")
headers = {k.strip().lower(): v.strip() for k, v in (l.split(b":", 1) for l in lines[1:])}
return lines[0], headers, rest
def front_end(stream): # uses Content-Length
line, h, rest = split_head(stream)
n = int(h[b"content-length"])
return line, rest[:n], rest[n:]
def back_end(stream): # uses Transfer-Encoding: chunked
line, h, rest = split_head(stream)
body = b""
while True:
size_line, _, rest = rest.partition(b"\r\n")
size = int(size_line, 16)
if size == 0:
rest = rest[2:] # the CRLF after the last chunk
return line, body, rest
body, rest = body + rest[:size], rest[size + 2:]
print("attack body length:", len(attack.split(b"\r\n\r\n", 1)[1]), "bytes; Content-Length says 47")
line, body, leftover = front_end(attack)
print("front end forwards ONE request:", line.decode(), "| body bytes:", len(body), "| leftover:", leftover)
line, body, leftover = back_end(attack)
print("back end sees request 1 end after the 0-chunk:", line.decode())
print("back end treats the rest as the start of the next request:", leftover.decode().split("\r\n")[0])
next_request = (leftover + victim).decode()
print("the victim's request, as the back end now reads it:")
for l in next_request.split("\r\n")[:4]:
print(" ", l)attack body length: 47 bytes; Content-Length says 47
front end forwards ONE request: POST /search HTTP/1.1 | body bytes: 47 | leftover: b''
back end sees request 1 end after the 0-chunk: POST /search HTTP/1.1
back end treats the rest as the start of the next request: GET /admin/delete?user=7 HTTP/1.1
the victim's request, as the back end now reads it:
GET /admin/delete?user=7 HTTP/1.1
X-Pad: GET /account HTTP/1.1
Host: shop.lab.test
Cookie: sid=victim-session
The front end saw one well-formed POST with a 47-byte body and nothing left over, so its WAF rules and access logs record a harmless search. The back end ended that request at the 0 chunk and kept the remaining bytes as the beginning of the next request on the connection. When the victim's request arrives on that connection, the two are glued together: the back end reads GET /admin/delete?user=7, with the victim's real request line swallowed into the junk X-Pad header and the victim's cookie attached. The attacker made a victim's session perform an action, or, with other prefixes, captured the victim's request or poisoned a cache. Real attacks also have to deal with connection reuse and timing, which is why testers confirm desyncs with timing and differential-response probes rather than with damaging payloads.
Cache poisoning: an unkeyed header
The toy application builds an absolute script URL from X-Forwarded-Host (common behind proxies, "so links work"). The cache keys only on host and path. One request with an attacker's header poisons the cached page for everyone.
cache = {}
def app(path, headers):
host = headers.get("X-Forwarded-Host", "shop.lab.test") # unkeyed input reflected
return f'<script src="https://{host}/static/app.js"></script>'
def cdn(path, headers, key_headers=()):
key = ("shop.lab.test", path) + tuple(headers.get(h) for h in key_headers)
if key not in cache:
cache[key] = app(path, headers)
return "MISS", cache[key]
return "HIT ", cache[key]
print("== cache keyed on host + path only")
print("attacker:", *cdn("/", {"X-Forwarded-Host": "evil.example"}))
print("victim 1:", *cdn("/", {}))
print("victim 2:", *cdn("/", {}))
cache.clear()
print("== fixed: the header is part of the key (or, better, never reflected)")
print("attacker:", *cdn("/", {"X-Forwarded-Host": "evil.example"}, key_headers=("X-Forwarded-Host",)))
print("victim 1:", *cdn("/", {}, key_headers=("X-Forwarded-Host",)))== cache keyed on host + path only
attacker: MISS <script src="https://evil.example/static/app.js"></script>
victim 1: HIT <script src="https://evil.example/static/app.js"></script>
victim 2: HIT <script src="https://evil.example/static/app.js"></script>
== fixed: the header is part of the key (or, better, never reflected)
attacker: MISS <script src="https://evil.example/static/app.js"></script>
victim 1: MISS <script src="https://shop.lab.test/static/app.js"></script>
Every visitor after the attacker loads JavaScript from the attacker's host, which is XSS delivered by your own CDN, for as long as the cache entry lives. Keying on the header fixes the cache, but the better fix is in the application: don't build URLs from request headers at all (the HTTP lesson made the same point about Host).
How they are detected
- Smuggling, in an authorised test: tools such as Burp's HTTP Request Smuggler extension send timing probes (a request that makes one parser wait for bytes the other considers sent) and differential probes, and report suspected CL.TE, TE.CL, TE.TE (obfuscated
Transfer-Encodingheaders such asTransfer-Encoding : chunkedorxchunked) and H2 downgrade issues. Run them only with permission: a successful probe can affect other users' requests. - Smuggling, defensively: front-end and back-end logs that disagree about request counts per connection; back-end requests with strange first lines (
0GET, junk prefixes); 400 errors on the back end with no matching front-end request. - Cache poisoning: tools like Param Miner guess unkeyed headers and parameters; send a candidate header with a unique value plus a cache buster, then check whether the value appears in a response fetched without the header.
- Monitoring: cached responses containing unexpected host names; sudden changes in a cached page's hash.
How they are prevented
- Smuggling: use HTTP/2 end to end (or at least between proxy and back end) where possible; configure front ends to normalise or reject ambiguous requests (both
Content-LengthandTransfer-Encoding, duplicated or malformed length headers, invalid chunk sizes, CR or LF inside header values); keep proxies and servers patched (desync bugs are fixed in their parsers regularly); don't reuse back-end connections across clients where the risk is high. - Cache poisoning: cache only what is meant to be shared (
Cache-Control: privateorno-storeon personalised responses), make the cache key include every input the response depends on (Vary), strip or ignore forwarding headers from clients at the edge, and never reflect unvalidated headers into responses.
Pitfalls
- Testing a single layer: smuggling is invisible when the app is tested without its real proxy chain; test the production-like stack.
- WAF rules as a fix: the WAF is often the layer being bypassed.
- Web cache deception, the mirror image: tricking a cache into storing a victim's private page under a static-looking URL (
/account/profile.css); fix by caching based on response headers, not file extensions.
Practice
1. In the smuggling toy, which header would a hardened front end refuse, and why does that stop the attack?
A request carrying both Content-Length and Transfer-Encoding. RFC 9112 says such a message must be treated carefully (TE wins, CL removed, or rejected). If the front end rejects it or forwards it with only Transfer-Encoding, both layers agree on where the request ends and nothing is left over.
2. A page's response includes the value of the X-Original-URL header and is cached for 10 minutes keyed on path. What do you test?
Send the page with X-Original-URL: /lab-marker-123 and a cache-buster parameter, then request the same URL (with the same buster) without the header; if the marker appears, the header is unkeyed and reflected: cache poisoning. Report it with the cache key and lifetime.
Test yourself
What makes request smuggling possible?
- Weak TLS
- Two HTTP parsers in a chain disagree about where a request ends
- Missing cookies
- SQL injection
In the toy, whose cookie did the smuggled request end up with?
- The attacker's
- The victim's, because the victim's request was appended to the smuggled prefix
- No cookie
- The proxy's
What is an unkeyed input in cache poisoning?
- A request without a key
- Input the response depends on but the cache key ignores, such as a reflected header
- An encrypted header
- A cookie with HttpOnly
Which fix addresses cache poisoning at its root in the toy app?
- A longer cache lifetime
- Not building URLs from request headers like X-Forwarded-Host
- More CDN nodes
- HTTP/1.0