How to avoid HTML injection and XSS in .JSP pages?

10

No PHP I have seen uses of htmlspecialchars and mysqli . But in Java is there any way to avoid XSS and HTML injection?

I'd also like to know what would be the best (safest) way: Escaping the elements ( HTML , Javascript ) or inserting a <pre> tag to view the data so this does not affect the page?

    
asked by anonymous 17.04.2015 / 18:42

2 answers

1

JSP's

The simplest way is to use the out from the JSTL Core library . Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${suaVariavel}" />

would be the same as:

<c:out value="${suaVariavel}" escapeXml="true" />

More detailed example in this reference link

A common mistake

Find that JSTL already comes inside WEB containers and forget to put JSTL in the project, which can be found here , or, to be imported as a dependency in a maven project:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

It is worth taking a look ...

ESAPI - Extra security for WEB applications

A utility lib that implements various security mechanisms. Allows you to safely read cookies, request, session parameters, and more.

    
20.04.2015 / 22:39
0

As Victor said, <pre> does not avoid this, you may be thinking that this tag is converting content to entities, but maybe it's just a mess.

I personally allow the exact recording of what was "written", but at the time of reading I use methods similar to htmlspecialchars , thus avoiding conflicts, since the texts did not change the recording.

If your concern is to read the data from a bank and print it on the screen, you can use it when reading the data from the line:

import org.apache.commons.lang.StringEscapeUtils;
...
String data = StringEscapeUtils.escapeHtml("<script>alert(1);</script>");

I do not know how your code is, and what framework you use, but I believe that the meaning is always this, to "escape" content at the time of viewing (correct me if I'm wrong).

Documentation: StringEscapeUtils (Commons Lang 2.6 API)

    
19.04.2015 / 21:53