Movatterモバイル変換


[0]ホーム

URL:


W3C

Content Security Policy Level 2

W3C Recommendation,

This version:
https://www.w3.org/TR/2016/REC-CSP2-20161215/
Latest version:
https://www.w3.org/TR/CSP2/
Latest version in series:
https://www.w3.org/TR/CSP/
Editor's Draft:
https://w3c.github.io/webappsec-csp/
Previous Versions:
https://www.w3.org/TR/2016/PR-CSP2-20161108/
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:
Mike West (Google Inc.)
Adam Barth (Google Inc.)
Dan Veditz (Mozilla Corporation)
Former Editors:
Brandon Sterne (formerly of Mozilla Corporation)

Errata for this document are recorded as issues.

The English version of this specification is the only normative version. Non-normativetranslations may also be available.

Copyright © 2016W3C® (MIT,ERCIM,Keio,Beihang). W3Cliability,trademark anddocument use rules apply.


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 theW3C technical reports index at https://www.w3.org/TR/.

Errata for this document arerecorded as issues. The latestCSP editors' draft shows current proposed resolution of erratain situ.

This document was published by theWeb Application Security Working Group as a Recommendation. The Working Group expects CSP Level 3 to obsolete this Recommendation. If you wish to make comments regarding this document, please raise an issuein the specification's issue tracker. Historical comments may also be found in the working group'semail archives.

Please see the Working Group'simplementation report.

This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

This document was produced by a group operating underthe5 February 2004 W3C Patent Policy.W3C maintains apublic list of any patent disclosuresmade 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 containsEssential Claim(s)must disclose the information in accordance withsection 6 of the W3C Patent Policy.

This document is governed by the1 September 2015 W3C Process Document.

W3C expects the functionality specified in this Recommendationwill not be affected by changes to referenced documents at an earlierprocess stage than Proposed Recommendation. Many of the referencedspecifications are at Working Draft status; implementors of CSP2should be aware that the mechanisms cited have content securityimplications and should track the progress of those specifications asthey are included in CSP implementations.

Development of CSP Level 2 concluded in 2014. Implementors of user-agents are strongly encouraged to base their work onContent Security Policy Level 3.

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 aContent-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 theContent 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. Aprotected resource’s ability to load Workers is now controlled viachild-src rather thanscript-src.
    3. Workers now have their own policy, separate from theprotected 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 theprotected resource’s ability to specify thedocument base URL.
    2. child-src deprecates and replacesframe-src, controlling theprotected resource’s ability to embed frames, and to load Workers.
    3. form-action controls theprotected resource’s ability to submit forms.
    4. frame-ancestors controls theprotected resource’s ability be embedded in other documents. It is meant to supplant theX-Frame-Options HTTP request header.
    5. plugin-types controls theprotected 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. ASecurityPolicyViolationEvent 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 viareport-uri, and those handed to the DOM viaSecurityPolicyViolationEvent events. These includeeffectiveDirective,statusCode,sourceFile,lineNumber, andcolumnNumber.
  6. Certain flags present in thesandbox 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
