Content Security Policy (CSP)
Master directive hierarchies, cryptographic nonces, hashes, and reporting.
Content Security Policy (CSP) is an HTTP response header that restricts the resources (scripts, styles, images, iframes, fonts) that the browser is allowed to load and execute for a given page, providing a powerful secondary defense against XSS and data exfiltration.
Even if an attacker finds an XSS injection flaw, a strict CSP will prevent the browser from executing inline `<script>` tags, block `eval()`, and prohibit `fetch()` calls to unauthorized attacker domains.
Deploy a strict nonce-based or hash-based CSP. Start with `Content-Security-Policy-Report-Only` to detect breaking changes before switching to enforcement mode.
Technical Deep Dive
Core CSP Directives Hierarchy
- default-srcFallback policy for all fetch directives if not explicitly specified.
- script-srcDefines valid sources for JavaScript. Use nonces ('nonce-RANDOM') or hashes instead of 'unsafe-inline'.
- connect-srcRestricts targets for fetch(), XMLHttpRequest, WebSocket, and EventSource.
- img-src & font-srcControls origins from which images and web fonts can be retrieved.
- frame-ancestorsReplaces X-Frame-Options to restrict which sites can embed your page in an iframe.
The Danger of unsafe-inline and unsafe-eval
Including `unsafe-inline` or `unsafe-eval` neuters CSP against XSS attacks. Modern best practice utilizes per-request cryptographically secure random nonces (`nonce-abc123xyz`) generated on the server.
Interactive Mental Model Simulation
Live VisualizerPolicy Directives
Allow scripts from my own domain
Allow scripts from trusted partner
Allow inline <script> tags (Dangerous!)
Browser Resource Loader
Code Implementation & Patching
// Ineffective / Overly Permissive CSP Header Content-Security-Policy: default-src * 'unsafe-inline' 'unsafe-eval'; // Defeats the purpose of CSP: any injected script or eval() will execute freely!
// Production-Grade Strict Nonce-Based CSP Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-rAnd0m123==' 'strict-dynamic'; style-src 'self' 'nonce-rAnd0m123=='; img-src 'self' data: https://images.unsplash.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; report-uri /api/csp-violations;
The server generates a unique cryptographic nonce per HTTP request. Only script tags containing matching nonce="rAnd0m123==" can run. Injected attacker scripts lack the nonce and are blocked.
Test Your Knowledge on Content Security Policy (CSP)
Challenge yourself with realistic scenario questions in the Web Security Arena.