tags:

views:

631

answers:

5

What should I do to prevent XSS in Java? I'm using Spring MVC. Right now I am just putting all places where I output user text into <c:out /> tags, but this seems error prone as I might miss a place.

Is there an easy systematic way to prevent this? Maybe like a filter or something?

EDIT: I'm collecting input by specifying @RequestParam parameters on my controller methods.

+2  A: 

Try XSSFilter.

Bozho
A: 

How are you collecting user input in the first place? This question / answer may assist if you're using a FormController:

Spring: escaping input when binding to command

Ben Poole
+4  A: 

In Spring you can encode the escape the html from JSP pages generated by <form> tags. This closes off a lot avenues for XSS attacks, this can be done automatically in three ways:

For the entire application in the web.xml file:

<context-param>
    <param-name>defaultHtmlEscape</param-name>
    <param-value>true</param-value>
</context-param>

For all forms on a given page in the file itself:

<spring:htmlEscape defaultHtmlEscape="true" /> 

For each form:

<form:input path="someFormField" htmlEscape="true" /> 
Tendayi Mawushe
I put <spring:htmlEscape defaultHtmlEscape="true" /> in an include file that I include in all my pages, but it doesn't seem to make a difference. Will that tag cause ${param.q} to be escaped?
Doug
Andreas
A: 

Always check manually the methods, tags you use, and make sure that they always escape (once) in the end. Frameworks have many bugs and differences in this aspect.

An overview: http://www.gablog.eu/online/node/91

sibidiba
+1  A: 

When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.

I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91

Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.

Erlend
"take special care" = use the `<c:out />`-tag when you output data in HTML attributes or javascript. (see my comment at Tendayi Mawushe's answer)
Andreas
Well, it's more than just using <c:out />. Javascript has other control characters than HTML, and can be attacked in different ways, and so needs to be handled using other types of escaping. A simple example:var a = '<c:out ... />'; var b = '<c:out ... />';If the input in a is a single backslash, script in b will run. Escaping depends on context.
Erlend