newbie newbie - 1 year ago 133
Java Question

XSS prevention in JSP/Servlet web application

How can I prevent XSS attacks in a JSP/Servlet web application?

Answer Source

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, cookies, URL, body, parameters, etc, the whole request. Also the user-controlled input which is stored in a database needs to be escaped during redisplaying.

For example:

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

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

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over 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 becomes unportable (e.g. when exporting data to CSV, XLS, PDF, etc which doesn't require HTML-escaping at all).

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a Markdown parser like Pegdown or a HTML parser like Jsoup for this. See also I'm looking for a Java HTML encoder.

The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.

An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download