Content Security Policy (CSP)

Content Security Policy (CSP) is a browser security mechanism that helps prevent XSS and other code injection attacks by specifying which sources of content are allowed to load and execute on a web page.

How CSP Works

CSP is delivered via HTTP header or meta tag. It defines policies for different content types (scripts, styles, images, etc.). Browsers block resources that violate the policy and can report violations to a specified endpoint.

CSP Header Example

Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://trusted-cdn.com;
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  report-uri /csp-report

Common Directives

  • default-src: Fallback for other directives
  • script-src: Valid sources for JavaScript
  • style-src: Valid sources for stylesheets
  • img-src: Valid sources for images
  • connect-src: Valid targets for fetch/XHR/WebSocket
  • frame-ancestors: Who can embed this page (clickjacking protection)

CSP Bypasses

  • unsafe-inline: Allows inline scripts, defeating XSS protection
  • unsafe-eval: Allows eval(), enabling code injection
  • Overly permissive wildcards: *.googleapis.com may host JSONP
  • Base-uri missing: Allows base tag injection
  • JSONP endpoints: Whitelisted domains with JSONP callbacks

See Also