Web Security 14 🛡️ Content Security Policy (CSP) — Writing strict script-src policies with nonces, hashes, and strict-dynamic
Content Security Policy (CSP) is the ultimate defense-in-depth mechanism for modern web applications. It serves as an instruction manual for the browser, defining exactly which domains, scripts, and styles are permitted to execute on your pages. In the era of Cross-Site Scripting (XSS), where a single malicious script injection can lead to complete session hijacking, CSP provides a declarative layer of protection that restricts the browser’s capabilities, even if an attacker successfully injects code into your HTML.
Writing a CSP is deceptively difficult. An overly permissive policy provides no security, while an overly restrictive one breaks the application. This chapter moves beyond basic “allowlisting” (which is now considered an anti-pattern) and focuses on “Strict CSP” design. We will master the use of nonces (number used once), cryptographic hashes, and the strict-dynamic directive to create a future-proof, robust defense that effectively mitigates XSS risks without becoming a maintenance burden.
Key point: Modern CSP is not about listing every trusted domain (which is impossible to maintain); it is about creating a “Strict CSP” that requires every script to be cryptographically verified via a nonce or hash, making injected scripts impossible to execute.
Why exists
The XSS paradox.
XSS happens because the browser trusts everything the server sends as “code.” CSP forces the browser to question that trust by requiring explicit authorization for every script, style, and object that attempts to load or execute.
The failure of allowlisting.
Early CSP design (e.g., script-src https://trusted.com) failed because attackers could easily bypass it by finding “gadgets”—legitimate scripts on that domain that could be exploited to load malicious code. Strict CSP moves away from domain allowlisting toward cryptographic verification.
The need for dynamic applications.
Modern apps are highly dynamic, loading scripts from various CDNs and local bundles. Managing a static allowlist is a DevOps nightmare. Nonces and strict-dynamic allow for a policy that adapts to the application’s runtime structure, authorizing only what you explicitly trust on a per-request basis.
The mitigation of “Blind” injection.
Attackers often use blind XSS, where they inject scripts that call home to their servers. A strict CSP disables connect-src and script-src for any unauthorized origin, preventing the injected script from reaching out to the attacker’s server to exfiltrate data.
The defense-in-depth requirement.
CSP does not fix XSS (proper sanitization does), but it ensures that if sanitization fails—and it eventually will—the attacker cannot turn that injection into a useful exploit. It is the seatbelt of web security.
a. The Strict CSP Pattern: Nonces and Hashes
A “Strict CSP” relies on nonces—random strings generated server-side for each request. The browser only executes <script> tags that carry the matching nonce. This makes static allowlisting obsolete, as an attacker cannot guess the nonce for the current request.
Content-Security-Policy: script-src 'nonce-randomString123' 'strict-dynamic'; object-src 'none'; base-uri 'none';
When you deploy this, your scripts must include the nonce:
<script nonce="randomString123">console.log("Trusted");</script>
If an attacker injects <script>alert(1)</script>, the browser rejects it because it lacks the valid nonce.
b. The strict-dynamic Directive
strict-dynamic is the magic directive that solves the “trusted chain” problem. If a script is loaded via a nonce, strict-dynamic tells the browser to trust any scripts that the initial script then loads. This allows your primary entry point (your bundle) to load other scripts dynamically without you needing to nonce every single one of them.
script-src 'nonce-randomString123' 'strict-dynamic' 'unsafe-inline' https:;
Note: Browsers that support strict-dynamic ignore the unsafe-inline and https: fallback, ensuring compatibility while maintaining high security.
c. Handling External Dependencies and Styles
What if you have to use a legacy script that you can’t easily nonce? You can use cryptographic hashes (sha256-...). You calculate the hash of the script content at build time, and add that hash to your policy. The browser checks the hash of the script tag against your policy and executes it only if they match.
script-src 'sha256-hashOfMyScriptContent';
For styles, use style-src 'unsafe-inline' cautiously, or better yet, nonce your <style> tags. Avoid using style-src allowlists, as they are prone to CSS-injection attacks that can exfiltrate data.
Complete Example Session
// ============================================
// PART 1: THE STRICT HEADER
// ============================================
// Header generated server-side per request
Content-Security-Policy: default-src 'self'; script-src 'nonce-ed741a' 'strict-dynamic'; object-src 'none'; base-uri 'none';
// ============================================
// PART 2: IMPLEMENTATION IN HTML
// ============================================
// Script in template
<script nonce="ed741a">
// This executes
initApp();
</script>
// ============================================
// PART 3: DYNAMIC LOADING
// ============================================
// This works because of 'strict-dynamic'
<script nonce="ed741a">
// app.js creates a script tag; browser trusts it
const s = document.createElement('script');
s.src = 'module.js';
document.body.appendChild(s);
</script>
// ============================================
// PART 4: REJECTED INJECTION
// ============================================
// This fails (no nonce)
<script>alert('hacked')</script>
The session shows the server-side generation of the nonce, the injection of the nonce into the template, the trusted dynamic loading, and the browser-level rejection of an un-nonced script tag.
Quick Reference
Directives Explained
| Directive | Purpose |
|---|---|
script-src | Where scripts come from |
object-src | Plugins (Flash, etc.) – set to 'none' |
base-uri | Prevents <base> tag injection – set to 'none' |
connect-src | Where XHR/Fetch can talk to |
Strict CSP Values
| Value | Role |
|---|---|
'nonce-...' | Cryptographic token for one request |
'sha256-...' | Static content verification |
'strict-dynamic' | Trusts scripts loaded by trusted scripts |
'self' | Allow from same origin |
Best Practices
✅ Do This:
// Generate a new nonce for EVERY request
const nonce = crypto.randomUUID(); // ✅
// Set 'object-src' to none to block Flash/Plugins
res.setHeader('Content-Security-Policy', "...object-src 'none'"); // ✅
// Use strict-dynamic for modern apps
// (Allows nested bundles) // ✅
// Report violations
res.setHeader('Content-Security-Policy-Report-Only', '...'); // ✅
❌ Don’t Do This:
// Use 'unsafe-inline' without nonces
// (Bypasses security for injected tags) // ❌
// Use 'unsafe-eval'
// (Enables RCE via eval()) // ❌
// Use domain allowlists (e.g., *.google.com)
// (Vulnerable to open redirects) // ❌
// Forget base-uri 'none'
// (Allows hijacking relative URLs) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Broken UI | Over-restrictive policy | Check console for CSP errors |
| No Reports | Missing report-to endpoint | Add a CSP reporting URL |
| XSS Bypass | Relying on unsafe-inline | Migrate to Nonces |
| IE Incompatibility | CSP not supported | Use X-Content-Security-Policy (Legacy) |
Real-World Examples
1. Server-Side Nonce Generation
const nonce = crypto.randomBytes(16).toString('base64');
res.setHeader('Content-Security-Policy', `script-src 'nonce-${nonce}' ...`);
2. Express CSP Middleware
app.use((req, res, next) => {
res.locals.nonce = crypto.randomUUID();
res.setHeader('Content-Security-Policy', `script-src 'nonce-${res.locals.nonce}'`);
next();
});
3. Reporting Endpoint
Content-Security-Policy: ...; report-uri /csp-violation-report
4. Disabling Plugins
object-src 'none';
5. Strict Base URI
base-uri 'none';
6. Dynamic Script Trust
script-src 'nonce-...' 'strict-dynamic';
7. Hash-based Script
script-src 'sha256-...' ;
8. Image Src Restriction
img-src 'self' https://trusted-cdn.com;
9. Connect Src (XHR)
connect-src 'self' https://api.my-app.com;
10. Frame Ancestors
frame-ancestors 'none'; // Clickjacking protection
Visual
The Nonce Flow
┌────────────────────────────────────────────────────────┐
│ SERVER: Generate Nonce (e.g., '123') │
│ │ │
│ HEADER: CSP: script-src 'nonce-123' │
│ │ │
│ HTML: <script nonce="123">...</script> │
│ │ │
│ BROWSER: Match? YES ──► EXECUTE │
│ Match? NO ──► BLOCK │
└────────────────────────────────────────────────────────┘
The strict-dynamic Chain
┌────────────────────────────────────────────────────────┐
│ NONCED SCRIPT (Trusted) │
│ │ │
│ Loads Bundle A ──► Trusted (via strict-dynamic) │
│ │ │
│ Loads Bundle B ──► Trusted (via strict-dynamic) │
│ │
│ [Dynamic loading allowed without re-noncing] │
└────────────────────────────────────────────────────────┘
The XSS Attack Block
┌────────────────────────────────────────────────────────┐
│ INJECTED SCRIPT (No Nonce) │
│ │ │
│ BROWSER: Checks Nonce ──► Fails │
│ │ │
│ BLOCKS EXECUTION │
└────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Policy Strategy | Strict CSP (Nonce-based) |
| Nonce | Random per request |
strict-dynamic | Enables nested script loading |
| Security | Block unsafe-inline, unsafe-eval |
| Plugins | Block object-src |
Key takeaways:
- Stop using allowlists. Do not list domains in your
script-src. Use nonces for primary scripts andstrict-dynamicto allow them to load dependencies. - Nonce every request. Generate a fresh, cryptographically secure random string for every page load and inject it into the CSP header and
<script>tags. - Lock down plugins. Always set
object-src 'none'andbase-uri 'none'to block plugin and base-tag injection attacks. - Enable reporting. Always configure a CSP report endpoint so you can see where your policy is breaking before you enforce it fully.
- Defense in depth. CSP is not a silver bullet; it is an enforcement mechanism. Even with a CSP, you must continue to sanitize user input to prevent XSS.
Remember: A Strict CSP is the most effective way to render XSS attacks useless. By shifting the burden of trust from the developer (who might make a mistake in an allowlist) to the browser (which enforces the crypto check), you create a security posture that is resilient, scalable, and impossible for an attacker to bypass without guessing your per-request nonce.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!