Content Security Policy (CSP)
An added layer of security that helps to detect and mitigate certain types of attacks, including XSS and data injection attacks.
Detailed Explanation
CSP is an HTTP header that allows site operators to restrict the resources (such as JavaScript, CSS, Images) that a browser is allowed to load for a given page. For example, a CSP can tell the browser to only execute scripts from the site's own origin, effectively blocking many third-party XSS attacks. It is one of the most powerful modern web security tools.
Quick Summary
Content Security Policy is a browser-enforced allowlist for what your page can load and execute. It turns a successful XSS injection from "attacker runs arbitrary JS" into "browser blocks the script."
Key Takeaways
- Delivered via the `Content-Security-Policy` HTTP header (or a `<meta>` tag with limited directives).
- Common directives: `script-src`, `style-src`, `img-src`, `connect-src`, `frame-ancestors`, `default-src`.
- Use nonces or hashes for inline scripts; avoid `'unsafe-inline'` and `'unsafe-eval'`, they neuter most of CSP's value.
- Roll out with `Content-Security-Policy-Report-Only` first to collect violations without breaking the site.
- `frame-ancestors` replaces the older `X-Frame-Options` header for clickjacking protection.
When to use it
- Blunting XSS attacks: even if injection succeeds, the malicious script can't load or run.
- Preventing exfiltration via `connect-src`, stolen data can't be POSTed to an attacker domain.
- Stopping clickjacking with `frame-ancestors 'self'` or `'none'`.
- Auditing third-party script sprawl by setting a strict policy and reviewing the violation reports.
Common Mistakes
- Including `'unsafe-inline'` in `script-src` to make legacy code work, defeats the protection entirely.
- Using a wildcard (`*`) or broad CDN allowlist that an attacker can host content on.
- Forgetting `default-src`, directives you didn't specify fall back to the browser default (often permissive).
- Shipping a strict policy without report-only testing, then breaking production analytics or fonts.
Content Security Policy (CSP), Frequently Asked
Nonce or hash for inline scripts?
Nonces are easier in server-rendered apps (regenerate per request, inject into the header and the `<script nonce=...>` attribute). Hashes are better when the inline content is fully static. Both let you avoid `'unsafe-inline'`.
Does CSP replace input sanitization?
No. CSP is defense-in-depth, it mitigates a successful XSS but doesn't prevent the injection in the first place. Output encoding and framework-provided escaping are still the primary defense.