Differences between revisions 3 and 4
Revision 3 as of 2009-09-20 23:20:03
Size: 9529
Editor: localhost
Comment: converted to 1.6 markup
Revision 4 as of 2010-01-28 07:54:09
Size: 9523
Editor: s235-200
Deletions are marked like this. Additions are marked like this.
Line 31: Line 31:
  securityCode = new Long(System.currentTimeMillis()).toString();   securityCode = Long.toString(System.currentTimeMillis());

Tapestry 5 and Cross-site request forgeries

Cross-site request forgeries (CSRF) is a web application vulnerability which is often overlooked by web developers. If your application is vulnerable to CSRF and an attacker can entice you to request a specific URL (like open a page, view an image in webmail etc.) the attacker can execute random Tapestry actions perform post's etc. without the users consent. For example an attacker can change the users password or change the email address used to sent a new password to.

For more info on CSRF see for example: http://en.wikipedia.org/wiki/Cross-site_request_forgery.

One way to protect against CSRF is to add a non-guessable code, from now on called sid, to the URLs that need to be protected against CSRF. The sid is added to the user session to make sure that every user has his/her own sid. When Tapestry receives a request (for a page or action) and that page/action need to be protected a check is done to see if the sid from the URL matches the sid stored in the user session. If the sid from the URL is missing or the sid from the URL is different from the sid in session you know that the request was not generated by Tapestry.

Howard suggested two possible solutions


My implementation uses the LinkFactory approach because it does not require changing any code other than adding a few lines to you application module (there are some exceptions but I come to that later).



The user sid need to be stored in the user session so we will need a ASO. The CSRF ASO uses currentTimeMillis as the source of the sid. This is just for demo purposes and you should change it to make it use some secure random source.

   1 public class CSRF 
   2 {
   3         private final String securityCode;
   5         public CSRF()
   6         {
   7                 // Note: Change this so the security code (sid) created by a
   8                 // secure random source (like SecureRandom)
   9                 securityCode = Long.toString(System.currentTimeMillis());
  10         }
  12         public String getSecurityCode() {
  13                 return securityCode;
  14         }
  15 }

Filter and LinkFactoryListener

To add the sid to newly created links we need an implementation of the LinkFactoryListener interface. For checking the sid we need an implementation of ComponentEventRequestFilter. The CSRF!FilterImpl implements both although they can be split-up into two different classes.

First the CSRFFilter interface (strictly not required but I like to use interfaces)

Interface (CSRFFilter)

   1 public interface CSRFFilter extends ComponentEventRequestFilter {
   2         /*
   3          * For now we do not need any methods.
   4          */
   5 }

Implementation (CSRFFilterImpl)

   1 /**
   2  * ComponentEventRequestFilter that checks if the request contains the correct secureID. Without
   3  * a secureID the application is vulnerable to 'Cross Site Request Forgeries' (CSRF).
   4  * 
   5  * Note: This filter only protects actions (like component actions and posts). It does not protect
   6  * a page render request but that should not be problematic because a page render should not
   7  * have any side effects just render the page.
   8  * 
   9  * @author Martijn Brinkers
  10  *
  11  */
  12 public class CSRFFilterImpl implements CSRFFilter, LinkFactoryListener
  13 {
  14         public static String CSRF_SECURITY_PARAMETER = "sid";
  16         private final ApplicationStateManager asm;
  17         private final Request request;
  18         private final Response response;
  19         private final LinkFactory linkFactory;
  20         private final RequestPageCache requestPageCache;
  22         /*
  23          * The page to redirect to when secureID is incorrect
  24          */
  25         private final String redirectTo;
  27         public CSRFFilterImpl(ApplicationStateManager asm, Request request, Response response, 
  28                         LinkFactory linkFactory, RequestPageCache requestPageCache, String redirectTo)
  29         {
  30                 Check.notNull(asm, "asm");
  31                 Check.notNull(request, "request");
  32                 Check.notNull(response, "response");
  33                 Check.notNull(linkFactory, "linkFactory");
  34                 Check.notNull(requestPageCache, "requestPageCache");
  35                 Check.notNull(redirectTo, "redirectTo");
  37                 this.asm = asm;
  38                 this.request = request;
  39                 this.response = response;
  40                 this.linkFactory = linkFactory;
  41                 this.requestPageCache = requestPageCache;
  42                 this.redirectTo = redirectTo;
  43         }
  45         private String getSecurityCode() {
  46                 return asm.get(CSRF.class).getSecurityCode();
  47         }
  49         public void createdActionLink(Link link) 
  50         {
  51                 link.addParameter(CSRF_SECURITY_PARAMETER, getSecurityCode());
  52         }
  54         public void createdPageLink(Link link) 
  55         {
  56                 /*
  57                  * Page links do not need the SecureID because pages should only show the page and
  58                  * not have any side effects.
  59                  */
  60         }
  62         public void handle(ComponentEventRequestParameters parameters, 
  63                         ComponentEventRequestHandler handler)
  64         throws IOException 
  65         {
  66         Page page = requestPageCache.get(parameters.getActivePageName());
  68         if (isCSRFProtected(page)) 
  69         {
  70                 /*
  71                  * Check if the secureID is equal to the secureID in the session
  72                  */
  73                 String secureID = request.getParameter(CSRF_SECURITY_PARAMETER);
  75                 CSRF csrf = asm.get(CSRF.class);
  77                 if (secureID == null || csrf == null || !csrf.getSecurityCode().equals(secureID)) 
  78                 {
  79                         /*
  80                          * Illegal secure ID so redirect
  81                          */
  82                 Link link = linkFactory.createPageLink(redirectTo, false);
  84                 response.sendRedirect(link);
  86                 return;
  87                 }
  88         }
  90         /*
  91          * Not protected or secureID is correct so continue
  92          */
  93         handler.handle(parameters);
  94         }
  96         private boolean isCSRFProtected(Page page)
  97         {
  98                 /*
  99                  * For now all actions are protected. We can always create a special Annotation when
 100                  * we need to specify which pages/actions are protected.
 101                  */
 102                 return true;
 103         }
 104 }

