posted 17-Apr-2012 | 26 comments | , , , ,

Cross-site request forgery attacks (CSRF) are very common in web applications and can cause significant harm if allowed. If you have never heard of CSRF I recommend you check out OWASPs page about it.

Luckily preventing CSRF attacks is quite simple, I’ll try to show you how they work and how we can defend from them in the least obtrusive way possible in Java based web apps.

Imagine you are about to perform a money transfer in your bank’s secure web page, when you click on the transfer option a form page is loaded that allows you to choose the debit and credit accounts, and enter the amount of money to move. When you are satisfied with your options you press “submit” and send the form information to your bank’s web server, which in turns performs the transaction.

Now add the following to the picture, a malicious website (which you think harmless of course) is open on another window/tab of your browser while you are innocently moving all your millions in your bank’s site. This evil site knows the bank’s web forms structure, and as you browse through it, it tries to post transactions withdrawing money from your accounts and depositing it on the evil overlord’s accounts, it can do it because you have an open and valid session with the banks site in the same browser! This is the basis for a CSRF attack.

One simple and effective way to prevent it is to generate a random (i.e. unpredictable) string when the initial transfer form is loaded and send it to the browser. The browser then sends this piece of data along with the transfer options, and the server validates it before approving the transaction for processing. This way, malicious websites cannot post transactions even if they have access to a valid session in a browser.

To implement this mechanism in Java I choose to use two filters, one to create the salt for each request, and another to validate it. Since the users request and subsequent POST or GETs that should be validated do not necessarily get executed in order, I decided to use a time based cache to store a list of valid salt strings.

The first filter, used to generate a new salt for a request and store it in the cache can be coded as follows:

package com.ricardozuasti.csrf;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.RandomStringUtils;

public class LoadSalt implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        // Assume its HTTP
        HttpServletRequest httpReq = (HttpServletRequest) request;

        // Check the user session for the salt cache, if none is present we create one
        Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>)
            httpReq.getSession().getAttribute("csrfPreventionSaltCache");

        if (csrfPreventionSaltCache == null){
            csrfPreventionSaltCache = CacheBuilder.newBuilder()
                .maximumSize(5000)
                .expireAfterWrite(20, TimeUnit.MINUTES)
                .build();

            httpReq.getSession().setAttribute("csrfPreventionSaltCache", csrfPreventionSaltCache);
        }

        // Generate the salt and store it in the users cache
        String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());
        csrfPreventionSaltCache.put(salt, Boolean.TRUE);

        // Add the salt to the current request so it can be used
        // by the page rendered in this request
        httpReq.setAttribute("csrfPreventionSalt", salt);

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}

I used Guava CacheBuilder to create the salt cache since it has both a size limit and an expiration timeout per entry. To generate the actual salt I used Apache Commons RandomStringUtils, powered by Java 6 SecureRandom to ensure a strong generation seed.

This filter should be used in all requests ending in a page that will link, post or call via AJAX a secured transaction, so in most cases it’s a good idea to map it to every request (maybe with the exception of static content such as images, CSS, etc.). It’s mapping in your web.xml should look similar to:

    ...
    <filter>
        <filter-name>loadSalt</filter-name>
        <filter-class>com.ricardozuasti.csrf.LoadSalt</filter-class>
    </filter>
    ...
    <filter-mapping>
        <filter-name>loadSalt</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>
    ...

As I said, to validate the salt before executing secure transactions we can write another filter:

package com.ricardozuasti.csrf;

import com.google.common.cache.Cache;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class ValidateSalt implements Filter  {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        // Assume its HTTP
        HttpServletRequest httpReq = (HttpServletRequest) request;

        // Get the salt sent with the request
        String salt = (String) httpReq.getParameter("csrfPreventionSalt");

        // Validate that the salt is in the cache
        Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>)
            httpReq.getSession().getAttribute("csrfPreventionSaltCache");

        if (csrfPreventionSaltCache != null &&
                salt != null &&
                csrfPreventionSaltCache.getIfPresent(salt) != null){

            // If the salt is in the cache, we move on
            chain.doFilter(request, response);
        } else {
            // Otherwise we throw an exception aborting the request flow
            throw new ServletException("Potential CSRF detected!! Inform a scary sysadmin ASAP.");
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}

