Exploit XSS: Bypass HTMLEncode()

Feb 10, 14 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:

Exploit XSS: Bypass HTMLEncode()

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?

Exploit XSS: Bypass HTMLEncode() Source Code

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:

Exploit XSS: Bypass HTML - HTML Source

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!

Exploit XSS: Bypass HTMLEncode() Exploit

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. &#33;. 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

Founder at Sunflower WIFI
Information security professional and full-stack software developer with over 10 years experience in enterprise software solutions.

Leave a Comment

Your email address will not be published. Required fields are marked *