安全防护

This commit is contained in:
lu7213 committed 2026-11-16 02:09:23 -05:00
1 parent 1daf477899
commit 98657ace5b
25 files changed
+570 -4

No files matched your search

@@ -0,0 +1,109 @@
package com.ruoyi.system.security;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.IdentityHashMap;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.error.YAMLException;
/**
* 为 Boot 2.2 适配 SnakeYAML 2.x,保留 Spring 的 Map/列表扁平化及多文档 profile 行为。
* 仅接受 YAML 标准数据类型;拒绝任意 Java 类型,限制别名、深度及输入量。
* 通过 spring.factories 在读取 application*.yml 之前注册,不能依赖普通 @Bean。
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
public final class SafeYamlPropertySourceLoader implements PropertySourceLoader {
@Override
public String[] getFileExtensions() {
return new String[] {"yml", "yaml"};
}
@Override
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
return new Processor().load(name, resource);
}
private static final class Processor extends YamlProcessor {
@Override
protected Yaml createYaml() {
LoaderOptions loader = new LoaderOptions();
loader.setAllowDuplicateKeys(false);
loader.setMaxAliasesForCollections(50);
loader.setNestingDepthLimit(50);
loader.setCodePointLimit(3 * 1024 * 1024);
DumperOptions dumper = new DumperOptions();
return new Yaml(new SafeConstructor(loader), new Representer(dumper), dumper, loader);
}
private List<PropertySource<?>> load(String name, Resource resource) throws IOException {
List<PropertySource<?>> sources = new ArrayList<>();
// 不调用旧版 YamlProcessor.process:其 DEBUG 日志会打印整个配置 Map。
// 只复用无日志的标准扁平化算法,配置秘密不能进入诊断输出。
try (Reader reader = new UnicodeReader(resource.getInputStream())) {
for (Object document : createYaml().loadAll(reader)) {
if (document != null) {
sources.add(new MapPropertySource(name + " (document #" + sources.size() + ")",
new LinkedHashMap<>(getFlattenedMap(asMap(document)))));
}
}
}
return sources;
}
private Map<String, Object> asMap(Object value) {
Map<String, Object> result = new LinkedHashMap<>();
Object normalized = convert(value, new IdentityHashMap<>(), 0, new int[1]);
if (!(normalized instanceof Map)) {
result.put("document", normalized);
return result;
}
((Map<?, ?>) normalized).forEach((key, item) -> result.put((String) key, item));
return result;
}
private Object convert(Object value, IdentityHashMap<Object, Boolean> visiting,
int depth, int[] visited) {
// 别名可构造循环或指数展开的图,解析器的语法深度限制不能单独防住扁平化阶段。
if (++visited[0] > 100000 || depth > 50) {
throw new YAMLException("YAML 配置展开规模超过限制");
}
if (!(value instanceof Map) && !(value instanceof Collection)) return value;
if (visiting.put(value, Boolean.TRUE) != null) {
throw new YAMLException("YAML 配置不允许循环别名");
}
try {
if (value instanceof Map) {
Map<String, Object> result = new LinkedHashMap<>();
((Map<?, ?>) value).forEach((key, item) -> result.put(
key instanceof String ? (String) key : "[" + key + "]",
convert(item, visiting, depth + 1, visited)));
return result;
}
List<Object> result = new ArrayList<>();
for (Object item : (Collection<?>) value) {
result.add(convert(item, visiting, depth + 1, visited));
}
return result;
} finally {
visiting.remove(value);
}
}
}
}
@@ -0,0 +1,4 @@
# Boot 2.2 的默认 YAML loader 依赖 SnakeYAML 1.x 已删除的无参构造器。
# 工厂优先级确保配置加载时选择本安全适配器,不需要升级整套 Spring。
org.springframework.boot.env.PropertySourceLoader=\
com.ruoyi.system.security.SafeYamlPropertySourceLoader
@@ -0,0 +1,102 @@
package com.ruoyi.system.security;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.Test;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import static org.junit.Assert.*;
public class SafeYamlPropertySourceLoaderTest {
@Configuration
public static class IsolatedConfiguration { }
@Test
public void actualBootStartupLoadsProfilesWithoutDatabaseOrSchedulers() {
SpringApplication app = new SpringApplication(IsolatedConfiguration.class);
app.setWebApplicationType(WebApplicationType.NONE);
app.setLogStartupInfo(false);
try (ConfigurableApplicationContext context = app.run(
"--spring.config.location=classpath:/security-bootstrap.yml",
"--spring.profiles.active=verified", "--spring.main.banner-mode=off")) {
assertEquals("profile-selected", context.getEnvironment().getProperty("security-test.value"));
assertEquals("MAINNET", context.getEnvironment().getProperty("security-test.labels[1]"));
assertEquals("fallback", context.getEnvironment().getProperty("security-test.placeholder"));
}
}
private List<PropertySource<?>> load(String text) throws Exception {
return new SafeYamlPropertySourceLoader().load("test",
new ByteArrayResource(text.getBytes(StandardCharsets.UTF_8)));
}
@Test
public void factoryIsSelectedBeforeLegacyBootLoader() {
List<PropertySourceLoader> loaders = SpringFactoriesLoader.loadFactories(
PropertySourceLoader.class, getClass().getClassLoader());
for (PropertySourceLoader loader : loaders) {
if (java.util.Arrays.asList(loader.getFileExtensions()).contains("yml")) {
assertEquals(SafeYamlPropertySourceLoader.class, loader.getClass());
return;
}
}
fail("未注册 YAML loader");
}
@Test
public void preservesDocumentsListsPlaceholdersAndUnicode() throws Exception {
List<PropertySource<?>> sources = load("spring:\n profiles: prod\npayment:\n name: 支付\n"
+ " nodes: [NILE, MAINNET]\n enabled: true\n url: ${RPC_URL:https://example.invalid}\n"
+ "---\nspring:\n profiles: local\npayment:\n enabled: false\n");
assertEquals(2, sources.size());
assertEquals("prod", sources.get(0).getProperty("spring.profiles"));
assertEquals("支付", sources.get(0).getProperty("payment.name"));
assertEquals("MAINNET", sources.get(0).getProperty("payment.nodes[1]"));
assertEquals(Boolean.TRUE, sources.get(0).getProperty("payment.enabled"));
assertEquals("${RPC_URL:https://example.invalid}", sources.get(0).getProperty("payment.url"));
assertEquals(Boolean.FALSE, sources.get(1).getProperty("payment.enabled"));
}
@Test
public void rejectsJavaTagsWithoutConstructingObjects() throws Exception {
for (String input : new String[] {"!!javax.script.ScriptEngineManager []",
"value: !!java.net.URL ['https://example.invalid/not-requested']",
"key: first\nkey: second\n"}) {
try { load(input); fail("危险 YAML 未被拒绝"); }
catch (YAMLException expected) { /* 拒绝解析,无网络或脚本操作。 */ }
}
try { new Yaml().load("!!javax.script.ScriptEngineManager []"); fail(); }
catch (YAMLException expected) { /* 升级后的通用构造器也默认拒绝 Java 标签。 */ }
}
@Test
public void rejectsExcessiveNesting() throws Exception {
StringBuilder text = new StringBuilder();
for (int i = 0; i < 100; i++) text.append('[');
text.append('0');
for (int i = 0; i < 100; i++) text.append(']');
try { load(text.toString()); fail(); }
catch (YAMLException expected) { }
}
@Test
public void rejectsAliasCyclesAndExponentialExpansionButPreservesSimpleAnchors() throws Exception {
assertEquals("value", load("base: &a {key: value}\ncopy: *a\n").get(0).getProperty("copy.key"));
try { load("cycle: &a [*a]\n"); fail(); }
catch (YAMLException expected) { }
StringBuilder bomb = new StringBuilder("a0: &a0 [value]\n");
for (int i = 1; i <= 18; i++) {
bomb.append("a").append(i).append(": &a").append(i)
.append(" [*a").append(i - 1).append(", *a").append(i - 1).append("]\n");
}
try { load(bomb.toString()); fail(); }
catch (YAMLException expected) { }
}
}
@@ -0,0 +1,11 @@
security-test:
value: base
labels:
- NILE
- MAINNET
placeholder: ${SECURITY_TEST_UNSET:fallback}
---
spring:
profiles: verified
security-test:
value: profile-selected