Revision 1148178 of Content Security Policy (CSP)

  • Revision slug: Web/HTTP/CSP
  • Revision title: Content Security Policy (CSP)
  • Revision id: 1148178
  • Created:
  • Creator: teoli
  • Is current revision? Yes
  • Comment

Revision Content

{{HTTPSidebar}}

Content Security Policy ({{Glossary("CSP")}}) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting ({{Glossary("XSS")}}) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware.

CSP is designed to be fully backward compatible; browsers that don't support it still work with servers that implement it, and vice-versa. Browsers that don't support CSP simply ignore it, functioning as usual, defaulting to the standard same-origin policy for web content. If the site doesn't offer the CSP header, browsers likewise use the standard same-origin policy.

To enable CSP, you need to configure your web server to return the {{HTTPHeader("Content-Security-Policy")}} HTTP header (sometimes you will see mentions of the X-Content-Security-Policy header, but that's an older version and you don't need to specify it anymore).

Alternatively, the {{HTMLElement("meta")}} element can be used to configure a policy.

Threats

Mitigating cross site scripting

A primary goal of CSP is to mitigate and report XSS attacks. XSS attacks exploit the browser's trust of the content received from the server. Malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from.

CSP makes it possible for server administrators to reduce or eliminate the vectors by which XSS can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those whitelisted domains, ignoring all other script (including inline scripts and event-handling HTML attributes).

As an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution.

Mitigating packet sniffing attacks

In addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content be loaded using HTTPS. A complete data transmission security strategy includes not only enforcing HTTPS for data transfer, but also marking all cookies with the secure flag and providing automatic redirects from HTTP pages to their HTTPS counterparts. Sites may also use the {{HTTPHeader("Strict-Transport-Security")}} HTTP header to ensure that browsers connect to them only over an encrypted channel.

Using CSP

Configuring Content Security Policy involves adding the {{HTTPHeader("Content-Security-Policy")}} HTTP header to a web page and giving it values to control resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross site scripting attack. This article explain how to construct such headers properly, and provides examples.

Specifying your policy

You can use the {{HTTPHeader("Content-Security-Policy")}} HTTP header to specify your policy, like this:

Content-Security-Policy: policy

The policy is a string containing the policy directives describing your Content Security Policy.

Writing a policy

A policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area. Your policy should include a {{CSP("default-src")}} policy directive, which is a fallback for other resource types when they don't have policies of their own (for a complete list, see the description of the {{CSP("default-src")}} directive). A policy needs to include a {{CSP("default-src")}} or {{CSP("script-src")}} directive to prevent inline scripts from running, as well as blocking the use of eval(). A policy needs to include a {{CSP("default-src")}} or {{CSP("style-src")}} directive to restrict inline styles from being applied from a {{HTMLElement("style")}} element or a style attribute.

Examples: Common use cases

This section provides examples of some common security policy scenarios.

Example 1

A web site administrator wants all content to come from the site's own origin (this excludes subdomains.)

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

Example 2

