W3C says there is a new attribute in HTML5.1 called nonce
for style
and script
that can be used by the Content Security Policy of a website.
I googled about it but finally didn't get it what actually this attribute do and what changes when using it?
The
nonce
attribute enables you to “whitelist” certain inlinescript
andstyle
elements, while avoiding use of the CSPunsafe-inline
directive (which would allow all inlinescript
/style
), so that you still retain the key CSP feature of disallowing inlinescript
/style
in general.So the
nonce
attribute is way of telling browsers that the inline contents of a particular script or style element were not injected into the document by some (malicious) third party, but were instead put into the document intentionally by whoever controls the server the document is served from.https://developers.google.com/web/fundamentals/security/csp/#if_you_absolutely_must_use_it gives a good example of how to use the
nonce
attribute, which comes down to the following steps:For every request your Web server receives for a particular document, have your backend generate a random base64-encoded string of at least 128 bits of data from a cryptographically secure random number generator; e.g.,
EDNnf03nceIOfn39fn3e9h3sdfa
. That’s your nonce.Take the nonce generated in step 1, and for any inline
script
/style
you want to “whitelist”, make your backend code insert anonce
attribute into the document before it’s sent over the wire, with that nonce as the value:Take the nonce generated in step 1, prepend
nonce-
to it, and make your backend generate a CSP header with that among the values of the source list forscript-src
orstyle-src
:So the mechanism of using a nonce is an alternative to instead having your backend generate a hash of the contents of the inline
script
orstyle
you want to allow, and then specifying that hash in the appropriate source list in your CSP header.Note that because browsers don’t (can’t) check that the nonce value sent changes between page requests, it’s possible—though totally inadvisable—to skip 1 above and not have your backend do anything dynamically for the nonce, in which case you could just put a
nonce
attribute with a static value into the HTML source of your doc, and send a static CSP header with that same nonce value.But the reason you’d not want to use a static nonce in that way is, it’d pretty much defeat the entire purpose of using the nonce at all to begin with—because, if you were to use a static nonce like that, at that point you might as well just be using
unsafe-inline
.