Security/CSP/Specification: Difference between revisions
No edit summary |
|||
Line 38: | Line 38: | ||
===Directives=== | ===Directives=== | ||
;allow: | |||
* The catch-all section that defines the security policy for all types of content which are not called out in any of the other directives. Defines the default policy for un-specified content types. | * The catch-all section that defines the security policy for all types of content which are not called out in any of the other directives. Defines the default policy for un-specified content types. | ||
* | * User Agents MUST not load content from any source if the allow directive is not explicitly specified. This can be considered equivalent to the policy "allow 'none'". | ||
* | * User Agents MUST enforce this directive for all HTTP requests not subject to one of the more specific directives. | ||
;options: | |||
* Options for modifying the underlying behavior of CSP are specified here. | * Options for modifying the underlying behavior of CSP are specified here. | ||
* The value of this directive is a space-separated list of LDH tokens, each specifying a feature to enable or disable: | * The value of this directive is a space-separated list of LDH tokens, each specifying a feature to enable or disable: | ||
** <tt>inline-script</tt> enables inline scripts and <tt>javascript:</tt> URIs | ** <tt>inline-script</tt> enables inline scripts and <tt>javascript:</tt> URIs | ||
** <tt>eval-script</tt> enables the <tt>eval()</tt> functionality of scripts interpreted by the browser, and allows code to be created from strings in uses of the <tt>new Function()</tt> constructor, <tt>setTimeout</tt> and <tt>setInterval</tt> | ** <tt>eval-script</tt> enables the <tt>eval()</tt> functionality of scripts interpreted by the browser, and allows code to be created from strings in uses of the <tt>new Function()</tt> constructor, <tt>setTimeout</tt> and <tt>setInterval</tt> | ||
* | * User Agents must ignore any tokens not recognized by CSP, and SHOULD post a non-fatal warning to the error console. | ||
;img-src: | |||
* Indicates which sources are valid for images and favicons. | * Indicates which sources are valid for images and favicons. | ||
* | * User Agents MUST not request images from non-approved sources. | ||
* | * User Agents MUST subject image requests to the allow directive if img-src is not explicitly specified. | ||
;media-src: | |||
* Indicates which sources are valid for <tt>audio</tt> and <tt>video</tt> elements. | * Indicates which sources are valid for <tt>audio</tt> and <tt>video</tt> elements. | ||
* <tt>audio</tt> and <tt>video</tt> elements from non-approved sources | * User Agents MUST not request <tt>audio</tt> and <tt>video</tt> elements from non-approved sources. | ||
* | * User Agents MUST subject audio and video requests to the allow directive if media-src is not explicitly specified. | ||
;script-src: | |||
* Indicates which sources are valid for scripts. | * Indicates which sources are valid for scripts. | ||
* | * Regulates which scripts can be loaded via the <tt>src=</tt> attribute. | ||
* | * User Agents MUST not request scripts from non-approved sources. | ||
* | * User Agents MUST subject script requests to the allow directive if script-src is not explicitly specified. | ||
;object-src: | |||
* Indicates which sources are valid for <tt>object</tt>, <tt>embed</tt>, and <tt>applet</tt> elements. | * Indicates which sources are valid for <tt>object</tt>, <tt>embed</tt>, and <tt>applet</tt> elements. | ||
* | * User Agents MUST not request objects from non-approved sources. | ||
* | * User Agents MUST subject object, embed, and applet requests to the allow directive if object-src is not explicitly specified. | ||
;frame-src: | |||
* Indicates which sources are valid for <tt>frame</tt> and <tt>iframe</tt> elements. | * Indicates which sources are valid for <tt>frame</tt> and <tt>iframe</tt> elements. | ||
* | * User Agents MUST not request frame content from non-approved sources. | ||
* User Agents MUST subject frame requests to the allow directive if frame-src is not explicitly specified. | |||
* | |||
;font-src: | |||
* Indicates which sources are valid for <tt>@font-src</tt> CSS loads. | * Indicates which sources are valid for <tt>@font-src</tt> CSS loads. | ||
* | * User Agents MUST not request fonts served from non-approved sources when intended for use as a font in CSS. | ||
* | * User Agents MUST subject requests caused by <tt>@font-src</tt> to the allow directive if font-src is not explicitly specified. | ||
;xhr-src: | |||
* Indicates which sources are valid for <tt>XMLHttpRequest</tt> connections. | * Indicates which sources are valid for <tt>XMLHttpRequest</tt> connections. | ||
* XMLHttpRequests | * User Agents MUST not cause XMLHttpRequests to open requests to sources not permitted by this directive. | ||
* | * User Agents MUST subject requests caused by <tt>XMLHttpRequest</tt> to the allow directive if xhr-src is not explicitly specified. | ||
;frame-ancestors: | |||
* Indicates which sources are valid <b>ancestors</b> for embedding the protected resource via <tt>object</tt>, <tt>frame</tt> and <tt>iframe</tt> tags. An ancestor is any HTML document between the protected resource and the top of the window frame tree; for example, if A embeds B which embeds C, both A and B are <b>ancestors</b> of C. If A embeds both B and C, B is <i>not</i> an ancestor of C, but A still <i>is</i>. | * Indicates which sources are valid <b>ancestors</b> for embedding the protected resource via <tt>object</tt>, <tt>frame</tt> and <tt>iframe</tt> tags. An ancestor is any HTML document between the protected resource and the top of the window frame tree; for example, if A embeds B which embeds C, both A and B are <b>ancestors</b> of C. If A embeds both B and C, B is <i>not</i> an ancestor of C, but A still <i>is</i>. | ||
* All web pages that are ancestors of the protected content must be indicated by the value of this directive. For example, if A embeds B which embeds C, and C defines a <tt>frame-ancestors</tt> as "B,C" then C is not rendered as a subframe. | * All web pages that are ancestors of the protected content must be indicated by the value of this directive. For example, if A embeds B which embeds C, and C defines a <tt>frame-ancestors</tt> as "B,C" then C is not rendered as a subframe. | ||
* Answers the question: "Which sites may embed this resource?" | * Answers the question: "Which sites may embed this resource?" | ||
* User Agents MUST not render the protected document when any of its frame ancestors are not allowed by this directive. | |||
* User Agents MUST always render the protected document if frame-ancestors is not explicitly specified. | |||
* Note that this directive addresses the [http://jeremiahgrossman.blogspot.com/2008/10/clickjacking-web-pages-can-see-and-hear.html clickjacking] threat, but not [http://www.cgisecurity.com/articles/csrf-faq.shtml CSRF] | * Note that this directive addresses the [http://jeremiahgrossman.blogspot.com/2008/10/clickjacking-web-pages-can-see-and-hear.html clickjacking] threat, but not [http://www.cgisecurity.com/articles/csrf-faq.shtml CSRF] | ||
** Using frame-ancestors, it is possible to prevent a resource from being framed within a malicious webpage. The browser will stop loading the protected document as soon as its frame-ancestors policy is received and a policy violation is determined. | ** Using frame-ancestors, it is possible to prevent a resource from being framed within a malicious webpage. The browser will stop loading the protected document as soon as its frame-ancestors policy is received and a policy violation is determined. | ||
** However, this directive <em>does not prevent the request for the document from being sent</em> to the framed document's server, as policy directives are received by the browser in the server's response. To mitigate Cross-Site Request Forgery, the [[Security/Sec-From|Sec-From header]] provides a more robust mechanism. | ** However, this directive <em>does not prevent the request for the document from being sent</em> to the framed document's server, as policy directives are received by the browser in the server's response. To mitigate Cross-Site Request Forgery, the [[Security/Sec-From|Sec-From header]] provides a more robust mechanism. | ||
;style-src: | |||
* Indicates which sources are valid for externally linked stylesheets. | * Indicates which sources are valid for externally linked stylesheets. | ||
* | * User Agents MUST always allow inline stylesheets and style attributes of HTML tags. | ||
* | * User Agents MUST not request stylesheets from sources not allowed by the style-src directive. | ||
* | * User Agents MUST subject stylesheet requests to the allow directive if style-src is not explicitly specified. | ||
;report-uri: | |||
* Instructs the browser where to send a report when CSP is violated. | * Instructs the browser where to send a report when CSP is violated. | ||
* The report will be an XML document with MIME type application/xml sent via POST to the specified URI contained in the value of this directive. | * The report will be an XML document with MIME type application/xml sent via POST to the specified URI contained in the value of this directive. | ||
* | * Acceptable report URIs MUST use the scheme and port as the protected content, and the [http://publicsuffix.org public suffix] and most general DNS label of the protected content and the report URI must match. For example www.foo.co.uk and reports.foo.co.uk, but not reports.bar.co.uk. Relative URIs are acceptable, and are resolved within the same scheme, host and port as the document served with the CSP. | ||
* Report URIs that don't match the public suffix and base host match requirements | * User Agents MUST send violation reports to any acceptable URIs in this directive. Details about the information provided in violation reports are found in the [[#Violation Report Syntax|Violation Report Syntax]] section. | ||
* | * User Agents MUST ignore report URIs that don't match the public suffix and base host match requirements. User Agents SHOULD log one error to an error console. User Agents MUST then continue CSP enforcement as if the report URI were not specified. | ||
* User Agents MUST not honor HTTP 3xx response codes to prevent HTTP header leakage across domains. | |||
;policy-uri: | |||
* Indicates the location of a file containing the security policies for the protected resource. | * Indicates the location of a file containing the security policies for the protected resource. | ||
* <tt>policy-uri</tt> | * <tt>policy-uri</tt> MUST only be defined in the absence of other policy definitions in the <tt>X-Content-Security-Policy</tt> HTTP header. | ||
* | * User Agents MUST raise a [[Security/CSP#Error_Handling|fatal error]] and MUST enforce the policy "allow 'none'" if <tt>policy-uri</tt> is defined among other directives in the header. | ||
* User Agents MUST ignore any policy URIs of a different origin (scheme, host, or port) from the protected content. User Agents SHOULD resolve relative URIs within the same scheme, host and port as the protected document. | |||
===Source Expression List=== | ===Source Expression List=== |
Revision as of 23:29, 8 March 2010
Specification
Content Security Policy is intended to help web designers or server administrators specify how content interacts on their web sites. It helps mitigate and detect types of attacks such as XSS and data injection. CSP is not intended to be a main line of defense, but rather one of the many layers of security that can be employed to help secure a web site. More information about the intended use of CSP is available in the goals section of the overview document.
The purpose of this document is to provide a detailed description of how Content Security Policy definitions can be deployed. It explains the syntax for creating a CSP policy definition and how the defined policies are received and enforced by a user agent.
Definitions
A policy is composed of directives, such as "allow none". Each directive is composed of a directive name and a directive value, which is either a list of host items or a URI, for certain types of directives.
When CSP is activated for a site, a few base restrictions in the browser environment are enforced by default to help provide proper enforcement of any policy defined. These base restrictions provide general security enhancements by limiting the types of dynamic content that is allowed: generally any script on a site that converts text into code (through the use of eval() or similar functions) is disallowed. Details of the refinements can be found in the Base Restrictions section.
Policy Language and Syntax
A policy is composed of directives with their corresponding values. Any number of directives can be defined, but the allow directive must always be present. Each directive is followed with a list of host expressions except for policy-uri and report-uri which contain a single URI value. Some example policy sets are provided below.
Note: In the case of policy refinements as described above, it is possible to have two report-uri values; in this situation, a copy of the report is sent to each of the two URIs.
Sample Policy Definitions
Example 1: Site wants all content to come from its own domain:
X-Content-Security-Policy: allow 'self'
Example 2: Auction site wants to allow images from anywhere, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from its server hosting sanitized JavaScript:
X-Content-Security-Policy: allow 'self'; img-src *; \ object-src media1.com media2.com *.cdn.com; \ script-src trustedscripts.example.com
Example 3: Server administrators want to deny all third-party scripts for the site, and a given project group also wants to disallow media from other sites (header provided by sysadmins and header provided by project group are both present):
X-Content-Security-Policy: allow *; script-src 'self' X-Content-Security-Policy: allow *; script-src 'self'; media-src 'self';
Example 4: Online payments site wants to ensure that all of the content in its pages is loaded over SSL to prevent attackers from eavesdropping on requests for insecure content:
X-Content-Security-Policy: allow https://*:443
Directives
- allow
- The catch-all section that defines the security policy for all types of content which are not called out in any of the other directives. Defines the default policy for un-specified content types.
- User Agents MUST not load content from any source if the allow directive is not explicitly specified. This can be considered equivalent to the policy "allow 'none'".
- User Agents MUST enforce this directive for all HTTP requests not subject to one of the more specific directives.
- options
- Options for modifying the underlying behavior of CSP are specified here.
- The value of this directive is a space-separated list of LDH tokens, each specifying a feature to enable or disable:
- inline-script enables inline scripts and javascript: URIs
- eval-script enables the eval() functionality of scripts interpreted by the browser, and allows code to be created from strings in uses of the new Function() constructor, setTimeout and setInterval
- User Agents must ignore any tokens not recognized by CSP, and SHOULD post a non-fatal warning to the error console.
- img-src
- Indicates which sources are valid for images and favicons.
- User Agents MUST not request images from non-approved sources.
- User Agents MUST subject image requests to the allow directive if img-src is not explicitly specified.
- media-src
- Indicates which sources are valid for audio and video elements.
- User Agents MUST not request audio and video elements from non-approved sources.
- User Agents MUST subject audio and video requests to the allow directive if media-src is not explicitly specified.
- script-src
- Indicates which sources are valid for scripts.
- Regulates which scripts can be loaded via the src= attribute.
- User Agents MUST not request scripts from non-approved sources.
- User Agents MUST subject script requests to the allow directive if script-src is not explicitly specified.
- object-src
- Indicates which sources are valid for object, embed, and applet elements.
- User Agents MUST not request objects from non-approved sources.
- User Agents MUST subject object, embed, and applet requests to the allow directive if object-src is not explicitly specified.
- frame-src
- Indicates which sources are valid for frame and iframe elements.
- User Agents MUST not request frame content from non-approved sources.
- User Agents MUST subject frame requests to the allow directive if frame-src is not explicitly specified.
- font-src
- Indicates which sources are valid for @font-src CSS loads.
- User Agents MUST not request fonts served from non-approved sources when intended for use as a font in CSS.
- User Agents MUST subject requests caused by @font-src to the allow directive if font-src is not explicitly specified.
- xhr-src
- Indicates which sources are valid for XMLHttpRequest connections.
- User Agents MUST not cause XMLHttpRequests to open requests to sources not permitted by this directive.
- User Agents MUST subject requests caused by XMLHttpRequest to the allow directive if xhr-src is not explicitly specified.
- frame-ancestors
- Indicates which sources are valid ancestors for embedding the protected resource via object, frame and iframe tags. An ancestor is any HTML document between the protected resource and the top of the window frame tree; for example, if A embeds B which embeds C, both A and B are ancestors of C. If A embeds both B and C, B is not an ancestor of C, but A still is.
- All web pages that are ancestors of the protected content must be indicated by the value of this directive. For example, if A embeds B which embeds C, and C defines a frame-ancestors as "B,C" then C is not rendered as a subframe.
- Answers the question: "Which sites may embed this resource?"
- User Agents MUST not render the protected document when any of its frame ancestors are not allowed by this directive.
- User Agents MUST always render the protected document if frame-ancestors is not explicitly specified.
- Note that this directive addresses the clickjacking threat, but not CSRF
- Using frame-ancestors, it is possible to prevent a resource from being framed within a malicious webpage. The browser will stop loading the protected document as soon as its frame-ancestors policy is received and a policy violation is determined.
- However, this directive does not prevent the request for the document from being sent to the framed document's server, as policy directives are received by the browser in the server's response. To mitigate Cross-Site Request Forgery, the Sec-From header provides a more robust mechanism.
- style-src
- Indicates which sources are valid for externally linked stylesheets.
- User Agents MUST always allow inline stylesheets and style attributes of HTML tags.
- User Agents MUST not request stylesheets from sources not allowed by the style-src directive.
- User Agents MUST subject stylesheet requests to the allow directive if style-src is not explicitly specified.
- report-uri
- Instructs the browser where to send a report when CSP is violated.
- The report will be an XML document with MIME type application/xml sent via POST to the specified URI contained in the value of this directive.
- Acceptable report URIs MUST use the scheme and port as the protected content, and the public suffix and most general DNS label of the protected content and the report URI must match. For example www.foo.co.uk and reports.foo.co.uk, but not reports.bar.co.uk. Relative URIs are acceptable, and are resolved within the same scheme, host and port as the document served with the CSP.
- User Agents MUST send violation reports to any acceptable URIs in this directive. Details about the information provided in violation reports are found in the Violation Report Syntax section.
- User Agents MUST ignore report URIs that don't match the public suffix and base host match requirements. User Agents SHOULD log one error to an error console. User Agents MUST then continue CSP enforcement as if the report URI were not specified.
- User Agents MUST not honor HTTP 3xx response codes to prevent HTTP header leakage across domains.
- policy-uri
- Indicates the location of a file containing the security policies for the protected resource.
- policy-uri MUST only be defined in the absence of other policy definitions in the X-Content-Security-Policy HTTP header.
- User Agents MUST raise a fatal error and MUST enforce the policy "allow 'none'" if policy-uri is defined among other directives in the header.
- User Agents MUST ignore any policy URIs of a different origin (scheme, host, or port) from the protected content. User Agents SHOULD resolve relative URIs within the same scheme, host and port as the protected document.
Source Expression List
Source expressions are a combination of scheme and often host and port. Source expressions may contain wildcards. Examples of host-only source expressions are "*.mozilla.com" and "mozilla.org". Internationalized domain names are specified according to their punycode representations.
Source expressions may also specify a scheme and/or port. If the scheme is not specified as part of the source expression it defaults to the same scheme as the protected document. If a port is not specified as the source expression, the port used for the source is the default port for the source's scheme (whether it is inherited or explicitly specified in the source expression).
When a scheme alone is the entire source expression (e.g., javascript:) host and port restrictions are not enforced. This is because for some schemes, host and port are irrelevant (e.g., data:).
Note that this inheriting of scheme causes SSL mixed content mode to be disabled by default. If a site wishes to include non-secure content in their top-level SSL page, they must opt-in to mixed content mode by specifying a non-secure scheme in the host expression.
Host-less Schemes
Valid sources do not always require a host. Schemes such as data and javascript can be enabled as a source by stating the name of the scheme followed by a colon. For example:
- javascript:
- allows javascript URIs
- data:
- expresses support for all data URIs.
Port Wildcards
A wildcard "*" token may be used in place of the port number. This indicates that all ports (except banned ports) are valid for the source. Examples:
- http://foo.com:*
- Any port may be used to access content from foo.com over http
- foo.com:*
- Any port may be used to access content from foo.com, over the same scheme as the CSP-protected resource
Hostname Wildcards
Each source expression's host name may contain up to one wildcard (*) and it must be the left-most DNS label.
Valid wildcard host names expressions include "*.mozilla.com" and "*".
Invalid wildcard host name expressions include "www.*.com", "*.mozilla.*" and "mozilla.*".
A wildcard token (*) matches zero or more DNS labels. All of "d.c.b.a", "c.b.a", and "b.a" match the expression "*.b.a".
Source Expression Keywords
In place of source expressions, these keywords can be used to specify classes of sources.
- 'none'
- Refers to the empty set (no hosts are valid)
- 'self'
- Refers to the source serving the protected content -- this is inclusive of scheme, host and port.
Formal Policy Syntax
<policy> ::= <allow-directive>";"<directive-list> <allow-directive> ::= allow <source-list> <directive-list> ::= <empty> | <directive>";"<directive-list> <directive> ::= <src-directive>" "<src-dir-value> | "options "<options-dir-value> | <uri-directive>" "<URI (RFC 2396)> | <future-directive>" "<future-value> <future-directive> ::= <ldh-str> <future-value> ::= <empty> | <future-value><fv-char> <options-dir-value> ::= <empty> | "eval-script" <options-dir-value> | "inline-script" <options-dir-value> | <(unrecognized)ldh-str> <options-dir-value> <src-directive> ::= "img-src" | "media-src" | "style-src" | "object-src" | "frame-src" | "font-src" | "script-src" | "xhr-src" | "frame-ancestors" <uri-directive> ::= "report-uri" | "policy-uri" <src-dir-value> ::= <source-list> | "'none'" <source-list> ::= <source> | <source-list>" "<source> <source> ::= "'self'" | <scheme><host><port> <scheme> ::= <empty> | <scheme-name>":" | <scheme-name>":/" | <scheme-name>"://" <scheme-name> ::= <alpha><scheme-suffix> <host> ::= <empty> | <host-name> <host-name> ::= "*" | <ldh-str> | <host-name>"."<ldh-str> <port> ::= <empty> | ":*" | ":"<integer> <scheme-suffix> ::= <scheme-chr> | <scheme-suffix><scheme-chr> <ldh-str> ::= <let-dig-hyp> | <ldh-symbol><let-dig-hyp> <let-dig-hyp> ::= <letter> | <digit> | "-" <scheme-chr> ::= <letter> | <digit> | "+" | "." | "-" <fv-char> ::= <letter> | <digit> | " " | "+" | "." | "-" | "_" | "'" | """ | "[" | "]" | "\" | "|" | "/" | "?" | "{" | "}" | "=" | "+" | "`" | "~" | "!" | "@" | "#" | "$" | "%" | "^" | "&" | "*" | "(" | ")" <letter> ::= "a"|"b"|"c"|"d"|"e"|"f"|"g"|"h"|"i" |"j"|"k"|"l"|"m"|"n"|"o"|"p"|"q"|"r" |"s"|"t"|"u"|"v"|"w"|"x"|"y"|"z" |"A"|"B"|"C"|"D"|"E"|"F"|"G"|"H"|"I" |"J"|"K"|"L"|"M"|"N"|"O"|"P"|"Q"|"R" |"S"|"T"|"U"|"V"|"W"|"X"|"Y"|"Z" <integer> ::= <digit> | <integer><digit> <digit> ::= "1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"|"0" <empty> ::= ""
Violation Report Syntax
CSP supports a reporting mechanism that allows browsers to notify content providers when their policy is violated. When a report-uri is provided and a policy is violated, information about the protected resource and the violating content is transmitted to the report-uri via HTTP POST if available in the employed scheme, otherwise an appropriate "submit" method is used. The user agent must not honor redirection responses. Such a report is an XML document containing the following fields:
- request
- HTTP request line of the resource whose policy is violated (including method, resource, path, HTTP version)
- request-headers
- HTTP request headers sent with the request (above) for the CSP-Protected content
- blocked-uri
- URI of the resource that was blocked from loading due to a violation in policy
- violated-directive
- The policy section that was violated (e.g., "script-src *.mozilla.org").
- original-policy
- The original policy as served in the X-Content-Security-Policy HTTP header (or if there were multiple headers, a comma separated list of the policies)
NOTE: in the case where a protected resource is not rendered because the frame-ancestors directive was violated, blocked-uri is not sent and is assumed to be the same as the request URI. The reason for this is because this situation is different from other policy violations: no third-party content was blocked, rather the protected content elected not to load since it does not trust the sites that have enframed it.
Violation Report XML Schema:
<?xml version="1.0" encoding="ISO-8859-1" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="csp-report"> <xs:complexType> <xs:sequence> <xs:element name="request" type="string" use="required" /> <xs:element name="request-headers" type="string" /> <xs:element name="blocked-uri" type="string" /> <xs:element name="violated-directive" type="string" use="required" /> <xs:element name="original-policy" type="string" use="required" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
The MIME type of the transmitted report will be set to application/xml.
Violation Report Sample
In this example, a page located at http://example.com/index.html was requested using HTTP 1.1 via the GET method. It provided a policy that included the directive "img-src self", which was violated by a request for http://evil.com/some_image.png. The sample XML data sent to the policy-specified report-uri follows.
<csp-report> <request>GET /index.html HTTP/1.1</request> <request-headers><![CDATA[ Host: example.com User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive ]]></request-headers> <blocked-uri>http://evil.com/some_image.png</blocked-uri> <violated-directive>img-src self</violated-directive> <original-policy>allow none; img-src *, allow self; img-src self</original-policy> </csp-report>
User Agent Behavior
Base Restrictions
The following restrictions will apply whenever any CSP directives are declared for a document:
No inline scripts will execute
- Restricted:
- The contents of internal <script> nodes
- javascript: URIs, e.g. <a href="javascript:bad_stuff()"> (unless enabled by policy)
- Event-handling attributes, e.g. <a onclick="bad_stuff()">
- Allowed:
- Script imported from external files hosted by white-listed sources and served with a Content-Type of application/javascript or application/json.
- Justification:
- XSS attacks are possible because the browser has no way to differentiate between content the server intended to send and content injected by an attacker. Content Security Policy forces the separation of code from content and requires authors to be explicit about the code they intend to execute
- Common vectors for injecting script into web pages have been restricted in CSP. With CSP enabled, the bar for a successful XSS attack is raised substantially, requiring an attacker to:
- inject a <script> tag into the target document
- point this tag at a script file on a white-listed host
- control the contents of the white-listed script file
- Note: websites are still able to peform event-handling in the following ways, both of which require being used from within valid white-listed script files:
- setting the on<event> properties of an element, e.g. element.onclick = myFunc;
- using addEventListener, e.g. element.addEventListener("click", myFunc, false);
- Sites may opt-out of this restriction by adding the inline keyword to the script-src directive.
- Vulnerability types mitigated:
- Reflected XSS
- Stored XSS
- javascript: link injection
- HTML attribute injection
On Violation: a violation report will be sent with the violated-directive value set to "Base Restriction Violation: no inline scripts will execute.".
Code will not be created from strings
- Restricted:
- eval()
- setTimeout called with a String argument, e.g. setTimeout("evil string...", 1000)
- setInterval called with a String argument, e.g. setInterval("evil string...", 1000)
- new Function constructor, e.g. var f = new Function("evil string...")
- Allowed:
- Functions declared using the function operator, e.g. function f() { some_code }, or var f = function() { some_code }
- setTimeout called with a Function argument, e.g. setTimeout(myFunc, 1000)
- setInterval called with a Function argument, e.g. setInterval(myFunc, 1000)
- Justification:
- eval and related functions make trivial the task of generating code from strings, which commonly come from untrusted sources, are loaded via insecure protocols, and can become tainted with attacker controlled data.
- Once tainted data has been introduced to a JavaScript program, it is extremely difficult to control its propogation and calls to eval and similar are likely to incorporate tainted strings containing malicious code.
- Note: the common AJAX pattern in which a site makes a XMLHttpRequest to fetch JSON data is still enabled under CSP using a JSON parser or inside a browser that has native JSON support.
- Sites may opt-out of this entire restriction by adding the eval-script keyword to the options directive. This allows the blocked eval(), setTimeout(), setInterval(), and new Function() calls to proceed.
- Vulnerability types mitigated:
- AJAX request tampering
- Improper use of dynamic properties
On Violation: a violation report will be sent with the violated-directive value set to "Base Restriction Violation: no code will be created with strings".
No data: URIs unless opted-in to via explicit policy
- Restricted:
- data: URIs as a source for inline content
- Allowed:
- data: URIs as a source for inline content when explicitly opted-in to, e.g. X-Content-Security-Policy: allow self; img-src data:
- Justification:
- The data: URI scheme is designed to allow the loading of arbitrary textual or binary data into a document, including HTML, scripts, images, media files, etc.
- data: URIs are a potential vector for HTML and script injection which can be used by an attacker for XSS or website defacement.
- The increase in attack surface created by data: URIs, and additional input sanitization required by sites wishing to use them justifies the opt-in requirement for this feature in CSP.
- Vulnerability types mitigated:
- data: URL script injection
- data: URIs can be re-enabled by adding "data:" as a source to any source directive. For example: img-src data: https://my-host.com.
XBL bindings must come from chrome: or resource: URIs
- Restricted:
- XBL bindings loaded via any protocol other than chrome: or resource:
- Allowed:
- XBL bindings loaded via the chrome: or resource: protocols
- Justification:
- XBL is used to define the properties and behaviors of elements in HTML, XUL, and SVG documents from external files and as such is a vector for script injection.
- Requiring that XBL bindings be loaded from either the chrome: or resource: protocol ensures that the bindings are part of a package already installed on a user's system. This prevents script from arbitrary locations on the Web from being included in a document via CSS.
- Note: this restriction still enables user stylesheets to use XBL, custom browser add-on bindings to be referenced by web content, and chrome UI features to be implemented in XBL, e.g. <video> controls.
- Vulnerability types mitigated:
- Stylesheet script injection
- Style attribute injection
Restrictions on policy-uri and report-uri
The optional directive policy-uri must refer to the same origin (scheme/host/port) as the protected document. The report-uri directive must refer to an origin with the same public suffix and base host. For instance, a report-uri in a policy for "www.mysite.com" may refer to anything that ends with "mysite.com". Additionally, policy-uri documents must be served with the MIME type text/x-content-security-policy to be valid
- Restricted:
- policy-uri directives which refer to a URI on a different host as the protected document, e.g. policy-uri http://other.tld/csp-policy.cgi
- policy-uri responses served with Content-Type other than text/x-content-security-policy, e.g. Content-Type: text/html, or Content-type: image/jpeg
- report-uri directives which refer to a URI on a different public suffix or base host than the protected document, e.g. report-uri http://other.tld/csp-report.cgi
- Allowed:
- policy-uri directives which refer to a URI on the same host as the protected document, e.g. policy-uri http://same.site/csp-policy.cgi. The policy document must also be served with the response header, Content-Type: text/x-content-security-policy
- report-uri directives which refer to a URI containing the same public suffix and base host as the protected document, e.g., on www.site.com there is a policy-uri http://same.site.com/csp-report.cgi
- Justification:
- A site which has not opted-in to using CSP should not be forced into using CSP by an attacker who can inject a policy-uri directive into a HTTP header. Restricting the policy-uri to the same host as the protected document, and requiring it to be served as text/x-content-security-policy ensures the site has positively opted-in to CSP.
- The report sent to the report-uri contains potentially sensitive information, including cookie values and query string parameters. This information is intended only for the protected site for debugging purposes or similar. An attacker should not be allowed to steal the report information by injecting a report-uri, along with an arbitrary policy to be violated.
Activation and Enforcement
CSP is activated by a client's browser when the X-Content-Security-Policy HTTP header is provided in a HTTP response.
The Content Security Policy to be enforced can be delivered to the browser in one of two ways: directly as the value in the X-Content-Security-Policy HTTP header or a file served from the same host as the resource to be secured. The X-Content-Security-Policy header must either contain a policy definition or a policy-uri field; if both are present, the browser will raise a CSP console error and enforce the most restrictive ("allow none") policy.
The syntax is identical between file-based and header-based policy. The contents of a policy file are equivalent to the value of the X-Content-Security-Policy header.
Policy Refinements with Multiple Headers
When multiple instances of the X-Content-Security-Policy HTTP header are present in an HTTP response, the intersection of the policies is enforced; essentially, the browser enforces a policy that is more strict than both the policies specified in the multiple headers, but only strict enough to correspond to rules in all policies. Any web request that satisfied all policies alone will be accepted by the new policy, but any request rejected by any of of the two policies will be rejected. The intersection is calculated on a directive-by-directive basis (i.e., the intersection of the allow directive is taken and enforced as the allow part of the effective policy). Explicitly, for two policies:
define R1 ≡ all URIs accepted by the first HTTP header CSP
define R2 ≡ all URIs accepted by the second HTTP header CSP
Re = {r | r ∈ R1 AND r ∈ R2}
(Re is the set of all URIs accepted by the intersected CSP)
If more than two instances of the X-Content-Security-Policy header are present in the response, the intersection is done digest-style: the first two policies are removed from the set of headers to digest, intersected, and the result is placed back in the set. This continues until only one policy remains. e.g.,
intersect(A, B, C, D) = intersect(A, intersect(B, intersect(C,D)))
If two policy headers are present, one (P1) may allow scripts from domains A, B and C. The policy in the other header (P2) may allow scripts from domains B, C and D. The policy enforced (Penforced) by the browser will allow scripts from domains B and C only (Penforced = P1 ∩ P2).
Why Intersect Policies?
Because the X-Content-Security-Policy header may appear multiple times in the response, it is possible they're crafted by different entities and may conflict. A decision must be made about which policy to use, or whether to combine them or not. Assuming there are two different policies present, there are five obvious ways to address this conflict:
- Ignore both. Raise error in the console. Enforce "allow none" (most secure).
Simplest and safest way to lock down when the policies conflict. - Ignore both. Raise error in the console. Enforce "allow *" (most relaxed).
This is a fail-open policy and will keep the site from breaking if two policies conflict. - Use the first header's policy.
- Use the second header's policy.
- Enforce the intersection of the policies.
This is the technique used by CSP. For each URI that is accepted by both policies, the new intersected policy will also accept the URI. Any request that is not accepted by both policies will be rejected by the new policy. This provides the ability for interaction between multiple policy specifications, allowing infrastructure admins to add a global policy to all sites on their network that may additionally want more restrictions. This technique allows the use of multiple headers to make a widely used policy more restrictive, but never more relaxed.
The fifth option, enforcing the intersection of the policies, is the best balance between safety and flexibility so CSP implements this conflict resolution technique. Furthermore, it is likely that those controlling the network are not always the same people who maintain or create the web application itself -- the ability to "refine" or further restrict enforced policies allows the web programmers to tighten the belt on a CSP-protected page without violating the policy set out by the network (possibly set by the sysadmins).
Conflicting report-uri values
If multiple headers define policies with report-uri values, a single report is sent to each of the provided URIs. If any report-uri values are the same, only one report for each violation is sent to that URI; essentially one report is sent to each distinct URI upon policy violation.
Report-duplication (or multiple reporting) is useful in the case where two different groups want to receive reports, but may not share access to the reports archive. Take for instance a large web company that has a separate sysadmin staff (who are also in charge of security at some level) and project teams. One project team may be interested in receiving reports about violations of their CSP, but are not interested in violations on other parts of the web site. The sysadmin team wants to record all violations from all parts of the site into a massive archive. The multiple reporting technique allows both entities to receive the reports they want without causing extra data-mining work on the part of the sysadmin team to isolate the reports that each project team may want.
Data Leak Vectors
Since HTTP headers and the entire request string are sent in the report, it is possible that, in case of compromise, a violation report could leak private information to an arbitrary URI. To avoid any possible cross-domain cookie or authentication token transfer, all reports must be sent to the same origin (scheme/host/port) that served the protected content.
Policy Refinement Procedure
Two headers present conflicting policies, they are resolved through a straightforward process: first the policies are made explicit (see below), then they are intersected, and the resulting policy is enforced. Through this process, the enforced policy will never be more lenient than either of the conflicting policies.
This refinement procedure is only followed if there are multiple instances of the X-Content-Security-Policy HTTP header present in the HTTP response.
Making a Policy Explicit
The CSP policy language allows implicit values for directives through use of the "allow" (default) policy directive. To make a policy explicit, the policy language is "expanded", or any missing directives are added with the value specified in the "allow" directive. This makes it easier to intersect policies and to enforce them, since all directives will have an explicit value.
Intersecting Policies
The core of combining two policies is essentially the creation of a new policy where any valid request will also satisfy both original policies. In essence, if one HTTP request is allowed by both policies in question, it will be allowed by the refined policy. If an HTTP request is disallowed by either specified policy it will be rejected by the refined policy.
In order to determine the intersection of two policies, the different directives are considered individually: for each directive in CSP, the values in both specified policies (A and B) are considered, and only those hosts allowed in both directive values are included in the intersection.
Handling Parse Errors
A number of different problems may be encountered while parsing the CSP policy. These parse errors are not policy violations, and any error messages caused by parse errors are separate from the violation report sites may elect to receive when their site's policies are violated, via the report-uri directive. Parse errors are only reported locally in the user agent.
- Unrecognized Directive
- If an unrecognized directive (name not recognized) is encountered by CSP, the directive and its value are skipped (up to a semicolon or end of header, whichever is first) and a warning message is logged to the Error Console stating the unrecognized directive name.
- Unrecognized options token
- If an unrecognized token is present in the options directive value, it is ignored and a warning message is logged to the Error Console stating the unrecognized token.
- Missing "allow"
- If the "allow" directive is not present, a warning message is logged to the Error Console and "allow none" is assumed by the policy. The rest of the policy is enforced as written assuming no other policy errors are encountered.
- Directive Syntax Error
- When any known directive contains a value that violates CSP syntax, Content Security Policy follows a "fail closed" security model and falls back to the most secure policy, "allow none".
- No Recognized Directives
- If no recognized directives are present in the stated policy, a warning message will be logged to the Error Console stating "invalid policy", and CSP will enforce the policy "allow none".
- Other Parsing Errors
- Any other parsing errors not covered here may cause CSP to fail closed. If such a case should arise, a message will be logged to the Error Console describing the violation.
Non-Normative Client-Side Considerations
- User Scripts
- CSP should not interfere with the operation of user-supplied scripts (such as browser add-ons and bookmarklets).
- Redirects to Content
- When a resource is requested from a URI X[0] protected by a policy CSP, that resource's URI is only loaded if permitted by CSP. If the URI X[0] resolves to an HTTP redirect of any kind (temporary or permanent) the new URI X[1] is also required to be permitted by the policy CSP. The effect is that all requests generated by the document must be permitted by the CSP whether they are the initial request or the steps taken during a redirect.
- Future Directives
- In order to support future directives (or new versions of this spec), CSP must parse but ignore directives with unknown names. When an unknown directive is encountered by the UA, a warning is posted to the error console, and the directive is ignored.
Report-Only mode
To ease deployment, CSP can be deployed in "report-only" mode where a policy served is not enforced, but any violations are reported to a provided URI. The effect is a "what if" scenario where a site can specify a policy and measure how much breaks.
Report-only mode is enabled by specifying a policy in the X-Content-Security-Policy-Report-Only header instead of the X-Content-Security-Policy header.
If both a X-Content-Security-Policy-Report-Only header and a X-Content-Security-Policy header are present in the same response, a warning is posted to the user agent's error console and any policy specified in X-Content-Security-Policy-Report-Only is ignored. The policy specified in X-Content-Security-Policy headers is enforced.
HTTP Server Behavior
HTTP Header Placement
The X-Content-Security-Policy HTTP Response header should be present in the Message Headers section of a server's HTTP response. Specifically, it must NOT appear in the Trailer Headers section of the response, so that the policy may be enforced as the rest of the page content loads. Multiple X-Content-Security-Policy Response headers will be considered; if more than one is present, the intersection of the policies is enforced.