A web site administrator wants to allow content from a trusted domain and all its subdomains (it doesn't have to be the same domain that the CSP is set on.)

Content-Security-Policy: default-src 'self' *.trusted.com

Example 3

A web site administrator wants to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code.

Content-Security-Policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com

Here, by default, content is only permitted from the document's origin, with the following exceptions:

  • Images may loaded from anywhere (note the "*" wildcard).
  • Media is only allowed from media1.com and media2.com (and not from subdomains of those sites).
  • Executable script is only allowed from userscripts.example.com.

Example 4

A web site administrator for an online banking site wants to ensure that all its content is loaded using SSL, in order to prevent attackers from eavesdropping on requests.

Content-Security-Policy: default-src https://onlinebanking.jumbobank.com

The server only permits access to documents being loaded specifically over HTTPS through the single origin onlinebanking.jumbobank.com.

Example 5

A web site administrator of a web mail site wants to allow HTML in email, as well as images loaded from anywhere, but not JavaScript or other potentially dangerous content.

Content-Security-Policy: default-src 'self' *.mailsite.com; img-src *

Note that this example doesn't specify a {{CSP("script-src")}}; with the example CSP, this site uses the setting specified by the {{CSP("default-src")}} directive, which means that scripts can be loaded only from the originating server.

Testing your policy

To ease deployment, CSP can be deployed in report-only mode. The policy is not enforced, but any violations are reported to a provided URI. Additionally, a report-only header can be used to test a future revision to a policy without actually deploying it.

You can use the {{HTTPHeader("Content-Security-Policy-Report-Only")}} HTTP header to specify your policy, like this:

Content-Security-Policy-Report-Only: policy 

If both a {{HTTPHeader("Content-Security-Policy-Report-Only")}} header and a {{HTTPHeader("Content-Security-Policy")}} header are present in the same response, both policies are honored. The policy specified in Content-Security-Policy headers is enforced while the Content-Security-Policy-Report-Only policy generates reports but is not enforced.

Browsers that support CSP always send a violation report for each attempt to violate the policy you have established if the policy contains a valid {{CSP("report-uri")}} directive.

Enabling reporting

By default, violation reports aren't sent. To enable violation reporting, you need to specify the {{CSP("report-uri")}} policy directive, providing at least one URI to which to deliver the reports:

Content-Security-Policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi

Then you need to set up your server to receive the reports; it can store or process them in whatever manner you feel is appropriate.

Violation report syntax

The report JSON object contains the following data:

document-uri
The URI of the document in which the violation occurred.
referrer
The referrer of the document in which the violation occurred.
blocked-uri
The URI of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port.
violated-directive
The name of the policy section that was violated.
original-policy
The original policy as specified by the Content-Security-Policy HTTP header.

Sample violation report

Let's consider a page located at http://example.com/signup.html. It uses the following policy, disallowing everything but stylesheets from cdn.example.com.
Content-Security-Policy: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports
The HTML of signup.html looks like this:
<!DOCTYPE html>
<html>
  <head>
    <title>Sign Up</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    ... Content ...
  </body>
</html>
Can you spot the mistake? Stylesheets are only allowed to be loaded from cdn.example.com, yet the website tries to load one from its own origin (http://example.com). A browser capable of enforcing CSP will send the following violation report as a POST request to http://example.com/_/csp-reports, when the document is visited:
{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",
    "referrer": "",
    "blocked-uri": "http://example.com/css/style.css",
    "violated-directive": "style-src cdn.example.com",
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"
  }
}

As you can see, the report includes the full path to the violating resource in blocked-uri. This is not always the case. For example, when the signup.html would attempt to load CSS from http://anothercdn.example.com/stylesheet.css, the browser would not include the full path but only the origin (http://anothercdn.example.com). The CSP specification gives an explanation of this odd behaviour. In summary, this is done to prevent leaking sensitive information about cross-origin resources. Note, that even the specification got this part wrong in its example on violation reports (blocked-uri should be "http://evil.example.com").

Browser compatibility

{{CompatMulti('[{"file": "http/headers/content-security-policy", "features": "Content-Security-Policy"}, {"file": "http/headers/content-security-policy-report-only", "features": "Content-Security-Policy-Report-Only"}]')}}

See also

Revision Source

<div>{{HTTPSidebar}}</div>

<p class="summary"><strong>Content Security Policy</strong> ({{Glossary("CSP")}}) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting ({{Glossary("XSS")}}) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware.</p>

<p>CSP&nbsp;is designed to be fully backward compatible; browsers that don't support it still work with servers that implement it, and vice-versa. Browsers that don't support CSP simply ignore it, functioning as usual, defaulting to the standard same-origin policy for web content. If the site doesn't offer the CSP&nbsp;header, browsers likewise use the standard <a href="/en-US/docs/Web/Security/Same-origin_policy" title="En/Same origin policy for JavaScript">same-origin policy</a>.</p>

<p>To enable CSP, you need to configure your web server to return the {{HTTPHeader("Content-Security-Policy")}} HTTP&nbsp;header (sometimes you will see mentions of the <code>X-Content-Security-Policy</code> header, but that's an older version and you don't need to specify it anymore).</p>

<p>Alternatively, the {{HTMLElement("meta")}} element can be used to configure a policy.</p>

<h2 id="Threats">Threats</h2>

<h3 id="Mitigating_cross_site_scripting">Mitigating cross site scripting</h3>

<p>A primary goal of CSP is to mitigate and report XSS&nbsp;attacks. XSS attacks exploit the browser's trust of the content received from the server. Malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from.</p>

<p>CSP&nbsp;makes it possible for server administrators to reduce or eliminate the vectors by which XSS&nbsp;can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those whitelisted domains, ignoring all other script (including inline scripts and event-handling HTML&nbsp;attributes).</p>

<p>As an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution.</p>

<h3 id="Mitigating_packet_sniffing_attacks">Mitigating packet sniffing attacks</h3>

<p>In addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content be loaded using HTTPS. A complete data transmission security strategy includes not only enforcing HTTPS for data transfer, but also marking all <a href="/en-US/docs/Web/HTTP/Cookies">cookies with the secure flag</a> and providing automatic redirects from HTTP&nbsp;pages to their HTTPS&nbsp;counterparts. Sites may also use the {{HTTPHeader("Strict-Transport-Security")}} HTTP header to ensure that browsers connect to them only over an encrypted channel<strong>.</strong></p>

<h2 id="Using_CSP">Using CSP</h2>

<p>Configuring Content Security Policy involves&nbsp;adding the {{HTTPHeader("Content-Security-Policy")}} HTTP header to a web page and giving it values to control resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross site scripting attack. This article explain how to construct such headers properly, and provides examples.</p>

<h3 id="Specifying_your_policy">Specifying your policy</h3>

<p>You can use the {{HTTPHeader("Content-Security-Policy")}} HTTP&nbsp;header to specify your policy, like this:</p>

<pre class="syntaxbox">
Content-Security-Policy: <em>policy</em></pre>

<p>The policy is a string containing the policy directives describing your Content Security Policy.</p>

<h3 id="Writing_a_policy">Writing a policy</h3>

<p>A policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area. Your policy should include a {{CSP("default-src")}} policy directive, which is a fallback for other resource types when they don't have policies of their own (for a complete list, see the description of the {{CSP("default-src")}} directive). A policy needs to include a {{CSP("default-src")}} or {{CSP("script-src")}} directive to prevent&nbsp;inline scripts from running, as well as blocking the use of <code>eval()</code>. A policy needs to include a {{CSP("default-src")}} or {{CSP("style-src")}} directive to restrict inline styles from being applied from a {{HTMLElement("style")}} element or a <code>style</code> attribute.</p>

<h2 id="Examples_Common_use_cases">Examples:&nbsp;Common use cases</h2>

<p>This section provides examples of some common security policy scenarios.</p>

<h3 id="Example_1">Example 1</h3>

<p>A web site administrator wants all content to come from the site's own origin (this excludes subdomains.)</p>

<pre class="syntaxbox">
Content-Security-Policy: default-src 'self'</pre>

<h3 id="Example_2">Example 2</h3>

<p>A&nbsp;web site administrator wants to allow content from a trusted domain and all its subdomains (it doesn't have to be the same domain that the CSP is set on.)</p>

<pre class="syntaxbox">
Content-Security-Policy: default-src 'self' *.trusted.com</pre>

<h3 id="Example_3">Example 3</h3>

<p>A web site administrator wants to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to&nbsp;trusted providers, and all scripts only to a specific server that hosts trusted code.</p>

<pre class="syntaxbox">
Content-Security-Policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com</pre>

<p>Here, by default, content is only permitted from the document's origin, with the following exceptions:</p>

<ul>
 <li>Images may loaded from anywhere (note the "*" wildcard).</li>
 <li>Media is only allowed from media1.com and media2.com (and not from subdomains of those sites).</li>
 <li>Executable script is only allowed from userscripts.example.com.</li>
</ul>

<h3 id="Example_4">Example 4</h3>

<p>A web site administrator for an online banking site wants to ensure that all its content is loaded using&nbsp;SSL, in order to prevent attackers from eavesdropping on requests.</p>

<pre class="syntaxbox">
Content-Security-Policy: default-src https://onlinebanking.jumbobank.com</pre>

<p>The server only permits access to documents being loaded specifically over HTTPS through the single origin onlinebanking.jumbobank.com.</p>

<h3 id="Example_5">Example 5</h3>

<p>A web site administrator of a web mail site wants to allow HTML&nbsp;in email, as well as images loaded from anywhere, but not JavaScript or other potentially dangerous content.</p>

<pre class="syntaxbox">
Content-Security-Policy: default-src 'self' *.mailsite.com; img-src *</pre>

<p>Note that this example doesn't specify a {{CSP("script-src")}}; with the example CSP, this site uses the setting specified by the {{CSP("default-src")}} directive, which means that scripts can be loaded only from the originating server.</p>

<h2 id="Testing_your_policy">Testing your policy</h2>

<p>To ease deployment, CSP can be deployed in report-only mode. The policy is not enforced, but any violations are reported to a provided URI. Additionally, a report-only header can be used to test a future revision to a policy without actually deploying it.</p>

<p>You can use the {{HTTPHeader("Content-Security-Policy-Report-Only")}} HTTP&nbsp;header to specify your policy, like this:</p>

<pre class="syntaxbox">
Content-Security-Policy-Report-Only: <em>policy</em> </pre>

<p>If both a {{HTTPHeader("Content-Security-Policy-Report-Only")}} header and a {{HTTPHeader("Content-Security-Policy")}} header are present in the same response, both policies are honored. The policy specified in <code>Content-Security-Policy</code> headers is enforced while the <code>Content-Security-Policy-Report-Only</code> policy generates reports but is not enforced.</p>

<p>Browsers that support CSP always send a violation report for each attempt to violate the policy you have established if the policy contains a valid {{CSP("report-uri")}} directive.</p>

<h2 id="Enabling_reporting">Enabling reporting</h2>

<p>By default, violation reports aren't sent. To enable violation reporting, you need to specify the {{CSP("report-uri")}} policy directive, providing at least one URI&nbsp;to which to deliver the reports:</p>

<pre class="syntaxbox">
Content-Security-Policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi</pre>

<p>Then you need to set up your server to receive the reports; it can store or process them in whatever manner you feel is appropriate.</p>

<h2 id="Violation_report_syntax">Violation report syntax</h2>

<p>The report JSON&nbsp;object contains the following data:</p>

<dl>
 <dt><code>document-uri</code></dt>
 <dd>The URI of the document in which the violation occurred.</dd>
 <dt><code>referrer</code></dt>
 <dd>The referrer of the document in which the violation occurred.</dd>
 <dt><code>blocked-uri</code></dt>
 <dd>The URI&nbsp;of the resource that was blocked from loading by the Content Security Policy. If the blocked URI is from a different origin than the document-uri, then the blocked URI is truncated to contain just the scheme, host, and port.</dd>
 <dt><code>violated-directive</code></dt>
 <dd>The name of the policy section that was violated.</dd>
 <dt><code>original-policy</code></dt>
 <dd>The original policy as specified by the <code>Content-Security-Policy</code> HTTP header.</dd>
</dl>

<h2 id="Sample_violation_report">Sample violation report</h2>

<div>Let's consider a page located at&nbsp;<code><a class="external" href="http://example.com/signup.html" rel="freelink">http://example.com/signup.html</a></code>. It uses the following policy, disallowing everything but stylesheets from <code>cdn.example.com</code>.</div>

<div>
<pre class="syntaxbox">
Content-Security-Policy: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports</pre>
</div>

<div>The HTML of <code>signup.html</code> looks like this:</div>

<pre class="brush: html">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Sign Up&lt;/title&gt;
    &lt;link rel="stylesheet" href="css/style.css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    ... Content ...
  &lt;/body&gt;
&lt;/html&gt;</pre>

<div>Can you spot the mistake? Stylesheets are only allowed to be loaded from <code>cdn.example.com</code>, yet the website tries to load one from its own origin (<code>http://example.com</code>). A browser capable of enforcing CSP will send the following violation report as a POST request to&nbsp;<code><a href="http://example.com/_/csp-reports" rel="freelink">http://example.com/_/csp-reports</a></code>, when&nbsp;the document is visited:</div>

<pre>
{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",
    "referrer": "",
    "blocked-uri": "http://example.com/css/style.css",
    "violated-directive": "style-src cdn.example.com",
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"
  }
}</pre>

<p>As you can see, the report includes the full path to the violating resource in <code>blocked-uri</code>. This is not always the case. For example, when the <code>signup.html</code> would attempt to load CSS from <a href="http://anothercdn.example.com/stylesheet.css"><code>http://anothercdn.example.com/stylesheet.css</code></a>, the browser would <em>not</em> include the full path but only the origin (<code>http://anothercdn.example.com</code>). The CSP specification <a href="http://www.w3.org/TR/CSP/#violation-reports">gives an explanation</a> of this odd behaviour. In summary, this is done to prevent leaking sensitive information about cross-origin resources. Note, that even the specification got this part wrong in its <a href="http://www.w3.org/TR/CSP/#sample-violation-report">example on violation reports</a>&nbsp;(<code>blocked-uri</code> should be "<code>http://evil.example.com</code>").</p>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>

<p>{{CompatMulti('[{"file": "http/headers/content-security-policy", "features": "Content-Security-Policy"}, {"file": "http/headers/content-security-policy-report-only", "features": "Content-Security-Policy-Report-Only"}]')}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{HTTPHeader("Content-Security-Policy")}}</li>
 <li>{{HTTPHeader("Content-Security-Policy-Report-Only")}}</li>
 <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">Content Security in WebExtensions</a></li>
 <li>
  <p><a href="/en-US/docs/Tools/GCLI/Display_security_and_privacy_policies">Display security and privacy policies In Firefox Developer Tools</a></p>
 </li>
</ul>
Revert to this revision