Asecurity 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 ofsecurity policy directives (script-src andobject-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 aname and avalue; a detailed grammar can be found in§4 Syntax and Algorithms.

protected resource
Asecurity policy is applied by a user agent to a specificresource representation, known as theprotected 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 inSection 2.3 of the Origin specification.[RFC6454]

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

HTTP 200 response
Defined inSection 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 inSection 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

Theapplet,audio,embed,iframe,img,link,object,script,source,track, andvideo are defined in[HTML5].

The termsauxiliary browsing contexts,opener browsing context, andnested browsing contexts are defined in the HTML5 specification.[HTML5]

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

TheXMLHttpRequest object is defined in theXMLHttpRequest specification.[XMLHTTPREQUEST]

TheWebSocket object is defined in theWebSocket specification.[WEBSOCKETS]

TheEventSource object is defined in theEventSource specification.[EVENTSOURCE]

Theruns a worker algorithm isdefined in the Web Workers spec.[WORKERS]

The termcallable refers to an object whose interface has one or morecallers as defined in theWeb 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 inSection 7 of HTTP/1.1 -- Message Syntax and Routing.[RFC7230]

The following core rules are included by reference, as defined inAppendix B.1 of[ABNF]:ALPHA (letters),DIGIT (decimal 0-9),WSP (white space) andVCHAR (printing characters).

3.Policy Delivery

The server delivers apolicy 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 HTMLmeta element (defined in§3.3 HTML meta Element).

3.1.Content-Security-Policy Header Field

TheContent-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 namedContent-Security-Policy with a givenresource representation.

A server MAY send differentContent-Security-Policy header field values with differentrepresentations of the same resource or with different resources.

Upon receiving an HTTP response containing at least oneContent-Security-Policy header field, the user agent MUSTenforce each of the policies contained in each such header field.

3.2.Content-Security-Policy-Report-Only Header Field

TheContent-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 willsend violation reports to the URL specified in the policy’sreport-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 theContent-Security-Policy header field.

A server MUST NOT send more than one HTTP header field namedContent-Security-Policy-Report-Only with a givenresource representation.

A server MAY send differentContent-Security-Policy-Report-Only header field values with differentrepresentations of the same resource or with different resources.

Upon receiving an HTTP response containing at least oneContent-Security-Policy-Report-Only header field, the user agent MUSTmonitor each of the policies contained in each such header field.

Note: TheContent-Security-Policy-Report-Only header isnot supported inside ameta element.

3.3. HTMLmeta Element

The server MAY supply policy via one or more HTMLmeta elements withhttp-equiv attributes that are anASCII 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 thepragma directives for themeta element:

Content security policy (http-equiv="content-security-policy")
  1. If the Document’shead element is not an ancestor of themeta element, abort these steps.
  2. If themeta element lacks acontent attribute, abort these steps.
  3. Letpolicy be the value of thecontent attribute of themeta element.
  4. Letdirective-set be the result ofparsingpolicy.
  5. Remove all occurrences ofreport-uri,frame-ancestors, andsandbox directives fromdirective-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 viameta.

  6. Enforce each of thedirectives indirective-set, asdefined for each directive type.

Authors arestrongly encouraged to placemeta elements as early in the document as possible, because policies inmeta elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using theLink HTTP response header field, and resources fetched or prefetched usinglink andscript elements which precede ameta-delivered policy will not be blocked.

Note: Apolicy specified via ameta 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 thecontent attribute of ameta element after the element has been parsed will be ignored.

Note: TheContent-Security-Policy-Report-Only header isnot supported inside ameta 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 anXMLHttpRequest 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 toexample.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 containsconnect-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 andhttp://example.net via thedefault-src directive. The second, however, would only allow script fromhttp://example.com/. Script will only load if it meets both policy’s criteria: in this case, the only origin that can match ishttp://example.com, as both policies allow it.

3.5.Policy applicability

This section is not normative.

Policies are associated with anprotected resource, andenforced ormonitored 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 TypeWhatpolicy applies?
Top-level ContextsHTML as a new, top-level browsing contextThe policy delivered with the resource
SVG, as a top-level documentPolicy delivered with the resource
Embedded Contexts Any resource included viaiframe,object, orembed The policy of the embedding resource controlswhat 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 aglobally unique identifier (or asrcdoc frame).
SVG, as an embedded document The policy delivered with the resource, or policy of the creating context if created from aglobally 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 aglobally unique identifier
SubresourcesSVG, inlined viasvgPolicy of the including context
SVG, as a resource documentPolicy of the including context
HTML via XMLHttpRequestPolicy of the context that performed the fetch
Image viaimg elementPolicy of the including context
JavaScript via ascript elementPolicy of the including context
SVG, viaimgNo policy; should be just as safe as JPG
SVG, as a WebFontNo 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. Eachdirective consists of adirective name and (optionally) adirective value, defined by the following ABNF:

policy-token    = [directive-token *( ";" [directive-token ] ) ]directive-token = *WSP [directive-name [ WSPdirective-value ] ]directive-name  = 1*( ALPHA / DIGIT / "-" )directive-value = *( WSP / <VCHAR except ";" and ","> )

4.1.1.Parsing Policies

Toparse the policypolicy, the user agent MUST use an algorithm equivalent to the following:

  1. Let theset of directives be the empty set.
  2. For each non-empty token returned bystrictly splitting the stringpolicy on the character U+003B SEMICOLON (;):
    1. Skip whitespace.
    2. Collect a sequence of characters that are notspace characters. The collected characters are thedirective name.
    3. If there are characters remaining intoken, skip ahead exactly one character (which must be aspace character).
    4. The remaining characters intoken (if any) are thedirective value.
    5. If theset of directives already contains a directive whose name is a case insensitive match fordirective name, ignore this instance of the directive and continue to the next token.
    6. Add adirective to theset of directives with namedirective name and valuedirective value.
  3. Return theset of directives.

4.2.Source List Syntax

Many CSP directives use a value consisting of asource list, defined in the ABNF grammar below.

Eachsource 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*WSPsource-expression ) *WSP ]                  / *WSP "'none'" *WSPsource-expression =scheme-source /host-source /keyword-source /nonce-source /hash-sourcescheme-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-valuehash-value        =base64-valuenonce-source      = "'nonce-"nonce-value "'"hash-algo         = "sha256" / "sha384" / "sha512"hash-source       = "'"hash-algo "-"hash-value "'"scheme-part       = <scheme production fromRFC 3986, section 3.1>host-part         = "*" / [ "*." ] 1*host-char *( "." 1*host-char )host-char         = ALPHA / DIGIT / "-"path-part         = <path production fromRFC 3986, section 3.3>port-part         = ":" ( 1*DIGIT / "*" )

If the policy contains anonce-source expression, the server MUST generate a fresh value for thenonce-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 thenonce-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.

Thehost-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 asxn--tdaaaaaa.de.

NOTE: Though IP addresses do match the grammar above, only127.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

Toparse a source listsource list, the user agent MUST use an algorithm equivalent to the following:

  1. Strip leading and trailing whitespace fromsource list.
  2. Ifsource list is anASCII case-insensitive match for the string'none' (including the quotation marks), return the empty set.
  3. Letset of source expressions be the empty set.
  4. For each token returned bysplittingsource list on spaces, if the token matches the grammar forsource-expression, add the token to theset of source expressions.
  5. Return theset 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 bepercent encoded as%3B and%2C respectively.

