Link Search Menu Expand Document

Cross-Site Request Forgery in Java

Prevention

Java does not provide a built-in protection against CSRF attacks; the developer must implement it by manually enforcing anti-CSRF tokens or by using one of the many, well-tested libraries available.

Servlet API

When using the standard Servlet API, the double submit cookie technique can be implemented as follows. To generate a random string to be used as a token, the SecureRandom class can be used, for example:

public class CSRF {
	public static String getToken() throws NoSuchAlgorithmException{
	    // generate random data
	    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	    byte[] data = new byte[16];
	    secureRandom.nextBytes(data);

	    // convert to Base64 string
	    return Base64.getEncoder().encodeToString(data);
	}
}

Assuming a JSP page is being used to render the HTML pages, the CSRF token can be added to the form and to the response cookie using the following snippet:

<%
// generate a random CSRF token 
String csrfToken = CSRF.getToken();

// place the CSRF token in a cookie
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("csrfToken", csrfToken);
response.addCookie(cookie);
%>

<form action="/action" method="POST">
  <input type="hidden" name="csrfToken" value="<%= csrfToken %>"/>
</form>

Finally, for each action, ensure the request is legit by checking that the CSRF token in the cookie matches the value in the form:

public void doAction(HttpServletRequest request, HttpServletResponse response) {
	// get the CSRF cookie
	String csrfCookie = null;
	for (Cookie cookie : request.getCookies()) {
		if (cookie.getName().equals("csrf")) {
			csrfCookie = cookie.getValue();
		}
	}

	// get the CSRF form field
	String csrfField = request.getParameter("csrf");

	// validate CSRF
	if (csrfCookie == null || csrfField == null || !csrfCookie.equals(csrfField)) {
		try {
			response.sendError(401);
		} catch (IOException e) {
			// ...
		}
		return;
	}

	// ...
}

References

OWASP - Cross-Site Request Forgery Cheat Sheet MITRE - CWE 352