views:

333

answers:

4

How can I prevent XSS attacks in Java? Are there any good libraries for that?

+1  A: 

The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.

On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.

sri
+4  A: 

Since XSS is usually a concern in webapplications I bet that you're talking about JSP/Servlet. XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request headers, URL, body, parameters, etc, the whole request. Also the user-controlled input which is stored in a database needs to be escaped.

For example:

<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>

This will escape under each <, >, ", ' and & which may malform the rendered HTML into HTML/XML entities as &lt;, &gt;, &quot;, &apos; and &amp;.

Note that you don't need to escape them in the Java (Servlet) code, since they doesn't harm in there. Some may opt to escape them during request processing (as you do in Servlet) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped or that the DB-stored data get unportable. The only concern in the server side with regard to databases is SQL injection prevention. Any decent ORM library (Hibernate and so on) have already taken this into account, but if you're working with "raw" JDBC, you need to ensure that you set user-controlled input using PreparedStatement instead of Statement.

BalusC
+1  A: 

I would suggest regularly testing for vulnerabilities using an automated tool, and fixing whatever it finds. It's a lot easier to suggest a library to help with a specific vulnerability then for all XSS attacks in general.

Skipfish is an open source tool from Google that I've been investigating: it finds quite a lot of stuff, and seems worth using.

Sean Reilly
Prevention is better than diagnosing (eg. skipfish) followed by subsequent quick-fixes.
sri
I disagree. Prevention without diagnosis is just dogma. Run the diagnosis as part of your CI cycle to avoid the "quick fix" problem.
Sean Reilly
A: 

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

Tom Hawtin - tackline