CSP

Category: Security

What is CSP?

Content Security Policy (CSP) is a security mechanism that helps prevent XSS (Cross-Site Scripting), clickjacking and other attacks through code injection.

How does CSP work?

CSP allows administrators to define from which sources the browser can load resources such as:

  • JavaScript
  • CSS styles
  • Images
  • Fonts
  • Iframes
  • Media files

Basic directives

DirectiveDescription
default-srcSets the default source for all resources
script-srcDefines allowed sources for JavaScript
style-srcDefines allowed sources for CSS styles
img-srcDefines allowed sources for images
connect-srcRestricts sources for XMLHttpRequest, WebSocket
font-srcDefines allowed sources for fonts
frame-srcDefines allowed sources for iframes

Examples of CSP policies

Example 1: Allowing only own resources

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

Example 2: Allowing specific external domains

Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.google.com; img-src 'self' https://cdn.example.com;

Example 3: Disabling inline JavaScript

Content-Security-Policy: script-src 'self'; object-src 'none'

Special values

  • 'none' - Disallows all sources
  • 'self' - Allows only from the same domain
  • 'unsafe-inline' - Allows inline code (inline)
  • 'unsafe-eval' - Allows eval() function
  • nonce-<value> - Allows specific inline script

Modes of operation

  • Enforce mode - Blocks resources violating the rules
  • Report-only mode - Reports only, but does not block (Content-Security-Policy-Report-Only)

Advantages

  • Effective protection against XSS attacks
  • Control over loaded resources
  • Possibility of monitoring and reporting
  • Support from all modern browsers