4.2.2.Matching Source Expressions

A URLurl is said tomatch a source expression for aprotected resource if the following algorithm returnsdoes match:

  1. Leturl be the result of processing the URL through theURL parser.
  2. If the source expression a consists of a single U+002A ASTERISK character (*), andurl’sscheme is not one ofblob,data,filesystem, then returndoes match.
  3. If the source expression matches the grammar forscheme-source:
    1. Ifurl’sscheme is anASCII case-insensitive match for the source expression’sscheme-part, returndoes match.
    2. Otherwise, returndoes not match.
  4. If the source expression matches the grammar forhost-source:
    1. Ifurl’shost isnull, returndoes not match.
    2. Leturl-scheme,url-host, andurl-port be thescheme,host, andport ofurl’s origin, respectively.

      Note: Ifurl doesn’t specify a port, then its origin’s port will be thedefault port forurl’sscheme.

    3. Leturl-path-list be thepath ofurl.
    4. If the source expression has ascheme-part that is not a case insensitive match forurl-scheme, then returndoes not match.
    5. If the source expression doesnot have a scheme, returndoes not match if any of the following are true:
      1. the scheme of the protected resource’s URL is a case insensitive match forHTTP, andurl-scheme isnot a case insensitive match for eitherHTTP orHTTPS
      2. the scheme of the protected resource’s URL isnot a case insensitive match forHTTP, andurl-scheme isnot a case insensitive match for the scheme of the protected resource’s URL.
    6. If the first character of the source expression’shost-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 ofurl-host, then returndoes not match.
    7. If the first character of the source expression’shost-part isnot an U+002A ASTERISK character (*) andurl-host is not a case insensitive match for the source expression’shost-part, then returndoes not match.
    8. If the source expression’shost-part matches theIPv4address production from[RFC3986], and is not127.0.0.1, or is anIPv6 address, returndoes 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 doesnot contain aport-part andurl-port is not thedefault port forurl-scheme, then returndoes not match.
    10. If the source expression does contain aport-part, then returndoes not match if both of the following are true:
      1. port-part doesnot contain an U+002A ASTERISK character (*)
      2. port-part doesnot represent the same number asurl-port
    11. If the source expression contains a non-emptypath-part, and the URL isnot the result of a redirect, then:
      1. Letexact-match betrue if the final character ofpath-part is not the U+002F SOLIDUS character (/), andfalse otherwise.
      2. Letsource-expression-path-list be the result of splittingpath-part on the U+002F SOLIDUS character (/).
      3. Ifsource-expression-path-list’s length is greater thanurl-path-list’s length, returndoes not match.
      4. For eachentry insource-expression-path-list:
        1. Percent decodeentry.
        2. Percent decode the first item inurl-path-list.
        3. Ifentry is not anASCII case-insensitive match for the first item inurl-path-list, returndoes not match.
        4. Pop the first item inurl-path-list off the list.
      5. Ifexact-match istrue, andurl-path-list is not empty, returndoes not match.
    12. Otherwise, returndoes match.
  5. If the source expression is a case insensitive match for'self' (including the quotation marks), then:
    1. Returndoes match ifthe origin ofurl matchesthe origin ofprotected resource’s URL.

      Note: This includes IP addresses. That is, a document athttps://111.111.111.111/ with apolicy ofimg-src 'self' can load the imagehttps://111.111.111.111/image.png, as the origins match.

  6. Otherwise, returndoes not match.

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

A URLurl is said tomatch a source list forprotected resource if at least one source expression in the set of source expressions obtained byparsing the source listmatchesurl forprotected 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 thedefault-src andscript-src directives, policy authors should be aware that allowing "data:" URLs is equivalent tounsafe-inline and allowing "blob:" or "filesystem:" URLs is equivalent tounsafe-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 expressionexample.com has no path, and therefore matches any file served from that host.
  2. The source expressionexample.com/scripts/ matches any file in thescripts directory ofexample.com, and any of its subdirectories. For example, bothhttps://example.com/scripts/file.js andhttps://example.com/scripts/js/file.js would match.
  3. The source expressionexample.com/scripts/file.js matches only the file namedfile.js in thescripts directory ofexample.com.
  4. Likewise, the source expressionexample.com/js matches only the file namedjs. In particular, note that it would not match files inside a directory namedjs. Files likeexample.com/js/file.js would be matched only if the source expression ended with a trailing "/", as inexample.com/js/.

Note: Query strings have no impact on matching: the source expressionexample.com/file matches all ofhttps://example.com/file,https://example.com/file?key=value,https://example.com/file?key=notvalue, andhttps://example.com/file?notkey=notvalue.

4.2.2.3.Paths and Redirects

