Ultimate Content Security Policy (CSP) Headers Cheatsheet: A Complete Reference Guide

Introduction: What Are CSP Headers and Why They Matter

Content Security Policy (CSP) is a security standard that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks. CSP headers allow website administrators to control which resources can be loaded and executed on their pages, creating a crucial defense layer against the most common web vulnerabilities.

Core Concepts of Content Security Policy

CSP Fundamentals

  • Policy Delivery: CSP is primarily delivered via HTTP headers or meta tags
  • Directives: Rules specifying allowed sources for different resource types
  • Source Lists: Origins from which content can be loaded
  • Violation Reporting: Mechanism to monitor policy violations
  • Levels: CSP has evolved through multiple levels (CSP 1.0, 2.0, 3.0) with increasing capabilities

CSP Implementation Methods

MethodSyntaxAdvantagesDisadvantages
HTTP HeaderContent-Security-Policy: directive source-listBrowser processes before page load, more secureRequires server-side configuration
Meta Tag<meta http-equiv="Content-Security-Policy" content="directive source-list">Can implement without server accessProcessed after HTML parsing begins
Report-Only ModeContent-Security-Policy-Report-Only: directive source-listTests policy without breaking functionalityDoesn’t actually block violations

Step-by-Step CSP Implementation Process

  1. Audit Your Resources: Identify all content sources used by your website
  2. Create a Baseline Policy: Start with a simple policy covering crucial directives
  3. Test in Report-Only Mode: Deploy using Content-Security-Policy-Report-Only
  4. Analyze Violation Reports: Review reports and adjust policy accordingly
  5. Gradually Tighten Policy: Incrementally restrict sources and add directives
  6. Implement Final Policy: Deploy the full CSP header
  7. Continuous Monitoring: Maintain violation reporting to catch new issues

Key CSP Directives by Category

Script Control Directives

  • script-src: Controls allowed sources for JavaScript
  • script-src-elem: Controls inline scripts and script elements (CSP3)
  • script-src-attr: Controls event handlers and JavaScript in attributes (CSP3)

Content Control Directives

  • default-src: Fallback for other fetch directives
  • style-src: Controls CSS sources
  • img-src: Controls image sources
  • font-src: Controls font loading sources
  • media-src: Controls audio and video sources
  • connect-src: Controls fetch, XHR, WebSocket connections

Frame and Object Directives

  • frame-src: Controls frames and iframes
  • frame-ancestors: Controls who can embed your site (replacing X-Frame-Options)
  • object-src: Controls Flash and other plugins
  • child-src: Controls workers and embedded frames (deprecated)

Special Directives

  • base-uri: Restricts URLs for <base> elements
  • form-action: Restricts URLs that forms can submit to
  • navigate-to: Restricts URLs that can be navigated to
  • upgrade-insecure-requests: Upgrades HTTP to HTTPS
  • require-trusted-types-for: Requires Trusted Types to prevent DOM-based XSS

Reporting Directives

  • report-uri: Specifies endpoint for violation reports (deprecated)
  • report-to: Modern reporting directive (CSP3)

Source List Keywords & Values

KeywordDescriptionExample Usage
'none'Blocks all sourcesscript-src 'none'
'self'Allows same-origin sourcesscript-src 'self'
'unsafe-inline'Allows inline scripts/stylesstyle-src 'unsafe-inline'
'unsafe-eval'Allows eval() and similarscript-src 'unsafe-eval'
'strict-dynamic'Propagates trust to scripts loaded by trusted scriptsscript-src 'strict-dynamic'
'nonce-{random}'Allows resources with matching nonce attributescript-src 'nonce-abc123'
'sha256-{hash}'Allows resources matching specific hashscript-src 'sha256-hash'
https:Allows any HTTPS sourcesimg-src https:
Domain nameAllows specific domainscript-src example.com

Common CSP Policy Examples

Basic Restrictive Policy

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'self'; form-action 'self';

Moderate Policy with CDN Support

Content-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' cdn.example.com; img-src 'self' data: cdn.example.com; font-src 'self' cdn.example.com; object-src 'none'; frame-ancestors 'self'; report-uri /csp-violation-report;

Enhanced Security with Nonces

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random-value}'; style-src 'self' 'nonce-{random-value}'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'; report-uri /csp-violation-report;

Common Challenges and Solutions

ChallengeSolution
Third-party scripts breakingUse nonces or hashes for trusted scripts; implement 'strict-dynamic'
Inline styles/scriptsReplace with external files, use nonces, or calculate hashes
Google Analytics issuesAdd www.google-analytics.com, ssl.google-analytics.com to CSP
Google Fonts problemsAdd fonts.googleapis.com and fonts.gstatic.com to appropriate directives
Reporting endpoint setupImplement simple server-side logging or use specialized CSP reporting services
Legacy browser supportUse backward-compatible directives and consider polyfills
Service worker conflictsAdd relevant domains to connect-src and worker-src

Best Practices and Practical Tips

Security Enhancement

  • Avoid 'unsafe-inline' and 'unsafe-eval': These significantly reduce CSP effectiveness
  • Use nonces or hashes for inline scripts when unavoidable
  • Implement 'strict-dynamic' to simplify policies while maintaining security
  • Set object-src 'none' to prevent plugin-based attacks
  • Configure frame-ancestors to prevent clickjacking
  • Add base-uri 'self' to prevent base URI injection attacks

Implementation Tips

  • Start in Report-Only mode to identify potential issues
  • Incrementally tighten policies rather than deploying strict rules immediately
  • Maintain a reporting endpoint to catch violations in production
  • Use specific directives instead of relying on default-src
  • Regularly audit and update your CSP as your site evolves
  • Test across browsers to ensure compatibility
  • Use automated tools to generate and validate policies

CSP Header Deployment by Web Server

Apache (.htaccess or httpd.conf)

<IfModule mod_headers.c>
  Header set Content-Security-Policy "default-src 'self'; script-src 'self';"
</IfModule>

Nginx (nginx.conf)

add_header Content-Security-Policy "default-src 'self'; script-src 'self';";

Express.js

app.use(function(req, res, next) {
  res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self';");
  next();
});

CSP Policy Evaluation Tools

ToolPurposeURL
CSP EvaluatorAnalyzes policy effectivenesshttps://csp-evaluator.withgoogle.com/
Report URICSP reporting servicehttps://report-uri.com/
CSP ScannerAutomated policy scanninghttps://cspscanner.com/
Security HeadersTests all security headershttps://securityheaders.com/
Mozilla ObservatoryComprehensive security testinghttps://observatory.mozilla.org/

CSP Levels Comparison

FeatureCSP Level 1CSP Level 2CSP Level 3
Basic directivesYesYesYes
NoncesNoYesYes
HashesLimitedYesYes
strict-dynamicNoNoYes
Reportingreport-urireport-urireport-to
Worker controlschild-srcchild-srcworker-src
Granular script controlNoNoscript-src-elem/script-src-attr
Navigation restrictionsNoNonavigate-to
Trusted TypesNoNorequire-trusted-types-for

Resources for Further Learning

Official Documentation

Tools and Services

Advanced Guides

Remember: A properly implemented CSP is an essential layer in a defense-in-depth security strategy, but it should complement, not replace, other security measures such as input validation, output encoding, and secure coding practices.

Scroll to Top