13

I want to escape for XSS in an HTML context, and so far I treat the <, >, and " characters. Apparently it is recommended to escape the ampersand as well, but why? (Other than for keeping the HTML valid, let's assume that this is not an issue)

So what I am asking is: When I escape <, > and ", can someone demonstrate how the ampersand can still allow an XSS attack in an HTML context?

Cheers!

AymDev
  • 6,626
  • 4
  • 29
  • 52
Brent Gallagher
  • 165
  • 1
  • 7

2 Answers2

9

You should really take a look at the OWASP XSS Prevention Cheat Sheet.

You should escape & because it can be used to circumvent other defenses. Consider this code:

<button onclick="confirm('Do you really want to delete <%= data_from_user; %> ?'">Delete</button>

To defend against XSS inside the onclick event handler, the developer escapes ', ", < and > in data_from_user and thinks everything is ok. The problem is that if the attacker types &#39; which passes the escaping, but ends up allowing the attacker to run javascript.

Example here: http://erlend.oftedal.no/blog/?blogid=124

Erlend
  • 4,336
  • 22
  • 25
  • Interesting example, cheers! What I tried was to inject this into the html: <script type="text/javascript"> Which does not get executed, howerver displayed as " – Brent Gallagher Feb 06 '12 at 00:58
  • Note that in the linked example, the attacker is not described as typing `'`; the attacker is described there as having typed in `Joe');alert('XSS` and the site made that `Joe');alert('XSS`, which was not correct escaping, because that escaped it as far as the HTML was concerned, but apostrophes were still being passed to the JS engine. It's true if an "&" was allowed to get through, the attacker could type it themselves, but the issue being focused on there is that (as mentioned in the OWASP XSS prevention cheat sheet), event-handler attribute text should be *JS*-escaped (\xHH). – Jacob C. Nov 20 '17 at 20:45
  • ...for that matter, the OWASP XSS Prevention Cheat Sheet [actually advises \xHH escaping **all** non-alphanumeric chars with ASCII values < 256](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.233_-_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_JavaScript_Data_Values)... just in case a careless dev uses an unquoted attribute somewhere. – Jacob C. Nov 20 '17 at 20:52
2

you use & to concatenate params in the URL:

Reflected XXS:
Script code is injected in the URL which the webpage reflects to victims

http://mybank.com/page?message= < script src = “evil _script.js” />

Adrian
  • 5,603
  • 8
  • 53
  • 85
  • 3
    Down-voter should explain his view. I agree with this answer. +1 – tusar Feb 03 '12 at 06:38
  • I did not downvote, but I don't see how the URL with the injected message relates to the ampersand. More: in the case of URL query assembling escaping doesn't help, the ampersand in URL parameter needs to be url encoded. – Jan Turoň Jan 17 '21 at 21:48