Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic nonce in ASP.NET MVC 4 for CSP

I have MVC application developed in ASP.NET MVC 4. I have using javascripts in several pages. Some of the javascripts are referenced as

@Scripts.Render("~/Scripts/bootstrap")
@Scripts.Render("~/Scripts/js")

and also there are some inline scripts like

<script type="javascript">

   // javascript code
</script>

I want to implement Content Security Policy for this site. The site is hosted in IIS. So in IIS i add content-security-policy header in HTTP Response Header as

object-src 'none';
 script-src 'nonce-{random}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:;
 base-uri 'self';
 report-uri https://csp.withgoogle.com/csp/<unique_id>/<application_version>

So every response will include this header.

Questions:

  1. How do i add randomly generated nonce into script tags and importantly how IIS would know randomly generated nonce value so it can include in response header? (i am assuming every response will have unique nonce value)
like image 618
Dinesh M Avatar asked Feb 06 '20 09:02

Dinesh M


People also ask

How to use nonce in ASP NET?

For WebForms technology, ASP.NET itself inserts some inline scripts. To add the nonce= attribute to them and use 'nonce-<base64-value>', you need to override the built-in methods, for example CreateHtmlTextWriter see Customize web form script generation.

What is CSP nonce?

Generate a nonce for 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)


1 Answers

Inserting nonce tags and especially matching them up in CSP is often tricky. If your script code is static and does not include anything that changes it would be much easier to whitelist them based on their hash. If you remove 'unsafe-inline' many browsers will tell you which hashes need to be added.

And please note that your script-src including https: and http: will allow it to load ANY script on http and https. If your page is served over https active mixed content will not be allowed and scripts on http will not load as a result.

like image 108
Halvor Sakshaug Avatar answered Sep 20 '22 12:09

Halvor Sakshaug