What’s the purpose of the HTML "nonce" attribute for script and style elements?

ata picture ata · Mar 21, 2017 · Viewed 88.6k times · Source

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 does and what changes when using it?

Answer

sideshowbarker picture sideshowbarker · Mar 21, 2017

The nonce attribute enables you to “whitelist” certain inline script and style elements, while avoiding use of the CSP unsafe-inline directive (which would allow all inline script/style), so that you still retain the key CSP feature of disallowing inline script/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.

The Web Fundamentals Content Security Policy article’s If you absolutely must use it ... section has a good example of how to use the nonce attribute, which amounts to the following steps:

  1. 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.

  2. Take the nonce generated in step 1, and for any inline script/style you want to “whitelist”, make your backend code insert a nonce attribute into the document before it’s sent over the wire, with that nonce as the value:

     <script nonce="EDNnf03nceIOfn39fn3e9h3sdfa">…</script>
    
  3. 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 for script-src or style-src:

     Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
    

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 or style 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.