1、起因

事件起因还是一个大佬 无在无不在 提交了份关于利用spring cloud gateway的spel漏洞,CVE-2022-22947。这个漏洞没什么太大的问题,利用就是通过动态路由注册进行触发,关键是通过X-Forwarded-Proto构造的请求包存在一定绕过的逻辑。这个解析处理的逻辑很有趣,不久前看到大佬星球也有文章详细说明了常见的解析问题,本次就把之前的Spring gateway定位记录做下分享;

👉 CVE-2022-22947漏洞的复习就看下面的链接吧,不过多介绍了

参考链接:

https://forum.butian.net/share/1410

https://www.cnpanda.net/sec/1159.html

https://www.cnblogs.com/zpchcbd/p/17659322.html

2、测试复现

请求包:

step1.创建路由:

POST/test/HTTP/1.1
Host:www.xxxxx.com
Content-Type:application/json
X-Forwarded-Proto: <https://www.baidu.com/actuator>?
Content-Length:340

从以上可知有个关键点在于X-Forwarded-Proto的请求,这个被gateway执行了。

3、失败的原因定位

X-Forwarded-Proto是一个HTTP请求头,它用于识别客户端与代理服务器或负载均衡器之间原始连接的协议。这个请求头通常由代理服务器设置,当它接收到来自客户端的请求并通过HTTP或HTTPS转发到后端服务器时。具体来说,X-Forwarded-Proto的值指示了客户端与代理服务器之间建立的原始连接类型:

  • 如果客户端通过HTTP(即未加密的HTTP/1.0或HTTP/1.1)连接到代理服务器,则X-Forwarded-Proto的值将为http。
  • 如果客户端通过HTTPS(即通过SSL/TLS加密的HTTP)连接到代理服务器,则X-Forwarded-Proto的值将为https。这个信息对于后端服务器来说非常重要,因为后端服务器可能需要知道原始请求是否是安全的,以便它可以做出相应的安全决策,例如重定向到HTTPS或确保正确的安全标头被设置。以下是几个使用场景:
  • 确保安全链接:后端服务器可以使用这个头部来确保所有的请求都是通过HTTPS进行的。
  • 日志记录:后端服务器可以记录原始请求的协议类型,以便进行调试和审计。
  • 应用逻辑:某些应用可能根据请求是HTTP还是HTTPS来改变行为。总之,X-Forwarded-Proto帮助确保在多层代理和负载均衡的环境下,后端服务能够正确地识别和处理客户端的原始请求协议。

之后对gateway处理请求的相关执行流程,发现主要是使用webflux对应的框架处理请求;

并且发现了 业务存在Globalfilter的逻辑处理使用UriComponentsBuilder,对组件检索发现

org.springframework.web.util.UriComponentsBuilder#adaptFromForwardedHeaders中存在对 X-Forwarded-Proto的处理过程

假设有一个请求的转发头如下:

X-Forwarded-For: 192.168.1.1
X-Forwarded-Proto: https
X-Forwarded-Host: ubackend.xxxxxx.cn
在调用 adaptFromForwardedHeaders 方法后,构建的 URI 可能会是:

<https://ubackend.xxxxxx.cn/account/details>

在 UriComponentsBuilder 中,最终的 URL 封装逻辑主要在 build() 和 buildAndExpand() 方法中完成。这些方法最终会调用 createUri() 方法来构建完整的 URI。

结合之前gateway的请求处理逻辑,因此猜测可能根因是这个方法adaptFromForwardedHeaders导致的,

spring-web5.3.9

  • org.springframework.web.server.adapter.HttpWebHandlerAdapter#handle(forwardedHeaderTransformer ! = nul)
  • org.springframework.web.server.adapter.ForwardedHeaderTransformer#apply(removeOnly = false)
  • org.springframework.web.util.UriComponentsBuilder#fromHttpRequest ( build ≠true)
  • org.springframework.web.util.UriComponentsBuilder#adaptFromForwardedHeaders

如上文所示,复现过程中发现有多个点不成立,代码中不存在forwardedHeaderTransformer 的配置,并且build 对应当前版本为true,也就是最终进行解析会报错;

4、柳暗花明

之后怀疑线上代码和本地不一致,找到业务下载了对应源码,以及测试环境地址(主机部署)、线上环境(容器化部署)

