Fighting XSS in .NET
Cross Site Scripting (XSS) is listed as the top vulnerability on the OWASP Top 10 and one of the more dangerous vulnerabilities on the web. Because of the different ways to manipulate content, fighting XSS is a chore. For proof, check out the “XSS Cheat Sheet” at http://ha.ckers.org/xss.html. That list is still growing…
The main way to fight cross site scripting is encoding. If convert unsafe characters into their html counterparts, then malicious code will not be executed. In .NET, the HttpUtility.HtmlEncode method converts some unsafe characters for you. This is a good way to cleanse content before it is interpreted by the browser, but it won’t stop all XSS vulnerabilities.
HtmlEncode uses “blacklisting” to block unsafe characters. Blacklisting will stop some attempts, but leaves room for other attacks to happen if the coder is not careful. HtmlEncode converts the following characters:
- <
- >
- &
- “
- Characters with values 160-255
This will block most, but what if you fall into a false sense of security and forget what HtmlEncode does? If you were to execute something like this:
<input value=’<%= HtmlEncode(thisAction’)’ %> id=’btnExecute’>
If thisAction equaled alert(document.cookie), then the attack would work. This approach doesn’t seem rational, but I’ve seen worse.
A better approach is to use whitelisting. If you escape everything except what needs to be there, then you decrease your threat surface substantially.