Content Security Policy (CSP)
Quick Reference Guide


The unsafe-hashes Source List Keyword

The unsafe-hashes Content Security Policy (CSP) keyword allows the execution of inline scripts within a JavaScript event handler attribute of a HTML element.

Warning

Whenever you see the prefix unsafe in a CSP keyword, that means that using this is not the most secure way to go. It is better to refactor your code to avoid using HTML event handler attributes (such as onload, onclick, onmouseover etc.)

Example using unsafe-hashes

Suppose you have some code throughout your application like this:

<button onClick="doSomething();">

When you enable a Content-Security-Policy on your site with a script-src, you will probably find that the above code is now in violation of your CSP policy. That is because it is considered an inline scripts and it will be blocked unless you specifically allow it.

Unsafe hashes allows us to do just that, by computing a SHA-256 hash of our code, in this case: doSomething(); we have the hashed result:

RFWPLDbv2BY+rCkDzsE+0fr8ylGr2R2faWMhq4lfEQc=

We can add the following to a script-src directive in our Content-Security-Policy header to allow this:

script-src 'unsafe-hashes' 'sha256-RFWPLDbv2BY+rCkDzsE+0fr8ylGr2R2faWMhq4lfEQc='

This will allow the javascript doSomething(); to run in our button, but it could also run in an element injected by an attacker.

What should you use instead of unsafe-hashes?

As we mentioned, the unsafe-hashes source list may be considered unsafe, so a better approach is to move the event handler logic into a JavaScript file.

For example, we could rewrite the code as:

<button id="doSomethingButton">

Then in our JS file, we add:

document.getElementById("doSomethingButton").addEventListener("click", function() {
	doSomething();
});

Or if you use jQuery, you can use something like this to your JavaScript file:

$('#doSomethingButton').click(function() {
	doSomething();
});

Browser Support for unsafe-hashes

The unsafe-hashes directive was added to CSP Level 3. It is currenlty only supported in Chrome 69+ or Chromium Based Edge 79+.

CSP Developer Field Guide

CSP Developer Field Guide

Want to learn more about CSP on the double? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.

Grab a Copy