Exploit XSS: Bypass HTMLEncode()

In a previous post, I described how to detect and exploit a basic cross site scripting (XSS) vulnerability. The vulnerability that was demonstrated was not being protected by any mechanism. This article will demonstrate exploiting the same vulnerability being protected by HTMLEncode() as oppose to HTMLAttributeEncode() as described in “How to Prevent Cross Site Scripting (XSS)“.
The source code from the previous demonstration looked like this:
Our exploit is taking advantage of “<%= Post.Title %>” not being encoded before it is placed in the “href” attribute of the “E-mail” anchor tag. The exploit string simply injects a double quote to close out the “href” attribute string and now we can freely add additional elements to the HTML tag, such as an “onmouseover” event to fire a JavaScript payload. What happens if we wrap “<% Post.Title %> with Server.HtmlEncode(), the built-in non-security aware .Net HTML Encoder?
After slightly modifying the content of the post (this happen to be a persistent cross site scripting vulnerability) and displaying it with the updated code, the HTML source code looks like this:
If you look at line 3, you will see we were still able to modify the HTML attributes with our slightly modified injection. What did we modify? HTMLEncode() escapes double quotes as they are part of the XML standard, however it does not escape single quotes, or tick marks. So the modification was to change our double quote injection to a single quote injection and viola!
An interesting item here is that our escaped double quotes seen on line 3 of the source are consumed without any issue by the JavaScript alert function!
The proper fix for this is to use a specific attribute encoder to escape all characters besides alphanumerics to the format of &#[ASCII DECIMAL]; e.g. !. A more security aware HTMLEncode() method, such as the OWASP ESAPI Encoder or the Microsoft AntiXSS encoder will also escape single quotes, or ticks, which would of prevented this particular attack from breaking out of the HTML attributes context. Another reason it is better to use libraries built for security instead of those built to enforce a standard, as the single tick mark is not disallowed in the XML specification.
A full explanation of the intricacies involved in protecting your application from cross site scripting attacks is explained here.
Brian Cardinale
Latest posts by Brian Cardinale (see all)
- Empower Those Who Stand, Forgive Those Who Stumble - January 21, 2017
- Add Custom Header to Nikto Scan - October 28, 2015
- CVE-2015-4670: Directory Traversal to Remote Code Execution in AjaxControlToolkit - June 22, 2015