CSP Violations

CSP Status: Inactive

Toggle CSP Here:

The examples here are code and practices that are likely to break when applying a CSP policy. Each of them has a corresponding fixed version on the CSP Compliant examples page

Inline script restrictions are described in the script-src of the CSP spec:

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

  • Whenever the user agent would execute an inline script from a script element that lacks a valid nonce for the allowed script sources, instead the user agent must not execute script, and must report a violation.
  • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent must not execute script, and must report a violation.
  • Whenever the user agent would execute script contained in a javascript URI, instead the user agent must not execute the script, and must report a violation. (The user agent should ignore this step when processing script contained in "bookmarklets").

(Firefox before 22 doesn't recognize 'unsafe-inline' (Bug 746978): see that bug comment for the directives to use before 22)

Inline Script Blocks

These are <script> blocks directly in the HTML; without 'unsafe-inline', <script> blocks will be ignored. (Fixing Inline Script Blocks)

The script below adds the current time here if it runs: .
  <script>
  document.getElementById('example-inline-script').innerHTML=new Date().toLocaleTimeString();
</script> 

Inline Event Handler

Use of javascript in event handlers, including the 'javascript:' prefix, anonymous functions, and predefined functions. (Fixing Inline Event Handlers)

This button will pop an alert if inline events are allowed:
  <button onclick='alert('Inline event handler ran')'>Try me</button>

'javascript:' URI

The use of 'javascript:' as the href target in a <a> tags. (Fixing 'javascript:' URIs)

This link will pop an alert if inline sources are allowed: Try Me
  <a href='javascript:alert('javascript: URI ran')'>Try Me</a>

Eval restrictions are described in the script-src of the CSP spec:

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

  • Instead of evaluating their arguments, both operator eval and function eval must throw a security exception. [ECMA-262]
  • When called as a constructor, the function Function must throw a security exception. [ECMA-262]
  • When called with a first argument that is non-callable (e.g., not a function), the setTimeout function must return zero without creating a timer.
  • When called with a first argument that is non-callable (e.g., not a function), the setInterval function must return zero without creating a timer.

Eval

Without unsafe-inline, eval throws an exception instead of executing.('Fixing' Eval usage)

Eval is used to set the value of this string: []
  eval('set_by_eval = 'Value was set OK';')

setTimeout() and setInterval()

Without unsafe-inline, setTimeout() and setInterval() can only be passed existing functions (not strings). (Fixing setTimeout())

They return 0 if they're stubbed due to CSP.

The return values here should all be zero if they were prevented from running: [ , , , , ]
  document.getElementById('example-settimeout-value1').innerHTML = setTimeout('var foo = 'bar';', 1000 * 3600);

document.write()

If called from an allowed script-src, document.write still works. However, it can't be used to create script blocks unless you also include 'unsafe-inline' in the policy, which you shouldn't do because it disables most of the protections of CSP. (Fixing document.write)

Using inline document.write():
Using document.write() invoked from a script on the current domain:
Using document.write(), invoked from a script on the current domain, to write a script block:
  <script>document.write('<strong>Written OK</strong>')</script>
  <script src='/static/violation_examples_docwrite.js'></script>
  <script src='/static/violation_examples_docwrite_script.js'></script>

Style restrictions are described in the style-src of the CSP spec:

If 'unsafe-inline' is not in allowed in allowed style sources:

  • Whenever the user agent would apply style from a style element that lacks a valid nonce from the allowed style sources, instead the user agent must ignore the style, and must report a violation.
  • Whenever the user agent would apply style from a style attribute, instead the user agent must ignore the style, and must report a violation.
  • Note: These restrictions on inline do not prevent the user agent from applying style from an external stylesheet (e.g., found via <link rel="stylesheet">). The user agent is also not prevented from applying style from Cascading Style Sheets Object Model (CSSOM)
  • Note: The style-src directive does not restrict the use of XSLT. XSLT is restricted by the script-src directive because the security consequences of including an untrusted XSLT stylesheet are similar to those incurred by including an untrusted script.

Style

Inline Style Attribute

Without 'unsafe-inline' inline style use of the <style> throws a violation instead of executing. (Fixing inline styles)

The following text will be blue if CSP is disabled:

This font should be blue

  <p style='color:blue;'>This font should be blue</p>

Internal Style Sheet

Without 'unsafe-inline' internal style sheet use of the <style> throws a violation instead of executing. (Fixing internal styles)

The following text will be blue if internal style sheets are allowed:
This font should be blue
  <style type='text/css'>
  .get-blue {color:blue;}
  </style>

  <div class='get-blue'>
    This font should be blue
  </div>

External Style Sheet

Without 'unsafe-inline' inline use of the <style> attribute to an external style sheet throws a violation instead of executing. (Fixing external stylesheets)

The following text will be blue if style sheets from 'self' are allowed:
This font should be blue

  <link rel='stylesheet' type='text/css' href='blue.css'><div class='get-blue-2'>This font should be blue</div>

Image restrictions are described in the img-src of the CSP spec:

Whenever the user agent fetches a URI (including when following redirects) in the course of one of the following activities, if the URI does not match the allowed image sources, the user agent must act as if it had received an empty HTTP 400 response and report a violation::

  • Requesting data for an image, such as when processing the src attribute of an img elements, the url() or image() values on any Cascading Style Sheets (CSS) property that is capable of loading an image, or the href attribute of a link element with an image-related relattribute, such as icon.

Image

Image Source

Use of the <img> tag with a 'src' to an external image throws a violation instead of requesting or loading. (Fixing remote images)

      <img src='https://www.google.com/images/srpr/logo4w.png'>
    

Embedded Image

Use of the <img> tag with a 'src' to embedded data, such as a base64 encoded image throws a violation instead of loading the image. (Fixing embedded images)

      <img alt='' src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD/2wBDAAEBAQEBAQEBAQECAQEBAgICAQECAgMCAgICAgMEAwMDAwMDBAQEBAUEBAQGBgYGBgYICAgICAkJCQkJCQkJCQn/2wBDAQICAgMDAwUEBAUIBgUGCAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQn/wAARCAAwADADAREAAhEBAxEB/8QAGQABAQEBAQEAAAAAAAAAAAAAAAgKCQUH/8QAKxAAAAQFAwMDBQEAAAAAAAAAAgMEBQABBgcICRESExQWFRciGSRak9YK/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/ANhEAgEAgEAgEBOV3sw8R8fKlQ0ZfvKW3NkKwc0JTo20pV9bs1NOShtONNILVlJXFUSaMkZpJgAmSDxmIApSnuGewfVbb3OtteSi2a5FobhMd1bd1H3Hj1e027JXxlX9meYlP7dciMNIN6R5Qyx8RT4jCIM9pynKA9yp6npqiaaqGs6zqFDSNH0ihVulV1W6KykDa2NqAoR6pWrVHiAUSSSUAQzDBikEIZTnOcpSgJytvnVhHeStGa29ocxrV3VuJUfcePUFTdwmF8el/ZkGKj+3Qolhp5vSIKGYPiGfEARCntKU5wFUwCAxZ/6NdJfUEzxzctbd7FGwHurbunLVslNvNQ+VU2x9F6Rvz4tOT9B4ckZ4uJCwkXMIJgny2kKc5ClIO/WifjfejEbTHxnx6yFoz2+vBb7zPy+kPUULt2nq1Vuzkl+6bT1KUzqJVJY/gYLbltPYUpykFU51W3rS8mEeY1obbs3kdxLq2ruFTdBU93BCPv3p8YViJCn66owogrqnmhDzMGEAd9xClKU5wGLPRP0T9TjEbU4xnyFyFxn9vrP2+8z8vq/zOlHbtPVqUdm1L9q2uylUZ1FSksHwLFty3nsGU5yDfrAIBAIBAIBAIDizqN6YmXGad7qWulYTVYuNgxR7BSqFgcrS0gU8jbXFySr1ysx3Nm3VG0FdY4pUWSLckQuJIdxzlsEIQF9AjUm/Invh+iqf7iAfQI1JvyJ74foqn+4gKpwn0hc3MXsnLZ30u9rO3Uywt3Q3rPkNgKkKfgsr/wCptKtvI7ia2qnIj7U9QBSDkmH8yw7cZ7CCHfqAQCAQCAQCA//Z' />
    

Frame restrictions are described in the child-src of the CSP spec:

The child-src directive governs the creation of nested browsing contexts as well as Worker execution contexts.

  • Whenever the user agent fetches a URI (including when following redirects) in the course of one of the following activities, if the URI does not match the allowed frame sources, the user agent must act as if it had received an empty HTTP 400 response and report a violation.
  • Report a violation when requesting data for display in a nested browsing context in the protected resource created by an iframe or a frame element.
  • Navigating such as nested browsing context.

Iframe Example 1

The use of the <iframe> tag with a 'src' to a frame or iframe throws a violation instead of loading the page. (Fixing iframes, 1)

www.iana.org should be rendered here:

       <iframe src='http://www.iana.org'></iframe>
    

Iframe Example 2

The use of the <iframe> tag with a 'src' to a frame or iframe throws a violation instead of loading the page. (Fixing IFrames, 2)

Write the Word 'Iframe' here:

    <IFRAME SRC='javascript:document.write('Iframe');'></IFRAME>
  

Remote Inline

Fonts can still be sourced from external domains, they just just need to be specified in the font-src directive.

This example uses a font from the Google Font API, so it also uses a style-src directive to allow the @font-face declaration to be loaded. (Fixing remote inline fonts)

This text should be in a non-standard font, sourced from a remote domain.
<link href='https://fonts.googleapis.com/css?family=Chela+One' rel='stylesheet' type='text/css'>

XMLHttpRequest

XHR requests are controlled by connect-src; simply include domains you want to allow connections to (* is supported). You'll need an appropriate Access-Control-Allow-Origin header on the remote side of course. (Fixing XmlHttpRequest)

(In Firefox before 22, 'xhr-src' was used instead of 'connect-src')

The response code of an XHR request to Github is here (or nothing if it was blocked):

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        document.getElementById('example-connect').innerHTML = xhr.status;
    }
}
// Github is a cross-origin early adopter, and don't seem like they'd mind the traffic
xhr.open('GET', 'https://api.github.com', true);
xhr.send(null);

Object

Valid object src locations should be specified in the object-src part of the policy. (Fixing object sources)

The box below is a demo Flash widget sourced from adobe.com.
<object type="application/x-shockwave-flash"
        data="https://helpx.adobe.com/content/help/en/flash-player/kb/find-version-flash-player/_jcr_content/main-pars/flash_0/file.res/widget.swf"
        width="406" height="140" style="visibility: visible;">
...
</object>

Embed

CSP 1.1 introduces the concept of plugin-types (not recognized in 1.0), allowing you to specify the MIME type of object and embed tags.

CSP also enforces that the expected MIME type (in the type attribute) matches the actual MIME type from the server header; make sure they agree. (Fixing allowed embed types)

An embedded PDF, sourced from the current domain:
    <embed src="/static/stack_smashing.pdf" type="application/pdf" width="800" height="150"></embed>