javascriptjavaxssapache-stringutils

Escaping characters to avoid XSS in Java


I need to escape characters to avoid XSS. I am using org.apache.commons.lang.StringEscapeUtils.escapeHtml(String str), which helps in the following way:

Raw input

" onmouseover=alert() src="

After escaping HTML becomes

" onmouseover=alert() src="

However, there are cases in which the reflected input is trapped in single quotes, such as:

test'];}alert();if(true){//

In that particular case, escaping HTML does not have any effect. However, org.apache.commons.lang.StringEscapeUtils also has a method called escapeJavascript(String str), which would convert the input into:

test\'];}alert();if(true){\/\/

The question here is, would you sanitize your input by escaping HTML first and then Javascript? The other would be to replace the single quote character with \' manually.

Any help will be greatly appreciated!


Solution

  • As @gabor-lengyel mentioned I should be able to escape a single quote with an html encoder.

    The problem I had is that I was using org.apache.commons.lang.stringescapeutils.escapeHtml and it is not capable of escaping single quotes with the corresponding HTML entity. I am now using org.springframework.web.util.HtmlUtils.htmlEscape, which is capable of dealing with both double and single quotes.

    Thank you @gabor-lengyel again for your help!