To avoid leaking path information cross-origin (as discussed in Egor Homakov’sUsing 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 ofimg-src example.com not-example.com/path:

  • Directly loadinghttps://not-example.com/not-path would fail, as it doesn’t match the policy.
  • Directly loadinghttps://example.com/redirector would pass, as it matchesexample.com.
  • Assuming thathttps://example.com/redirector delivered a redirect response pointing tohttps://not-example.com/not-path, the load would succeed, as the initial URL matchesexample.com, and the redirect target matchesnot-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. Thenonce attribute

Nonce sources require a newnonce attribute to be added to bothscript andstyle elements.

partial interfaceHTMLScriptElement {  attribute DOMStringnonce;};
nonce, of typeDOMString
This attributereflects the value of the element’snonce content attribute.
partial interfaceHTMLStyleElement {  attribute DOMStringnonce;};
nonce, of typeDOMString
This attributereflects the value of the element’snonce content attribute.

4.2.4.Valid Nonces

An element has avalid nonce for aset of source expressions if the value of the element’snonce attribute afterstripping leading and trailing whitespace is a case-sensitive match for thenonce-value component of at least onenonce-source expression inset of source expressions.

4.2.5.Valid Hashes

Anelement’s content isthe script block’s source forscript elements, or the value of the element’stextContent IDL attribute for non-script elements such asstyle.

Thedigest ofelement’s content for is the result of applying analgorithm to theelement’s content.

To determine whetherelement has avalid hash for aset of source expressions, execute the following steps:

  1. Lethashes be a list of allhash-source expressions inset of source expressions.
  2. For eachhash inhashes:
    1. Letalgorithm be:
    2. Letexpected be thehash-value component ofhash.
    3. Letactual be thebase64 encoding of the binarydigest ofelement’s content using thealgorithm algorithm.
    4. Ifactual is a case-sensitive match forexpected, returntrue and abort these steps.
  3. Returnfalse.

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 theactual hash value.

4.3.Media Type List Syntax

Theplugin-types directive uses a value consisting of amedia type list.

Eachmedia type in the media type list represents a specific type of resource that can be retrieved and used to instantiate aplugin in the protected resource.

media-type-list   =media-type *( 1*WSPmedia-type )media-type        = <type from RFC 2045> "/" <subtype from RFC 2045>

4.3.1.Parsing

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

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

4.3.2.Matching

A media typematches a media type list if, and only if, the media type is anASCII case-insensitive match for at least one token in the set of media types obtained byparsing the media type list.

4.4.Reporting

Tostripuri for reporting, the user agent MUST use an algorithm equivalent to the following:

  1. If theorigin ofuri is aglobally unique identifier (for example,uri has a scheme ofdata,blob, orfilesystem), then abort these steps, and return the ASCII serialization ofuri’s scheme.
  2. If theorigin ofuri is not the same as theorigin of the protected resource, then abort these steps, and return theASCII serialization ofuri’s origin.
  3. Returnuri, with anyfragment component removed.

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

  1. Prepare a JSON objectviolation 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
    Theaddress of the protected resource,stripped for reporting.
    effective-directive
    The name of the policy directive that was violated. This will contain thedirective 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 thedefault-src directive.
    original-policy
    The originalpolicy, as received by the user agent.
    referrer
    Thereferrer attribute of the protected resource, or the empty string if the protected resource has no referrer.
    status-code
    Thestatus-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 thedefault-src directive in the case of violations caused by falling back to thedefault 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 thescript-src directive), the user agent MAY add the following keys and values toviolation:
    source-file
    The URL of the resource where the violation occurred,stripped for reporting.
    line-number
    The line number insource-file on which the violation occurred.
    column-number
    The column number insource-file on which the violation occurred.
  3. Returnviolation.

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.

Tosend violation reports, the user agent MUST use an algorithm equivalent to the following:

  1. Prepare aJSON objectreport object with a single key,csp-report, whose value is the result ofgenerating a violation report object.
  2. Letreport body be theJSON stringification ofreport object.
  3. For eachreport URL in theset of report URLs:
    1. If the user agent has already sent a violation report for the protected resource toreport URL, and that report contained an entity body that exactly matchesreport body, the user agent MAY abort these steps and continue to the nextreport URL.
    2. Queue a task tofetchreport URL from the origin of the protected resource, with the synchronous flagnot set, using HTTP methodPOST, with aContent-Type header field ofapplication/csp-report, and an entity body consisting ofreport body. If the origin ofreport URL isnot 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.) Thetask source for thesetasks is theContent Security Policy task source.

Toreport a violation, the user agent MUST:

  1. Fire a violation event at the protected resource’sDocument.
  2. If theset 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

Toenforce a policy, the user agent MUSTparse 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.

Tomonitor a policy, the user agent MUSTparse 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 isgenerated 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 bothContent-Security-Policy andContent-Security-Policy-Report-Only header fields. For example, if a server operator may wish toenforce 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 agentmonitors orenforces 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 agentruns a worker:

  • If the worker’s script’s origin is aglobally unique identifier (for example, the worker’s script’s URL has a scheme ofdata,blob, orfilesystem), then:
    • If the user agent is enforcing a CSP policy for theowner document orparent worker, the user agent MUST enforce the CSP policy for the worker.
    • If the user agent is monitoring a CSP policy for theowner document orparent worker, the user agent MUST monitor the CSP policy for the worker.
  • Otherwise:
    • If the worker’s script is delivered with aContent-Security-Policy HTTP header containing the valuepolicy, the user agent MUSTenforcepolicy for the worker.
    • If the worker’s script is delivered with aContent-Security-Policy-Report-Only HTTP header containing the valuepolicy, the user agent MUSTmonitorpolicy for the worker.

