diff --git a/java/org/apache/catalina/filters/CsrfPreventionFilter.java b/java/org/apache/catalina/filters/CsrfPreventionFilter.java index 749c16520ef1..414a2abe796d 100644 --- a/java/org/apache/catalina/filters/CsrfPreventionFilter.java +++ b/java/org/apache/catalina/filters/CsrfPreventionFilter.java @@ -33,6 +33,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; +import javax.servlet.http.HttpSession; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; @@ -153,15 +154,19 @@ public void doFilter(ServletRequest request, ServletResponse response, } } - LruCache nonceCache = - (LruCache) req.getSession(true).getAttribute( - Constants.CSRF_NONCE_SESSION_ATTR_NAME); + HttpSession session = req.getSession(false); + + @SuppressWarnings("unchecked") + LruCache nonceCache = (session == null) ? null + : (LruCache) session.getAttribute( + Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); - if (nonceCache != null && !nonceCache.contains(previousNonce)) { + if (nonceCache == null || previousNonce == null || + !nonceCache.contains(previousNonce)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } @@ -169,7 +174,10 @@ public void doFilter(ServletRequest request, ServletResponse response, if (nonceCache == null) { nonceCache = new LruCache<>(nonceCacheSize); - req.getSession().setAttribute( + if (session == null) { + session = req.getSession(true); + } + session.setAttribute( Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); }