Copyright © 2014 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.
This document defines a policy language used to declare a set of content restrictions for a web resource, and a mechanism for transmitting the policy from a server to a client where the policy is enforced.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This document was published by the Web Application Security Working Group as a Candidate Recommendation. This document is intended to become a W3C Recommendation.
The (archived) public mailing list public-webappsec@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “CSP2” in the subject, preferably like this: “[CSP2] …summary of comment…”
Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
The entrance criteria for this document to enter the Proposed Recommendation stage is to have a minimum of two independent and interoperable user agents that implementation all the features of this specification, which will be determined by passing the user agent tests defined in the test suite developed by the Working Group.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 1 August 2014 W3C Process Document.
The following features are at-risk, and may be dropped during the CR period:
This section is not normative.
This document defines Content Security Policy, a mechanism web applications can use to mitigate a broad class of content injection vulnerabilities, such as cross-site scripting (XSS). Content Security Policy is a declarative policy that lets the authors (or server administrators) of a web application inform the client about the sources from which the application expects to load resources.
To mitigate XSS attacks, for example, a web application can declare that it only expects to load script from specific, trusted sources. This declaration allows the client to detect and block malicious scripts injected into the application by an attacker.
Content Security Policy (CSP) is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth, to reduce the harm caused by content injection attacks. As a first line of defense against content injection, server operators should validate their input and encode their output.
There is often a non-trivial amount of work required to apply CSP to an existing web application. To reap the greatest benefit, authors will need to move all inline script and style out-of-line, for example into external scripts, because the user agent cannot determine whether an inline script was injected by an attacker.
To take advantage of CSP, a web application opts into using CSP by supplying a
Content-Security-Policy
HTTP header. Such policies apply to the
current resource representation only. To supply a policy for an entire site,
the server needs to supply a policy with each resource representation.
This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes, and adds support for a number of new directives and capabilities which are summarized below:
Note: Paths are technically new in CSP2, but they were already implemented in many user agents before this revision of CSP was completed, so noting the change here seems reasonable.
unsafe-redirect
expression.
child-src
rather than
script-src
.
base-uri
controls the protected
resource’s ability to specify the document base
URL.
child-src
deprecates and replaces
frame-src
, controlling the protected
resource’s ability to embed frames, and to load Workers.
form-action
controls the protected
resource’s ability to submit forms.
frame-ancestors
controls the protected
resource’s ability be embedded in other documents. It is meant
to supplant the X-Frame-Options
HTTP request header.
plugin-types
controls the protected
resource’s ability to load specific types of plugins.
referrer
controls the protected resource’s
referrer policy [REFERRER].
reflected-xss
controls the user agent’s built-in
heuristics to actively protect against XSS. It is meant to supplant
the X-XSS-Protection
HTTP request header.
CSP
request header is now sent with relevant requests, as
described in §3.4 The CSP
HTTP Request Header.
SecurityPolicyViolationEvent
is fired upon violations, as described
in §6.3 Firing Violation Events.
report-uri
, and those handed to the DOM via
SecurityPolicyViolationEvent
events. These include
effectiveDirective
, statusCode
, sourceFile
, lineNumber
,
columnNumber
.
This section defines several terms used throughout the document.
The term security policy refers to either:
The security policies defined by this document are applied by a user agent on a per-resource representation basis. Specifically, when a user agent receives a policy along with the representation of a given resource, that policy applies to that resource representation only. This document often refers to that resource representation as the protected resource.
A security policy
directive is a portion of a policy that declares the specific
set of restrictions for a particular resource type, or which manipulates a
specific aspect of a protected resource’s configuration. A server transmits
its security policy for a particular protected resource as a collection of
directives, such as default-src 'self'
, each of which
declares a specific set of restrictions for that resource as instantiated
by the user agent. More details are provided in the
§7 Directives section.
A directive consists of a directive name, which indicates the privileges controlled by the directive, and a directive value, which specifies the restrictions the policy imposes on those privileges.
The term origin is defined in the Origin specification. [RFC6454]The term globally unique identifier is defined in section 4 of the Origin specification. Note that URLs that do not use hierarchical elements as naming authorities have origins which are globally unique identifiers. [RFC6454]
The term URI is defined in the URI specification. [URI]
The term resource representation is defined Section 3 of HTTP/1.1 -- Semantics and Content [RFC7231]
The terms JSON object and JSON stringification are defined in the JSON specification. [RFC4627]
The applet
, audio
,
embed
, iframe
,
img
, link
,
object
, script
,
source
, track
, and
video
elements are defined in the HTML5
specification. [HTML5]
The terms auxiliary browsing contexts, opener browsing context, and nested browsing contexts are defined in the HTML5 specification. [HTML5]
A plugin is defined in the HTML5 specification. [HTML5]
The <@font-face>
Cascading Style Sheets (CSS) rule is defined
in the CSS Fonts Module Level 3 specification. [CSS3-FONTS]
The XMLHttpRequest
object is defined in the
XMLHttpRequest
specification. [XMLHTTPREQUEST]
The WebSocket
object is defined in the WebSocket
specification. [WEBSOCKETS]
The EventSource
object is defined in the EventSource
specification. [EVENTSOURCE]
The Augmented Backus-Naur Form (ABNF) notation used in this document is specified in RFC5234. [ABNF]
This document also uses the ABNF extension "#rule" as defined in Section 7 of HTTP/1.1 -- Message Syntax and Routing. [RFC7230]
The following core rules are included by reference, as defined in
Appendix B.1
of [ABNF]: ALPHA
(letters), DIGIT
(decimal
0-9), WSP
(white space) and VCHAR
(printing
characters).
SHA-256, SHA-384, and SHA-512 are the digest algorithms defined by the NIST.
The runs a worker algorithm is defined in the Web Workers spec. [WORKERS]
The term callable refers to an object whose interface has one or more callers as defined in the Web IDL specification [WEBIDL].
An HTTP 200 response is defined in Section 6.3.1 of HTTP/1.1 -- Semantics and Content [RFC7231]
The server delivers the policy to the user agent via an HTTP response header or an HTML meta element. Servers are informed that requests are subject to a policy via an HTTP request header.
Content-Security-Policy
Header Field
The Content-Security-Policy
header field is
the preferred mechanism for delivering a policy.
"Content-Security-Policy:" 1#policy-token
For example:
Content-Security-Policy: script-src 'self'
A server MAY send more than one HTTP header field named
Content-Security-Policy
with a given resource
representation.
A server MAY send different Content-Security-Policy
header field values with different representations of the same
resource or with different resources.
Upon receiving an HTTP response containing at least one
Content-Security-Policy
header field, the user agent
MUST enforce each of the policies contained in each such
header field.
Content-Security-Policy-Report-Only
Header Field
The Content-Security-Policy-Report-Only
header field lets servers experiment with policies by monitoring (rather
than enforcing) a policy.
"Content-Security-Policy-Report-Only:" 1#policy-token
For example, server operators might wish to develop their security policy iteratively. The operators can deploy a report-only policy based on their best estimate of how their site behaves:
Content-Security-Policy-Report-Only: script-src 'self'; report-uri /csp-report-endpoint/
If their site violates this policy the user agent will send violation
reports to the URI specified in the policy’s report-uri
directive, but allow the violating resources to load regardless. Once a site
has confidence that the policy is appropriate, they can start enforcing the
policy using the Content-Security-Policy
header field.
A server MAY send more than one HTTP header field named
Content-Security-Policy-Report-Only
with a given
resource representation.
A server MAY send different
Content-Security-Policy-Report-Only
header field values
with different representations of the same resource or with different
resources.
Upon receiving an HTTP response containing at least one
Content-Security-Policy-Report-Only
header field, the
user agent MUST monitor each of the policies
contained in each such header field.
Note: The Content-Security-Policy-Report-Only
header is not supported inside a meta
element.
meta
Element
The server MAY supply a policy in an HTML meta
element with an http-equiv
attribute that
is a case insensitive match for the string
"Content-Security-Policy
". For example:
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">Add the following entry to the pragma directives for the
meta
element:
http-equiv="content-security-policy"
)
head
element is
not an ancestor of the meta
element, abort
these steps.meta
element lacks a
content
attribute, abort these
steps.content
attribute of the
meta
element.reflected-xss
,
report-uri
, and sandbox
directives from directive-set.Authors are strongly encouraged to place the
meta
element as early in the document as
possible to reduce the risk of content injection before a protective
policy can be read and enforced.
Note: A policy specified via a meta
element will be enforced along with any other policies active for the
protected resource, regardless of where they’re specified. The general
mechanism for determining the effect of enforcing multiple policies is
detailed in the §3.5 Enforcing multiple policies.
section.
Note: Modifications to the content
attribute of a meta
element after the
element has been parsed will be ignored.
Note: The Content-Security-Policy-Report-Only
header is not supported inside a meta
element.
CSP
HTTP Request HeaderThe CSP
header field indicates that a particular
request is subject to a policy, and its value is defined by the
following ABNF grammar:
"CSP:" 1#csp-header-value csp-header-value = *WSP "active"
If the user agent is monitoring or enforcing a policy
that includes directives whose value is a source list, and whose
source list contains the 'unsafe-redirect'
source expression,
then the user agent MUST send a header field named CSP
along with requests for resources whose origin does not
match the protected resource’s origin. The value of this header MUST
be active
.
The user agent MAY choose to send this header only if the request is for a
resource type which the active policy would effect. That is, given a policy
of img-src example.com 'unsafe-redirect'
, the user agent
would send CSP: active
along with requests for images, but
might choose not to send the header with requests for script.
Note: The central reason for including this header is that it hints to a
server that information about redirects might be leaked as a side-effect
of a page’s active policy. If this header is present, a server might decline
to redirect a logged-out user from example.com
to
accounts.example.com
, for example, as a malicious embedder
might otherwise be able to determine the user’s logged-in status.
This section is not normative.
The above sections note that when multiple policies are present,
each must be enforced or reported, according to its type. An example
will help clarify how that ought to work in practice. The behavior of
an XMLHttpRequest
might seem unclear given a site
that, for whatever reason, delivered the following HTTP headers:
Content-Security-Policy: default-src 'self' http://example.com http://example.net; connect-src 'none'; Content-Security-Policy: connect-src http://example.com/; script-src http://example.com/
Is a connection to example.com
allowed or not? The
short answer is that the connection is not allowed. Enforcing both
policies means that a potential connection would have to pass through
both unscathed. Even though the second policy would allow this
connection, the first policy contains connect-src
'none'
, so its enforcement blocks the connection. The impact is
that adding additional policies to the list of policies to enforce can
only further restrict the capabilities of the protected resource.
To demonstrate that further, consider a script tag on this page.
The first policy would lock scripts down to 'self'
,
http://example.com
and http://example.net
via the default-src
directive. The second, however,
would only allow script from http://example.com/
. Script
will only load if it meets both policy’s criteria: in this case, the only
origin that can match is http://example.com
, as both
policies allow it.
This section is not normative.
Policies are associated with an protected resource, and enforced or monitored for that resource. If a resource does not create a new execution context (for example, when including a script, image, or stylesheet into a document), then any policies delivered with that resource are discarded without effect. Its execution is subject to the policy or policies of the including context. The following table outlines examples of these relationships:
Resource Type | What policy applies? | |
---|---|---|
Top-level Contexts | HTML as a new, top-level browsing context | The policy delivered with the resource |
SVG, as a top-level document | Policy delivered with the resource | |
Embedded Contexts | Any resource included via iframe, object, or embed | The policy of the embedding resource controls what may be embedded. The embedded resource, however, is controlled by the policy delivered with the resource, or the policy of the embedding resource if the embedded resource is a globally unique identifier (or a srcdoc frame). |
SVG, as an embedded document | The policy delivered with the resource, or policy of the creating context if created from a globally unique identifier. | |
JavaScript, as a Worker, Shared Worker or Service Worker | The policy delivered with the resource, or policy of the creating context if created from a globally unique identifier | |
Subresources | SVG, inlined via svg | Policy of the including context |
SVG, as a resource document | Policy of the including context | |
HTML via XMLHttpRequest | Policy of the context that performed the fetch | |
Image via img element | Policy of the including context | |
JavaScript via a script element | Policy of the including context | |
SVG, via img | No policy; should be just as safe as JPG | |
SVG, as a WebFont | No policy; should be just as safe as WOFF |
A Content Security Policy consists of a U+003B SEMICOLON
(;
) delimited list of directives. Each directive
consists of a directive name and (optionally) a
directive value, defined by the following ABNF:
policy-token = [ directive-token *( ";" [ directive-token ] ) ] directive-token = *WSP [ directive-name [ WSP directive-value ] ] directive-name = 1*( ALPHA / DIGIT / "-" ) directive-value = *( WSP / <VCHAR except ";" and ","> )
To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:
;
):
Many CSP directives use a value consisting of a source list, defined in the ABNF grammar below.
Each source expression in the source list represents a
location from which content of the specified type can be retrieved.
For example, the source expression 'none'
represents
the empty set of URIs, and the source expression
'unsafe-inline'
represents content supplied inline in the
resource itself.
source-list = *WSP [ source-expression *( 1*WSP source-expression ) *WSP ] / *WSP "'none'" *WSP source-expression = scheme-source / host-source / keyword-source / nonce-source / hash-source scheme-source = scheme-part ":" host-source = [ scheme-part "://" ] host-part [ port-part ] [ path-part ] keyword-source = "'self'" / "'unsafe-inline'" / "'unsafe-eval'" / "'unsafe-redirect'" base64-value = 1*( ALPHA / DIGIT / "+" / "/" )*2( "=" ) nonce-value = base64-value hash-value = base64-value nonce-source = "'nonce-" nonce-value "'" hash-algo = "sha256" / "sha384" / "sha512" hash-source = "'" hash-algo "-" hash-value "'" scheme-part = <scheme production from RFC 3986, section 3.1> host-part = "*" / [ "*." ] 1*host-char *( "." 1*host-char ) host-char = ALPHA / DIGIT / "-" path-part = <path production from RFC 3986, section 3.3> port-part = ":" ( 1*DIGIT / "*" )
If the policy contains a nonce-source
expression, the
server MUST generate a fresh value for the nonce-value
directive at random and independently each time it transmits a policy.
This requirement ensures that the nonce-value
is
difficult for an attacker to predict.
The host-char
production intentionally contains only
ASCII characters; internationalized domain names cannot be entered
directly into a policy string, but instead MUST be Punycode-encoded
[RFC3492]. For example, the domain üüüüüü.de
would be
encoded as xn--tdaaaaaa.de
.
To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:
'none'
(including the quotation
marks), return the empty set.source-expression
, add the token to the set
of source expressions.Note: Characters like U+003B SEMICOLON (;
) and
U+002C COMMA (,
) cannot appear in source expressions
directly: if you’d like to include these characters in a source
expression, they must be percent
encoded as %3B
and %2C
respectively.
A URI is said to match a source expression if the following algorithm returns does match:
*
), and the URI’s scheme is not of a type
designating a globally unique identifier, (such as
blob:
, data:
, or filesystem:
)
then return does match.scheme-source
:
scheme-part
, return
does match.host-source
:
/
).scheme-part
that is not a case insensitive match for uri-scheme,
then return does not match.HTTP
, and
uri-scheme is not a case
insensitive match for either HTTP
or
HTTPS
HTTP
, and uri-scheme is
not a case insensitive match
for the scheme of the protected resource’s URI.host-part
is an U+002A ASTERISK character
(*
) and the remaining characters, including the
leading U+002E FULL STOP character (.
), are not a
case insensitive match for the rightmost characters of
uri-host, then return does not match.host-part
is not an U+002A ASTERISK
character (*
) and uri-host is not a
case insensitive match for the source expression’s
host-part
, then return does not
match.port-part
and uri-port is not the
default port for uri-scheme, then return does not
match.port-part
, then return does not match if
path-part
, and the URI is not the
result of a redirect, then:
path-part
’s percent-encoded characters./
), and
decoded-path is not a prefix of
uri-path, then return does not
match./
),
and decoded-path is not an exact match for
uri-path then return does not
match.'self'
(including the quotation marks),
then:
A URI is said to match a source list if the following conditions are met:
'unsafe-redirect'
.
*
).
Note: No URIs match an empty set of source expressions, such as the set
obtained by parsing the source list 'none'
.
This section is not normative.
As defined above, special URI schemes that refer to specific pieces of
unique content, such as "data:", "blob:" and "filesystem:" are
excluded from matching a policy of *
and must be
explicitly listed. Policy authors should note that the content of
such URIs is often derived from a response body or execution in a
Document context, which may be unsafe. Especially for the
default-src
and script-src
directives, policy authors should be aware that allowing "data:" URIs
is equivalent to unsafe-inline
and allowing "blob:" or
"filesystem:" URIs is equivalent to unsafe-eval
.
This section is not normative.
The rules for matching source expressions that contain paths
are simpler than they look: paths that end with the '/'
character match all files in a directory and its subdirectories. Paths
that do not end with the '/'
character match only one
specific file. A few examples should make this clear:
example.com
has no path,
and therefore matches any file served from that host.example.com/scripts/
matches any file in the scripts
directory of
example.com
, and any of its subdirectories. For
example, both https://example.com/scripts/file.js
and https://example.com/scripts/js/file.js
would
match.example.com/scripts/file.js
matches only the file
named file.js
in the scripts
directory
of example.com
.example.com/js
matches only the file named js
. In particular, note
that it would not match files inside a directory named
js
. Files like example.com/js/file.js
would be matched only if the source expression ended with a
trailing "/", as in example.com/js/
.Note: Query strings have no impact on matching: the source
expression example.com/file?key=value
matches all of
https://example.com/file
,
https://example.com/file?key=value
,
https://example.com/file?key=notvalue
, and
https://example.com/file?notkey=notvalue
.
To avoid leaking path information cross-origin (as discussed
in Egor Homakov’s
Using Content-Security-Policy for Evil),
the matching algorithm ignores the path component of a source
expression if the resource being loaded is the result of a
redirect. For example, given a page with an active policy of
img-src example.com not-example.com/path
:
https://not-example.com/not-path
would fail, as it doesn’t match the policy.https://example.com/redirector
would pass, as it matches example.com
.https://example.com/redirector
delivered a redirect response pointing to https://not-example.com/not-path
,
the load would succeed, as the initial URL matches example.com
,
and the redirect target matches not-example.com/path
if we ignore its path component.This restriction reduces the granularity of a document’s policy when redirects are in play, which isn’t wonderful, but given that we certainly don’t want to allow brute-forcing paths after redirects, it seems a reasonable compromise.
The relatively long thread "Remove paths from CSP?" from public-webappsec@w3.org has more detailed discussion around alternate proposals.
nonce
attribute
Nonce sources require a new attribute to be added to both
script
and style
elements: nonce
.
partial interface HTMLScriptElement { attribute DOMString nonce; };
nonce
content attribute.partial interface HTMLStyleElement { attribute DOMString nonce; };
nonce
content attribute.An element has a valid nonce for a set of source
expressions if the value of the element’s
nonce
attribute after
stripping
leading and trailing whitespace is a case-sensitive match for the
nonce-value
component of at least one
nonce-source
expression in set of source
expressions.
An element’s content is the script block’s
source for script
elements, or the
value of the element’s
textContent
IDL attribute for non-script
elements such as
style
.
The digest of element’s content for is the result of applying an algorithm to the element’s content.
To determine whether element has a valid hash for a set of source expressions, execute the following steps:
hash-source
expressions in set of source
expressions.hash-value
component of hash.Note: If an element has an invalid hash, it would be helpful if the user agent reported the failure to the author by adding a warning message containing the actual hash value.
The plugin-types
directive uses a value consisting
of a media type list.
Each media type in the media type list represents a specific type of resource that can be retrieved and used to instantiate a plugin in the protected resource.
media-type-list = media-type *( 1*WSP media-type ) media-type = <type from RFC 2045> "/" <subtype from RFC 2045>
To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:
media-type
, add the token to the
set of media types. Otherwise ignore the token.A media type matches a media type list if, and only if, the media type is a case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.
To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:
data
, blob
, or filesystem
), then
abort these steps, and return the ASCII serialization of
uri’s scheme.To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:
script-src
") even if that
directive does not explicitly appear in the policy, but is
implicitly activated via the default-src
directive.status-code
of the HTTP response that
contained the protected resource, if the protected resource was
obtained over HTTP. Otherwise, the number 0.default-src
directive
in the case of violations caused by falling back to the
default sources when enforcing
a directive.script-src
directive), the user agent MAY add the
following keys and values to violation:
source-file
on which
the violation occurred.source-file
on which
the violation occurred.Note: blocked-uri
will not contain the final location of a
resource that was blocked after one or more redirects. It instead will
contain only the location that the protected resource requested, before
any redirects were followed.
To send violation reports, the user agent MUST use an algorithm equivalent to the following:
csp-report
, whose value is the result of generating
a violation report object.POST
, with a Content-Type
header field
of application/csp-report
, and an entity body
consisting of report body. If the origin of
report URI is not the same as the
origin of the protected resource, the block cookies flag MUST also
be set. The user agent MUST NOT follow redirects when fetching this
resource. (Note: The user agent ignores the fetched resource.)
The task source for these
tasks is the Content Security Policy task
source.To report a violation, the user agent MUST:
Document
.Note: This section of the specification should not be interpreted as limiting user agents' ability to apply restrictions to violation reports in order to limit data leakage above and beyond what these algorithms specify.
To enforce a policy, the user agent MUST parse the policy and enforce each of the directives contained in the policy, where the specific requirements for enforcing each directive are defined separately for each directive (See §7 Directives, below).
Generally speaking, enforcing a directive prevents the protected resource from performing certain actions, such as loading scripts from URIs other than those indicated in a source list. These restrictions make it more difficult for an attacker to abuse an injection vulnerability in the resource because the attacker will be unable to usurp the resource’s privileges that have been restricted in this way.
Note: User agents may allow users to modify or bypass policy enforcement through user preferences, bookmarklets, third-party additions to the user agent, and other such mechanisms.
To monitor a policy, the user agent MUST parse the policy and monitor each of the directives contained in the policy.
Monitoring a directive does not prevent the protected resource from undertaking any actions. Instead, any actions that would have been prevented by the directives are allowed, but a violation report is generated and reported to the developer of the web application. Monitoring a policy is useful for testing whether enforcing the policy will cause the web application to malfunction.
A server MAY cause user agents to monitor one policy while enforcing
another policy by returning both Content-Security-Policy
and Content-Security-Policy-Report-Only
header fields.
For example, if a server operator may wish to enforce one policy but
experiment with a stricter policy, she can monitor the stricter policy while
enforcing the original policy. Once the server operator is satisfied that
the stricter policy does not break the web application, the server operator
can start enforcing the stricter policy.
If the user agent monitors or enforces a policy that does not contain any directives, the user agent SHOULD report a warning message in the developer console.
If the user agent monitors or enforces a policy that contains an unrecognized directive, the user agent SHOULD report a warning message in the developer console indicating the name of the unrecognized directive.
If the user agent monitors or enforces a policy that contains
a directive that contains a source list, then the user agent MUST set
a CSP
Request Header when requesting cross-origin
resources, as described in §3.4 The CSP
HTTP Request Header.
Whenever a user agent runs a worker:
data
, blob
, or filesystem
), then:
Content-Security-Policy
HTTP header containing the
value policy, the user agent MUST enforce
policy for the worker.Content-Security-Policy-Report-Only
HTTP header
containing the value policy, the user agent MUST
monitor policy for the worker.srcdoc
IFramesWhenever a user agent creates an iframe
srcdoc
document in a browsing context nested in the
protected resource, if the user agent is enforcing any policies
for the protected resource, the user agent MUST enforce those
policies on the iframe
srcdoc
document as well.
Whenever a user agent creates an iframe
srcdoc
document in a browsing context nested in the
protected resource, if the user agent is monitoring any policies for the
protected resource, the user agent MUST monitor those policies on
the iframe
srcdoc
document as well.
SecurityPolicyViolationEvent
Interface
[Constructor(DOMString type, optional SecurityPolicyViolationEventInit eventInitDict)] interface SecurityPolicyViolationEvent : Event { readonly attribute DOMString documentURI; readonly attribute DOMString referrer; readonly attribute DOMString blockedURI; readonly attribute DOMString violatedDirective; readonly attribute DOMString effectiveDirective; readonly attribute DOMString originalPolicy; readonly attribute DOMString sourceFile; readonly attribute DOMString statusCode; readonly attribute long lineNumber; readonly attribute long columnNumber; };
document-uri
property of violation reports for a description of this property.referrer
property of violation reports for a description of this property.blocked-uri
property of violation reports for a description of this property.violated-directive
property of violation reports for a description of this property.effective-directive
property of violation reports for a description of this property.original-policy
property of violation reports for a description of this property.status-code
property of violation reports for a description of this property.source-file
property of violation reports for a description of this property.line-number
property of violation reports for a description of this property.column-number
property of violation reports for a description of this property.SecurityPolicyViolationEventInit
Interface
dictionary SecurityPolicyViolationEventInit : EventInit { DOMString documentURI; DOMString referrer; DOMString blockedURI; DOMString violatedDirective; DOMString effectiveDirective; DOMString originalPolicy; DOMString sourceFile; long lineNumber; long columnNumber; };
document-uri
property of violation reports for a description of this property.referrer
property of violation reports for a description of this property.blocked-uri
property of violation reports for a description of this property.violated-directive
property of violation reports for a description of this property.effective-directive
property of violation reports for a description of this property.original-policy
property of violation reports for a description of this property.source-file
property of violation reports for a description of this property.line-number
property of violation reports for a description of this property.column-number
property of violation reports for a description of this property.To fire a violation event, the user agent MUST use an algorithm equivalent to the following:
securitypolicyviolation
using the
SecurityPolicyViolationEvent
interface
with the following initializations:
blockedURI
MUST be initialized to the value of
report object’s blocked-uri
key.documentURI
MUST be initialized to the value of
report object’s document-uri
key.effectiveDirective
MUST be initialized to the value of
report object’s effective-directive
key.originalPolicy
MUST be initialized to the value of
report object’s original-policy
key.referrer
MUST be initialized to the value of
report object’s referrer
key.violatedDirective
MUST be initialized to the value of
report object’s violated-directive
key.sourceFile
MUST be initialized to the value of
report object’s source-file
key.lineNumber
MUST be initialized to the value of
report object’s line-number
key.columnNumber
MUST be initialized to the value of
report object’s column-number
key.The task source for these tasks is the Content Security Policy task source.
This section describes the content security policy directives introduced in this specification. Directive names are case insensitive.
In order to protect against Cross-Site Scripting (XSS), web application authors SHOULD include:
script-src
and
object-src
directives, ordefault-src
directive, which covers both
scripts and plugins.In either case, authors SHOULD NOT include either
'unsafe-inline'
or data:
as valid sources in
their policies. Both enable XSS attacks by allowing code to be included
directly in the document itself; they are best avoided completely.
Redirects are another area of potential concern. Authors SHOULD NOT include
'unsafe-redirect'
as valid sources in their policies. It makes
it more difficult to reason about the complete set of resources that a policy
allows, especially given the path behavior outlined in the
§4.2.2.3 Paths and Redirects section.
base-uri
The base-uri
directive restricts the URIs that can
be used to specify the document base URL. The syntax for
the name and value of the directive are described by the following ABNF
grammar:
directive-name = "base-uri" directive-value = source-list
The term allowed base URIs refers to the result of
parsing the base-uri
directive’s
value as a source list.
Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:
child-src
The child-src
directive governs the creation of
nested browsing contexts as well as Worker execution
contexts. The syntax for the name and value of the directive are described
by the following ABNF grammar:
directive-name = "child-src" directive-value = source-list
The term allowed child sources refers to the result of
parsing the child-src
directive’s value as a source list if a child-src
directive is explicitly specified, and otherwise to the
default sources.
To enforce the child-src
directive the user agent MUST
enforce the frame-src
directive.
Whenever the user agent fetches a URL while processing the
Worker
or SharedWorker
constructors
[WORKERS], the user agent MUST act as if there was a fatal network
error and no resource was obtained, and report a violation
if the URI does not match the
allowed child sources.
connect-src
The connect-src
directive restricts which URIs the
protected resource can load using script interfaces. The syntax for the name
and value of the directive are described by the following ABNF grammar:
directive-name = "connect-src" directive-value = source-list
The term allowed connection targets refers to the result of
parsing the connect-src
directive’s value as a source list if the policy contains an
explicit connect-src
directive, or otherwise to the
default sources.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed connection targets, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
send()
method of an XMLHttpRequest
object.WebSocket
constructor.EventSource
constructor.sendBeacon()
method [BEACON]This section is not normative.
JavaScript offers a few mechanisms that directly connect to an
external server to send or receive information. EventSource
maintains an open HTTP connection to a server in order to receive push
notifications, WebSockets
open a bidirectional communication
channel between your browser and a server, and XMLHttpRequest
makes arbitrary HTTP requests on your behalf. These are powerful APIs that
enable useful functionality, but also provide tempting avenues for data
exfiltration.
The connect-src
directive allows you to ensure that
these sorts of connections are only opened to origins you trust.
Sending a policy that defines a list of source expressions for this
directive is straightforward. For example, to limit connections to
only example.com
, send the following header:
Content-Security-Policy: connect-src example.com
All of the following will fail with the preceding directive in place:
new WebSocket("wss://evil.com/");
(new XMLHttpRequest()).open("GET", "https://evil.com/", true);
new EventSource("https://evil.com");
default-src
The default-src
directive sets a default
source list for a number of directives. The syntax for the name and
value of the directive are described by the following ABNF grammar:
directive-name = "default-src" directive-value = source-list
Let the default sources be the result of
parsing the default-src
directive’s value as a source list if a default-src
directive is explicitly specified, and otherwise the U+002A ASTERISK
character (*).
To enforce the default-src
directive, the user agent
MUST enforce the following directives:
If not specified explicitly in the policy, the directives listed above will use the default sources as their source list.
This section is not normative.
default-src
, as the name implies, serves as a default
source list which the other source list-style directives will use as
a fallback if they’re not otherwise explicitly set. That is, consider
the following policy declaration:
Content-Security-Policy: default-src 'self'
Under this policy, fonts, frames, images, media, objects, scripts, and styles will all only load from the same origin as the protected resource, and connections will only be made to the same origin. Adding a more specific declaration to the policy would completely override the default source list for that resource type.
Content-Security-Policy: default-src 'self'; script-src example.com
Under this new policy, fonts, frames, and etc. continue to be load
from the same origin, but scripts will only load from
example.com
. There’s no inheritance; the
script-src
directive sets the allowed sources of
script, and the default list is not used for that resource type.
Given this behavior, one good way of building a policy for a site
would be to begin with a default-src
of
'none'
, and to build up a policy from there that contains
only those resource types which are actually in use for the page you’d
like to protect. If you don’t use webfonts, for instance, there’s no
reason to specify a source list for font-src
;
specifying only those resource types a page uses ensures that the
possible attack surface for that page remains as small as possible.
font-src
The font-src
directive restricts from where the
protected resource can load fonts. The syntax for the name and value
of the directive are described by the following ABNF grammar:
directive-name = "font-src" directive-value = source-list
The term allowed font sources refers to the result of
parsing the font-src
directive’s value as a source list if the policy contains an
explicit font-src
, or otherwise to the
default sources.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed font sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
form-action
The form-action
restricts which URIs can be used as
the action of HTML form
elements. The syntax for the name and
value of the directive are described by the following ABNF grammar:
directive-name = "form-action" directive-value = source-list
The term allowed form actions refers to the result of
parsing the form-action
directive’s value as a source list.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed form actions, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
form
element.Note: form-action
does not fall back to the default
sources when the directive is not defined. That is, a policy that
defines default-src 'none'
but not
form-action
will still allow form submissions to any
target.
frame-ancestors
The frame-ancestors
directive indicates whether the
user agent should allow embedding the resource using a
frame
, iframe
,
object
, embed
or
applet
tag, or equivalent
functionality in non-HTML resources. Resources can use this directive to
avoid many UI Redressing [UIREDRESS] attacks by avoiding being embedded
into potentially hostile contexts.
The syntax for the name and value of the directive are described by the following ABNF grammar:
ancestor-source-list = [ ancestor-source *( 1*WSP ancestor-source ) ] / "'none'" ancestor-source = scheme-source / host-source directive-name = "frame-ancestors" directive-value = ancestor-source-list
The term allowed frame ancestors refers to the result of
parsing the frame-ancestors
directive’s value as a source list. If a frame-ancestors
directive is not explicitly included in the policy, then allowed frame
ancestors is "*
".
To enforce the frame-ancestors
directive, whenever the
user agent would load the protected resource into a nested browsing
context, the user agent MUST perform the following steps:
Steps 2.2 and 2.3 ensure that the blocked frame appears to be a normal cross-origin document’s load. If these steps are ignored, leakage of a document’s policy state is possible. The user agent MAY implement these steps by instead redirecting the user to friendly error page in a unique origin which provides the option of opening the blocked page in a new top-level browsing context.
The frame-ancestors
directive MUST be ignored
when monitoring a policy, and when a contained in a
policy defined via a meta
element.
Note: frame-ancestors
does not fall back to the
default sources when the directive is not defined. That is, a policy
that defines default-src 'none'
but not
frame-ancestors
will still allow the resource to be framed from
anywhere.
When generating a violation report for a frame-ancestors
violation, the user agent MUST NOT include the value of the embedding
ancestor as a blocked-uri
value unless it is same-origin with
the protected resource, as disclosing the value of cross-origin ancestors
is a violation of the Same-Origin Policy.
X-Frame-Options
This directive is similar to the X-Frame-Options
header that
several user agents have implemented. The 'none'
source
expression is roughly equivalent to that header’s DENY
,
'self'
to SAMEORIGIN
, and so on. The major
difference is that many user agents implement SAMEORIGIN
such
that it only matches against the top-level document’s location. This
directive checks each ancestor. If any ancestor doesn’t match, the load
is cancelled. [RFC7034]
The frame-ancestors
directive obsoletes the
X-Frame-Options
header. If a resource has both policies,
the frame-ancestors
policy SHOULD be enforced and the
X-Frame-Options
policy SHOULD be ignored.
This section is not normative.
Multiple source-list expressions are allowed in a single policy (in contrast
to X-Frame-Options
, which allows only one) to enable
scenarios involving embedded application components that are multiple levels
below the top-level browsing context.
Many common scenarios for permissioned embedding (e.g. embeddable payment,
sharing or social apps) involve potentially many hundreds or thousands of
valid source-list
expressions, but it is strongly recommended
against accommodating such scenarios with a static
frame-ancestors
directive listing multiple values. In such
cases it is beneficial to generate this value dynamically, based on an
HTTP Referer header or an explicitly passed-in value, to allow only the
sources necessary for each given embedding of the resource.
Consider a service providing a payments application at
https://payments/makeEmbedded
. The service allows this resource
to be embedded by both merchant Alice and merchant Bob, who compete with each
other. Sending:
Content-Security-Policy: frame-ancestors https://alice https://bob
would allow Bob to re-frame Alice’s resource and create fraudulent clicks,
perhaps discrediting Alice with her customers or the payments service. If the
payments service used additional information (e.g. as part of a URL like
https://payments/makeEmbedded?merchant=alice
) to send
individually-tailored headers listing only the source-list expressions
needed by each merchant, this attack would be eliminated.
frame-src
The frame-src
directive is deprecated.
Authors who wish to govern nested browsing contexts SHOULD use the
child-src
directive instead.
The frame-src
directive restricts from where the
protected resource can embed frames. The syntax for the name
and value of the directive are described by the following ABNF
grammar:
directive-name = "frame-src" directive-value = source-list
The term allowed frame sources refers to the result of
parsing the frame-src
directive’s value as a source list if the policy contains an
explicit frame-src
, or otherwise to the list of
allowed child sources.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed frame sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
iframe
or
a frame
element.img-src
The img-src
directive restricts from where the
protected resource can load images. The syntax for the name and value
of the directive are described by the following ABNF grammar:
directive-name = "img-src" directive-value = source-list
The term allowed image sources refers to the result of
parsing the img-src
directive’s value as a source list if the policy contains an
explicit img-src
, or otherwise to the list of
default sources.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed image sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
src
or
srcset
attributes of an
img
element, the
src
attribute of an
input
element with a type of
image
,
the poster
attribute of a
video
element,
the url(), <image()> or <image-set()> values on any
Cascading Style Sheets (CSS)
property that is capable of loading an image [CSS4-IMAGES], or
the href
attribute of a
link
element with an image-related
rel
attribute, such as
icon
.media-src
The media-src
directive restricts from where the
protected resource can load video, audio, and associated text tracks.
The syntax for the name and value of the directive are described by the
following ABNF grammar:
directive-name = "media-src" directive-value = source-list
The term allowed media sources refers to the result of
parsing the media-src
directive’s value as a source list if the policy contains an
explicit media-src
, or otherwise to the list of
default sources.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed media sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
object-src
The object-src
directive restricts from where
the protected resource can load plugins. The syntax for the name and value
of the directive are described by the following ABNF grammar:
directive-name = "object-src" directive-value = source-list
The term allowed object sources refers to the result of
parsing the object-src
directive’s value as a source list if the policy contains an
explicit object-src
, or otherwise to the list of
default sources.
Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed object sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
data
attribute of an
object
element, the
src
attribute of an
embed
elements, or the
code
or
archive
attributes of an
applet
element.object
or an embed
element.It is not required that the consumer of the element’s data be a
plugin in order for the object-src
directive to be
enforced. Data for any object
,
embed
, or applet
element MUST match the allowed object sources in order to be fetched.
This is true even when the element data is semantically equivalent to
content which would otherwise be restricted by one of the other
directives, such as an
object
element with a text/html
MIME type.
Whenever the user agent would load a plugin without an associated
URI (e.g., because the object
element lacked a
data
attribute), if the protected resource’s URI does not
match the allowed object sources,
the user agent MUST NOT load the plugin.
plugin-types
The plugin-types
directive restricts the set
of plugins that can be invoked by the protected resource by limiting
the types of resources that can be embedded. The syntax for the name
and value of the directive are described by the following ABNF
grammar:
directive-name = "plugin-types" directive-value = media-type-list
The term allowed plugin media types refers to the result of
parsing the plugin-types
directive’s value as a media type list.
Whenever the user agent would instantiate a plugin
to handle resource while enforcing the plugin-types
directive, the user agent MUST instead act as though the plugin reported an
error and report a violation if any of the following
conditions hold:
object
or
embed
element that does not explicitly
declare a MIME type via a
type
attribute.object
or
embed
element, and the media type declared
in the element’s type
attribute is not
a case-insensitive match for the resource’s media
type.applet
element, and resource’s
media type is not a case-insensitive match for
application/x-java-applet
.Note: In any of these cases, acting as though the plugin reported an error will cause the user agent to display the fallback content.
Whenever the user agent creates a plugin document in a
nested browsing context in the protected resource, if the user
agent is enforcing any plugin-types
directives for the
protected resource, the user agent MUST enforce those
plugin-types
directives on the plugin document as well.
Whenever the user agent creates a plugin document in a
nested browsing context in the protected resource, if the user
agent is monitoring any plugin-types
directives for the
protected resource, the user agent MUST monitor those
plugin-types
directives on the plugin document as well.
This section is not normative.
The plugin-types
directive whitelists a certain set
of MIME types that can be embedded in a protected resource. For
example, a site might want to ensure that PDF content loads, but that
no other plugins can be instantiated. The following directive would
satisfy that requirement:
Content-Security-Policy: plugin-types application/pdf
Resources embedded via an embed
or
object
element delivered with an
application/pdf
content type would be rendered in the
appropriate plugin; resources delivered with some other content type
would be blocked. Multiple types can be specified, in any order. If the
site decided to additionally allow Flash at some point in the future, it
could do so with the following directive:
Content-Security-Policy: plugin-types application/pdf application/x-shockwave-flash
Note: Wildcards are not accepted in the plugin-types
directive. Only the resource types explicitly listed in the directive
will be allowed.
This section is not normative.
Enforcing the plugin-types
directive requires that
object
and embed
elements declare the expected media type of the resource they include via
the type
attribute. If an author expects
to load a PDF, she could specify this as follows:
<object data="resource" type="application/pdf"></object>
If resource isn’t actually a PDF file, it won’t load. This prevents certain types of attacks that rely on serving content that unexpectedly invokes a plugin other than that which the author intended.
Note: resource will not load in this scenario even if its media type is otherwise whitelisted: resources will only load when their media type is whitelisted and matches the declared type in their containing element.
referrer
The referrer
directive specifies the referrer
policy [REFERRER] that the user agent applies when determining what
referrer information should be included with requests made, and with
browsing contexts created from the context of the
protected resource. The syntax for the name and value of the directive
are described by the following ABNF grammar:
directive-name = "referrer" directive-value = "no-referrer" / "no-referrer-when-downgrade" / "origin" / "origin-when-cross-origin" / "unsafe-url"
Note: The directive name does not share the HTTP header’s misspelling.
When enforcing the referrer
directive, the user agent
MUST execute [REFERRER]'s
Set environment’s referrer policy to policy.
algorithm on the protected resource’s JavaScript global
environment using the result of executing the
Determine token’s Policy
algorithm on the referrer
directive’s value.
This section is not normative.
A protected resource can prevent referrer leakage by specifying
no-referrer
as the value of its policy’s
referrer
directive:
Content-Security-Policy: referrer no-referrer;
This will cause all requests made from the protected resource’s
context to have an empty Referer
[sic] header.
reflected-xss
The reflected-xss
directive instructs a user agent
to activate or deactivate any heuristics used to filter or block
reflected cross-site scripting attacks. The syntax for the name and
value of the directive are described by the following ABNF grammar:
directive-name = "reflected-xss" directive-value = "allow" / "block" / "filter"
A user agent with support for XSS protection MUST enforce this directive as follows:
allow
, the user
agent MUST disable its active protections against reflected cross-site
scripting attacks for the protected resource.filter
, the user
agent MUST enable its active protections against reflected cross-site
scripting attacks for the protected resource. This might result in
filtering script that is believed to be reflected being filtered or
selectively blocking script execution.block
, the user
agent MUST stop rendering the protected resource upon detection of
reflected script, and instead act as if there was a fatal network
error and no resource was obtained, and report a
violation:
If the user agent’s active protections against reflected cross-site scripting attacks detect or prevent script execution, the user agent MUST report a violation.
Note: The reflected-xss
directive will be ignored if
contained within a
meta
element.
X-XSS-Protection
This directive is meant to subsume the functionality provided by
the proprietary X-XSS-Protection
HTTP header which is
supported by a number of user agents. Roughly speaking:
reflected-xss allow
is equivalent to
X-XSS-Protection: 0
reflected-xss filter
is equivalent to
X-XSS-Protection: 1
reflected-xss block
is equivalent to
X-XSS-Protection: 1; mode=block
report-uri
The report-uri
directive specifies a URI to
which the user agent sends reports about policy violation. The syntax
for the name and value of the directive are described by the following
ABNF grammar:
directive-name = "report-uri" directive-value = uri-reference *( 1*WSP uri-reference ) uri-reference = <URI-reference from RFC 3986>
The set of report URIs is the value of the
report-uri
directive, each resolved relative to the
protected resource’s URI.
The process of sending violation reports to the URIs specified in this directive’s value is defined in this document’s §4.4 Reporting section.
Note: The report-uri
directive will be ignored if contained
within a meta
element.
sandbox
The sandbox
directive specifies an HTML
sandbox policy that the user agent applies to the protected resource.
The syntax for the name and value of the directive are described by
the following ABNF grammar:
directive-name = "sandbox" directive-value = "" / sandbox-token *( 1*WSP sandbox-token ) sandbox-token = <token from RFC 7230>
When enforcing the sandbox
directive, the user agent
MUST parse a sandboxing directive using the
directive-value
as the input and protected
resource’s forced sandboxing flag set
as the output. [HTML5]
Note: The sandbox
directive will be ignored when
monitoring a policy, and when contained in a policy defined via a
meta
element.
This section is not normative.
HTML5 defines a sandbox
attribute for
iframe
elements, intended to allow web authors
to reduce the risk of including potentially untrusted content by imposing
restrictions on that content’s abilities. When the attribute is set,
the content is forced into a unique origin, prevented from submitting
forms, running script, creating or navigating other browsing contexts,
and prevented from running plugins. These restrictions can be loosened
by setting certain flags as the attribute’s value.
The sandbox
directive allows any resource, framed or
not, to ask for the same sorts of restrictions to be applied to
itself.
For example, a message board or email system might provide
downloads of arbitrary attachments provided by other users. Attacks
that rely on tricking a client into rendering one of these attachments
could be mitigated by requesting that resources only be rendered in a
very restrictive sandbox. Sending the sandbox
directive
with an empty value establishes such an environment:
Content-Security-Policy: sandbox
More trusted resources might be allowed to run in an environment
with fewer restrictions by adding allow-*
flags to the
directive’s value. For example, you can allow a page that you trust
to run script, while ensuring that it isn’t treated as same-origin
with the rest of your site. This can be accomplished by sending the
sandbox
directive with the
allow-scripts
flag:
Content-Security-Policy: sandbox allow-scripts
The set of flags available to the CSP directive should match those
available to the iframe
attribute.
Currently, those include:
allow-forms
allow-pointer-lock
allow-popups
allow-same-origin
allow-scripts
, andallow-top-navigation
Note: Like the rest of Content Security Policy, the sandbox
directive is meant as a defense-in-depth. Web authors would be well-served
to use it in addition to standard sniffing-mitigation and
privilege-reduction techniques.
script-src
The script-src
directive restricts which scripts the
protected resource can execute. The directive also controls other resources,
such as XSLT style sheets [XSLT], which can cause the user agent to
execute script. The syntax for the name and value of the directive are
described by the following ABNF grammar:
directive-name = "script-src" directive-value = source-list
The term allowed script sources refers to the result of
parsing the script-src
directive’s value as a source list if the policy contains an
explicit script-src
, or otherwise to the default
sources.
If 'unsafe-inline'
is not in the
list of allowed script sources, or if at least one
nonce-source
or hash-source
is
present in the list of allowed script sources:
script
element that lacks a valid nonce
and lacks a valid hash for the allowed script
sources, instead the user agent MUST NOT execute script, and
MUST report a violation.javascript
URI, instead the user agent MUST NOT execute
the script, and MUST report a violation.If 'unsafe-eval'
is not in allowed script
sources:
eval
and function eval
[ECMA-262]
MUST throw an EvalError
exception.Function
[ECMA-262] MUST throw an EvalError
exception.setTimeout()
function MUST
return zero without creating a timer.setInterval()
function MUST
return zero without creating a timer.Whenever the user agent fetches a URI (including when following redirects) in the course of one of the following activities, if the URI does not match the allowed script sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
src
attribute
of a script
element that lacks a
valid nonce for the allowed script sources.importScripts
method on a WorkerGlobalScope object. [WORKERS]href
attribute of a link
element with a rel
attribute containing the token
import
. [HTML-IMPORTS]<?xml-stylesheet?>
processing directive in an XML
document [XML11], the href
attributes
on <xsl:include>
and <xsl:import>
elements.script
elements
This section is not normative.
The script-src
directive lets developers specify
exactly which script elements on a page were intentionally included
for execution. Ideally, developers would avoid inline script entirely
and whitelist scripts by URL. However, in some cases, removing inline
scripts can be difficult or impossible. For those cases, developers can
whitelist scripts using a randomly generated nonce.
Usage is straightforward. For each request, the server
generates a unique value at random, and includes it in the
Content-Security-Policy
header:
Content-Security-Policy: default-src 'self'; script-src 'self' https://example.com 'nonce-$RANDOM'
This same value is then applied as a nonce
attribute
to each script
element that ought to be
executed. For example, if the server generated the random value
Nc3n83cnSAd3wc3Sasdfn939hc3
, the server would send the
following policy:
Content-Security-Policy: default-src 'self'; script-src 'self' https://example.com 'nonce-Nc3n83cnSAd3wc3Sasdfn939hc3'
Script elements can then execute either because their
src
URLs are whitelisted or because
they have a valid nonce:
<script> alert("Blocked because the policy doesn’t have 'unsafe-inline'.") </script> <script nonce="EDNnf03nceIOfn39fn3e9h3sdfa"> alert("Still blocked because nonce is wrong.") </script> <script nonce="Nc3n83cnSAd3wc3Sasdfn939hc3"> alert("Allowed because nonce is valid.") </script> <script src="https://example.com/allowed-because-of-src.js"></script> <script nonce="EDNnf03nceIOfn39fn3e9h3sdfa" src="https://elsewhere.com/blocked-because-nonce-is-wrong.js"></script> <script nonce="Nc3n83cnSAd3wc3Sasdfn939hc3" src="https://elsewhere.com/allowed-because-nonce-is-valid.js"></script>
Note that the nonce’s value is not a hash or signature that verifies the contents of the script resources. It’s quite simply a random string that informs the user agent which scripts were intentionally included in the page.
Script elements with the proper nonce execute, regardless of whether they’re inline or external. Script elements without the proper nonce don’t execute unless their URLs are whitelisted. Even if an attacker is able to inject markup into the protected resource, the attack will be blocked by the attacker’s inability to guess the random value.
script
elements
This section is not normative.
The script-src
directive lets developers whitelist a
particular inline script by specifying its hash as an allowed source
of script.
Usage is straightforward. The server computes the hash of a
particular script block’s contents, and includes the base64 encoding
of that value in the Content-Security-Policy
header:
Content-Security-Policy: default-src 'self'; script-src 'self' https://example.com 'sha256-base64 encoded hash'
Each inline script block’s contents are hashed, and compared against
the whitelisted value. If there’s a match, the script is executed. For
example, the SHA-256 digest of alert('Hello, world.');
is
YWIzOWNiNzJjNDRlYzc4MTgwMDhmZDlkOWI0NTAyMjgyY2MyMWJlMWUyNjc1ODJlYWJhNjU5MGU4NmZmNGU3OAo=
.
If the server sent the following header:
Content-Security-Policy: script-src 'sha256-YWIzOWNiNzJjNDRlYzc4MTgwMDhmZDlkOWI0NTAyMjgyY2MyMWJlMWUyNjc1ODJlYWJhNjU5MGU4NmZmNGU3OAo='
Then the following script tag would result in script execution:
<script>alert('Hello, world.');</script>
Whitespace is significant. The following scripts blocks would not hash to the same value, and would therefore not execute:
<script> alert('Hello, world.');</script> <script>alert('Hello, world.'); </script> <script> alert('Hello, world.'); </script> <script> alert('Hello, world.'); </script>
Note also that the hash applies only to inline script. An
externalized script containing the value
alert('Hello, world.');
would not execute if its
origin was not whitelisted as a valid source of script.
style-src
The style-src
directive restricts which styles the
user may applies to the protected resource. The syntax for the name and
value of the directive are described by the following ABNF grammar:
directive-name = "style-src" directive-value = source-list
The term allowed style sources refers to the result of
parsing the style-src
directive’s value as a source list if the policy contains an
explicit style-src
, or otherwise to the default sources.
If 'unsafe-inline'
is not in the
list of allowed style sources, or if at least one
nonce-source
or hash-source
is present in the list of allowed style sources:
style
element that lacks a
valid nonce and lacks a valid hash for the
allowed style sources, instead the user agent MUST
ignore the style, and MUST report a violation.style
attribute, instead the user agent
MUST
ignore the style, and MUST report a
violation.Note: These restrictions on inline do not prevent the user agent
from applying style from an external stylesheet (e.g., found via
<link rel="stylesheet" ...>
).
If 'unsafe-eval'
is not in allowed style
sources, then:
cssText
setters and insertRule
methods. [CSSOM] [HTML5]Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed style sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:
href
attribute of a link
element with a
rel
attribute containing the token
stylesheet
or when processing the <@import>
directive in a stylesheet.Note: The style-src
directive does not restrict the
use of XSLT. XSLT is restricted by the script-src
directive because the security consequences of including an untrusted
XSLT stylesheet are similar to those incurred by including an
untrusted script.
style
elements
This section is not normative.
See the script-src
nonce usage information for detail; the application of nonces
to style
elements is similar enough to avoid
repetition here.
style
elements
This section is not normative.
See the script-src
hash usage information for detail; the application of hashes
to style
elements is similar enough to avoid
repetition here.
This section provides some sample use cases and supporting policies.
Content-Security-Policy: default-src 'self'
Content-Security-Policy: default-src 'self'; img-src *; object-src media1.example.com media2.example.com *.cdn.example.com; script-src trustedscripts.example.com
Content-Security-Policy: default-src https: 'unsafe-inline' 'unsafe-eval'
This policy allows inline content (such as inline
script
elements), use of eval
,
and loading resources over https
. Note: This policy does
not provide any protection from cross-site scripting vulnerabilities.
script
elements
wishes to ensure that script is only executed from its own origin, and those
elements it intentionally inserted inline:
Content-Security-Policy: script-src 'self' 'nonce-$RANDOM';
The inline script
elements would then only
execute if they contained a matching nonce
attribute:
<script nonce="$RANDOM">...</script>
This section contains an example violation report the user agent might sent to a server when the protected resource violations a sample policy.
In the following example, the user agent rendered a representation
of the resource http://example.org/page.html
with the
following policy:
default-src 'self'; report-uri http://example.org/csp-report.cgi
The protected resource loaded an image from
http://evil.example.com/image.png
, violating the
policy.
{ "csp-report": { "document-uri": "http://example.org/page.html", "referrer": "http://evil.example.com/haxor.html", "blocked-uri": "http://evil.example.com/image.png", "violated-directive": "default-src 'self'", "effective-directive": "img-src", "original-policy": "default-src 'self'; report-uri http://example.org/csp-report.cgi" } }
The style-src
directive restricts the locations from
which the protected resource can load styles. However, if the user agent uses a
lax CSS parsing algorithm, an attacker might be able to trick the user
agent into accepting malicious "stylesheets" hosted by an otherwise
trustworthy origin.
These attacks are similar to the CSS cross-origin data leakage attack described by Chris Evans in 2009. User agents SHOULD defend against both attacks using the same mechanism: stricter CSS parsing rules for style sheets with improper MIME types.
The violation reporting mechanism in this document has been
designed to mitigate the risk that a malicious web site could use
violation reports to probe the behavior of other servers. For example,
consider a malicious web site that white lists https://example.com
as a source of images. If the malicious site attempts to load
https://example.com/login
as an image, and the
example.com
server redirects to an identity provider (e.g.,
idenityprovider.example.net
), CSP will block the request.
If violation reports contained the full blocked URI, the violation
report might contain sensitive information contained in the redirected URI,
such as session identifiers or purported identities. For this reason, the
user agent includes only the origin of the blocked URI.
The Content-Security-Policy
header is an end-to-end
header. It is processed and enforced at the client and, therefore,
SHOULD NOT be modified or removed by proxies or other intermediaries not
in the same administrative domain as the resource.
The originating administrative domain for a resource might wish to
apply a Content-Security-Policy
header outside of the
immediate context of an application. For example, a large organization
might have many resources and applications managed by different
individuals or teams but all subject to a uniform organizational
standard. In such situations, a Content-Security-Policy
header might be added or combined with an existing one at a network-edge
security gateway device or web application firewall. To enforce multiple
policies, the administrator SHOULD combine the policy into a single header.
An administrator might wish to use different combination algorithms
depending on his or her intended semantics.
One sensible policy combination algorithm is to start by allowing a default set of sources and then letting individual upstream resource owners expand the set of allowed sources by including additional origins. In this approach, the resultant policy is the union of all allowed origins in the input policies.
Another sensible policy combination algorithm is to intersect the given policies. This approach enforces that content comes from a certain whitelist of origins, for example, preventing developers from including third-party scripts or content in violation of organizational standards and practices. In this approach, the combination algorithm forms the combined policy by removing disallowed hosts from the policies supplied by upstream resource owners.
Interactions between the default-src
and other directives
SHOULD be given special consideration when combining policies. If none
of the policies contains a default-src
directive, adding new
src directives results in a more restrictive policy. However, if one or
more of the input policies contain a default-src
directive,
adding new src directives might result in a less restrictive policy, for
example, if the more specific directive contains a more permissive set of
allowed origins.
Using a more restrictive policy than the input policy authored by the resource owner might prevent the resource from rendering or operating as intended.
Note also that migration to HTTPS
from HTTP
may require updates to the policy in order to keep things running as
before. Source expressions like http://example.com
do
not match HTTPS
resources. For example,
administrators SHOULD carefully examine existing policies before rolling
out HTTP Strict Transport Security
headers for an application. [RFC6797]
The permanent message header field registry should be updated with the following registrations: [RFC3864]
Content-Security-Policy
Header Field)Content-Security-Policy-Report-Only
Header Field)CSP
HTTP Request Header)In addition to the documents in the W3C Web Application Security working group, the work on this document is also informed by the work of the IETF websec working group, particularly that working group’s requirements document: draft-hodges-websec-framework-reqs.
A portion of the frame-ancestors
directive was
originally developed as X-Frame-Options
. [RFC7034]
Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.
All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]
Examples in this specification are introduced with the words "for example"
or are set apart from the normative text with class="example"
,
like this:
This is an example of an informative example.
Informative notes begin with the word "Note" and are set apart from the
normative text with class="note"
, like this:
Note, this is an informative note.
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.
A conformant user agent must implement all the requirements listed in this specification that are applicable to user agents.
A conformant server must implement all the requirements listed in this specification that are applicable to servers.