如何在Spring中拦截RequestRejectedException?

时间:2018-08-10 14:33:12

标签: java spring logging spring-security exception-handling

我在Tomcat日志中看到{em> 一吨RequestRejectedException(下面粘贴的示例)。这些在几个月前进行次要版本升级(Spring Security 4.2.4,IIRC)之后开始出现在我的日志文件中,因此,这显然是默认情况下启用的Spring新安全功能。 reported here是一个类似的问题,但是我的问题专门涉及如何在控制器中拦截这些异常。记录了针对此问题的Spring Security错误(Provide a way to handle RequestRejectedException)。但是,直到Spring 5.1,他们才将目标对准该问题。

我了解why these exceptions are being thrown,但我不想disable this security feature

我想对该功能进行一些控制,以便:

  1. 我知道我不会阻止合法用户访问我的网站。
  2. 我可以看到哪些请求正在触发此请求(它们是SQL注入攻击吗?)
  3. 我可以调整服务器响应。 Spring Security防火墙将完整的堆栈跟踪和500 Internal Server Error(非常错误,应该为400 Bad Request)一起转储到Web客户端(信息公开)。

我想找到一种方法来记录所请求的URL,同时还要专门针对这些异常取消堆栈跟踪,因为这些异常会污染我的日志文件而没有提供任何有用的信息。理想情况下,我想拦截这些异常并在我的应用程序层中处理它们,而不是根本不在Tomcat日志中报告它们。

例如,这是每天出现在我的catalina.out中的数千个日志条目之一:

Aug 10, 2018 2:01:36 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";"
        at org.springframework.security.web.firewall.StrictHttpFirewall.rejectedBlacklistedUrls(StrictHttpFirewall.java:265)
        at org.springframework.security.web.firewall.StrictHttpFirewall.getFirewalledRequest(StrictHttpFirewall.java:245)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:193)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
        at org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:486)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)

我在两天内看到了3200多个日志,并且它迅速成为catalina.out日志文件的最大贡献者,以至于阻止了我看到其他合理的问题。本质上,这项新的Spring Security功能是内置的“拒绝服务”的一种形式,并且自4月以来浪费了我很多时间。我并不是说这不是一个重要功能,只是默认实现完全被破坏,我想找到一种方法来以开发人员和系统管理员的身份对其进行某种控制。

我使用一个自定义的错误控制器来拦截Spring中的许多其他异常类型(包括IOException)。但是,RequestRejectedException似乎由于某种原因而失败。

这是我的ErrorController.java的相关部分,目的是让我了解要完成的工作:

@ControllerAdvice
public final class ErrorController
{
    /**
     * Logger.
     */
    private static final Logger LOGGER = Logger.getLogger(ErrorController.class.getName());

