8

I have an img tag on a page with an line style that looks like this:

style="height:50px;width:180px;display:block;"

I can't move it to an external stylesheet because the img tag is generated by a 3rd party control. So I copied the hash displayed in Chrome developer tools.

Part of the Content-Security-Policy looks like this:

style-src 'self' 'sha256-7kYG54iPGE/Vf+GFqobEwpF9bfCAVA/elCz7OiSmMl0=';

But Chrome still blocks it with the following message:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'sha256-7kYG54iPGE/Vf+GFqobEwpF9bfCAVA/elCz7OiSmMl0='". Either the 'unsafe-inline' keyword, a hash ('sha256-7kYG54iPGE/Vf+GFqobEwpF9bfCAVA/elCz7OiSmMl0='), or a nonce ('nonce-...') is required to enable inline execution.

The hash in the policy matches the required hash in the error message. Why is Chrome still blocking it?

Thanks...

td48260
  • 83
  • 1
  • 4
  • I wonder if this could be because the inline style may be applied after the policy is being parsed. So the server sends the policy, Chrome parses it, no inline style exists, then JS modifies it and now chrome considers it wrong. –  Nov 14 '19 at 19:43

1 Answers1

7

It looks like that with Chrome (but not Firefox) you also need to explicitly allow 'unsafe-hashes' since giving the hashes alone seem to apply only for script and style sections and not attributes. See 8.3. Usage of "'unsafe-hashes'". With that your CSP should look like this:

style-src 'self' 'unsafe-hashes' 'sha256-7kYG54iPGE/Vf+GFqobEwpF9bfCAVA/elCz7OiSmMl0=';

For more discussions about why Chrome decided to behave this way see this Chromium issue and this W3C issue.

Steffen Ullrich
  • 201,479
  • 30
  • 402
  • 465
  • 1
    When i added 'unsafe-hashes' it worked. I've looked at several CSP reference sites that don't even mention 'unsafe-hashes'. Good to know. Thanks!. – td48260 Nov 14 '19 at 21:27
  • Literally the first time I heard of 'unsafe-hashes' –  Nov 21 '19 at 16:34