Explain the commonly used filters in Tomcat

Time:2021-10-29

1、 Cross domain filter corsfilter

Org.apcache.catalina.filters.corsfilter is an implementation of cross domain resource sharing specification, which is often used for front-end and back-end separation, static resources and back-end separation, etc. It mainly adds the access control – * header in the httpservletresponse, and protects the HTTP response from splitting. If the request is invalid or access is prohibited, it returns a 403 response code.

1.1 configuration example


<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

1.2 parameter description

1、cors.allowed.origins

List of cross domain resources allowed to access, “*” indicates that resources from any domain are allowed to be accessed. Multiple domains are separated by commas, and the default is “*”

2、cors.allowed.methods

A list of HTTP methods that can be used to access resources, separated by “,” and used for cross domain requests. These methods will appear in the part of access control allow methods in the prefligh response header, and t default to “get, post, head, options”

3、cors.allowed.headers

The request headers that can be used when constructing requests are separated by “,” and these methods will appear in a part of the preflight response header access control allow headers. The default values are origin, accept, x-requested-with, content type, access control request method, access control request headers

4、cors.exposed.headers

The list of header information allowed to be accessed by the browser is separated by “,”. These methods will appear in part of the access control allow headers of the preflight response header, which is empty by default.

5、cors.preflight.maxage

The time, in seconds, that the browser allows to cache preflight request results. If it is a negative number, it means that corsfilter will not add the header to the preflight response. These methods will appear in the access control Max age part of the preflight response header, which defaults to 1800

6、cors.support.credentials

Indicates whether the resource supports user certificates. These methods will appear in the part of access control allow credentials in the preflight response header. The default is true

7、cors.request.decorate

Whether the CORS specification attribute has been added to HttpServletRequest. The default is true. Corsfiter will add request related information for HttpServletRequest. If cors.request.decorate is configured as true, the following properties will be added

1) Cors.iscorsrequest: used to determine whether the request is a CORS request.

2) Cors.request.origin: source URL, the URL of the page from which the request originated.

3) Cors.request.type: the request type of CORS, as follows:

SIMPLE: a request that is not a preflight request.

ACTUAL: request led by preflight request.

PRE_FLIGHT: preflight request

NOT_CORS: normal co domain request

INVALID_CORS: invalid domain request

4) Cors.request.headers: the request header information sent as the preflight request access control request header.

2、 CSRF protection filter csrfpreventionfilter

Org.apcache.catalina.filters.csrfpreventionfilter provides basic CSRF protection for web applications. All links of the returned clients are encoded through httpservletresponse.encoderedirecturl (string) and httpservletresponse.encodeurl (string). The filter generates a random number and stores it in the session for comparison. The URL is encoded using the random number. When the next request is received, the random number in the request is compared with that in the session. Only when they are the same, the request will be allowed.

2.1 configuration example


<filter>
    <filter-name>CsrfPreventionFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CsrfPreventionFilter</filter-class>
    <init-param>
        <param-name>denyStatus</param-name>
        <param-value>403</param-value>
    </init-param>
    <init-param>
        <param-name>entryPoints</param-name>
        <param-value>/html,/html/list</param-value>
    </init-param>
    <init-param>
        <param-name>nonceCacheSize</param-name>
        <param-value>5</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CsrfPreventionFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2.2 parameter description

1. Denystatus: HTTP response. It is used to reject the request. The default value is 403

2. Entrypoints: URL lists separated by “,” which will not be subject to random number detection (mainly used to navigate away from the protected application and then return)


if ("GET".equals(req.getMethod()) && this.entryPoints.contains(this.getRequestedPath(req))) {
                skipNonceCheck = true;
 }

3. Noncecachesize: random number cache size. The previously published random number is cached in an LRU cache to support concurrent requests. It is limited for browser refresh and other behaviors (which may cause the random number to be not current). The default is 5


private int nonceCacheSize = 5;
....
if (nonceCache == null) {
    nonceCache = new CsrfPreventionFilter.LruCache(this.nonceCacheSize);
      if (session == null) {
           session = req.getSession(true);
       }

    session.setAttribute("org.apache.catalina.filters.CSRF_NONCE", nonceCache);
}

4. Randomclass: a class used to generate random numbers. It must be a java.util.random instance. If it is not set, it defaults to java.security.securerandom

3、 Prevent parameter Loss Filter failedrequestfilter

Org.apcache.catalina.filters.failedrequestfilter is used to trigger the parameter resolution of the request. When the parameter resolution fails, the request will be rejected. This filter is used to ensure that the parameter information submitted by the client is not lost. The principle of this filter is: call servletrequest.getparameter first (the first call will trigger the request parameter resolution of Tomcat server. If the parameter resolution fails, put the result into the request attribute org.apache.catalina.parameter_parse_failed), and then judge the attribute org.apache.catalina.parameter_ parse_ The value of failed. If it is not empty, it will directly return 400.

In order to correctly parse parameters, you need to set the character set encoding filter SetCharacterEncoding filter before this filter. In addition, the filter does not support R initialization parameters

