Top Description Inners Fields Constructors Methods
org.apache.catalina.filters

public Class CsrfPreventionFilter

extends CsrfPreventionFilterBase
Class Inheritance
Imports
java.io.IOException, .Serializable, java.util.ArrayList, .Collection, .Collections, .HashSet, .LinkedHashMap, .Map, .Set, java.util.function.Predicate, java.util.regex.Pattern, jakarta.servlet.FilterChain, .FilterConfig, .ServletContext, .ServletException, .ServletRequest, .ServletResponse, jakarta.servlet.http.HttpServletRequest, .HttpServletResponse, .HttpServletResponseWrapper, .HttpSession, org.apache.juli.logging.Log, .LogFactory

Provides basic CSRF protection for a web application. The filter assumes that:

CSRF protection is enabled by generating random nonce values which are stored in the client's HTTP session. Each URL encoded using HttpServletResponse#encodeURL(String) has a URL parameter added which, when sent to the server in a future request, will be checked against this stored set of nonces for validity.

Some URLs should be accessible even without a valid nonce parameter value. These URLs are known as "entry points" because clients should be able to "enter" the application without first establishing any valid tokens. These are configured with the entryPoints filter init-param.

Some URLs should not have nonce parameters added to them at all

Nested and Inner Type Summary

Modifier and TypeClass and Description
protected static class
protected static class
CsrfPreventionFilter.LruCache<
The type held by this cache.
T
>

Despite its name, this is a FIFO cache not an LRU cache.

protected static class
CsrfPreventionFilter.MimePredicate

A no-nonce Predicate that evaluates a MIME type instead of a URL.

protected static interface
protected static class
CsrfPreventionFilter.PatternPredicate

A no-nonce Predicate that matches a regular expression.

protected static class
CsrfPreventionFilter.PrefixPredicate

A no-nonce Predicate that matches a prefix.

protected static class
CsrfPreventionFilter.SuffixPredicate

A no-nonce Predicate that matches a suffix.

Field Summary

Modifier and TypeField and Description
private ServletContext
context

The servlet context in which this Filter is operating.

private static final String
DEFAULT_NO_NONCE_URL_PATTERNS

The default set of URL patterns for which nonces will not be appended.

private boolean
enforce

Flag which determines whether this Filter is in "enforcement" mode (the default) or in "reporting" mode.

private final Set<String>
private final Log
private int
private String
private String
noNoncePatterns

A set of comma-separated URL patterns which will have no nonce parameters added to them.

private Collection<Predicate<String>>

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected CsrfPreventionFilter.NonceCache<String>

Returns:

A newly created NonceCache
createNonceCache
(HttpServletRequest
The request that triggered the need to create the nonce cache. Unused by the default implementation.
request
,
HttpSession
The session associated with the request.
session
)

Create a new NonceCache and store in the HttpSession.

protected static Predicate<String>

Returns:

