XSS prevention in JSP/Servlet web application

147,622

Solution 1

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 parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests 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(param.foo)}"></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 or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes &amp;amp; instead of &amp; and ultimately the enduser would see &amp; being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

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 HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also Markdown or HTML.

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 (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

Solution 2

I had great luck with OWASP Anti-Samy and an AspectJ advisor on all my Spring Controllers that blocks XSS from getting in.

public class UserInputSanitizer {

    private static Policy policy;
    private static AntiSamy antiSamy;

    private static AntiSamy getAntiSamy() throws PolicyException  {
        if (antiSamy == null) {
            policy = getPolicy("evocatus-default");
            antiSamy = new AntiSamy();
        }
        return antiSamy;

    }

    public static String sanitize(String input) {
        CleanResults cr;
        try {
            cr = getAntiSamy().scan(input, policy);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return cr.getCleanHTML();
    }

    private static Policy getPolicy(String name) throws PolicyException {
        Policy policy = 
            Policy.getInstance(Policy.class.getResourceAsStream("/META-INF/antisamy/" + name + ".xml"));
        return policy;
    }

}

You can get the AspectJ advisor from the this stackoverflow post

I think this is a better approach then c:out particular if you do a lot of javascript.

Solution 3

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.

Solution 4

Managing XSS requires multiple validations, data from the client side.

  1. Input Validations (form validation) on the Server side. There are multiple ways of going about it. You can try JSR 303 bean validation(hibernate validator), or ESAPI Input Validation framework. Though I've not tried it myself (yet), there is an annotation that checks for safe html (@SafeHtml). You could in fact use Hibernate validator with Spring MVC for bean validations -> Ref
  2. Escaping URL requests - For all your HTTP requests, use some sort of XSS filter. I've used the following for our web app and it takes care of cleaning up the HTTP URL request - http://www.servletsuite.com/servlets/xssflt.htm
  3. Escaping data/html returned to the client (look above at @BalusC explanation).

Solution 5

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.

Share:
147,622

Related videos on Youtube

newbie
Author by

newbie

Java developer

Updated on July 05, 2022

Comments

  • newbie
    newbie almost 2 years

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

  • Sripathi Krishnan
    Sripathi Krishnan about 14 years
    Prevention is better than diagnosing (eg. skipfish) followed by subsequent quick-fixes.
  • Sean Reilly
    Sean Reilly about 14 years
    I disagree. Prevention without diagnosis is just dogma. Run the diagnosis as part of your CI cycle to avoid the "quick fix" problem.
  • Tyler
    Tyler over 12 years
    Just because you're using Hibernate, doesn't mean you're safe from SQL injection. See blog.harpoontech.com/2008/10/… for example.
  • BalusC
    BalusC about 12 years
    @chad: that's not true. It's only the case when you're string-concatenating user-controlled input straight in the SQL/HQL/JPQL query like so "SELECT ... WHERE SOMEVAL = " + someval instead of using parameterized queries as you've shown. No one ORM can safeguard against this kind of developer mistakes.
  • chadmaughan
    chadmaughan about 12 years
    @BalusC - Doh! I had that reversed. Vulnerable example is: Query query = session.createQuery("SELECT * FROM TABLE WHERE SOMEVAL = " + someval); Using the binding syntax ":" in Hibernate (like my example above) prevents SQL injection. Deleting comment to prevent someone using my bad example.
  • Guido Celada
    Guido Celada over 9 years
    I think you DO have to validate in the server aswell. All the validation can be bypassed by altering the HTTP parameters. And sometimes, the data that you persist can be consumed by other applications in an enterprise app. Sometimes you dont have access to the views of the other applications so you need to sanitze the input before persisting in the database.
  • BalusC
    BalusC over 9 years
    @Guido: you're not understanding the problem.
  • Guido Celada
    Guido Celada over 9 years
    @BalusC: please expand.
  • Shubham Maheshwari
    Shubham Maheshwari over 8 years
    The normal practice is to HTML-escape any user-controlled data during redisplaying, not during processing the submitted data in servlet nor during storing in DB. If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.
  • Adam Gent
    Adam Gent over 8 years
    Yes and no. Although the general practice is to escape on display there are many reasons you might want to sanitize on write. There are some cases where you do want your users to enter a subset of HTML and although you could sanitize on display this is actually rather slow and even confusing to users. Second if you share the data with 3rd party services like external APIs those services may or may not do the proper sanitizing themselves.
  • Shubham Maheshwari
    Shubham Maheshwari over 8 years
    as you and me both mentioned, the "normal practice" is to escape on display. What you have mentioned in you above comment are more specific use cases and hence would agreeably require specific solutions.
  • Adam Gent
    Adam Gent over 8 years
    Yes I perhaps should make my use case more clear. I work on mainly content management (HTML editing) things.
  • Venkaiah Yepuri
    Venkaiah Yepuri over 7 years
    @BalusC: Hi Bal, by using yours suggestion I get removed 4 XSS issues in my app thanks a lot for useful solution. Here I need yours suggestion again as I displaying dom object using jstl espression like <div><c:out value="${htmlContent}" escapeXml="false" /></div> here htmlContentvalue is something like <span><h1>Hi</h1></span> (this value coming from database) now if I remove escapeXml="false" from c:out then its displays as it is on page then if keep escapeXml="false" its parsing the dom object properly but when my htmlContent having some script code then xss issue is coming.
  • Venkaiah Yepuri
    Venkaiah Yepuri over 7 years
    @BalusC: if htmlContent is <span><h1><script>alert("Hi");</script></h1></span> then if I use <c:out value="${htmlContent}" escapeXml="false" /></div> in jsp then on browser user will get alert box so it may leades XSS issue. Please suggest me what I can do in this situation.
  • BalusC
    BalusC over 7 years
    @Venki: Just read 4th paragraph of answer which tells something about dealing with user-controlled HTML.
  • Jonathan Laliberte
    Jonathan Laliberte almost 7 years
    Great answer @BalusC Thanks a bunch! Quick question though if you don't mind. So i shouldn't escape html on user input, only when displaying it? Is that what you mean by double escaping? And if not, how does one go about escaping user input using a textarea, not an input field? Is ( htmlEscape="true" ) correct?
  • peater
    peater almost 5 years
    Please note: "HTML entity encoding doesn't work if you're putting untrusted data inside a <script> tag anywhere, or an event handler attribute like onmouseover, or inside CSS, or in a URL." github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/…
  • peater
    peater almost 5 years
    The OWASP cheat sheets have moved to GitHub. Here is the link for the XSS Prevention Cheat Sheet github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/…
  • BalusC
    BalusC almost 5 years
    @peater: Yup, when putting untrusted data inside JS code, you need to JS-encode instead of HTML-encode. And, when putting untrusted data inside CSS code, you need to CSS-encode instead of HTML-encode. And, when putting untrusted data inside URLs, you need to URL-encode instead of HTML-encode. HTML encoding should only be used for putting untrusted data inside HTML code.
  • Raphael Onofre
    Raphael Onofre over 4 years
    Just to add some info here, escapeXml default property in c:out tag is 'true'
  • Sam
    Sam almost 4 years
    Hi Brad, Above use case is what i am looking for.could you please help explain how can you prevent xss in case of above scenario(foreach one)
  • Brad Parks
    Brad Parks almost 4 years
    The only one I really remember now is using the EL resolver - that's what we ended up using at our company. Basically it automatically escapes everything, and if you really really dont want something escaped, you can wrap it in <enhance:out escapeXml="false"> as detailed in the article.