5.2.srcdoc IFrames

Whenever a user agent createsaniframesrcdoc document in a browsing context nested in the protected resource, if the user agent isenforcing anypolicies for the protected resource, the user agent MUSTenforce thosepolicies on theiframesrcdoc document as well.

Whenever a user agent createsaniframesrcdoc 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 MUSTmonitor those policies on theiframesrcdoc document as well.

6.Script Interfaces

6.1.SecurityPolicyViolationEvent Interface

[Constructor(DOMStringtype, optionalSecurityPolicyViolationEventIniteventInitDict)]interfaceSecurityPolicyViolationEvent :Event {    readonly    attribute DOMStringdocumentURI;    readonly    attribute DOMStringreferrer;    readonly    attribute DOMStringblockedURI;    readonly    attribute DOMStringviolatedDirective;    readonly    attribute DOMStringeffectiveDirective;    readonly    attribute DOMStringoriginalPolicy;    readonly    attribute DOMStringsourceFile;    readonly    attribute DOMStringstatusCode;    readonly    attribute longlineNumber;    readonly    attribute longcolumnNumber;};
documentURI, of typeDOMString, readonly
Refer to thedocument-uri property of violation reports for a description of this property.
referrer, of typeDOMString, readonly
Refer to thereferrer property of violation reports for a description of this property.
blockedURI, of typeDOMString, readonly
Refer to theblocked-uri property of violation reports for a description of this property.
violatedDirective, of typeDOMString, readonly
Refer to theviolated-directive property of violation reports for a description of this property.
effectiveDirective, of typeDOMString, readonly
Refer to theeffective-directive property of violation reports for a description of this property.
originalPolicy, of typeDOMString, readonly
Refer to theoriginal-policy property of violation reports for a description of this property.
statusCode, of typeDOMString, readonly
Refer to thestatus-code property of violation reports for a description of this property.
sourceFile, of typeDOMString, readonly
Refer to thesource-file property of violation reports for a description of this property.
lineNumber, of typelong, readonly
Refer to theline-number property of violation reports for a description of this property.
columnNumber, of typelong, readonly
Refer to thecolumn-number property of violation reports for a description of this property.

6.2.SecurityPolicyViolationEventInit Interface

dictionarySecurityPolicyViolationEventInit :EventInit {    DOMStringdocumentURI;    DOMStringreferrer;    DOMStringblockedURI;    DOMStringviolatedDirective;    DOMStringeffectiveDirective;    DOMStringoriginalPolicy;    DOMStringsourceFile;    longlineNumber;    longcolumnNumber;};
documentURI, of typeDOMString
Refer to thedocument-uri property of violation reports for a description of this property.
referrer, of typeDOMString
Refer to thereferrer property of violation reports for a description of this property.
blockedURI, of typeDOMString
Refer to theblocked-uri property of violation reports for a description of this property.
violatedDirective, of typeDOMString
Refer to theviolated-directive property of violation reports for a description of this property.
effectiveDirective, of typeDOMString
Refer to theeffective-directive property of violation reports for a description of this property.
originalPolicy, of typeDOMString
Refer to theoriginal-policy property of violation reports for a description of this property.
sourceFile, of typeDOMString
Refer to thesource-file property of violation reports for a description of this property.
lineNumber, of typelong
Refer to theline-number property of violation reports for a description of this property.
columnNumber, of typelong
Refer to thecolumn-number property of violation reports for a description of this property.

6.3.Firing Violation Events

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

  1. Letreport object be the result ofgenerating a violation report object.
  2. Queue a task tofire an event namedsecuritypolicyviolation using theSecurityPolicyViolationEvent interface with the following initializations:
    • blockedURI MUST be initialized to the value ofreport object’sblocked-uri key.
    • documentURI MUST be initialized to the value ofreport object’sdocument-uri key.
    • effectiveDirective MUST be initialized to the value ofreport object’seffective-directive key.
    • originalPolicy MUST be initialized to the value ofreport object’soriginal-policy key.
    • referrer MUST be initialized to the value ofreport object’sreferrer key.
    • violatedDirective MUST be initialized to the value ofreport object’sviolated-directive key.
    • sourceFile MUST be initialized to the value ofreport object’ssource-file key.
    • lineNumber MUST be initialized to the value ofreport object’sline-number key.
    • columnNumber MUST be initialized to the value ofreport object’scolumn-number key.

Thetask source for thesetasks is theContent 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' ordata: 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

Thebase-uri directive restricts the URLs that can be used to specify thedocument 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 termallowed base URLs refers to the result ofparsing thebase-uri directive’s value as a source list.

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

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

  1. If the previous step was not successful, or the result of the previous step does notmatch theallowed base URLs for theprotected resource, then thedocument base URL isfallback base URL. Otherwise, it is the result of the previous step.

7.2.child-src

Thechild-src directive governs the creation ofnested 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 termallowed child sources refers to the result ofparsing thechild-src directive’s value as a source list if achild-src directive is explicitly specified, and otherwise to thedefault sources.

7.2.1.Nested Browsing Contexts

To enforce thechild-src directive the user agent MUST enforce theframe-src directive.

7.2.2.Workers