curl '<http://127.0.0.1:8081/123123123>' \\
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \\
  -H 'x-forwarded-proto: <https://www.baidu.com/actuator?'>

之后本以为彻底没希望,结果看之前的检索记录:https://blog.csdn.net/netyeaxi/article/details/128729640

发现这个问题一早就发现了,结果一直没有本地测试。测试确实是server.forwardHeadersStrategy=native这个配置导致的;这个配置是spring boot在云环境自动生效。

根因分析

  • org.springframework.boot.cloud.CloudPlatform
  • Spring Boot 通过检查特定的环境变量来识别当前的运行环境。容器化环境(如 Docker、Kubernetes)通常会设置一些特定的环境变量,这些变量可以用来判断应用是否在容器中运行
  • 云环境会导致默认配置发生变化;
  • server.forwardHeadersStrategy=native
  • spring.main.cloud-platform: *KUBERNETES 和上面效果是一致的;*
  • 关键路径跟踪
  • org.springframework.boot.autoconfigure.web.embedded.NettyWebServerFactoryCustomizer#getOrDeduceUseForwardHeaders
  • 初始化解析配置
  • org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory#createHttpServer
  • 当设置NATIVE时候,在NettyReactiveWebServerFactory中根据该设置为true这初始化DefaultHttpForwardedHeaderHandler对象;当相关路由过来时则会使用该对象进行相关请求头处理;
  • reactor.netty.http.server.DefaultHttpForwardedHeaderHandler#apply
  • 解析对应的connectionInfo
  • org.springframework.http.server.reactive.ReactorServerHttpRequest#resolveBaseUrl
  • 解析组装最终的url

初始化解析配置

org.springframework.boot.autoconfigure.web.embedded.NettyWebServerFactoryCustomizer#getOrDeduceUseForwardHeaders

    private boolean getOrDeduceUseForwardHeaders() {
        if (this.serverProperties.getForwardHeadersStrategy() == null) {
            CloudPlatform platform = CloudPlatform.getActive(this.environment);
            return platform != null && platform.isUsingForwardHeaders();
        }
        return this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NATIVE);
    }
  • org.springframework.boot.cloud.CloudPlatform

spring.main.cloud-platform 可以直接设置对应值进行设置当前环境。

  • KUBERNETES
  • CLOUD_FOUNDRY
  • HEROKU
  • SAP
  • NONE(禁用检测)

实际应用场景

配置示例:

# 强制指定为Kubernetes平台
spring.main.cloud-platform=KUBERNETES

# 或者禁用云平台检测
spring.main.cloud-platform=NONE
  • org.springframework.boot.autoconfigure.web.embedded.NettyWebServerFactoryCustomizer#getOrDeduceUseForwardHeaders判断当前环境选择
private boolean getOrDeduceUseForwardHeaders() {
		if (this.serverProperties.getForwardHeadersStrategy() == null) {
			CloudPlatform platform = CloudPlatform.getActive(this.environment);
			return platform != null && platform.isUsingForwardHeaders();
		}
		return this.serverProperties.getForwardHeadersStrategy().equals(ServerProperties.ForwardHeadersStrategy.NATIVE);
	}
  • org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory#createHttpServer
private HttpServer createHttpServer() {
		HttpServer server = HttpServer.create();
		if (this.resourceFactory != null) {
			LoopResources resources = this.resourceFactory.getLoopResources();
			Assert.notNull(resources, "No LoopResources: is ReactorResourceFactory not initialized yet?");
			server = server.runOn(resources).bindAddress(this::getListenAddress);
		}
		else {
			server = server.bindAddress(this::getListenAddress);
		}
		if (getSsl() != null && getSsl().isEnabled()) {
			server = customizeSslConfiguration(server);
		}
		if (getCompression() != null && getCompression().getEnabled()) {
			CompressionCustomizer compressionCustomizer = new CompressionCustomizer(getCompression());
			server = compressionCustomizer.apply(server);
		}
		server = server.protocol(listProtocols()).forwarded(this.useForwardHeaders);
		return applyCustomizers(server);
	}
  • reactor.netty.http.server.DefaultHttpForwardedHeaderHandler解析对应的connectionInfo,这里就会发现https://datatracker.ietf.org/doc/html/rfc7239这里的标准设计了,其实感觉走parseForwardedInfo的逻辑其实也是一样的;关键在于构建的connectionInfo这个内容的schema已经发生了变化;