A Predicate which can match the specified pattern, or null if the pattern is null or blank.
createNoNoncePredicate
(ServletContext
the Servlet context
context
,
String
The pattern to match e.g. *.foo or /bar/*.
pattern
)

Creates a predicate that can match the specified type of pattern.

protected static Collection<Predicate<String>>

Returns:

A collection of predicates representing the URL patterns.
createNoNoncePredicates
(ServletContext
the Servlet context
context
,
String
A comma-separated string of URL matching patterns.
patterns
)

Creates a collection of matchers from a comma-separated string of patterns.

public void
doFilter(ServletRequest
The request to process
request
,
ServletResponse
The response associated with the request
response
,
FilterChain
Provides access to the next filter in the chain for this filter to pass the request and response to for further processing
chain
)

Implements jakarta.servlet.Filter.doFilter.

The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.

protected boolean

Returns:

true if the CSRF prevention should be enforced, false if the CSRF prevention should only be logged in DEBUG mode.
enforce
(HttpServletRequest
The request.
req
,
String
The path of the request being evaluated.
requestedPath
)

Check to see if the request and path should be enforced or only observed and reported.

protected CsrfPreventionFilter.NonceCache<String>

Returns:

The NonceCache currently associated with the request and/or session
getNonceCache
(HttpServletRequest
The request that triggered the need to obtain the nonce cache. Unused by the default implementation.
request
,
HttpSession
The session associated with the request.
session
)

Obtain the NonceCache associated with the request and/or session.

public void
init(FilterConfig
The configuration information associated with the filter instance being initialised
filterConfig
)

Overrides org.apache.catalina.filters.CsrfPreventionFilterBase.init.

Overrides default jakarta.servlet.Filter.init.

Iterates over the configuration parameters and either logs a warning, or throws an exception for any parameter that does not have a matching setter in this filter.

public boolean

Returns:

true if CSRF protection will be enforced or false if all requests will be allowed and failures will be logged as DEBUG messages.
isEnforce
()

Gets the flag to enforce CSRF protection or just log failures as DEBUG messages.

public void
setEnforce(boolean
true to enforce CSRF protection or false to log DEBUG messages and allow all requests.
enforce
)

Sets the flag to enforce CSRF protection or just log failures as DEBUG messages.

public void
setEntryPoints(String
Comma separated list of URLs to be configured as entry points.
entryPoints
)

Entry points are URLs that will not be tested for the presence of a valid nonce.

public void
setNonceCacheSize(int
The number of nonces to cache
nonceCacheSize
)

Sets the number of previously issued nonces that will be cached on a LRU basis to support parallel requests, limited use of the refresh and back in the browser and similar behaviors that may result in the submission of a previous nonce rather than the current one.

public void
setNonceRequestParameterName(String
The request parameter name to use for CSRF nonces.
parameterName
)

Sets the request parameter name to use for CSRF nonces.

public void
setNoNonceURLPatterns(String
A comma-separated list of URL patterns that will not have nonces added to them. Patterns may begin or end with a * character to denote a suffix-match or prefix-match. Any matched URL will not have a CSRF nonce added to it when passed through HttpServletResponse#encodeURL(String).
patterns
)

Sets the list of URL patterns to suppress nonce-addition for.

protected boolean
protected boolean

Returns:

true if a nonce should be created, otherwise false
skipNonceGeneration
(HttpServletRequest
The request that triggered the need to potentially create the nonce.
request
)

Determines whether a nonce should be created.

Inherited from org.apache.catalina.filters.CsrfPreventionFilterBase:
generateNoncegetDenyStatusgetLoggergetRequestedPathisConfigProblemFatalsetDenyStatussetRandomClass

Field Detail

contextback to summary
private ServletContext context

The servlet context in which this Filter is operating.

DEFAULT_NO_NONCE_URL_PATTERNSback to summary
private static final String DEFAULT_NO_NONCE_URL_PATTERNS

The default set of URL patterns for which nonces will not be appended.

enforceback to summary
private boolean enforce

Flag which determines whether this Filter is in "enforcement" mode (the default) or in "reporting" mode.

entryPointsback to summary
private final Set<String> entryPoints
logback to summary
private final Log log

Hides org.apache.catalina.filters.CsrfPreventionFilterBase.log.

nonceCacheSizeback to summary
private int nonceCacheSize
nonceRequestParameterNameback to summary
private String nonceRequestParameterName
noNoncePatternsback to summary
private String noNoncePatterns

A set of comma-separated URL patterns which will have no nonce parameters added to them.

noNoncePredicatesback to summary
private Collection<Predicate<String>> noNoncePredicates

Constructor Detail

CsrfPreventionFilterback to summary
public CsrfPreventionFilter()

Method Detail

createNonceCacheback to summary
protected CsrfPreventionFilter.NonceCache<String> createNonceCache(HttpServletRequest request, HttpSession session)

Create a new NonceCache and store in the HttpSession. This method is provided primarily for the benefit of sub-classes that wish to customise this behaviour.

Parameters
request:HttpServletRequest

The request that triggered the need to create the nonce cache. Unused by the default implementation.

session:HttpSession

The session associated with the request.

Returns:CsrfPreventionFilter.NonceCache<String>

A newly created NonceCache

createNoNoncePredicateback to summary
protected static Predicate<String> createNoNoncePredicate(ServletContext context, String pattern)

Creates a predicate that can match the specified type of pattern.

Parameters
context:ServletContext

the Servlet context

pattern:String

The pattern to match e.g. *.foo or /bar/*.

Returns:Predicate<String>

A Predicate which can match the specified pattern, or null if the pattern is null or blank.

createNoNoncePredicatesback to summary
protected static Collection<Predicate<String>> createNoNoncePredicates(ServletContext context, String patterns)

Creates a collection of matchers from a comma-separated string of patterns.

Parameters
context:ServletContext

the Servlet context

patterns:String

A comma-separated string of URL matching patterns.

Returns:Collection<Predicate<String>>

A collection of predicates representing the URL patterns.

doFilterback to summary
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException

Implements jakarta.servlet.Filter.doFilter.

Doc from jakarta.servlet.Filter.doFilter.

The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

A typical implementation of this method would follow the following pattern:-
1. Examine the request
2. Optionally wrap the request object with a custom implementation to filter content or headers for input filtering
3. Optionally wrap the response object with a custom implementation to filter content or headers for output filtering
4. a) Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()),
4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing
5. Directly set headers on the response after invocation of the next entity in the filter chain.

Parameters
request:ServletRequest

The request to process

response:ServletResponse

The response associated with the request

chain:FilterChain

Provides access to the next filter in the chain for this filter to pass the request and response to for further processing

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs during this filter's processing of the request
ServletException:
if the processing fails for any other reason
enforceback to summary
protected boolean enforce(HttpServletRequest req, String requestedPath)

Check to see if the request and path should be enforced or only observed and reported. Note that the requestedPath parameter is purely a performance optimization to avoid calling getRequestedPath(HttpServletRequest) multiple times.

Parameters
req:HttpServletRequest

The request.

requestedPath:String

The path of the request being evaluated.

Returns:boolean

true if the CSRF prevention should be enforced, false if the CSRF prevention should only be logged in DEBUG mode.

getNonceCacheback to summary
protected CsrfPreventionFilter.NonceCache<String> getNonceCache(HttpServletRequest request, HttpSession session)

Obtain the NonceCache associated with the request and/or session. This method is provided primarily for the benefit of sub-classes that wish to customise this behaviour.

Parameters
request:HttpServletRequest

The request that triggered the need to obtain the nonce cache. Unused by the default implementation.

session:HttpSession

The session associated with the request.

Returns:CsrfPreventionFilter.NonceCache<String>

The NonceCache currently associated with the request and/or session

initback to summary
public void init(FilterConfig filterConfig) throws ServletException

Overrides org.apache.catalina.filters.CsrfPreventionFilterBase.init.

Overrides default jakarta.servlet.Filter.init.

Doc from org.apache.catalina.filters.FilterBase.init.

Iterates over the configuration parameters and either logs a warning, or throws an exception for any parameter that does not have a matching setter in this filter.

Parameters
filterConfig:FilterConfig

The configuration information associated with the filter instance being initialised

Annotations
@Override
Exceptions
ServletException:
if isConfigProblemFatal() returns true and a configured parameter does not have a matching setter
isEnforceback to summary
public boolean isEnforce()

Gets the flag to enforce CSRF protection or just log failures as DEBUG messages.

Returns:boolean

true if CSRF protection will be enforced or false if all requests will be allowed and failures will be logged as DEBUG messages.

setEnforceback to summary
public void setEnforce(boolean enforce)

Sets the flag to enforce CSRF protection or just log failures as DEBUG messages.

Parameters
enforce:boolean

true to enforce CSRF protection or false to log DEBUG messages and allow all requests.

setEntryPointsback to summary
public void setEntryPoints(String entryPoints)

Entry points are URLs that will not be tested for the presence of a valid nonce. They are used to provide a way to navigate back to a protected application after navigating away from it. Entry points will be limited to HTTP GET requests and should not trigger any security sensitive actions.

Parameters
entryPoints:String

Comma separated list of URLs to be configured as entry points.

setNonceCacheSizeback to summary
public void setNonceCacheSize(int nonceCacheSize)

Sets the number of previously issued nonces that will be cached on a LRU basis to support parallel requests, limited use of the refresh and back in the browser and similar behaviors that may result in the submission of a previous nonce rather than the current one. If not set, the default value of 5 will be used.

Parameters
nonceCacheSize:int

The number of nonces to cache

setNonceRequestParameterNameback to summary
public void setNonceRequestParameterName(String parameterName)

Sets the request parameter name to use for CSRF nonces.

Parameters
parameterName:String

The request parameter name to use for CSRF nonces.

setNoNonceURLPatternsback to summary
public void setNoNonceURLPatterns(String patterns)

Sets the list of URL patterns to suppress nonce-addition for. Some URLs do not need nonces added to them such as static resources. By not adding nonces to those URLs, HTTP caches can be more effective because the CSRF prevention filter won't generate what look like unique URLs for those commonly-reused resources.

Parameters
patterns:String

A comma-separated list of URL patterns that will not have nonces added to them. Patterns may begin or end with a * character to denote a suffix-match or prefix-match. Any matched URL will not have a CSRF nonce added to it when passed through HttpServletResponse#encodeURL(String).

skipNonceCheckback to summary
protected boolean skipNonceCheck(HttpServletRequest request)
skipNonceGenerationback to summary
protected boolean skipNonceGeneration(HttpServletRequest request)

Determines whether a nonce should be created. This method is provided primarily for the benefit of sub-classes that wish to customise this behaviour.

Parameters
request:HttpServletRequest

The request that triggered the need to potentially create the nonce.

Returns:boolean

true if a nonce should be created, otherwise false

org.apache.catalina.filters back to summary

protected Class CsrfPreventionFilter.CsrfResponseWrapper

extends HttpServletResponseWrapper
Class Inheritance

Field Summary

Modifier and TypeField and Description
private final String
private final String
private final Collection<Predicate<String>>

Constructor Summary

AccessConstructor and Description
public
CsrfResponseWrapper(HttpServletResponse response, String nonceRequestParameterName, String nonce, Collection<Predicate<String>> noNoncePatterns)

Method Summary

Modifier and TypeMethod and Description
private String
public String
encodeRedirectURL(String
the url to be encoded.
url
)

Overrides jakarta.servlet.http.HttpServletResponseWrapper.encodeRedirectURL.

Implements jakarta.servlet.http.HttpServletResponse.encodeRedirectURL.

The default behavior of this method is to return encodeRedirectURL(String url) on the wrapped response object.

public String
encodeURL(String
the url to be encoded.
url
)

Overrides jakarta.servlet.http.HttpServletResponseWrapper.encodeURL.

Implements jakarta.servlet.http.HttpServletResponse.encodeURL.

The default behavior of this method is to call encodeURL(String url) on the wrapped response object.

private boolean
Inherited from jakarta.servlet.http.HttpServletResponseWrapper:
addCookieaddDateHeaderaddHeaderaddIntHeadercontainsHeadergetHeadergetHeaderNamesgetHeadersgetStatusgetTrailerFieldssendErrorsendErrorsendRedirectsetDateHeadersetHeadersetIntHeadersetStatussetTrailerFields

Field Detail

nonceback to summary
private final String nonce
nonceRequestParameterNameback to summary
private final String nonceRequestParameterName
noNoncePatternsback to summary
private final Collection<Predicate<String>> noNoncePatterns

Constructor Detail

CsrfResponseWrapperback to summary
public CsrfResponseWrapper(HttpServletResponse response, String nonceRequestParameterName, String nonce, Collection<Predicate<String>> noNoncePatterns)

Method Detail

addNonceback to summary
private String addNonce(String url)
encodeRedirectURLback to summary
public String encodeRedirectURL(String url)

Overrides jakarta.servlet.http.HttpServletResponseWrapper.encodeRedirectURL.

Implements jakarta.servlet.http.HttpServletResponse.encodeRedirectURL.

Doc from jakarta.servlet.http.HttpServletResponseWrapper.encodeRedirectURL.

The default behavior of this method is to return encodeRedirectURL(String url) on the wrapped response object.

Parameters
url:String

Doc from jakarta.servlet.http.HttpServletResponse.encodeRedirectURL.

the url to be encoded.

Returns:String

Doc from jakarta.servlet.http.HttpServletResponse.encodeRedirectURL.

the encoded URL if encoding is needed; the unchanged URL otherwise.

Annotations
@Override
encodeURLback to summary
public String encodeURL(String url)

Overrides jakarta.servlet.http.HttpServletResponseWrapper.encodeURL.

Implements jakarta.servlet.http.HttpServletResponse.encodeURL.

Doc from jakarta.servlet.http.HttpServletResponseWrapper.encodeURL.

The default behavior of this method is to call encodeURL(String url) on the wrapped response object.

Parameters
url:String

Doc from jakarta.servlet.http.HttpServletResponse.encodeURL.

the url to be encoded.

Returns:String

Doc from jakarta.servlet.http.HttpServletResponse.encodeURL.

the encoded URL if encoding is needed; the unchanged URL otherwise.

Annotations
@Override
shouldAddNonceback to summary
private boolean shouldAddNonce(String url)
org.apache.catalina.filters back to summary

protected Class CsrfPreventionFilter.LruCache<T>

extends Object
implements CsrfPreventionFilter.NonceCache<T>
Class Inheritance
All Implemented Interfaces
org.apache.catalina.filters.CsrfPreventionFilter.NonceCache, java.io.Serializable
Type Parameters
<T>
The type held by this cache.

Despite its name, this is a FIFO cache not an LRU cache. Using an older nonce should not delay its removal from the cache in favour of more recent values.

Field Summary

Modifier and TypeField and Description
private final Map<T, T>
private static final long

Constructor Summary

AccessConstructor and Description
public
LruCache(final int cacheSize)

Method Summary

Modifier and TypeMethod and Description
public void
public boolean
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

cacheback to summary
private final Map<T, T> cache
serialVersionUIDback to summary
private static final long serialVersionUID

Constructor Detail

LruCacheback to summary
public LruCache(final int cacheSize)

Method Detail

addback to summary
public void add(T key)

Implements org.apache.catalina.filters.CsrfPreventionFilter.NonceCache.add.

Annotations
@Override
containsback to summary
public boolean contains(T key)

Implements org.apache.catalina.filters.CsrfPreventionFilter.NonceCache.contains.

Annotations
@Override
org.apache.catalina.filters back to summary

protected Class CsrfPreventionFilter.MimePredicate

extends Object
implements Predicate<String>
Class Inheritance
  • java.lang.Object
  • org.apache.catalina.filters.CsrfPreventionFilter.MimePredicate
All Implemented Interfaces
java.util.function.Predicate

A no-nonce Predicate that evaluates a MIME type instead of a URL. It can be used with any other Predicate for matching the actual value of the MIME type.

Field Summary

Modifier and TypeField and Description
private final ServletContext
private final Predicate<String>

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public Predicate<String>
public boolean
test(String
the input argument
t
)

Implements java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

contextback to summary
private final ServletContext context
predicateback to summary
private final Predicate<String> predicate

Constructor Detail

MimePredicateback to summary
public MimePredicate(ServletContext context, Predicate<String> predicate)

Method Detail

getPredicateback to summary
public Predicate<String> getPredicate()
testback to summary
public boolean test(String t)

Implements java.util.function.Predicate.test.

Doc from java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Parameters
t:String

the input argument

Returns:boolean

true if the input argument matches the predicate, otherwise false

Annotations
@Override
org.apache.catalina.filters back to summary

protected Interface CsrfPreventionFilter.NonceCache<T>

extends Serializable
Known Direct Implementers
org.apache.catalina.filters.CsrfPreventionFilter.LruCache

Method Summary

Modifier and TypeMethod and Description
public void
add(T nonce)

public boolean
contains(T nonce)

Method Detail

addback to summary
public void add(T nonce)
containsback to summary
public boolean contains(T nonce)
org.apache.catalina.filters back to summary

protected Class CsrfPreventionFilter.PatternPredicate

extends Object
implements Predicate<String>
Class Inheritance
  • java.lang.Object
  • org.apache.catalina.filters.CsrfPreventionFilter.PatternPredicate
All Implemented Interfaces
java.util.function.Predicate

A no-nonce Predicate that matches a regular expression.

Field Summary

Modifier and TypeField and Description
private final Pattern

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public boolean
test(String
the input argument
t
)

Implements java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

patternback to summary
private final Pattern pattern

Constructor Detail

PatternPredicateback to summary
public PatternPredicate(String regex)

Method Detail

testback to summary
public boolean test(String t)

Implements java.util.function.Predicate.test.

Doc from java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Parameters
t:String

the input argument

Returns:boolean

true if the input argument matches the predicate, otherwise false

Annotations
@Override
org.apache.catalina.filters back to summary

protected Class CsrfPreventionFilter.PrefixPredicate

extends Object
implements Predicate<String>
Class Inheritance
  • java.lang.Object
  • org.apache.catalina.filters.CsrfPreventionFilter.PrefixPredicate
All Implemented Interfaces
java.util.function.Predicate

A no-nonce Predicate that matches a prefix.

Field Summary

Modifier and TypeField and Description
private final String

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public boolean
test(String
the input argument
t
)

Implements java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

prefixback to summary
private final String prefix

Constructor Detail

PrefixPredicateback to summary
public PrefixPredicate(String prefix)

Method Detail

testback to summary
public boolean test(String t)

Implements java.util.function.Predicate.test.

Doc from java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Parameters
t:String

the input argument

Returns:boolean

true if the input argument matches the predicate, otherwise false

Annotations
@Override
org.apache.catalina.filters back to summary

protected Class CsrfPreventionFilter.SuffixPredicate

extends Object
implements Predicate<String>
Class Inheritance
  • java.lang.Object
  • org.apache.catalina.filters.CsrfPreventionFilter.SuffixPredicate
All Implemented Interfaces
java.util.function.Predicate

A no-nonce Predicate that matches a suffix.

Field Summary

Modifier and TypeField and Description
private final String

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public boolean
test(String
the input argument
t
)

Implements java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

suffixback to summary
private final String suffix

Constructor Detail

SuffixPredicateback to summary
public SuffixPredicate(String suffix)

Method Detail

testback to summary
public boolean test(String t)

Implements java.util.function.Predicate.test.

Doc from java.util.function.Predicate.test.

Evaluates this predicate on the given argument.

Parameters
t:String

the input argument

Returns:boolean

true if the input argument matches the predicate, otherwise false

Annotations
@Override