Whenever the user agentfetches a URL while processing theWorker orSharedWorker constructors[WORKERS], the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation if the URL does notmatch theallowed child sources for theprotected resource.

7.3.connect-src

Theconnect-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 termallowed connection targets refers to the result ofparsing theconnect-src directive’s value as a source list if the policy contains an explicitconnect-src directive, or otherwise to thedefault sources.

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed connection targets for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport 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, andXMLHttpRequest makes arbitrary HTTP requests on your behalf. These are powerful APIs that enable useful functionality, but also provide tempting avenues for data exfiltration.

Theconnect-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 onlyexample.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

Thedefault-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 thedefault sources be the result ofparsing thedefault-src directive’s value as a source list if adefault-src directive is explicitly specified, and otherwise the U+002A ASTERISK character (*).

To enforce thedefault-src directive, the user agent MUST enforce the following directives:

If not specified explicitly in the policy, the directives listed above will use thedefault 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 willonly load fromexample.com. There’s no inheritance; thescript-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 adefault-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 forfont-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

Thefont-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 termallowed font sources refers to the result ofparsing thefont-src directive’s value as a source list if the policy contains an explicitfont-src, or otherwise to thedefault sources.

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed font sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport 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

Theform-action restricts which URLs can be used as the action of HTMLform 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 termallowed form actions refers to the result ofparsing theform-action directive’s value as a source list.

Whenever the user agentfetches a URL in the course of processing an HTMLform element, if the URL does notmatch theallowed form actions for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation.

Note:form-action does not fall back to thedefault sources when the directive is not defined. That is, a policy that definesdefault-src 'none' but notform-action will still allow form submissions to any target.

7.7.frame-ancestors

Theframe-ancestors directive indicates whether the user agent should allow embedding the resource using aframe,iframe,object,embed orapplet 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*WSPancestor-source ) ] / "'none'"ancestor-source      =scheme-source /host-sourcedirective-name  = "frame-ancestors"directive-value =ancestor-source-list

The termallowed frame ancestors refers to the result ofparsing theframe-ancestors directive’s value as a source list. If aframe-ancestors directive is not explicitly included in the policy, thenallowed frame ancestors is "*".

To enforce theframe-ancestors directive, whenever the user agent would load the protected resource into anested browsing context, the user agent MUST perform the following steps:

  1. LetnestedContext be the nested browsing context into which the protected resource is being loaded.
  2. LetancestorList be the list of allancestors ofnestedContext.
  3. For eachancestorContext inancestorList:
    1. Letdocument beancestorContext’sactive document.
    2. Ifdocument’s URL does notmatch theallowed frame ancestors for theprotected 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 emptyHTTP 200 response.
        2. Redirect the user to a friendly error page which provides the option of opening the blocked page in a newtop-level browsing context.
      3. Parse a sandboxing directive using the empty string as theinput and the newly created document’sforced sandboxing flag set as theoutput.
      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.

Theframe-ancestors directive MUST be ignored whenmonitoring a policy, and when a contained in a policy defined via ameta element.

Note:frame-ancestors does not fall back to thedefault sources when the directive is not defined. That is, a policy that definesdefault-src 'none' but notframe-ancestors will still allow the resource to be framed from anywhere.

When generating a violation report for aframe-ancestors violation, the user agent MUST NOT include the value of the embedding ancestor as ablocked-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 toX-Frame-Options

This directive is similar to theX-Frame-Options header that several user agents have implemented. The'none' source expression is roughly equivalent to that header’sDENY,'self' toSAMEORIGIN, and so on. The major difference is that many user agents implementSAMEORIGIN 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]

Theframe-ancestors directiveobsoletes theX-Frame-Options header. If a resource has both policies, theframe-ancestors policy SHOULD be enforced and theX-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 toX-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 validsource-list expressions, but it is strongly recommended against accommodating such scenarios with a staticframe-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 athttps://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 likehttps://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

Theframe-src directive isdeprecated. Authors who wish to govern nested browsing contexts SHOULD use thechild-src directive instead.

Theframe-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 termallowed frame sources refers to the result ofparsing theframe-src directive’s value as a source list if the policy contains an explicitframe-src, or otherwise to the list ofallowed child sources.

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed frame sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation:

7.9.img-src

Theimg-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 termallowed image sources refers to the result ofparsing theimg-src directive’s value as a source list if the policy contains an explicitimg-src, or otherwise to the list ofdefault sources.

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed image sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation:

  • Requesting data for an image, such as when processing thesrc orsrcset attributes of animg element, thesrc attribute of aninput element with a type ofimage, theposter attribute of avideo element, theurl(),image() orimage-set() values on any Cascading Style Sheets (CSS) property that is capable of loading an image[CSS4-IMAGES], or thehref attribute of alink element with an image-relatedrel attribute, such asicon.

7.10.media-src

Themedia-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 termallowed media sources refers to the result ofparsing themedia-src directive’s value as a source list if the policy contains an explicitmedia-src, or otherwise to the list ofdefault sources.

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed media sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation:

  • Requesting data for a video or audio clip, such as when processing thesrc attribute of avideo,audio,source, ortrack element.

7.11.object-src