public ConnectionInfo apply(ConnectionInfo connectionInfo, HttpRequest request) {
		String forwardedHeader = request.headers().get(FORWARDED_HEADER);
		if (forwardedHeader != null) {
			return parseForwardedInfo(connectionInfo, forwardedHeader);
		}
		return parseXForwardedInfo(connectionInfo, request);
	}

	private ConnectionInfo parseForwardedInfo(ConnectionInfo connectionInfo, String forwardedHeader) {
		String forwarded = forwardedHeader.split(",", 2)[0];
		Matcher hostMatcher = FORWARDED_HOST_PATTERN.matcher(forwarded);
		if (hostMatcher.find()) {
			connectionInfo = connectionInfo.withHostAddress(
					AddressUtils.parseAddress(hostMatcher.group(1), connectionInfo.getHostAddress().getPort(),
							DEFAULT_FORWARDED_HEADER_VALIDATION));
		}
		Matcher protoMatcher = FORWARDED_PROTO_PATTERN.matcher(forwarded);
		if (protoMatcher.find()) {
			connectionInfo = connectionInfo.withScheme(protoMatcher.group(1).trim());
		}
		Matcher forMatcher = FORWARDED_FOR_PATTERN.matcher(forwarded);
		if (forMatcher.find()) {
			connectionInfo = connectionInfo.withRemoteAddress(
					AddressUtils.parseAddress(forMatcher.group(1).trim(), connectionInfo.getRemoteAddress().getPort(),
							DEFAULT_FORWARDED_HEADER_VALIDATION));
		}
		return connectionInfo;
	}

	private ConnectionInfo parseXForwardedInfo(ConnectionInfo connectionInfo, HttpRequest request) {
		String ipHeader = request.headers().get(X_FORWARDED_IP_HEADER);
		if (ipHeader != null) {
			connectionInfo = connectionInfo.withRemoteAddress(
					AddressUtils.parseAddress(ipHeader.split(",", 2)[0], connectionInfo.getRemoteAddress().getPort()));
		}
		String hostHeader = request.headers().get(X_FORWARDED_HOST_HEADER);
		if (hostHeader != null) {
			String portHeader = request.headers().get(X_FORWARDED_PORT_HEADER);
			int port = connectionInfo.getHostAddress().getPort();
			if (portHeader != null && !portHeader.isEmpty()) {
				String portStr = portHeader.split(",", 2)[0].trim();
				if (portStr.chars().allMatch(Character::isDigit)) {
					port = Integer.parseInt(portStr);
				}
				else if (DEFAULT_FORWARDED_HEADER_VALIDATION) {
					throw new IllegalArgumentException("Failed to parse a port from " + portHeader);
				}
			}
			connectionInfo = connectionInfo.withHostAddress(
					AddressUtils.createUnresolved(hostHeader.split(",", 2)[0].trim(), port));
		}
		String protoHeader = request.headers().get(X_FORWARDED_PROTO_HEADER);
		if (protoHeader != null) {
			connectionInfo = connectionInfo.withScheme(protoHeader.split(",", 2)[0].trim());
		}
		return connectionInfo;
	}

5、总结

  • 容器化环境spring boot会默认开启某些设置,如这次的server.forwardHeadersStrategy=native会导致使用netty存在x-forwarded-proto解析路径的差异问题。(本地debug完全复现不了,线上还能稳定存在,这个在定位问题的时候很折磨)
  • reactor.netty.http.server.DefaultHttpForwardedHeaderHandler#apply 这里对于schema的获取判断逻辑,测试下在spring cloud gateway版本3.1.9、4.1.0、4.3.0都是有效的。具体为啥要直接获取还不是很理解?正常来说应该只有http、https两种情况;
  • SRC大佬出手果然不一样,对应用框架及相关协议足够了解才能手到擒来,真就有时候给你扫描器你也不知道咋用。感觉还是要多关注下rfc协议,https://datatracker.ietf.org/doc/html/rfc7239 某些绕过方法看来就写在文档里;