7

New to Content Security Policy stuff so not sure if this is possible or not, but wondering how to add a hash or nonce for some inline script within a HTML element's attribute.

For example:

<form method="post" onsubmit="function();">

Gives me the following CSP error in Google Chrome:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'. Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

I've tried hashing just the script e.g. function(); as well as onsubmit="function" and neither work. I tried adding a nonce to the form element but that didn't help.

If needed I can move the event binding outside of the element attribute, just curious if there is a way to adhere to a CSP with the above.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
flex
  • 71
  • 1
  • 2
  • Possible duplicate of [Script causes “Refused to execute inline script: Either the 'unsafe-inline' keyword, a hash… or a nonce is required to enable inline execution”](https://stackoverflow.com/questions/46256983/script-causes-refused-to-execute-inline-script-either-the-unsafe-inline-keyw) – Heretic Monkey Jun 13 '18 at 16:58
  • That error message is misleading. See https://github.com/w3c/webappsec/issues/468. Despite what that error message might lead you to think, in CSP2 and in current browsers, a hash or nonce can only enable you to allow scripts in `script` elements — not scripts in event-handler attributes. The best thing to do instead is what the answer at https://stackoverflow.com/a/46259847/441757 says: Un-inline those event handlers. – sideshowbarker Jun 13 '18 at 17:09
  • In CSP3, though, you can specify 'unsafe-hashed-attributes' for the script-src directive and that’ll enable you to use a hash or nonce to allow scripts in event-handler attributes too. See https://docs.google.com/document/d/1_nYS4gWYO2Oh8rYDyPglXIKNsgCRVhmjHqWlTAHst7c/edit#heading=h.h95n37p306j5 and https://w3c.github.io/webappsec-csp/#unsafe-hashed-attributes-usage & https://www.chromestatus.com/feature/5867082285580288. But it’s not supported in any browsers yet (not even in Chrome — it’s still in development; see https://bugs.chromium.org/p/chromium/issues/detail?id=771922). – sideshowbarker Jun 13 '18 at 17:10
  • @sideshowbarker I wondered if that might be the case, but at least wanted to ask the question and see. Appreciate the help! – flex Jun 14 '18 at 07:23

1 Answers1

1

Go to your endpoint where your content is being blocked. Check out the console on your browser. Your browser will notify the content which is being blocked, and it will also give you the hash you have to use to unblock that content via CSP.

Source: https://www.troyhunt.com/locking-down-your-website-scripts-with-csp-hashes-nonces-and-report-uri/