Theobject-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 termallowed object sources refers to the result ofparsing theobject-src directive’s value as a source list if the policy contains an explicitobject-src, or otherwise to the list ofdefault sources.

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed object sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation:

It is not required that the consumer of the element’s data be aplugin in order for theobject-src directive to be enforced. Data for anyobject,embed, orapplet element MUST match theallowed 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 anobject element with atext/html MIME type.

Whenever the user agent would load aplugin without an associated URL (e.g., because theobject element lacked adata attribute), if the protected resource’s URL does notmatch theallowed object sources for theprotected resource, the user agent MUST NOT load the plugin.

7.12.plugin-types

Theplugin-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 termallowed plugin media types refers to the result ofparsing theplugin-types directive’s value as a media type list.

Whenever the user agent would instantiate aplugin to handleresource while enforcing theplugin-types directive, the user agent MUST instead act as though the plugin reported an errorandreport 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 thefallback content.

Whenever the user agent creates aplugin document as theactive document of achild browsing context of theprotected resource, if the user agent is enforcing anyplugin-types directives for the protected resource, the user agent MUSTenforce thoseplugin-types directives on the plugin document as well.

Whenever the user agent creates aplugin document as theactive document of achild browsing context of theprotected resource, if the user agent is monitoring anyplugin-types directives for the protected resource, the user agent MUSTmonitor thoseplugin-types directives on the plugin document as well.

7.12.1.Usage

This section is not normative.

Theplugin-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 anembed orobject element delivered with anapplication/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 theplugin-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 theplugin-types directive requires thatobject andembed elements declare the expected media type of the resource they include via thetype attribute. If an author expects to load a PDF, she could specify this as follows:

<object data="resource" type="application/pdf"></object>

Ifresource 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 whitelistedand matches the declared type in their containing element.

7.13.report-uri

Thereport-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*WSPuri-reference )uri-reference     = <URI-reference from RFC 3986>

Theset of report URLs is the value of thereport-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: Thereport-uri directive will be ignored if contained within ameta element.

7.14.sandbox

Thesandbox 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*WSPsandbox-token )sandbox-token     = <token from RFC 7230>

When enforcing thesandbox directive, the user agent MUSTparse a sandboxing directive using thedirective-value as theinput and protected resource’sforced sandboxing flag set as the output.[HTML5]

Thesandbox directive will be ignored whenmonitoring a policy, and when contained in a policy defined via ameta element. Moreover, this directive has no effect whenmonitored, 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 aDocument. 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, butallow-scripts andallow-same-origin have special requirements.

When a resource is loaded while executing theruns aWorker 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. Thesandbox directive delivered with the resource doesnot contain theallow-scripts flag.
  2. Thesandbox directive delivered with the resource doesnot contain theallow-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 asandbox attribute foriframe 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.

Thesandbox 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 thesandbox 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 addingallow-* 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 thesandbox directive with theallow-scripts flag:

Content-Security-Policy:sandboxallow-scripts

The set of flags available to the CSP directive should match those available to theiframe attribute. Currently, those include:

Note: Like the rest of Content Security Policy, thesandbox directive is meant as a defense-in-depth. Web authors would be well-served to use itin addition to standard sniffing-mitigation and privilege-reduction techniques.

7.15.script-src

Thescript-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 termallowed script sources refers to the result ofparsing thescript-src directive’s value as a source list if the policy contains an explicitscript-src, or otherwise to thedefault sources.

If'unsafe-inline' isnot in the list ofallowed script sources, or if at least onenonce-source orhash-source is present in the list ofallowed script sources:

  • Whenever the user agent would execute an inline script from ascript element that lacks avalid nonceand lacks avalid hash for theallowed script sources, instead the user agent MUST NOT execute script,and MUSTreport 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 MUSTreport a violation.
  • Whenever the user agent would execute script contained in ajavascript URL, instead the user agent MUST NOT execute the script,and MUSTreport a violation.

If'unsafe-eval' isnot inallowed script sources:

  • Instead of evaluating their arguments, both operatoreval and functioneval[ECMA-262] MUST throw anEvalError exception.
  • When called as a constructor, the functionFunction[ECMA-262] MUST throw anEvalError exception.
  • When called with a first argument that is notcallable (a string, for example), thesetTimeout() function MUST return zero without creating a timer.
  • When called with a first argument that is notcallable (a string, for example), thesetInterval() function MUST return zero without creating a timer.

Whenever the user agentfetches a URL (including when following redirects) in the course of one of the following activities, if the URL does notmatch theallowed script sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation:

  • Requesting a script while processing thesrc attribute of ascript element that lacks avalid nonce for theallowed script sources.
  • Requesting a script while invoking theimportScripts method on a WorkerGlobalScope object.[WORKERS]
  • Requesting an HTML component, such as when processing thehref attribute of alink element with arel attribute containing the tokenimport.[HTML-IMPORTS]
  • Requesting an Extensible Stylesheet Language Transformations (XSLT)[XSLT], such as when processing the<?xml-stylesheet?> processing directive in an XML document[XML11], thehref attributes on<xsl:include> and<xsl:import> elements.

7.15.1. Nonce usage forscript elements

This section is not normative.

Thescript-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. Foreach request, the server generates a unique value at random, and includes it in theContent-Security-Policy header:

