Search code examples
javaspring-securitycsrf

Protect an old web application against CSRF without adding hidden input in all forms


During a recent security scan of our Java web application, we found out CSRF vulnerabilities. I know for a newer app which is using a security framework like Spring Security, we could easily add a hidden input with every form and do other required configurations and that would solve the problem.

<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>

But ours is a very old app still using acegi-security (1.0.2) and has 100s of forms written in JSPs. Adding an input type hidden csrf token on all these forms seems very tedious. Is there a smarter way of securing my application without all of this hard work.


Solution

  • Thank you for your feedback and answers. I followed the following solution. I created two filters. SetCsrfTokenFilter. The doFilter method does the following.

    HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpRes = (HttpServletResponse) response;
        String randomLong = ""+random.nextLong();
        Cookie cookie = new Cookie("csrfToken", randomLong);        
        httpRes.addCookie(cookie);
        next.doFilter(request, response);   
    

    VerifyCsrfTokenFilter. The doFilter method does the following

    String csrfToken = httpReq.getParameter("csrfToken");
            String tokenFromCookie = getCsrfTokenFromCookie(httpReq);
            if (WmUtil.isEmpty(csrfToken) || !csrfToken.equals(tokenFromCookie)) {
                httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }           
            else {
                next.doFilter(request, response);
            }
    

    Added both these filters for almost all urls in my web.xml. And finally in my jsp pages injected below code through jquery in all forms.

    <input type="hidden" name="csrfToken" value="readFromCookieThroughJavascript"/>
    

    This solved my problem and next scan could not find any csrf issues. For those of you who want complete source code of filters on server side and javascript code on client side, I have created a git project. https://github.com/anilpank/oldWebAppCsrfProtection