Skip to content

Content Security Policy (CSP)

Content Security Policy (CSP) is an HTTP security header designed to mitigate Cross-Site Scripting (XSS) attacks by restricting the resources a browser is allowed to load for a specific page.^[600-developer-tools-security-strict-transport-security.md]

Mechanism

CSP operates by using a whitelist approach to control the origin of specific types of content, such as script, object, style, and font.^[600-developer-tools-security-strict-transport-security.md] By defining valid sources, the browser blocks any resource not explicitly permitted. It also allows for restrictions on dangerous JavaScript features, such as preventing the use of eval.^[600-developer-tools-security-strict-transport-security.md]

Directives

CSP is configured through a series of directives that specify the allowed sources for different content types. Common directives include^[600-developer-tools-security-strict-transport-security.md]:

  • default-src: Serves as the fallback default for other resource types.
  • script-src: Defines valid sources for JavaScript.
  • img-src: Defines valid sources for images.
  • font-src: Defines valid sources for font files.
  • frame-src: Defines valid sources for frames.

Implementation Example

A CSP header can be set to enforce strict rules. The following example allows scripts only from the current origin and a specific domain, and images from the current origin and an AWS S3 bucket^[600-developer-tools-security-strict-transport-security.md]:

Content-Security-Policy: default-src 'self'; script-src 'self' *.google.com 'unsafe-eval'; img-src 'self' *.amazonaws.com data:

In this configuration^[600-developer-tools-security-strict-transport-security.md]: * default-src 'self' restricts all resources to the site's own origin unless overridden by a specific directive. * script-src 'self' *.google.com 'unsafe-eval' permits scripts from the own site and Google subdomains, and explicitly allows the use of eval. * img-src 'self' *.amazonaws.com data: permits images from the own site, Amazon S3, and base64 encoded data strings.

Context

While the X-XSS-Protection header previously provided similar defenses, CSP is considered the modern standard and replacement for XSS mitigation.^[600-developer-tools-security-strict-transport-security.md]

  • [[X-Frame-Options]]
  • [[Strict-Transport-Security]]
  • HTTP Headers

Sources

^[600-developer-tools-security-strict-transport-security.md]