Springboot 学习 之 Springboot2 漏洞问题

1. 背景

截至 2025 年 4 月 10 日,Spring Framework 5.x 已停止维护,但免费的 5.x 最新版本 Spring Framework 5.3.39 仍然存在多个未修复的高危漏洞,5.3.40、5.3.41 为企业版版本

2. 遗留高危漏洞

2.1. CVE-2016-1000027(高危 | 远程代码执行漏洞)

攻击者通过构造恶意序列化数据发送至 HTTP 接口,触发 反序列化 漏洞,从而执行任意代码‌

2.1.1. 场景

使用 HTTP Invoker 提供 RPC 服务调用

2.1.2. 预防

默认 处于 关闭 状态‌,想要使用需通过显式配置启用

2.1.3. 查验

通过 Spring IOC 查看 HttpInvokerServiceExporter 实例是否存在

2.2. ‌CVE-2024-38816(路径遍历)

攻击者构造包含特殊路径(如 ../..\\)的恶意 HTTP 请求,绕过安全限制,访问文件系统中 Spring 进程权限内 的任意文件(如 /etc/passwd),导致敏感数据泄露‌

2.1.1. 场景

使用 ‌WebMvc.fn‌ 或 ‌WebFlux.fn‌ 提供 静态资源Spring Framework 应用‌,并且使用 FileSystemResource 或类似实现‌ 用来定位文件。

2.1.2. 预防

  • 升级到安全的版本
  • Spring Security HTTP 防火墙
  • Tomcat / Jetty 等容器防御机制
  • 优先使用 ClassPathResource 替代 FileSystemResource 提供静态资源‌
  • 特别注意 new FileSystemResource("D:\\code\\demo\\static\\"),必须以 \\ 结尾,否则依然可以利用 ../ 达到路径遍历效果

2.1.3. 补丁

参照:Spring Framework 6.x 修复代码 !!! 复制链接访问,跳转会被拦截

