-1

I am trying to generate random values for nonce, but the generated value don't show in the nonce attributes.

My generated code: It is giving an error getRandomValues is not a function

const nonce = Crypto.getRandomValues(new Uint8Array(32)).toString('base64');
const nonceBase64 = btoa(nonce);
const scripts = document.querySelectorAll('body script');

for (const script of scripts) {
  script.setAttribute('nonce', nonceBase64);
}

The script in the document

<script>
 // inline script
</script>

The rules is also set in my web.config file

<add name="Content-Security-Policy" value="default-src 'self';
 script-src 'report-sample' 'self' https://www.google-analytics.com/analytics.js />

Can anyone assist me on fixing what is not right here? I spent days trying to solve it. I read different documentation but no result.

Touffy
  • 6,309
  • 22
  • 28
  • 2
    https://developer.mozilla.org/en-US/docs/Web/API/Crypto: _"The Web Crypto API **is accessed through the global crypto property**, which is a Crypto object."_ -> `crypto.getRandomValues(...)` – CBroe Aug 03 '23 at 07:18
  • 2
    (Not sure if trying to retro-actively set a nonce on the client side(?) for script elements that have already been parsed, is going to achieve anything though.) – CBroe Aug 03 '23 at 07:20
  • What should I do? I have been struggling for days now and I have no idea what next. Any suggestion? – Neron Godfather Aug 03 '23 at 07:24
  • First, learn to use the console to test your code step by step, so you can fix easy mistakes without asking StackOverflow. Then so some reading on [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP). – Touffy Aug 03 '23 at 07:43
  • Well, in the console like I said it says getRandomValues is not a function and got some error on the restriction from CSP that prevents script to run (I should either use hashes or nonce). – Neron Godfather Aug 03 '23 at 09:14

1 Answers1

0
  1. 'Crypto' is the constructor (the "class", if that makes more sense to you) for crypto. You should generally not use the former. crypto.getRandomValues() definitely works.

  2. toString('base64') only works in Node.js. In the browser or Deno, ArrayView.toString takes no argument and doesn't help at all in this case. To encode your nonce to base64, use btoa(String.fromCharCode(...array))).

tl;dr :

const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))))
Touffy
  • 6,309
  • 22
  • 28
  • Sure, I will give it a try. Is there anything I should pass in the web.config to register the nonce value in the policy? Thanks – Neron Godfather Aug 03 '23 at 07:30
  • That's another question and very relevant to your problem, but StackOverflow isn't the right place. You have too much to catch up on with basic HTTP and JavaScript before you try messing up with CSP nonces. – Touffy Aug 03 '23 at 07:36