If you want to include JavaScript code in the <script> block as follows:
<script> var myVariable = '<%=thisIsWrong %>'; </script>
Then, in this context, you should use HttpUtility.JavaScriptStringEncode . This function also correctly encodes special characters, so if </script> should appear in the script tag when trying to close the HTML script tag, ready for an XSS attack, it will display as:
\u003c/script\u003e
which is the correct encoding for JavaScript to understand as </script> but without a browser interpreting it as a literal closing tag script. Some naively written JavaScript coding procedures will not convert this because the sequence does not contain the characters \ , " or ' .
If you are not sure that closing script tags is not displayed, such an attack is possible. Imagine this is the input for your application:
</script><script>alert(1)</script>
which is displayed in the browser as
<script type="text/javascript"> alert('</script><script>alert(1)</script>'); </script>
and the browser interprets the script tag ending in alert('</script> , and simply executes what is in the new script tag.
Using the JavaScriptStringEncode function is safe because it displays as:
<script type="text/javascript"> alert('\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e'); </script>
which does not contain </script> for interpreting the browser.
There is System.Web.HttpUtility.JavaScriptStringEncode (), but it uses a blacklist to encode, so it is unlikely to be as good as a whitelist encoder.
Some of the other encoding functions in .NET use blacklist methods, however in my own testing, JavaScriptStringEncode seems to be enough.
OWASP Recommendation for JavaScript
With the exception of alphanumeric characters, avoid all characters less than 256 with the \ xHH format to prevent the data value from being turned off in a script context or other attribute.
so you can easily write your own to fit that.
Note that if you want to include code in attribute tags:
<a href="http://example.com" onclick="alert('<%=wrong>')">Click</a>
then the OWASP method means that you also do not need to worry about HTML encoding (because in fact no HTML characters with a special meaning are output). Without (e.g. with JavaScriptScriptEncode ) you also need to encode HTML.
Having said all this, a safer way to get closer to it is as an answer to my question. A safe way to insert dynamic values into external JavaScript files . Use the data- attributes to place dynamic values in the DOM (in HTML), and then use JavaScript to extract these values. This will prevent all headaches in JavaScript encoding.