Add nonce attribute to auto-generated WebForms scr

2019-05-24 11:54发布

问题:

While implementing the CSP header on my website, I am facing problems with the automatically generated postback JavaScript that webforms adds to the page:

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

To support some other script tags inline I have successfully added the nonce attribute, however I can find no way to modify this piece of generated code to do the same thing. I have explored ClientScript.GetPostBackEventReference but this appears to control the JavaScript within, nothing about the rendering of the <script> tag itself.

The solution does not necessarily need to involve adding the nonce attribute, anything that complies will do. For example, if there is an ASP.NET setting which can be configured to load this script as a file (which I can whitelist) that would be fine.

回答1:

Good luck implementing a good CSP on ASP.NET with Webforms Scheme - WebForms controls will add a whole bunch of inline scripts like on this login button:

<a id="btnLogin" class="btn btn-info pull-right" href="javascript:__doPostBack(&#39;btnLogin&#39;,&#39;&#39;)">Login</a>

If you're not using many <asp:... controls, you might be alright.

To allow the above script you want to run, you can add this to your CSP after script-src:

sha256-uVkxb0ccirYwSBxwdr2/4qtJEH1eBw7MslAgyLdAVVY="

It lets your browser know that it should execute any script that has that sha256 hash.

The hash I've given you may not work if you're using different newlines to what I'm using (which I believe is windows style).

You should also be careful that if you don't have a page which changes the default form id to something other than "form1".