Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSP hash or nonce for inline JS within attribute

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.

like image 591
flex Avatar asked Jun 13 '18 16:06

flex


People also ask

How does nonce work in CSP?

A nonce is a random number used only once per page load. A nonce-based CSP can only mitigate XSS if the nonce value is not guessable by an attacker. A nonce for CSP needs to be: A cryptographically strong random value (ideally 128+ bits in length)

Is unsafe-inline safe?

As you might guess it is generally unsafe to use unsafe-inline . The unsafe-inline keyword annuls most of the security benefits that Content-Security-Policy provide. When someone requests that URL the bad-stuff. js will execute.

How do I fix Content Security Policy blocks inline execution of scripts and stylesheets?

The Content Security Policy (CSP) prevents cross-site scripting attacks by blocking inline execution of scripts and style sheets. To solve this, move all inline scripts (e.g. onclick=[JS code]) and styles into external files. adding the hash or nonce of the inline script to your CSP header.


1 Answers

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/

like image 181
Wellington PF Avatar answered Oct 20 '22 12:10

Wellington PF