//Determine whether it is a valid request: org.apache.catalina.parameter_ parse_ Failed is null
private boolean isGoodRequest(ServletRequest request) {
    request.getParameter("none");
    return request.getAttribute("org.apache.catalina.parameter_parse_failed") == null;
}

4、 Get client IP filter remoteaddrfilter

Org.apcache.catalina.filters.remoteaddrfiler allows you to compare whether the submitted client IP address (obtained through servletrequest.getremoteaddr) conforms to the specified regular expression.

4.1 configuration example


<filter>
    <filter-name>Remote Address Filter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteAddrFilter</filter-class>
    <init-param>
    <param-name>allow</param-name>
    <param-value>127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>Remote Address Filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

4.2 parameter description

1. Allow: Specifies the IP address of the client to which access is allowed

2. Deny: access denied client address

3. Denystatus: the HTTP response returned when the request is rejected.

5、 Get client host filter remotehostfilter

Org.apcache.catalina.filters.remotehostfiler allows you to compare whether the host name of the client submitting the request conforms to the specified regular expression to determine whether the request is allowed to continue processing. The parameters are the same as remoteaddrfilter

6、 Get the original client IP filter remoteipfilter

When the client accesses the server through HTTP proxy or load balancing, for the server, the request directly comes from the front proxy server. At this time, the obtained remote IP is actually the IP address of the proxy server.

6.1. How to obtain the IP address of the original client

The HTTP protocol records the IP address from the asset client to the pre proxy of the application server through the x-forwarded-for header information. By parsing the request header, remoteipfilter replaces the IP address and host name in the request with the real IP address and host information of the client. In addition, it can also replace the current protocol name http / HTTPS through the x-forwarded-proto request header Server port and request.secure.

The format of x-forward-for is as follows:

X-Forwarded-For: client, proxy1, proxy2

The leftmost client is the most original client IP. In the above example, the client passes through proxy1, proxy2 and proxy3 (the last layer of proxy3 is not displayed and is obtained through servletrquest.getremoteaddr). In the case of load balancing, remoteaddrfilter and remotehostfilter need to be used with this filter, otherwise the access to the client cannot be restricted correctly.

Generally, we use the following java code to obtain x-forward-for:


public static String getIp(HttpServletRequest request) {
    String requestAddr = request.getHeader("x-forwarded-for");
    if (requestAddr == null || requestAddr.length() == 0 || "unknown".equalsIgnoreCase(requestAddr)) {
        requestAddr = request.getHeader("Proxy-Client-IP");
    }

    if (requestAddr == null || requestAddr.length() == 0 || "unknown".equalsIgnoreCase(requestAddr)) {
        requestAddr = request.getHeader("WL-Proxy-Client-IP");
    }

    if (requestAddr == null || requestAddr.length() == 0 || "unknown".equalsIgnoreCase(requestAddr)) {
        requestAddr = request.getRemoteAddr();
    }

    return requestAddr;
}

6.2 configuration example

1) Basic processing x-forward-for header configuration


<filter>
    <filter-name>RemoteIpFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>RemoteIpFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

2) Handle the configuration of x-forward-for and x-forward-proto headers


<filter>
    <filter-name>RemoteIpFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    <init-param>
    <param-name>protocolHeader</param-name>
    <param-value>x-forwarded-proto</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>RemoteIpFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

3) Advanced configuration using internal agents


<filter>
    <filter-name>RemoteIpFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    <init-param>
        <param-name>allowedInternalProxies</param-name>
        <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
    </init-param>
    <init-param>
        <param-name>remoteIpHeader</param-name>
        <param-value>x-forwarded-for</param-value>
    </init-param>
    <init-param>
        <param-name>remoteIpProxiesHeader</param-name>
        <param-value>x-forwarded-by</param-value>
    </init-param>
    <init-param>
        <param-name>protocolHeader</param-name>
        <param-value>x-forwarded-proto</param-value>
    </init-param>
</filter>

4) Use trusted agent advanced configuration


<filter>
    <filter-name>RemoteIpFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    <init-param>
        <param-name>allowedInternalProxies</param-name>
        <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
    </init-param>
    <init-param>
        <param-name>remoteIpHeader</param-name>
        <param-value>x-forwarded-for</param-value>
    </init-param>
    <init-param>
        <param-name>remoteIpProxiesHeader</param-name>
        <param-value>x-forwarded-by</param-value>
    </init-param>
    <init-param>
        <param-name>trustedProxies</param-name>
        <param-value>proxy1|proxy2</param-value>
    </init-param>
</filter>

7、 Character set encoding filter SetCharacterEncoding filter

It provides a way to set character set encoding. Generally, iso-8859-1 encoding is the default, but UTF-8 encoding is recommended in the actual production environment, and the encoding in the request can be used when no encoding is specified or forcibly overwritten.

7.1 configuration example


<filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>ignore</param-name>
        <param-value>false</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

7.2 parameter description

1. Encoding: Specifies the character set encoding

2. Ignore: indicates whether to ignore the character set encoding set by the client request. If it is true, the requested character set encoding will be overwritten. If it is false, it will be set when the request does not specify a character set encoding. The default is false

The above is to explain the details of Tomcat commonly used filters. For more information about Tomcat filters, please pay attention to other relevant articles of developeppaer!