Content-Security-Policy (CSP) is an HTTP header that allows the server to tell the browser which resources it can load and from which origins. It is the most effective defense against Cross-Site Scripting (XSS) attacks, which rank first on the OWASP Top 10 list of most common web vulnerabilities. Without CSP, any malicious script injected into the page can execute with the same privileges as legitimate code.
What Damage Can XSS Cause Without CSP?
If an attacker manages to inject malicious JavaScript into your page (through an unsanitized form, a comment, a URL parameter or a compromised third-party script), they can: steal session cookies and impersonate the user, redirect visitors to phishing sites, log keystrokes and capture passwords, extract payment form data, or run cryptocurrency miners in the visitor's browser. CSP blocks unauthorized resources from loading before they can execute.
Main CSP Directives
- default-src: default source for all resource types without a specific directive.
- script-src: origins allowed for JavaScript. The most important directive — restricts where JS can execute from.
- style-src: origins allowed for CSS stylesheets.
- img-src: origins allowed for images.
- font-src: origins allowed for web fonts (Google Fonts, FontAwesome, etc.).
- connect-src: origins for fetch, XMLHttpRequest, WebSocket and EventSource calls.
- frame-ancestors: controls who can embed the page in an iframe (replaces X-Frame-Options).
- form-action: restricts HTML form destinations — important to prevent post-XSS phishing.
Example of a Working CSP Policy
Implementation in Nginx
Implementation in Apache
Strategy: Start with Report-Only
To implement CSP without risking breaking anything in production, first use the Content-Security-Policy-Report-Only header. This variant reports violations in the browser console (and to an endpoint if you configure report-uri) without blocking anything. Once you have identified and authorized all legitimate origins, switch to the definitive header.
Mistakes to Avoid
- 'unsafe-eval' in script-src: allows eval() and Function constructor — nullifies XSS protection based on dynamic injection.
- 'unsafe-inline' in script-src: allows inline scripts (<script>...</script>) — the most common XSS attack vector.
- Forgetting third-party origins used in production: Google Analytics, PayPal, CDN fonts. Check the browser console to identify them.
- Not including frame-ancestors: leaves the site exposed to clickjacking where it is embedded in an invisible iframe.
- Skipping Report-Only mode: implementing directly can break third-party functionality in production.
DomainScored detects whether Content-Security-Policy is missing, if it uses dangerous directives like 'unsafe-eval', or if frame-ancestors protection is absent. The HTTP Headers module shows CSP status alongside the other 5 relevant security headers.