Explain Codes LogoExplain Codes Logo

How does Content Security Policy (CSP) work?

web-development
best-practices
security
csp
Alex KataevbyAlex Kataev·Jan 13, 2025
TLDR

CSP is the security wizard of your web app, meticulously formulating access rules for external resources thereby shielding your site from XSS menace.

Sample:

Content-Security-Policy: script-src 'self' https://safe-scripts.com;

Above example reiterates that scripts can be invoked only from your domain ('self') or the specific allowed source (https://safe-scripts.com), eliminating the scope for unfriendly scripts.

Setting up your security policy

Unpacking CSP is no rocket science. With the right knobs and dials, your site's security can be boosted manifold.

Source Specification

  • Use default-src directive to set a global policy for fetching resources.
  • Apply script-src, style-src, img-src, connect-src directives for a more granular control over resource loading.
  • Employ 'self' keyword for allowing sources from your own domain.

Handling Inline scripts and Eval

  • 'unsafe-inline' permits usage of inline script and style blocks.
  • The keyword 'unsafe-eval' activates JavaScript eval() function and its analogues.

Tuning Protocols and Ports

  • Clearly specify the required protocols (http, https, data, etc.) and ports or employ wildcard (*) as necessary.
  • Apply 'filesystem' to enable loading resources over file:// protocol.

Best practices

  • Steer clear from default-src *. It's like weaving a welcome mat for trojans.
  • Prefer external files for scripts and styles and meticulously enlist them in the whitelist.
  • When using Apache, opt for mod_security for an added layer of protection.

Crafting an effective policy

Implementing CSP is more art than science. Let's brush up our weapons (I mean knowledge).

Granular Directives

  • Draft separate directives for each resource type—scripts, styles, images, etc., instead of a broadsword approach.
  • Use hashes and nonces to whitelist specific inline scripts.

Infrastructure & Deployment

  • With Apache, roll out CSP via mod_headers without mutating application code.
  • Support aliases in Apache to optimize complex CSP policies.

Monitor, Adapt & Overcome

  • Configure report-uri or report-to directives to gather violation reports.
  • Keep your CSP polished and ready in response to changing dynamics.

Educate & Validate

  • Make use of tools like Google's CSP Evaluator to test your policies.
  • Stay on top of the game with resources from W3C, OWASP, and Google's CSP Fundamentals.