Content-Security-Policy:default-src 'self';script-src 'self' https://example.com 'nonce-$RANDOM'

This same value is then applied as anonce attribute to eachscript element that ought to be executed. For example, if the server generated the random valueNc3n83cnSAd3wc3Sasdfn939hc3, 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 theirsrc URLs are whitelisted or because they have avalid 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 isnot 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 forscript elements

This section is not normative.

Thescript-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 theContent-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 ofalert('Hello, world.'); isqznLcsROx4GACP2dm0UCKCzCG+HiZ1guq6ZZDob/Tng=.

You can obtain the digest of a string on the command line simply via theopenssl 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 thereforenot 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 appliesonly to inline script. An externalized script containing the valuealert('Hello, world.'); wouldnot execute if its origin was not whitelisted as a valid source of script.

7.16.style-src

Thestyle-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 termallowed style sources refers to the result ofparsing thestyle-src directive’s value as a source list if the policy contains an explicitstyle-src, or otherwise to thedefault sources.

If'unsafe-inline' isnot in the list ofallowed style sources, or if at least onenonce-source orhash-source is present in the list ofallowed 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' isnot inallowed style sources, then:

Whenever the user agentfetches a URL in the course of one of the following activities, if the URL does notmatch theallowed style sources for theprotected resource, the user agent MUST act as if there was a fatal network error and no resource was obtained,andreport a violation:

  • Requesting an external stylesheet when processing thehref of alink element whoserel attribute contains the tokenstylesheet.
  • Requesting an external stylesheet when processing the <<@import>> directive.
  • Requesting an external stylesheet when processing aLink HTTP response header field[RFC5988].

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

Note: Thestyle-src directive does not restrict the use of XSLT. XSLT is restricted by thescript-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 forstyle elements

This section is not normative.

See thescript-src nonce usage information for detail; the application of nonces tostyle elements is similar enough to avoid repetition here.

7.16.2. Hash usage forstyle elements

This section is not normative.

See thescript-src hash usage information for detail; the application of hashes tostyle elements is similar enough to avoid repetition here.

8.Examples

8.1.Sample Policy Definitions

This section provides some sample use cases and supportingpolicies.

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 inlinescript elements), use ofeval, and loading resources overhttps. Note: This policy does not provide any protection from cross-site scripting vulnerabilities.

A website that relies on inlinescript 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 inlinescript elements would then only execute if they contained a matchingnonce 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 resourcehttp://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 fromhttp://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

Thestyle-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 theCSS 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 listshttps://example.com as a source of images. If the malicious site attempts to loadhttps://example.com/login as an image, and theexample.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 (viaimg.naturalHeight, for instance). An earlier version of this specification defined aCSP request header which servers could use (in conjunction with thereferer andorigin headers) to determine whether or not it was completely safe to redirect a user. This header caused some issues with CORS processing (tracked inwhatwg/fetch#52), and has been punted to the next version of this document.

10.Implementation Considerations

TheContent-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 aContent-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, aContent-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 thedefault-src and other directives SHOULD be given special consideration when combining policies. If none of the policies contains adefault-src directive, adding new src directives results in a more restrictive policy. However, if one or more of the input policies contain adefault-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 toHTTPS fromHTTP may require updates to the policy in order to keep things running as before. Source expressions likehttp://example.com donot matchHTTPS resources. For example, administrators SHOULD carefully examine existing policies before rolling outHTTP 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 forhttp resources, but would not send violation reports forframe-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. Theframe-ancestor directive MUST take effect before a document is loaded into anested 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', andscheme- orport-relative source expressions.
  2. Likewise, theLink 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 effectivebefore 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=stylesheetContent-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 (SeeContent-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 (SeeContent-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 theIETF websec working group, particularly that working group’s requirements document:draft-hodges-websec-framework-reqs.

A portion of theframe-ancestors directive was originally developed asX-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 withclass="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 withclass="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

Aconformant user agent must implement all the requirements listed in this specification that are applicable to user agents.

Aconformant 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 interfaceHTMLScriptElement {  attribute DOMStringnonce;};partial interfaceHTMLStyleElement {  attribute DOMStringnonce;};[Constructor(DOMStringtype, optionalSecurityPolicyViolationEventIniteventInitDict)]interfaceSecurityPolicyViolationEvent :Event {    readonly    attribute DOMStringdocumentURI;    readonly    attribute DOMStringreferrer;    readonly    attribute DOMStringblockedURI;    readonly    attribute DOMStringviolatedDirective;    readonly    attribute DOMStringeffectiveDirective;    readonly    attribute DOMStringoriginalPolicy;    readonly    attribute DOMStringsourceFile;    readonly    attribute DOMStringstatusCode;    readonly    attribute longlineNumber;    readonly    attribute longcolumnNumber;};dictionarySecurityPolicyViolationEventInit :EventInit {    DOMStringdocumentURI;    DOMStringreferrer;    DOMStringblockedURI;    DOMStringviolatedDirective;    DOMStringeffectiveDirective;    DOMStringoriginalPolicy;    DOMStringsourceFile;    longlineNumber;    longcolumnNumber;};


[8]ページ先頭

©2009-2025 Movatter.jp