Content Security Policy (CSP)

Medium•

CSP is a powerful defense against XSS attacks. Properly configured CSP can prevent most XSS vulnerabilities by controlling resource loading.

Quick Navigation: CSP Implementation • Best Practices

Quick Decision Guide

Quick Setup Guide:

Basic CSP Header: Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'

Express.js: app.use((req, res, next) => { res.setHeader('Content-Security-Policy', "default-src 'self'"); next(); })

Report-Only Mode: Test without blocking: Content-Security-Policy-Report-Only - violations logged but not blocked.

Common Issues: - Inline scripts blocked → Use nonces or move to external files - Third-party scripts blocked → Add domain: script-src 'self' https://cdn.example.com - Styles not working → Add 'unsafe-inline' to style-src (less secure but often needed)

Best Practice: Start strict (default-src 'self'), then relax specific directives as needed. Use report-only mode first to identify violations.

Security: Essential header alongside HTTPS. Prevents XSS by blocking unauthorized script execution.

CSP Implementation

Setting CSP Headers

HTTP Header:

Content-Security-Policy: default-src 'self'; script-src 'self'

Meta Tag (HTML):

<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; script-src 'self'">

Common Directives

'self': Same origin only

'unsafe-inline': Allow inline scripts/styles (not recommended)

'unsafe-eval': Allow eval() (not recommended)

'none': Block all sources

https://example.com: Specific domain allowed

Report-Only Mode

Use Content-Security-Policy-Report-Only to test CSP without blocking:

•Monitor violations
•Adjust policy gradually
•Switch to enforce mode when ready

Best Practices

Start Strict, Relax Gradually

Initial Policy:

•default-src 'self'
•Add specific sources as needed
•Avoid 'unsafe-inline' and 'unsafe-eval'

Use Nonces for Inline Scripts

Instead of 'unsafe-inline':

•Generate random nonce per request
•Include nonce in script tag
•Add nonce to CSP header

Example:

<!-- Server generates nonce -->
<script nonce="[NONCE_VALUE]">
  // Inline script
</script>

<!-- CSP header -->
Content-Security-Policy: script-src 'nonce-[NONCE_VALUE]'

Monitor CSP Violations

Set up reporting:

•Use report-uri or report-to directive
•Monitor violation reports
•Adjust policy based on real usage

Key Takeaways

1CSP prevents XSS by controlling resource loading
2Start with strict policy, relax as needed
3Avoid 'unsafe-inline' - use nonces instead
4Use report-only mode for testing
5Monitor CSP violations in production
6CSP complements other security measures