【SpringCloudGateway】SpringCloudGateway 增加指定IP过滤器,保护actuator端点


一.背景

  去年SpringCloudGateway爆出了远程代码执行漏洞(CVE-2022-22947,具体表现就是可以通过查询和修改actuator相关的信息,导致网关路由异常

  官方给出了升级Gateway版本的方案,但由于升级Gateway版本影响面太大,实际情况比并支持我们这边错,这里通记录下的WebFilter拦截指定请求的的方案

二.想法

  参考网关请求的执行流程,由于请求进入网关时,需要进入一系列的过滤器如下图
  

   配置了健康检查端点以后,需要对   /actuator路径下的请求进行过滤,但是这些请求是Springboot框架内置的接口请求,不会进入GatewayFilter,因为WebFilter的执行顺序优先于GatewayFilter,因此需要在WebFilter这一层就给过滤和拦截掉这些请求

三.实现

  
复制代码
/**
 * @author Sam.yang
 * @since 2023/11/25 13:53
 */
@Slf4j
@Configuration
public class CustomWebFilterConfig {

    @Autowired
    private ApplicationConfig applicationConfig;

    @Bean
    public WebFilter webFilter() {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();
            URI uri = request.getURI();
            String requestPath = uri.getPath();
            String remoteAddress = request.getRemoteAddress().getAddress().getHostAddress();
            String host = uri.getHost();
            log.info("当前接口请求域名:{},接口请求地址:{},请求IP地址:{}", host, requestPath, remoteAddress);
            if (requestPath.startsWith("/actuator")) {
                log.info("当前请求为健康检查端点请求,请求路径:{},请求地址:{}", requestPath, host);
                Optional<String> optional = applicationConfig.getActuatorIps().stream().filter(x -> x.equals(remoteAddress))
                        .findAny();
                if (optional.isPresent()) {
                    return chain.filter(exchange);
                }
                log.error("当前请求非白名单请求,请求路径:{},请求地址:{}", requestPath, host);
                return response.writeWith(Mono.just(response.bufferFactory().wrap("Access Denied".getBytes())));
            } else {
                return chain.filter(exchange);
            }
        };
    }

}
复制代码

  applicationConfig 配置类信息如下:

复制代码
/**
 * @author Sam.yang
 * @since 2023/12/15 20:42
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "application.allows")
public class ApplicationConfig {

    /**
     * 健康检查端点请求IP
     */
    private List<String> actuatorIps;

}
复制代码

  可以看到只允许指定IP访问健康检查的端点接口,避免了一刀切的问题

 

四.参考

  1.https://cloud.tencent.com/developer/article/2164533

posted @   听风是雨  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
/* 看板娘 */
点击右上角即可分享
微信分享提示