Content Security Policy (CSP)

Content Security Policy is delivered via HTTP response header. It defines approved sources of content that the browser may load. It helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks.

When the browser loads a web page, it loads many other assets along with it. For example, stylesheets, fonts, javascript files. The browser loads these assets because it is instructed to do so by the source code of the page. It has no way of knowing whether or not any of those files should or should not be loaded.

A CSP header allows you to define approved sources for content on your site that the browser can load.

Writing CSP Policy

CSP is described using a series of policy directives. The policy should include a default-src directive, which is a fallback for resource types when they don't have policies of their own.

default-src: Serves as a fallback for the other fetch directives.

script-src: Restricts the URLs which can be loaded using script interfaces.

object-src: Specifies valid sources for the <object> and <embed> elements.

style-src: Specifies valid sources for stylesheets.

img-src: Specifies valid sources of images and favicons.

media-src: Specifies valid sources for loading media using the <audio> , <video> and <track> elements.

frame-src: Specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.

font-src: Specifies valid sources for fonts loaded using @font-face.

connect-src: Restricts the URLs which can be loaded using script interfaces.

form-action: Restricts the URLs which can be used as the target of a form submissions from a given context.

report-uri: Specifies a URI to which the user agent sends reports about policy violation.

You can be as specific or as broad as you like when creating a CSP and fine tune it so that it meets your requirements exactly.

Keywords

  1. 'none' blocks the use of this type of resource
  2. 'self' matches the current origin (but not subdomains)
  3. 'unsafe-inline' allows the use of inline JS and CSS
  4. 'unsafe-eval' allows the use of mechanisms like eval()

Examples

Example 1

Content-Security-Policy: default-src https:

This will allow any assets to be loaded over https from any origin.

Example 2

Content-Security-Policy: default-src example.com

This will allow any assets to be loaded from any origin on example.com using any scheme or port.

Example 3

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

This will allow all content to come from the site's own origin.

Reporting Violations

The report-uri directive specifies a location that the browser should POST a JSON formatted violation report to in the event it has to take action based on the CSP.