The Application module

You will need to add the following lines to your application module (or better create a special separate security module)

   1     public static void contributeFactoryDefaults(
   2             MappedConfiguration<String, String> configuration)
   3     {
   4           // sets the page to redirect to when the sid is incorrect
   5         configuration.add("csrf.redirectTo", "accessdenied");
   6     }
   9     /*
  10      * Builds the 'Cross Site Request Forgeries' (CSRF) filter.
  11      * 
  12      * Note: must be EagerLoad'ed because we want the LinkFactory listener to be active from the
  13      * start.
  14      */
  15     @EagerLoad
  16     public static CSRFFilter buildCSRFLinkFactoryListener(ApplicationStateManager asm, 
  17                 Request request, Response response, LinkFactory linkFactory,
  18                 RequestPageCache requestPageCache, @Inject @Value("${csrf.redirectTo}") String redirectTo)
  19     {
  20         CSRFFilterImpl filter = new CSRFFilterImpl(asm, request, response, linkFactory,
  21                         requestPageCache, redirectTo);
  23         linkFactory.addListener(filter);
  25         return filter;
  26     }
  28     public void contributeComponentEventRequestHandler(OrderedConfiguration<ComponentEventRequestFilter> configuration,
  29                 CSRFFilter csrfFilter)
  30     {
  31         /*
  32          * Make sure the CSRF filter is injected before anything else
  33          */
  34         configuration.add("CSRFFilter", csrfFilter, "after:UploadException", "before:Ajax");
  35     }

The gotcha's

1.Only action links are protected. I think that page rendering should not contain any side-effects (ie. they should only render a page) so not having a sid on a page link should not be a problem security wise. A sid on a page link is also not something you want because it creates 'ugly' links that cannot be bookmarked (because the sid wil be invalid after the session is renewed). 2.Because every link now contains an extra attribute (?sid=xxxx) this can interfere with an existing application. A problem I encountered was that some AJAX links (like used by some Tapestry 3'rd party components) created in a Javascript library did not cope with a URL attributes. Fixing it however was pretty straightforward (see below) 3.All links (and form submits) are now protected so you somehow need to have a page (login page for example) that is not protected otherwise it is impossible to add the sid to the user session. Because I use (native) Spring security this was solved for automatically because the login page is handled by Spring security so you need white-filter the login page. You can for example add a white-filter check to CSRF!FilterImpl.isCSRFProtected to filter out the login page. Another option would be to create a special Annotation (for example @NoCSRF) and check if that page contains the annotation.

Using a LinkFactory protects all action links (which I like because you cannot forget a link) but if you want to protect just a few links you can create a Mixin that just adds the 'sid' attribute. In the filter you now need to know which actions are protected and which not so you will need to do some extra filtering (see gotcha 3 above for some tips).

If you have any question feel free to ask

Martijn Brinkers


Tapestry5CSRF (last edited 2010-01-28 07:54:09 by s235-200)