Content Security Policy (CSP)
Problem
Any injected script can execute freely, stealing user data or modifying the page. Third-party dependencies or compromised CDNs can load malicious code without detection. Inline scripts from XSS attacks bypass all other security measures.
Solution
Set HTTP headers that restrict which resources the browser can load, preventing execution of unauthorized scripts and styles. This mitigates XSS attacks by establishing a whitelist of trusted content sources.
Example
This example demonstrates a Content Security Policy header that restricts resource loading to prevent unauthorized script execution and XSS attacks.
Content-Security-Policy:
# Default policy: only allow resources from same origin
default-src 'self';
# Scripts: allow from same origin and specific trusted CDN only
script-src 'self' https://trusted-cdn.com;
# Styles: allow from same origin and inline styles (use with caution)
style-src 'self' 'unsafe-inline';
# Images: allow from same origin, data URIs, and any HTTPS source
img-src 'self' data: https:;
Benefits
- Significantly reduces risk of XSS attacks by blocking unauthorized scripts.
- Prevents malicious code injection even if other defenses fail.
- Provides defense-in-depth security layer beyond input sanitization.
- Can detect and block attacks by reporting violations.
- Works at the browser level independent of application code.
Tradeoffs
- Can break applications that rely on inline scripts or eval.
- Requires careful configuration to avoid blocking legitimate resources.
- Difficult to implement incrementally without breaking existing functionality.
- Browser support varies for newer
CSP
features. - May conflict with third-party scripts and analytics tools that expect inline code.