Changes

Jump to: navigation, search

Security/CSP/Specification

1,033 bytes removed, 22:34, 8 March 2010
no edit summary
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.
=Background= [[Security/CSP|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 [[Security/CSP#Goals|goals]] section. TODO: It is straightforward to convert a web site into one that can support CSP without loss of functionality. For more information, see [[Converting Your Site to CSP]]. =TerminologyDefinitions=
A <b>policy</b> is composed of <b>directives</b>, such as "<tt>allow none</tt>". Each directive is composed of a <b>directive name</b> and a <b>directive value</b>, which is either a list of <b>host items</b> or a <b>URI</b>, for certain types of directives.
When CSP is activated for a site, a few <b>[[Security/CSP#Content_Restrictions|refinementsbase restrictions]]</b> to in the browser environment are made enforced <i>no matter the policyby default</i> to help provide proper enforcement of any policy defined. These refinements base restrictions provide general security enhancements by placing restrictions on limiting the types of dynamic content that is allowed: generally any script on a site that converts text into code (through the use of <tt>eval()</tt> or similar functions) is disallowed. Details of the refinements can be found in the [[Security/CSP/Specification#Content_RestrictionsBase_Restrictions|Content Base Restrictions]] section.
=Content Restrictions=Policy Language and Syntax==
The main goal of Content Security Policy A policy is to prevent malicious code from being injected into a website and executed within the context composed of that sitedirectives with their corresponding values. Hence Any number of directives can be defined, a recurring theme in CSP is to prevent but the creation of script code from potentially tainted strings<b><tt>allow</tt> directive must always be present</b>. It should be made clear that it Each directive is not the intent of CSP to prevent '''navigation to arbitrary sites''', but rather to restrict the types followed with a list of script, media, host expressions except for <tt>policy-uri</tt> and other resources that may be used on <tt>report-uri</tt> which contain a web pagesingle URI value. Some [[Security/CSP/Spec#Sample_Policy_Definitions|example policy sets]] are provided below.
The following restrictions will apply whenever any CSP directives are declared for Note: In the case of policy refinements as described above, it is possible to have two report-uri values; in this situation, a document:copy of the report is sent to each of the two URIs.
==No inline scripts will execute==
<font color="#a00">
* 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()">
</font>
<font color="#060">
* Allowed:
** Script imported from external files hosted by white-listed sources and served with a Content-Type of <tt>application/javascript</tt> or <tt>application/json</tt>.
</font>
* 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 <tt>inline</tt> keyword to the [[Security/CSP/Spec#script-src|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 <tt>violated-directive</tt> value set to "Base Restriction Violation: no inline scripts will execute.".===Sample Policy Definitions===
==Code will not be created from strings==<font color="#a00"b>* RestrictedExample 1:** 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...")</fontb><font color="#060">* 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)</font>* Justification:** eval and related functions make trivial the task of generating code from strings, which commonly Site wants all content to 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.** Noteown domain: 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 X-out of this entire restriction by adding the <tt>evalContent-script</tt> keyword to the [[Security/CSP/Spec#options|options]] directive. This allows the blocked <tt>eval()</tt>, <tt>setTimeout()</tt>, <tt>setInterval()</tt>, and <tt>new Function()</tt> calls to proceed.* Vulnerability types mitigated-Policy:*# AJAX request tampering*# Improper use of dynamic propertiesallow 'self'
'''On Violation:''' a violation report will be sent with the <ttb>violated-directiveExample 2:</ttb> value set Auction site wants to "Base Restriction Violationallow 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: no code will be created with strings"allow 'self'; img-src *; \ object-src media1.com media2.com *.cdn.com; \ script-src trustedscripts.example.com
==No data: URIs unless opted-in to via explicit policy==<font color="#a00"b>* RestrictedExample 3:** data: URIs as a source for inline content</fontb><font color="#060">* AllowedServer 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):** data: URIs as a source for inline content when explicitly opted-in to, e.g. X-Content-Security-Policy: allow self*; imgscript-src data:'self'</font>* Justification:** The data X-Content-Security-Policy: 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: <tt>imgsrc 'self'; media-src data: https://my-host.com</tt>.'self';
==XBL bindings must come from chrome: or resource: URIs==
<font color="#a00">
* Restricted:
** XBL bindings loaded via any protocol other than chrome: or resource:
</font>
<font color="#060">
* Allowed:
** XBL bindings loaded via the chrome: or resource: protocols
</font>
* 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. &lt;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<font color="#a00"b>* 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 httpExample 4://other.tld/csp-report.cgi</fontb><font color="#060">* Allowed:** policy-uri directives which refer to a URI on the same host as the protected document, e.g. policy-uri http://same.Online payments 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</font>* 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 <tt>X-Content-Security-Policy</tt> 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 <tt>X-Content-Security-Policy</tt> HTTP header or a file served from the same host as the resource wants to be secured. The <tt>X-Content-Security-Policy</tt> header must either contain a policy definition <i>or</i> a <tt>policy-uri</tt> field; if both are present, the browser will raise a [[Security/CSP/Spec#Error_Handling|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. ==HTTP Header Placement==The <tt>X-Content-Security-Policy</tt> HTTP Response header should be present in the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 Message Headers] section of a server's HTTP response. Specifically, it must NOT appear in the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.40 Trailer Headers] section of the response, so ensure that the policy may be enforced as the rest all of the page content loads. Multiple <tt>X-Content-Security-Policy</tt> Response headers will be considered; if more than one is present, the intersection of the policies is enforced. ==Policy Refinements with Multiple Headers==When multiple instances of the <tt>X-Content-Security-Policy</tt> HTTP header are present in an HTTP response, the intersection of the policies its pages 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 loaded over SSL 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 prevent attackers from eavesdropping on a directive-by-directive basis (i.e., the intersection of the <tt>allow</tt> directive is taken and enforced as the <tt>allow</tt> part of the effective policy). Explicitly, requests for two policiesinsecure content<blockquote>define R<sub>1</sub> &equiv; all URIs accepted by the first HTTP header CSP<br/> define R<sub>2</sub> &equiv; all URIs accepted by the second HTTP header CSP<br/>  R<sub>e</sub> = {r | r &isin; R<sub>1</sub> AND r &isin; R<sub>2</sub>}<br/> (R<sub>e</sub> is the set of all URIs accepted by the intersected CSP)<br/></blockquote> If more than two instances of the <tt> X-Content-Security-Policy</tt> 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 (P<sub>1</sub>) may allow scripts from domains A, B and C. The policy in the other header (P<sub>2</sub>) may allow scripts from domains B, C and D. The policy enforced (P<sub>enforced</sub>) by the browser will allow scripts from domains B and C only (P<sub>enforced</sub> = P<sub>1</sub> &cap; P<sub>2</sub>). ===Why Intersect Policies?=== Because the <tt>X-Content-Security-Policy</tt> 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 conflicthttps#<b>Ignore both. Raise error in the console. Enforce "allow none" (most secure).</b><br/>Simplest and safest way to lock down when the policies conflict.#<b>Ignore both. Raise error in the console. Enforce "allow *" (most relaxed).</b><br/>This is a fail-open policy and will keep the site from breaking if two policies conflict.#<b>Use the first header's policy.</b>#<b>Use the second header's policy.</b>#<b>Enforce the intersection of the policies.</b><br/><i>This is the technique used by CSP</i>. For each URI that is accepted by <i>both</i> policies, the new intersected policy will also accept the URI. Any request that is not accepted by <i>both</i> 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 <tt>report-uri</tt> values===If multiple headers define policies with <tt>report-uri</tt> values, a single report is sent to each of the provided URIs. If any <tt>report-uri</tt> 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, <b>all reports must be sent to the same origin (scheme/host/port) that served the protected content</b>. ===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 <i>never be more lenient</i> than either of the conflicting policies. [[Image:CSP_Policy_Refinement_Overview.png|Policy Refinement Overview]] This refinement procedure is only followed if there are multiple instances of the <tt>X-Content-Security-Policy</tt> 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. [[Image:CSP_Policy_Explicification.png|Making a policy explicit]] ====Intersecting Policies==== The core of combining two policies is essentially the creation of a <i>new policy where any valid request will also satisfy both original policies</i>. 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 <i>disallowed by either specified policy</i> it will be rejected by the refined policy. [[Image:CSP_Policy_Intersect.png|Intersecting two explicit CSPs]] 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.  [[Image:CSP_Directive_Intersect.png|Intersecting two directives]] =Policy Language and Syntax=443
A policy is composed of directives with their corresponding values. Any number of directives can be defined, but the <b><tt>allow</tt> directive must always be present</b>. Each directive is followed with a list of host expressions except for <tt>policy-uri</tt> and <tt>report-uri</tt> which contain a single URI value. Some [[Security/CSP/Spec#Sample_Policy_Definitions|example policy sets]] are provided below.===Directives===
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. ==Directives== ==allow=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.
* If the allow directive is not explicitly specified, no content from any source will be loaded. This is equivalent to the policy "allow 'none'".
* All HTTP requests not subject to one of the more specific directives are subject to the allow directive (including XMLHttpRequests).
====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:
* Any tokens not recognized by CSP are ''ignored'', and a non-fatal warning is posted to the error console.
====img-src====
* Indicates which sources are valid for images and favicons.
* Images from non-approved sources will not be requested or loaded.
* If img-src is not explicitly specified, image requests are subject to the allow directive.
====media-src====
* 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 will not be requested or loaded.
* If media-src is not explicitly specified, media requests are subject to the allow directive.
====script-src====
* Indicates which sources are valid for scripts.
* Only scripts loaded via the <tt>src=</tt> attribute will be loaded
* Sites may opt-out of the [[Security/CSP/Spec#Code_will_not_be_created_from_strings|"No code from strings"]] restriction by adding the <tt>'eval-script'</tt> token to the <tt>options</tt> directive
====object-src====
* Indicates which sources are valid for <tt>object</tt>, <tt>embed</tt>, and <tt>applet</tt> elements.
* Objects from non-approved sources will not be requested or loaded.
* If object-src is not explicitly specified, object requests are subject to the allow directive.
====frame-src====
* Indicates which sources are valid for <tt>frame</tt> and <tt>iframe</tt> elements.
* Answers the question: "Documents from which sources may be embedded in my resource?"
* If frame-src is not explicitly specified, frame requests are subject to the allow directive.
====font-src====
* Indicates which sources are valid for <tt>@font-src</tt> CSS loads.
* Fonts served from non-approved sources must not be requested for use as a font in CSS.
* If font-src is not explicitly specified, requests by <tt>@font-src</tt> are subject to the allow directive.
====xhr-src====
* Indicates which sources are valid for <tt>XMLHttpRequest</tt> connections.
* XMLHttpRequests may not be opened to sources not permitted by this directive.
* If xhr-src is not explicitly specified, requests by <tt>XMLHttpRequest</tt> objects are subject to the allow directive.
====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>.
* 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.
* If frame-ancestors is not explicitly specified, any site may embed the page employing this policy.
====style-src====
* Indicates which sources are valid for externally linked stylesheets.
* Inline stylesheets and style attributes of HTML tags are globally allowed.
* If style-src is not explicitly specified, stylesheet requests are subject to the allow directive.
====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.
* HTTP 3xx response codes are not honored by the user agent. No redirection from the Report URI is allowed to prevent HTTP header leakage across domains.
====policy-uri====
* Indicates the location of a file containing the security policies for the protected resource.
* <tt>policy-uri</tt> should only be defined in the absence of other policy definitions in the <tt>X-Content-Security-Policy</tt> HTTP header. If <tt>policy-uri</tt> is defined among other directives in the header, a [[Security/CSP#Error_Handling|console error]] is raised and the policy enforced by CSP is the most restrictive policy: "allow none".
* Policy URIs must be of the same origin (scheme/host/port) as the protected content. Relative URIs are acceptable, and are resolved within the same scheme, host and port as the document served with the CSP.
===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 "<tt>*.mozilla.com</tt>" and "<tt>mozilla.org</tt>". Internationalized domain names are specified according to their [http://tools.ietf.org/html/rfc3492 punycode representations].
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 <tt>data</tt> and <tt>javascript</tt> can be enabled as a source by stating the name of the scheme followed by a colon. For example:
;<tt>javascript:</tt>: allows javascript URIs
====Port Wildcards====
A wildcard "*" token may be used in place of the port number. This indicates that all ports (except [http://www.mozilla.org/projects/netlib/PortBanning.html banned ports]) are valid for the source. Examples:
;<tt>foo.com:*</tt>: 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.
A wildcard token (*) matches <i>zero or more DNS labels</i>. All of "<tt>d.c.b.a</tt>", "<tt>c.b.a</tt>", and "<tt>b.a</tt>" match the expression "<tt>*.b.a</tt>".
====Source Expression Keywords====
In place of source expressions, these keywords can be used to specify classes of sources.
; <tt>'self'</tt> : Refers to the source serving the protected content -- this is inclusive of scheme, host and port.
===Formal Policy Syntax===
<policy> ::= <allow-directive>";"<directive-list>
<empty> ::= ""
==Sample Policy Definitions== <b>Example 1:</b> Site wants all content to come from its own domain: X-Content-Security-Policy: allow 'self' <b>Example 2:</b> 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 <b>Example 3:</b> 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';  <b>Example 4:</b> 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 =User-Agent and Other 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 <tt>X-Content-Security-Policy-Report-Only</tt> header instead of the <tt>X-Content-Security-Policy</tt> header.  If both a <tt>X-Content-Security-Policy-Report-Only</tt> header and a <tt>X-Content-Security-Policy</tt> header are present in the same response, a warning is posted to the user agent's error console and any policy specified in <tt>X-Content-Security-Policy-Report-Only</tt> is ignored. The policy specified in <tt>X-Content-Security-Policy</tt> headers is enforced. =Violation Report Syntax==
CSP supports a reporting mechanism that allows browsers to notify content providers when their policy is violated. When a <tt>report-uri</tt> is provided and a policy is violated, information about the protected resource and the violating content is transmitted to the <tt>report-uri</tt> via HTTP POST if available in the employed scheme, otherwise an appropriate "submit" method is used. The user agent <i>must not</i> honor redirection responses. Such a report is an XML document containing the following fields:
The MIME type of the transmitted report will be set to <tt>application/xml</tt>.
===Violation Report Sample===
In this example, a page located at <tt>http://example.com/index.html</tt> was requested using HTTP 1.1 via the GET method. It provided a policy that included the directive "<tt>img-src self</tt>", which was violated by a request for <tt><nowiki>http://evil.com/some_image.png</nowiki></tt>. The sample XML data sent to the policy-specified <tt>report-uri</tt> follows.
</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===<font color="#a00">* 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()"></font><font color="#060">* Allowed:** Script imported from external files hosted by white-listed sources and served with a Content-Type of <tt>application/javascript</tt> or <tt>application/json</tt>.</font>* 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 <tt>inline</tt> keyword to the [[Security/CSP/Spec#script-src|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 <tt>violated-directive</tt> value set to "Base Restriction Violation: no inline scripts will execute.". ===Code will not be created from strings===<font color="#a00">* 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...")</font><font color="#060">* 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)</font>* 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 <tt>eval-script</tt> keyword to the [[Security/CSP/Spec#options|options]] directive. This allows the blocked <tt>eval()</tt>, <tt>setTimeout()</tt>, <tt>setInterval()</tt>, and <tt>new Function()</tt> calls to proceed.* Vulnerability types mitigated:*# AJAX request tampering*# Improper use of dynamic properties '''On Violation:''' a violation report will be sent with the <tt>violated-directive</tt> value set to "Base Restriction Violation: no code will be created with strings". ===No data: URIs unless opted-in to via explicit policy===<font color="#a00">* Restricted:** data: URIs as a source for inline content</font><font color="#060">* 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:</font>* 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: <tt>img-src data: https://my-host.com</tt>. ===XBL bindings must come from chrome: or resource: URIs===<font color="#a00">* Restricted:** XBL bindings loaded via any protocol other than chrome: or resource:</font><font color="#060">* Allowed:** XBL bindings loaded via the chrome: or resource: protocols</font>* 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. &lt;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<font color="#a00">* 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</font><font color="#060">* 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</font>* 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 <tt>X-Content-Security-Policy</tt> 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 <tt>X-Content-Security-Policy</tt> HTTP header or a file served from the same host as the resource to be secured. The <tt>X-Content-Security-Policy</tt> header must either contain a policy definition <i>or</i> a <tt>policy-uri</tt> field; if both are present, the browser will raise a [[Security/CSP/Spec#Error_Handling|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 <tt>X-Content-Security-Policy</tt> 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 <tt>allow</tt> directive is taken and enforced as the <tt>allow</tt> part of the effective policy). Explicitly, for two policies: <blockquote>define R<sub>1</sub> &equiv; all URIs accepted by the first HTTP header CSP<br/> define R<sub>2</sub> &equiv; all URIs accepted by the second HTTP header CSP<br/>  R<sub>e</sub> = {r | r &isin; R<sub>1</sub> AND r &isin; R<sub>2</sub>}<br/> (R<sub>e</sub> is the set of all URIs accepted by the intersected CSP)<br/></blockquote> If more than two instances of the <tt>X-Content-Security-Policy</tt> 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 (P<sub>1</sub>) may allow scripts from domains A, B and C. The policy in the other header (P<sub>2</sub>) may allow scripts from domains B, C and D. The policy enforced (P<sub>enforced</sub>) by the browser will allow scripts from domains B and C only (P<sub>enforced</sub> = P<sub>1</sub> &cap; P<sub>2</sub>). ===Why Intersect Policies?=== Because the <tt>X-Content-Security-Policy</tt> 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: #<b>Ignore both. Raise error in the console. Enforce "allow none" (most secure).</b><br/>Simplest and safest way to lock down when the policies conflict.#<b>Ignore both. Raise error in the console. Enforce "allow *" (most relaxed).</b><br/>This is a fail-open policy and will keep the site from breaking if two policies conflict.#<b>Use the first header's policy.</b>#<b>Use the second header's policy.</b>#<b>Enforce the intersection of the policies.</b><br/><i>This is the technique used by CSP</i>. For each URI that is accepted by <i>both</i> policies, the new intersected policy will also accept the URI. Any request that is not accepted by <i>both</i> 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 <tt>report-uri</tt> values===If multiple headers define policies with <tt>report-uri</tt> values, a single report is sent to each of the provided URIs. If any <tt>report-uri</tt> 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, <b>all reports must be sent to the same origin (scheme/host/port) that served the protected content</b>. ===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 <i>never be more lenient</i> than either of the conflicting policies. [[Image:CSP_Policy_Refinement_Overview.png|Policy Refinement Overview]] This refinement procedure is only followed if there are multiple instances of the <tt>X-Content-Security-Policy</tt> 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. [[Image:CSP_Policy_Explicification.png|Making a policy explicit]] ====Intersecting Policies==== The core of combining two policies is essentially the creation of a <i>new policy where any valid request will also satisfy both original policies</i>. 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 <i>disallowed by either specified policy</i> it will be rejected by the refined policy. [[Image:CSP_Policy_Intersect.png|Intersecting two explicit CSPs]] 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.  [[Image:CSP_Directive_Intersect.png|Intersecting two directives]]   ==Handling Parse Errors==
A number of different problems may be encountered while parsing the CSP policy.
These parse errors are not <em>policy violations</em>, and any error messages caused by parse errors are separate from the violation report sites may elect to receive when their site's <em>policies are violated</em>, via the report-uri directive. Parse errors are only reported locally in the user agent.
;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 <tt>X-Content-Security-Policy-Report-Only</tt> header instead of the <tt>X-Content-Security-Policy</tt> header.
 
If both a <tt>X-Content-Security-Policy-Report-Only</tt> header and a <tt>X-Content-Security-Policy</tt> header are present in the same response, a warning is posted to the user agent's error console and any policy specified in <tt>X-Content-Security-Policy-Report-Only</tt> is ignored. The policy specified in <tt>X-Content-Security-Policy</tt> headers is enforced.
 
 
=HTTP Server Behavior=
 
==HTTP Header Placement==
The <tt>X-Content-Security-Policy</tt> HTTP Response header should be present in the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 Message Headers] section of a server's HTTP response. Specifically, it must NOT appear in the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.40 Trailer Headers] section of the response, so that the policy may be enforced as the rest of the page content loads. Multiple <tt>X-Content-Security-Policy</tt> Response headers will be considered; if more than one is present, the intersection of the policies is enforced.
Canmove, confirm
1,537
edits

Navigation menu