/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.function;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.function.Function;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.server.PathContainer;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * Lookup function used by {@link RouterFunctions#resources(String, Resource)}.
 *
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 * @since 5.2
 */
class PathResourceLookupFunction implements Function<ServerRequest, Optional<Resource>> {

	private final PathPattern pattern;

	private final Resource location;


	public PathResourceLookupFunction(String pattern, Resource location) {
		Assert.hasLength(pattern, "'pattern' must not be empty");
		Assert.notNull(location, "'location' must not be null");
		this.pattern = PathPatternParser.defaultInstance.parse(pattern);
		this.location = location;
	}


	@Override
	public Optional<Resource> apply(ServerRequest request) {
		PathContainer pathContainer = request.requestPath().pathWithinApplication();
		if (!this.pattern.matches(pathContainer)) {
			return Optional.empty();
		}

		pathContainer = this.pattern.extractPathWithinPattern(pathContainer);
		String path = processPath(pathContainer.value());
		if (!StringUtils.hasText(path) || isInvalidPath(path)) {
			return Optional.empty();
		}
		if (isInvalidEncodedInputPath(path)) {
			return Optional.empty();
		}

		if (!(this.location instanceof UrlResource)) {
			path = UriUtils.decode(path, StandardCharsets.UTF_8);
		}

		try {
			Resource resource = this.location.createRelative(path);
			if (resource.isReadable() && isResourceUnderLocation(resource)) {
				return Optional.of(resource);
			}
			else {
				return Optional.empty();
			}
		}
		catch (IOException ex) {
			throw new UncheckedIOException(ex);
		}
	}

	/**
	 * Process the given resource path.
	 * <p>The default implementation replaces:
	 * <ul>
	 * <li>Backslash with forward slash.
	 * <li>Duplicate occurrences of slash with a single slash.
	 * <li>Any combination of leading slash and control characters (00-1F and 7F)
	 * with a single "/" or "". For example {@code "  / // foo/bar"}
	 * becomes {@code "/foo/bar"}.
	 * </ul>
	 */
	protected String processPath(String path) {
		path = StringUtils.replace(path, "\\", "/");
		path = cleanDuplicateSlashes(path);
		return cleanLeadingSlash(path);
	}

	private String cleanDuplicateSlashes(String path) {
		StringBuilder sb = null;
		char prev = 0;
		for (int i = 0; i < path.length(); i++) {
			char curr = path.charAt(i);
			try {
				if ((curr == '/') && (prev == '/')) {
					if (sb == null) {
						sb = new StringBuilder(path.substring(0, i));
					}
					continue;
				}
				if (sb != null) {
					sb.append(path.charAt(i));
				}
			}
			finally {
				prev = curr;
			}
		}
		return sb != null ? sb.toString() : path;
	}

	private String cleanLeadingSlash(String path) {
		boolean slash = false;
		for (int i = 0; i < path.length(); i++) {
			if (path.charAt(i) == '/') {
				slash = true;
			}
			else if (path.charAt(i) > ' ' && path.charAt(i) != 127) {
				if (i == 0 || (i == 1 && slash)) {
					return path;
				}
				return (slash ? "/" + path.substring(i) : path.substring(i));
			}
		}
		return (slash ? "/" : "");
	}

	private boolean isInvalidPath(String path) {
		if (path.contains("WEB-INF") || path.contains("META-INF")) {
			return true;
		}
		if (path.contains(":/")) {
			String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
			if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
				return true;
			}
		}
		return path.contains("..") && StringUtils.cleanPath(path).contains("../");
	}

	private boolean isInvalidEncodedInputPath(String path) {
		if (path.contains("%")) {
			try {
				// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
				String decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8);
				if (isInvalidPath(decodedPath)) {
					return true;
				}
				decodedPath = processPath(decodedPath);
				if (isInvalidPath(decodedPath)) {
					return true;
				}
			}
			catch (IllegalArgumentException ex) {
				// May not be possible to decode...
			}
		}
		return false;
	}

	private boolean isResourceUnderLocation(Resource resource) throws IOException {
		if (resource.getClass() != this.location.getClass()) {
			return false;
		}

		String resourcePath;
		String locationPath;

		if (resource instanceof UrlResource) {
			resourcePath = resource.getURL().toExternalForm();
			locationPath = StringUtils.cleanPath(this.location.getURL().toString());
		}
		else if (resource instanceof ClassPathResource classPathResource) {
			resourcePath = classPathResource.getPath();
			locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath());
		}
		else if (resource instanceof ServletContextResource servletContextResource) {
			resourcePath = servletContextResource.getPath();
			locationPath = StringUtils.cleanPath(((ServletContextResource) this.location).getPath());
		}
		else {
			resourcePath = resource.getURL().getPath();
			locationPath = StringUtils.cleanPath(this.location.getURL().getPath());
		}

		if (locationPath.equals(resourcePath)) {
			return true;
		}
		locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
		return (resourcePath.startsWith(locationPath) && !isInvalidEncodedResourcePath(resourcePath));
	}

	private boolean isInvalidEncodedResourcePath(String resourcePath) {
		if (resourcePath.contains("%")) {
			// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
			try {
				String decodedPath = URLDecoder.decode(resourcePath, StandardCharsets.UTF_8);
				if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
					return true;
				}
			}
			catch (IllegalArgumentException ex) {
				// May not be possible to decode...
			}
		}
		return false;
	}

	@Override
	public String toString() {
		return this.pattern + " -> " + this.location;
	}

}

2.3. CVE-2024-38819(路径遍历)

CVE-2024-38816

3. 升级到 Spring Framework 6.x

3.1. 波及范围

3.1.1. java jdk 17+

Spring Framework 6JDK 17 设为 最低支持版本彻底放弃JDK 8 及更早版本 的支持‌

3.1.2. SpringBoot 3

Spring Framework 6 必须与 Spring Boot 3 配合使用,两者属于配套技术栈。Spring Boot 3 的底层依赖已强制升级至 Spring Framework 6.0,无法向下兼容 Spring Framework 5.x 版本‌

3.1.3. SpringCloud 2023.0.0 +

Spring Cloud 2023.0.0(即 Spring Cloud 3)是首个支持 Spring Boot 3 的版本,其底层依赖已适配 Spring Framework 6 的技术规范‌

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值