Chrome version 18+: How to allow inline scripting with a Content Security Policy?

Hash usage for inline scripts is permitted in Content Security Policy Level 2. From the example in the spec:

Content-Security-Policy: script-src 'sha512-YWIzOWNiNzJjNDRlYzc4MTgwMDhmZDlkOWI0NTAyMjgyY2MyMWJlMWUyNjc1ODJlYWJhNjU5MGU4NmZmNGU3OAo='

An alternative is the nonce, again from the examples:

Content-Security-Policy: script-src 'self' 'nonce-$RANDOM';

then

<script nonce="$RANDOM">...</script>
<script nonce="$RANDOM" src='save-because-nonce'></script>

These appears supported in Chrome 40+, but I am uncertain what luck one would have with other browsers at the moment.


The following answer is true for older versions of Chrome (<46). For more recent ones, please check @Chris-Hunt answer https://stackoverflow.com/a/38554505/422670

I just posted a very similar answer for the question https://stackoverflow.com/a/11670319/422670

As is said, there's no way to relax the inline security policy in v2 extensions. unsafe-inline simply does not work, intentionally.

There really is no other way than moving all your javascript into js files and point to them with a <script src>.

There's, though, the option to do Eval and new Function inside a sandboxed iframe, for instance with the following lines in the manifest:

"sandbox": {
    "pages": [
      "page1.html",
      "directory/page2.html"
    ]
},

A sandboxed page will not have access to extension or app APIs, or direct access to non-sandboxed pages (it may communicate with them via postMessage()). You can further restrict the sandbox rights with a specific CSP

There's now a full example from the Google Chrome team on the github eval in iframe on how to circumvent the problem by communicating with a sandboxed iframe, as well as a short analytics tutorial

Thanks to Google, there's a lot of extension rewriting in the lineup :(

EDIT

It is possible relax the security policy for REMOTE scripts. But not for inlines.

The policy against eval() and its relatives like setTimeout(String), setInterval(String), and new Function(String) can be relaxed by adding 'unsafe-eval' to your policy: "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

However, we strongly recommend against doing this. These functions are notorious XSS attack vectors.

this appeared in the trunk documentation and is discussed in the thread "eval re-allowed"

inline scripts will not be back though:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.


For recent versions of Chrome (46+), the previously accepted answer is no longer true. unsafe-inline still has no effect (in the manifest and in meta header tags), but per the documentation, you can use the technique described here to relax the restriction.

Hash usage for <script> elements

The script-src directive lets developers whitelist a particular inline script by specifying its hash as an allowed source of script.

Usage is straightforward. The server computes the hash of a particular script block’s contents, and includes the base64 encoding of that value in the Content-Security-Policy header:

Content-Security-Policy: default-src 'self';
                     script-src 'self' https://example.com 'sha256-base64 encoded hash'

Example

Consider the following:

manifest.json:

{
  "manifest_version": 2,
  "name": "csp test",
  "version": "1.0.0",
  "minimum_chrome_version": "46",
  "content_security_policy": "script-src 'self' 'sha256-WOdSzz11/3cpqOdrm89LBL2UPwEU9EhbDtMy2OciEhs='",
  "background": {
    "page": "background.html"
  }
}

background.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script>alert('foo');</script>
  </body>
</html>

Result:
alert dialog from inline script

Further investigation

I also tested putting the applicable directive in a meta tag instead of the manifest. While the CSP indicated in the console message did include the content of the tag, it would not execute the inline script (in Chrome 53).

new background.html:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'sha256-WOdSzz11/3cpqOdrm89LBL2UPwEU9EhbDtMy2OciEhs='">
  </head>
  <body>
    <script>alert('foo');</script>
  </body>
</html>

Result:
console error messages about content security policy

Appendix: Generating the hashes

Here are two methods for generating the hashes:

  1. Python (pass JS to stdin, pipe it somewhere else):
import hashlib
import base64
import sys

def hash(s):
    hash = hashlib.sha256(s.encode()).digest()
    encoded = base64.b64encode(hash)
    return encoded

contents = sys.stdin.read()
print(hash(contents))
  1. In JS, using the Stanford Javascript Crypto Library:
var sjcl = require('sjcl');
// Generate base64-encoded SHA256 for given string.
function hash(s) {
  var hashed = sjcl.hash.sha256.hash(s);
  return sjcl.codec.base64.fromBits(hashed);
}

Make sure when hashing the inline scripts that the whole contents of the script tag are included (including all leading/trailing whitespace). If you want to incorporate this into your builds, you can use something like cheerio to get the relevant sections. Generically, for any html, you can do:

var $ = cheerio.load(html);
var csp_hashes = $('script')
  .map((i, el) => hash($(el).text())
  .toArray()
  .map(h => `'sha256-${h}'`)
  .join(' ');
var content_security_policy = `script-src 'self' 'unsafe-eval' ${csp_hashes}; object-src 'self'`;

This is the method used in hash-csp, a gulp plugin for generating hashes.


Afaik, this is a bug.

"default-src 'self' https://ssl.google-analytics.com"

works, while

"default-src 'self' http://ssl.google-analytics.com"

doesnt.

It's really bleeding edge technology, check http://code.google.com/p/chromium/issues/detail?id=105796 for details.

Update: http://code.google.com/p/chromium/issues/detail?id=107538 refers to this issue.