You should configure this filter for every request that needs to be secure (i.e. retrieves or modifies sensitive information, move money, etc.), for example:

    ...
    <filter>
        <filter-name>validateSalt</filter-name>
        <filter-class>com.ricardozuasti.csrf.ValidateSalt</filter-class>
    </filter>
    ...
    <filter-mapping>
        <filter-name>validateSalt</filter-name>
        <url-pattern>/transferMoneyServlet</url-pattern>
    </filter-mapping>
    ...

After configuring both servlets all your secured requests should fail :). To fix it you have to add, to each link and form post that ends in a secure URL, the csrfPreventionSalt parameter containing the value of the request parameter with the same name. For example, in an HTML form within a JSP page:

...
<form action="/transferMoneyServlet" method="get">
    <input type="hidden" name="csrfPreventionSalt" value="<c:out value='${csrfPreventionSalt}'/>"/>
    ...
</form>
...

Of course you can write a custom tag, a nice Javascript code or whatever you prefer to inject the new parameter in every needed link/form.

  • Rahul Ahluwalia

    Guys check this out…..   Whether you are a professional developer or
    a student, every1 can submit their apps developed by using the Series 40 Web
    apps SDK and win.

    Register today to submit ur apps….   

    http://bit.ly/ICUrkh

  • http://www.facebook.com/gcziprusz Gabriel Cziprusz

    How would the code below change if it was https?
     // Assume its HTTP
           HttpServletRequest httpReq = (HttpServletRequest) request;

  • http://ricardozuasti.com/ Ricardo Zuasti

    It wouldn’t change at all. The HttpServletRequest object is agnostic of the transport layer used (SSL or regular). Actually the application server doesn’t mind at all if your connection is encrypted, on the HTTP side all requests look the same, there is just a flag and some extra metadata for you to peek into if you want to get specific SSL information (like client certificates).

  • Pingback: CSRF Mitigation With AspectJ and AOP « BojanSimic.com

  • Ajeet Singh

    Thanks a lot Ricardo for this Simple and great tutorial. I was seeking from last few days and voila It works.

  • Ajeet Singh

    Hi Ricardo, have a little confusion. Just want to know, how your code is different from the what the Apache Tomcat 6+ version provides us org.apache.catalina.filters.CsrfPreventionFilter to prevent the same thing..? Can we use CsrfPreventionFilter
    for the same purpose? If Yes, then how can we achieve it ..? Waiting for your reply. (Please reply on my email ID also)
    Thanks.

  • http://ricardozuasti.com/ Ricardo Zuasti

    Ajeet, hi. Indeed the Apache CsrfPreventionFilter filter prevents the exact same problem, it slightly different implementation wise, but just as effective. Check out their documentation on how to use it at http://tomcat.apache.org/tomcat-6.0-doc/config/filter.html#CSRF_Prevention_Filter.

  • Pingback: JavaPins

  • Chris

    Hi Ajeet, It would be a great help if you post the code you used to implement the org.apache.catalina.filters.CsrfPreventionFilter.

  • Balu

    I am getting 3 problems
    1.The method getIfPresent(String) is undefined for the type Cache
    The method getIfPresent(String) is undefined for the type Cache
    2.The method put(String, Boolean) is undefined for the type Cache
    3.The method build(CacheLoader) in the type CacheBuilder is not applicable for the arguments ()

  • http://ricardozuasti.com/ Ricardo Zuasti

    Balu, it seems you have a different Cache class. Check that you have the latest Google JAR file or that you do not have a “Cache” class from a different package thats being used instead of the one in the sample.

  • Peter

    Hello, if I want to implement your approach for an already existing dojo_single_page_project, I have to change every xhr call in order to add the hidden parameter? It’s a such huge job…
    Maybe I just want to hack/override into dojo.xhrGet and dojo.xhrPost to add it.

  • http://ricardozuasti.com/ Ricardo Zuasti

    Peter, you need to achieve a way in which a unique code is sent from the client to the server on each request and validated on the server. This typically implies modifying all your urls/form posts to contain such parameter, depending on your development framework adding this can be more or less work, I haven’t worked with dojo so I can give you any specific pointers on how to do it yourself… sorry

    r.

  • derya

    this doesnt work for struts or jsf

  • Rama

    Hi Ricardo
    I am facing some small problem please help me out.
    I am getting null value for the
    String salt = (String) httpReq.getParameter(“csrfPreventionSalt”);
    However i have given the value my jsp as:
    <input type="hidden" name="csrfPreventionSalt" value="”/>
    .could you tell me where i am doing mistake…..

  • rama

    <input type="hidden"
    name="csrfPreventionSalt" value="”
    />

  • http://ricardozuasti.com/ Ricardo Zuasti

    Rama, the code seems fine, you should check that the form is actually being posted to the component using the parameters and that there are no client side redirects (which could erase all POST/GET parameters).

    cheers,
    r.

  • rama

    Ricardo the jsp page is like that:

    <input type="hidden" name="csrfPreventionSalt" value="<c:out value='${csrfPreventionSalt}'/<br />&gt.
    So here post we are using to send the all login information for the valid user.
    there is no client side redirect is happening.

  • Shadab

    Thanks for the nice post.
    I want to add the csrfPreventionSalt parameter to all the forms. Is there a way to do so? I dont want to add this parameter manually to hundreds of pages.

  • http://ricardozuasti.com/ Ricardo Zuasti

    It really depends on which framework you are using. If you have plain hand made HTML forms I guess you have to add it manually to all pages…

    cheers,
    r.

  • kailash

    I am working in a legacy jsp based project in which I have to secure certain
    links for CSRF. I made the CSRF filter similar to the one mentioned in this
    blog. But the problem is that certain jsp are accessible by url option like
    url=adduser.jsp?opt=init and once jsp is displayed , user can do app state
    changing action from it. So if I use the common filter to protect this jsp ,
    then I have to add the token on url link itself like url=adduser.jsp?opt=init&tkn=lalala
    which I need to avoid. Do you have any idea how can i remove this from url and
    make a generic code rather then coding in individual jsp and adding token
    checking code before doing any state change operation

  • vijay

    Is it possible to do, both the create and validate request in one filter..
    Thanks in Advance

  • Kailash Nirmal

    Respected Ricardozuasti,

    Thanks a lot for a wonderful article. Sir I need one quick help. I have very small and simple application where authentication is very important. Security team has asked to protect against CSRF. I have implemented above two filter class. First filter class should get call on each request. However when to call second filter class. I understand the logic. But in my application, i dont use any servlets. I have JSPS, Java Classes only. So i have 3 JSPs where form is defined. Please Please let me know how to configure this? It’s urgent sir. How to map second filter class i.e. validateSalt to those 3 JPSs? can I call it for all JSPs? And also tell me please how to fetch value without JSTL. like <c:out value='${csrfPreventionSalt}. How to do this in JSP. I am not much experienced in Java. Please help me.

    Hoping for your favorable response.

    Regards
    Kailash

  • Kailash Nirmal

    I am getting null as value for csrfPreventionSaltCache.getIfPresent(salt). Can anyone help please immediate.

    Thanks in advance.

  • Sachin Singh

    Hi Kailash,

    The token value is injected in the form/jsp using value=”",while the Validate class is checking only for the salt value. For your case remove c:out tag and the null pointer exception should go away. Your token value injection code should look like this –> value=”${csrfPreventionSalt}”.

  • Kailash Nirmal

    Thanks Sachin for the reply.

    I have resolved the issue.

    Regards,
    Kailash