Skip to main content

Cross-site request forgery prevention filter in GlassFish 3.1.1

Posted by swchan2 on May 31, 2011 at 3:06 PM PDT

Cross-site request forgery (CSRF)
is a malicious attack exploiting the trust of a site from a user's browser.
As an example, an user may be tricked to invoke a url to do a bank transaction
by either clicking on the url or accessing the url through .

In GlassFish 3.1.1, there is a
CSRF prevention filter,
org.apache.catalina.filters.CsrfPreventionFilter,
which is based on Tomcat 7.
The filter basically uses nonce exchange to a secure the communication.

There are three possible initialization parameters for the above filter:

Filter init-param Short Description Default

entryPoints A comma separated list of URLs that will not be checked for nonce in HTTP GET method. none

nonceCacheSize number of cached nonce based on LRU. This is used for parallel requests, for instance from frames. 5

randomClass The name of the class to generate the nonces. The class must extends java.util.Random. java.security.SecureRandom

By default, the filter is not turned on.

One can prevent the CSRF attack for a given web application as follows:

  1. enabling the filter in web.xml

    For instance,
      <filter>
        <filter-name>csrf<filter-name>
        <filter-class>org.apache.catalina.filters.CsrfPreventionFilter<filter-class>
      <filter>
      <filter-mapping>
        <filter-name>csrf<filter-name>
        <url-pattern>/myservlet<url-pattern>
      <filter-mapping>
       
  2. sending the nonce in each HTTP request associated to the filter

    One can do this with the help of HttpServletResponse#encodeURL(String url)
    and HttpServletResponse#encodeRedirectURL(String url).
    Or one can pass back the nonce as a request parameter with name org.apache.catalina.filters.CSRF_NONCE, which is the value of the constant org.apache.catalina.filters.Constants.CSRF_NONCE_REQUEST_PARAM.

    For instance, in a jsp page, instead of having

      <a href="index.jsp">Go to index</a>

    we will have
            
      <a href="<%=response.encodeURL("index.jsp")%>">Go to index</a>
       

Note that one can also enable the CSRF prevention filter for a given domain
by adding the filter in default-web.xml for the domain.