    /**
     * Generates an Error page by intercepting exceptions generated from HttpFirewall.
     *
     * @param ex A RequestRejectedException exception.
     * @return The tile definition name for the page.
     */
    @ExceptionHandler(RequestRejectedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleRequestRejectedException(final HttpServletRequest request, final RequestRejectedException ex)
    {
        if (LOGGER.isLoggable(Level.INFO))
        {
            LOGGER.log(Level.INFO, "Request Rejected", ex);
        }

        LOGGER.log(Level.WARNING, "Rejected request for [" + request.getRequestURL().toString() + "]. Reason: " + ex.getMessage());
        return "errorPage";
    }

    /**
     * Generates a Server Error page.
     *
     * @param ex An exception.
     * @return The tile definition name for the page.
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleException(final Exception ex)
    {
        if (LOGGER.isLoggable(Level.SEVERE))
        {
            LOGGER.log(Level.SEVERE, "Server Error", ex);
        }

        return "errorPage";
    }
}

此错误控制器适用于许多异常。例如,它成功拦截了此IllegalStateException

Aug 05, 2018 7:50:30 AM com.mycompany.spring.controller.ErrorController handleException
SEVERE: Server Error
java.lang.IllegalStateException: Cannot create a session after the response has been committed
        at org.apache.catalina.connector.Request.doGetSession(Request.java:2999)
...

但是,这并没有拦截RequestRejectedException(如上述第一个日志示例中缺少“服务器错误”所示)。

如何在错误控制器中拦截RequestRejectedException

7 个答案:

答案 0 :(得分:14)

也可以通过简单的过滤器进行处理,这将导致404错误响应

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LogAndSuppressRequestRejectedExceptionFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(req, res);
        } catch (RequestRejectedException e) {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            log
                .warn(
                        "request_rejected: remote={}, user_agent={}, request_url={}",
                        request.getRemoteHost(),  
                        request.getHeader(HttpHeaders.USER_AGENT),
                        request.getRequestURL(), 
                        e
                );

            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

答案 1 :(得分:6)

我实现了example.data <- data.frame(x.var = rep(-2:2, 5), y.var = rep(-2:2, each=5), boolean.var = as.logical(sample(1:1000, 25) %% 2)) library(ggplot2) library(tidyr) example.data %>% ggplot(aes(fill = boolean.var)) + geom_rect(xmin = -1, xmax = 1, ymin = -1, ymax = 1) + scale_x_continuous(name = "(X Title)", position = "top", limits = c(-0.5,0.5)) + scale_y_continuous(name = "(Y Title)", position = "right", limits = c(-0.5,0.5)) + scale_fill_discrete(guide = FALSE) + facet_grid(y.var ~ x.var) + theme(panel.margin=unit(0.25 , "lines"), axis.title = element_text(size = 24, margin = margin(20, 20, 20, 20)), axis.ticks = element_blank(), axis.text = element_blank(), axis.title.x.top = element_text(margin = margin(1, 0, 15, 0)), axis.title.y.right = element_text(margin = margin(0, 1, 0, 15))) 的子类,该子类将请求信息记录到控制台,并抛出了一个带有抑制了堆栈跟踪的新异常。这部分解决了我的问题(至少现在我可以看到错误的请求了。)

如果您只想查看没有堆栈跟踪的拒绝请求,这就是您要寻找的答案。

如果要在控制器中处理这些异常,请参阅accepted answer,以获取完整的(但稍微复杂一些)解决方案。


LoggingHttpFirewall.java

此类扩展了StrictHttpFirewall以捕获StrictHttpFirewall并引发来自请求的元数据和抑制的堆栈跟踪的新异常。

RequestRejectedException

WebSecurityConfig.java

import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.web.firewall.FirewalledRequest; import org.springframework.security.web.firewall.RequestRejectedException; import org.springframework.security.web.firewall.StrictHttpFirewall; /** * Overrides the StrictHttpFirewall to log some useful information about blocked requests. */ public final class LoggingHttpFirewall extends StrictHttpFirewall { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(LoggingHttpFirewall.class.getName()); /** * Default constructor. */ public LoggingHttpFirewall() { super(); return; } /** * Provides the request object which will be passed through the filter chain. * * @returns A FirewalledRequest (required by the HttpFirewall interface) which * inconveniently breaks the general contract of ServletFilter because * we can't upcast this to an HttpServletRequest. This prevents us * from re-wrapping this using an HttpServletRequestWrapper. * @throws RequestRejectedException if the request should be rejected immediately. */ @Override public FirewalledRequest getFirewalledRequest(final HttpServletRequest request) throws RequestRejectedException { try { return super.getFirewalledRequest(request); } catch (RequestRejectedException ex) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Intercepted RequestBlockedException: Remote Host: " + request.getRemoteHost() + " User Agent: " + request.getHeader("User-Agent") + " Request URL: " + request.getRequestURL().toString()); } // Wrap in a new RequestRejectedException with request metadata and a shallower stack trace. throw new RequestRejectedException(ex.getMessage() + ".\n Remote Host: " + request.getRemoteHost() + "\n User Agent: " + request.getHeader("User-Agent") + "\n Request URL: " + request.getRequestURL().toString()) { private static final long serialVersionUID = 1L; @Override public synchronized Throwable fillInStackTrace() { return this; // suppress the stack trace. } }; } } /** * Provides the response which will be passed through the filter chain. * This method isn't extensible because the request may already be committed. * Furthermore, this is only invoked for requests that were not blocked, so we can't * control the status or response for blocked requests here. * * @param response The original HttpServletResponse. * @return the original response or a replacement/wrapper. */ @Override public HttpServletResponse getFirewalledResponse(final HttpServletResponse response) { // Note: The FirewalledResponse class is not accessible outside the package. return super.getFirewalledResponse(response); } } 中,将HTTP防火墙设置为WebSecurityConfig

LoggingHttpFirewall

结果

将该解决方案部署到生产环境后,我很快发现@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * Default constructor. */ public WebSecurityConfig() { super(); return; } @Override public final void configure(final WebSecurity web) throws Exception { super.configure(web); web.httpFirewall(new LoggingHttpFirewall()); // Set the custom firewall. return; } } 的默认行为正在阻止Google将我的网站编入索引!

StrictHttpFirewall

我一发现,便迅速部署了一个新版本(包含在my other answer中),该新版本寻找Aug 13, 2018 1:48:56 PM com.mycompany.spring.security.AnnotatingHttpFirewall getFirewalledRequest WARNING: Intercepted RequestBlockedException: Remote Host: 66.249.64.223 User Agent: Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) Request URL: https://www.mycompany.com/10.1601/tx.3784;jsessionid=692804549F9AB55F45DBD0AFE2A97FFD 并允许这些请求通过。可能还有其他请求也应该通过,现在我可以检测到这些请求。

答案 2 :(得分:5)

对于Spring安全版本5.4及更高版本,您可以简单地创建类型为RequestRejectedHandler的bean,该bean将被注入Spring安全过滤器链中

import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;

@Bean
RequestRejectedHandler requestRejectedHandler() {
   // sends an error response with a configurable status code (default is 400 BAD_REQUEST)
   // we can pass a different value in the constructor
   return new HttpStatusRequestRejectedHandler();
}

答案 3 :(得分:4)

事实证明,尽管HttpFirewallStrictHttpFirewall包含几个设计错误(在下面的代码中记录),但是逃避Spring Security的一个真正的防火墙几乎是不可能的并将HttpFirewall信息通过请求属性传输到HandlerInterceptor,该信息可以将这些标记的请求传递到 real (持久性)防火墙,而无需牺牲将其标记在其中的原始业务逻辑第一名。此处记录的方法应该是面向未来的,因为它符合HttpFirewall接口的简单约定,其余的只是核心Spring Framework和Java Servlet API。

这实际上是my earlier answer的更复杂但更完整的替代方法。在此答案中,我实现了StrictHttpFirewall的新子类,该子类在特定的日志记录级别截获并记录被拒绝的请求,还向HTTP请求添加了一个属性,该属性将其标记为供下游过滤器(或控制器)处理。此外,此AnnotatingHttpFirewall提供了一种inspect()方法,该方法允许子类添加用于阻止请求的自定义规则。

此解决方案分为两部分:(1) Spring Security 和(2) Spring Framework(Core),因为这是导致此问题的原因。首先,这显示了如何桥接它。

作为参考,已在Spring 4.3.17和Spring Security 4.2.6上进行了测试。 Spring 5.1发布时可能会有重大变化。


第1部分:Spring Security

这是在Spring Security中执行日志记录和标记的解决方案的一半。


AnnotatingHttpFirewall.java

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.security.web.firewall.StrictHttpFirewall;

/**
 * Overrides the StrictHttpFirewall to log some useful information about blocked requests.
 */
public class AnnotatingHttpFirewall extends StrictHttpFirewall
{
    /**
     * The name of the HTTP header representing a request that has been rejected by this firewall.
     */
    public static final String HTTP_HEADER_REQUEST_REJECTED_FLAG = "X-HttpFirewall-RequestRejectedFlag";

    /**
     * The name of the HTTP header representing the reason a request has been rejected by this firewall.
     */
    public static final String HTTP_HEADER_REQUEST_REJECTED_REASON = "X-HttpFirewall-RequestRejectedReason";

    /**
     * Logger.
     */
    private static final Logger LOGGER = Logger.getLogger(AnnotatingHttpFirewall.class.getName());

    /**
     * Default constructor.
     */
    public AnnotatingHttpFirewall()
    {
        super();
        return;
    }

    /**
     * Provides the request object which will be passed through the filter chain.
     *
     * @param request The original HttpServletRequest.
     * @returns A FirewalledRequest (required by the HttpFirewall interface) which
     *          inconveniently breaks the general contract of ServletFilter because
     *          we can't upcast this to an HttpServletRequest. This prevents us
     *          from re-wrapping this using an HttpServletRequestWrapper.
     */
    @Override
    public FirewalledRequest getFirewalledRequest(final HttpServletRequest request)
    {
        try
        {
            this.inspect(request); // Perform any additional checks that the naive "StrictHttpFirewall" misses.
            return super.getFirewalledRequest(request);
        } catch (RequestRejectedException ex) {
            final String requestUrl = request.getRequestURL().toString();

            // Override some of the default behavior because some requests are
            // legitimate.
            if (requestUrl.contains(";jsessionid="))
            {
                // Do not block non-cookie serialized sessions. Google's crawler does this often.
            } else {
                // Log anything that is blocked so we can find these in the catalina.out log.
                // This will give us any information we need to make
                // adjustments to these special cases and see potentially
                // malicious activity.
                if (LOGGER.isLoggable(Level.WARNING))
                {
                    LOGGER.log(Level.WARNING, "Intercepted RequestBlockedException: Remote Host: " + request.getRemoteHost() + " User Agent: " + request.getHeader("User-Agent") + " Request URL: " + request.getRequestURL().toString());
                }

                // Mark this request as rejected.
                request.setAttribute(HTTP_HEADER_REQUEST_REJECTED, Boolean.TRUE);
                request.setAttribute(HTTP_HEADER_REQUEST_REJECTED_REASON, ex.getMessage());
            }

            // Suppress the RequestBlockedException and pass the request through
            // with the additional attribute.
            return new FirewalledRequest(request)
            {
                @Override
                public void reset()
                {
                    return;
                }
            };
        }
    }

    /**
     * Provides the response which will be passed through the filter chain.
     * This method isn't extensible because the request may already be committed.
     * Furthermore, this is only invoked for requests that were not blocked, so we can't
     * control the status or response for blocked requests here.
     *
     * @param response The original HttpServletResponse.
     * @return the original response or a replacement/wrapper.
     */
    @Override
    public HttpServletResponse getFirewalledResponse(final HttpServletResponse response)
    {
        // Note: The FirewalledResponse class is not accessible outside the package.
        return super.getFirewalledResponse(response);
    }

    /**
     * Perform any custom checks on the request.
     * This method may be overridden by a subclass in order to supplement or replace these tests.
     *
     * @param request The original HttpServletRequest.
     * @throws RequestRejectedException if the request should be rejected immediately.
     */
    public void inspect(final HttpServletRequest request) throws RequestRejectedException
    {
        final String requestUri = request.getRequestURI(); // path without parameters
//        final String requestUrl = request.getRequestURL().toString(); // full path with parameters

        if (requestUri.endsWith("/wp-login.php"))
        {
            throw new RequestRejectedException("The request was rejected because it is a vulnerability scan.");
        }

        if (requestUri.endsWith(".php"))
        {
            throw new RequestRejectedException("The request was rejected because it is a likely vulnerability scan.");
        }

        return; // The request passed all custom tests.
    }
}

WebSecurityConfig.java

WebSecurityConfig中,将HTTP防火墙设置为AnnotatingHttpFirewall

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
    /**
     * Default constructor.
     */
    public WebSecurityConfig()
    {
        super();
        return;
    }

    @Override
    public final void configure(final WebSecurity web) throws Exception
    {
        super.configure(web);
        web.httpFirewall(new AnnotatingHttpFirewall()); // Set the custom firewall.
        return;
    }
}

第2部分:Spring框架

可以想象,该解决方案的第二部分可以实现为ServletFilterHandlerInterceptor。我要走HandlerInterceptor的道路,因为它似乎具有最大的灵活性,并且可以直接在Spring框架内工作。


RequestBlockedException.java

此自定义异常可以由错误控制器处理。可以对此进行扩展,以添加可从原始请求(甚至是完整请求本身)获得的,与应用程序业务逻辑(例如,持久性防火墙)有关的任何请求标头,参数或属性。

/**
 * A custom exception for situations where a request is blocked or rejected.
 */
public class RequestBlockedException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    /**
     * The requested URL.
     */
    private String requestUrl;

    /**
     * The remote address of the client making the request.
     */
    private String remoteAddress;

    /**
     * A message or reason for blocking the request.
     */
    private String reason;

    /**
     * The user agent supplied by the client the request.
     */
    private String userAgent;

    /**
     * Creates a new Request Blocked Exception.
     *
     * @param reqUrl The requested URL.
     * @param remoteAddr The remote address of the client making the request.
     * @param userAgent The user agent supplied by the client making the request.
     * @param message A message or reason for blocking the request.
     */
    public RequestBlockedException(final String reqUrl, final String remoteAddr, final String userAgent, final String message)
    {
        this.requestUrl = reqUrl;
        this.remoteAddress = remoteAddr;
        this.userAgent = userAgent;
        this.reason = message;
        return;
    }

    /**
     * Gets the requested URL.
     *
     * @return A URL.
     */
    public String getRequestUrl()
    {
        return this.requestUrl;
    }

    /**
     * Gets the remote address of the client making the request.
     *
     * @return A remote address.
     */
    public String getRemoteAddress()
    {
        return this.remoteAddress;
    }

    /**
     * Gets the user agent supplied by the client making the request.
     *
     * @return  A user agent string.
     */
    public String getUserAgent()
    {
        return this.userAgent;
    }

    /**
     * Gets the reason for blocking the request.
     *
     * @return  A message or reason for blocking the request.
     */
    public String getReason()
    {
        return this.reason;
    }
}

FirewallInterceptor.java

在Spring Security过滤器运行后(即AnnotatingHttpFirewall标记了应拒绝的请求之后,将调用此拦截器。此拦截器将检测请求上的那些标志(属性)并引发自定义异常,即错误控制器可以处理。

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Intercepts requests that were flagged as rejected by the firewall.
 */
public final class FirewallInterceptor implements HandlerInterceptor
{
    /**
     * Default constructor.
     */
    public FirewallInterceptor()
    {
        return;
    }

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception
    {
        if (Boolean.TRUE.equals(request.getAttribute(AnnotatingHttpFirewall.HTTP_HEADER_REQUEST_REJECTED)))
        {
            // Throw a custom exception that can be handled by a custom error controller.
            final String reason = (String) request.getAttribute(AnnotatingHttpFirewall.HTTP_HEADER_REQUEST_REJECTED_REASON);
            throw new RequestRejectedByFirewallException(request.getRequestURL().toString(), request.getRemoteAddr(), request.getHeader(HttpHeaders.USER_AGENT), reason);
        }

        return true; // Allow the request to proceed normally.
    }

    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception
    {
        return;
    }

    @Override
    public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception
    {
        return;
    }
}

WebConfig.java

WebConfig中,将FirewallInterceptor添加到注册表中。

@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter
{
    /**
     * Among your other methods in this class, make sure you register
     * your Interceptor.
     */
    @Override
    public void addInterceptors(final InterceptorRegistry registry)
    {
        // Register firewall interceptor for all URLs in webapp.
        registry.addInterceptor(new FirewallInterceptor()).addPathPatterns("/**");
        return;
    }
}

ErrorController.java

这专门处理上述自定义异常,并在记录所有相关信息并为自定义应用程序防火墙调用任何特殊业务逻辑时,为客户端生成一个干净的错误页面。

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.web.servlet.NoHandlerFoundException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import RequestBlockedException;

@ControllerAdvice
public final class ErrorController
{
    /**
     * Logger.
     */
    private static final Logger LOGGER = Logger.getLogger(ErrorController.class.getName());

    /**
     * Generates an Error page by intercepting exceptions generated from AnnotatingHttpFirewall.
     *
     * @param request The original HTTP request.
     * @param ex A RequestBlockedException exception.
     * @return The tile definition name for the page.
     */
    @ExceptionHandler(RequestBlockedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleRequestBlockedException(final RequestBlockedException ex)
    {
        if (LOGGER.isLoggable(Level.WARNING))
        {
            LOGGER.log(Level.WARNING, "Rejected request from " + ex.getRemoteAddress() + " for [" + ex.getRequestUrl() + "]. Reason: " + ex.getReason());
        }

        // Note: Perform any additional business logic or logging here.

        return "errorPage"; // Returns a nice error page with the specified status code.
    }

    /**
     * Generates a Page Not Found page.
     *
     * @param ex A NoHandlerFound exception.
     * @return The tile definition name for the page.
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleException(final NoHandlerFoundException ex)
    {
        return "notFoundPage";
    }
}

FirewallController.java

具有默认映射的控制器,该控制器抛出NoHandlerFoundException。 这规避了DispatcherServlet.noHandlerFound中的“鸡与蛋”策略,允许该方法始终 查找映射,以便始终调用FirewallInterceptor.preHandle。这使RequestRejectedByFirewallException的优先级高于NoHandlerFoundException

为什么这是必需的:

here所述,当从NoHandlerFoundException抛出DispatcherServlet时(即,当请求的URL没有对应的映射时),没有办法处理从URL中生成的异常。防火墙上方(在调用preHandle()之前抛出了NoHandlerFoundException),因此这些请求将进入您的404视图(在我的情况下,这不是您想要的行为-您会看到很多“没有映射找到带有URI的HTTP请求...”消息)。可以通过将特殊标头的检查移到noHandlerFound方法中来解决此问题。不幸的是,如果没有从头开始编写新的Dispatcher Servlet,就无法做到这一点,那么您最好扔掉整个Spring框架。由于受保护方法,私有方法和最终方法的混合使用,并且其属性不可访问(没有getter或setter),因此无法扩展DispatcherServlet。也不能包装该类,因为没有可以实现的通用接口。此类中的默认映射提供了一种优雅的方式来规避所有这些逻辑。

重要警告:下面的RequestMapping将防止解析静态资源,因为它优先于所有已注册的ResourceHandler。我仍在寻找解决方法,但是一种可能是尝试this answer中建议的一种处理静态资源的方法。

import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.NoHandlerFoundException;

@Controller
public final class FirewallController
{
    /**
     * The name of the model attribute (or request parameter for advertisement click tracking) that contains the request URL.
     */
    protected static final String REQUEST_URL = "requestUrl";

    /**
     * The name of the model attribute that contains the request method.
     */
    protected static final String REQUEST_METHOD = "requestMethod";

    /**
     * The name of the model attribute that contains all HTTP headers.
     */
    protected static final String REQUEST_HEADERS = "requestHeaders";

    /**
     * Default constructor.
     */
    public FirewallController()
    {
        return;
    }

    /**
     * Populates the request URL model attribute from the HTTP request.
     *
     * @param request The HTTP request.
     * @return The request URL.
     */
    @ModelAttribute(REQUEST_URL)
    public final String getRequestURL(final HttpServletRequest request)
    {
        return request.getRequestURL().toString();
    }

    /**
     * Populates the request method from the HTTP request.
     *
     * @param request The HTTP request.
     * @return The request method (GET, POST, HEAD, etc.).
     */
    @ModelAttribute(REQUEST_METHOD)
    public final String getRequestMethod(final HttpServletRequest request)
    {
        return request.getMethod();
    }

    /**
     * Gets all headers from the HTTP request.
     *
     * @param request The HTTP request.
     * @return The request headers.
     */
    @ModelAttribute(REQUEST_HEADERS)
    public final HttpHeaders getRequestHeaders(final HttpServletRequest request)
    {
        return FirewallController.headers(request);
    }

    /**
     * A catch-all default mapping that throws a NoHandlerFoundException.
     * This will be intercepted by the ErrorController, which allows preHandle to work normally.
     *
     * @param requestMethod The request method.
     * @param requestUrl The request URL.
     * @param requestHeaders The request headers.
     * @throws NoHandlerFoundException every time this method is invoked.
     */
    @RequestMapping(value = "/**") // NOTE: This prevents resolution of static resources. Still looking for a workaround for this.
    public void getNotFoundPage(@ModelAttribute(REQUEST_METHOD) final String requestMethod, @ModelAttribute(REQUEST_URL) final String requestUrl, @ModelAttribute(REQUEST_HEADERS) final HttpHeaders requestHeaders) throws NoHandlerFoundException
    {
        throw new NoHandlerFoundException(requestMethod, requestUrl, requestHeaders);
    }

    /**
     * Gets all headers from a HTTP request.
     *
     * @param request The HTTP request.
     * @return The request headers.
     */
    public static HttpHeaders headers(final HttpServletRequest request)
    {
        final HttpHeaders headers = new HttpHeaders();

        for (Enumeration<?> names = request.getHeaderNames(); names.hasMoreElements();)
        {
            final String headerName = (String) names.nextElement();

            for (Enumeration<?> headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();)
            {
                headers.add(headerName, (String) headerValues.nextElement());
            }
        }

        return headers;
    }
}

结果

当这两个部分都起作用时,您将看到记录以下两个警告(第一个是Spring Security中的警告,第二个是Spring Framework(Core)ErrorController)。现在,您可以完全控制日志记录,并且可以根据需要调整可扩展的应用程序防火墙。

Sep 12, 2018 10:24:37 AM com.mycompany.spring.security.AnnotatingHttpFirewall getFirewalledRequest
WARNING: Intercepted org.springframework.security.web.firewall.RequestRejectedException: Remote Host: 0:0:0:0:0:0:0:1 User Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0 Request URL: http://localhost:8080/webapp-www-mycompany-com/login.php
Sep 12, 2018 10:24:37 AM com.mycompany.spring.controller.ErrorController handleException
WARNING: Rejected request from 0:0:0:0:0:0:0:1 for [http://localhost:8080/webapp-www-mycompany-com/login.php]. Reason: The request was rejected because it is a likely vulnerability scan.

答案 4 :(得分:1)

一种非常简单的方法是使用 web.xml ;在该文件中指定错误页面:

<error-page>
  <exception-type>org.springframework.security.web.firewall.RequestRejectedException</exception-type>
  <location>/request-rejected</location>
</error-page>

对于指定的路径(位置),在带有@Controller注释的类中添加映射:

@RequestMapping(value = "/request-rejected")
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody String handleRequestRejected(
        @RequestAttribute(RequestDispatcher.ERROR_EXCEPTION) RequestRejectedException ex,
        @RequestAttribute(RequestDispatcher.ERROR_REQUEST_URI) String uri) {

    String msg = ex.getMessage();

    // optionally log the message and requested URI (slf4j)
    logger.warn("Request with URI [{}] rejected. {}", uri, msg);

    return msg;
}

答案 5 :(得分:1)

我在this commit

中看到了最近github更改中的一些可行解决方案

如果您注册类型为RequestRejectedHandler的bean,或者如我所见,它应该可以工作,在WebSecurity中还将通过WebSecurityConfigurerAdapter进行集成。不幸的是,使用依赖项管理的2.3.3 RELEASE中可能未包含此更改。它应该存在于Spring Security Config 5.4.0-M1中。对于依赖性管理,它是版本2.4.0-M1。

或早或晚,遇到此问题的人们应该在标准版本中看到此更改。

答案 6 :(得分:0)

另一种处理方法是使用Spring AOP。我们可以围绕FilterChainProxy.doFilter()方法创建建议,以捕获HttpFirewall引发的任何RequestRejectedException,并将其转换为400 BAD_REQUEST

@Aspect
@Component
public class FilterChainProxyAdvice {

    @Around("execution(public void org.springframework.security.web.FilterChainProxy.doFilter(..))")
    public void handleRequestRejectedException (ProceedingJoinPoint pjp) throws Throwable {
        try {
            pjp.proceed();
        } catch (RequestRejectedException exception) {
            HttpServletResponse response = (HttpServletResponse) pjp.getArgs()[1]);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}