安全防护

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

@@ -1,4 +1,7 @@
# 当前证据
实施:Quartz 源码方法注解允许列表,覆盖启动/CRUD/恢复/立即运行/创建调度/最终执行;保留8类现有专用任务入口,所有 @Scheduled 业务不改。两根POM SnakeYAML 2.3,使用安全属性加载适配器保持 Boot 2.2 profile/扁平化兼容。管理接口来源过滤默认回环,提供代理及 nftables 模板;真实服务器地址/回调出站清单未知,线上网络规则不能盲目应用。
实际捕获栈确认 Quartz -> JobInvokeUtil -> Yaml.load -> ScriptEngineManager -> URLClassLoader -> Pinggy;用户提供 sys_job 8/12 启用的恶意 YAML 任务及 11 的命令载荷。数据库写入入口未确认。
Quartz 源码在兄弟仓库 ruoyi-common,应用使用本地依赖 JAR,必须构建并交付该模块,不能仅改 myEpusdt。
扩展静态扫描完成:466 个运行依赖 JAR、125848 个条目,目标域名/IP 的明文、UTF-16、Base64 和百分号编码均未命中,扫描错误 0;阴性结果不能排除动态拼接、数据库配置或实际部署差异。
前轮已确认 AWS ELB 域名为 grpc.nile.trongrid.io 的 CNAME。
前轮扫描运行依赖未找到两个 Pinggy 域名明文。org.json:json:19970182 含授权校验逻辑,但尚未与 Pinggy 关联。
@@ -1,4 +1,8 @@
# 排查进度
最终安全测试17项全部通过:Quartz6、安全YAML6、来源过滤4、现有全部YAML配置兼容1。此前原91项业务/诊断回归0失败、1跳过。修复别名循环/指数展开及CGLIB代理授权兼容后完成增量打包。
完成clean package和后续最终源码package;实际发布classpath再次运行11项YAML/来源测试全通过。外置lib仅snakeyaml-2.3.jar;Quartz源码制品与发布制品SHA256一致;执行器内含新system及SnakeYAML2.3。仅清理并重建标准target构建输出,没有删除业务数据或任务证据。
代理/nftables仅交付模板,Windows无nginx/nft工具也无远程Linux会话,未宣称线上生效;真实数据库任务与网络清单需在部署环境核对。
安全修复首轮验证:Quartz隔离5项全通过;应用相关100项、0失败、1跳过(含5项安全YAML测试、4项来源过滤测试),真实最小Spring启动验证profile选择。另新增当前全部配置文件兼容测试准备运行。已有JDK8/SnakeYAML2.x无参构造器不兼容通过优先属性加载工厂适配,未升级整套Spring。
最终相关回归:91 项,0 失败,0 错误,1 项跳过;其中诊断独立 JVM 测试 5 项全部通过,新增验证已有安全策略拒绝读取诊断配置时仍正常启动。
扩展扫描 466 个依赖 JAR 的 125848 条目,无目标字符串命中、无扫描错误。已完成中文启用与判读文档;仍需实际复现环境输出才能归因具体包。
已读取两个入口、POM、配置和当前工作区规则。保留已有修改,不执行 Git 历史查询。
+5 -1
View File
@@ -1,6 +1,6 @@
# Pinggy 异常外联定位
## Next Step
在实际复现服务启用诊断,采集首条完整调用栈以确认请求来源;本地实现与验证已完成。
本地实现、测试及打包完成;按安全部署文档在实际环境配置可信来源/出站目标并切换新制品。
### Phase 1: 当前调用链与证据检查
**Status:** complete
### Phase 2: 定位代码与隔离验证
@@ -9,3 +9,7 @@
**Status:** complete
## Boundaries
不改业务逻辑,不主动请求可疑域名,不启动带真实数据库及链上调度的完整服务。
### Phase 4: 安全修复与兼容性核查
**Status:** complete
### Phase 5: 安全回归与部署交付
**Status:** complete
+3
View File
@@ -1,5 +1,8 @@
## 平台简介
Quartz 任意调用和 YAML 远程加载链已增加执行允许列表及安全解析,管理接口默认仅允许回环来源。
部署必须同步更新 Quartz/system/YAML 依赖,并按[安全加固说明](docs/security-hardening.md)配置可信来源和代理规则。
临时排查未知域名外联可启用[网络调用来源诊断](docs/network-request-trace.md),记录 DNS 调用栈和实际加载的 JAR 来源;默认关闭,适用于 JDK 8。
TRON 密钥生成、地址校验和离线签名恢复通过现有 Trident 与 `TronKey` 适配实现,不再依赖 `tron-wallet-cli`;钱包派生路径、地址编码和投票交易行为保持兼容。后端请使用 JDK 8 编译。
+32
View File
@@ -0,0 +1,32 @@
# nftables 配置模板,不能原样部署:必须替换服务 UID 并填入所有业务目标。
# 仅约束专用 Java 服务用户的出站流量,不清空现有防火墙规则。
# 其他出站链仍可进一步拒绝本表放行的流量。需同时检查容器网络/转发路径。
define service_uid = 99999
table inet usdt_egress {
set dns4 { type ipv4_addr; flags interval; }
set dns6 { type ipv6_addr; flags interval; }
set business4 { type ipv4_addr; flags interval; }
set business6 { type ipv6_addr; flags interval; }
set database4 { type ipv4_addr; flags interval; }
set database6 { type ipv6_addr; flags interval; }
chain output {
type filter hook output priority 10; policy accept;
meta skuid $service_uid jump java_egress
}
chain java_egress {
# 保留现有连接的返回流量;应用应在规则生效后重启,避免保留旧恶意出站连接。
ct state established,related accept
oifname "lo" accept
ip daddr @dns4 udp dport 53 accept
ip6 daddr @dns6 udp dport 53 accept
ip daddr @dns4 tcp dport 53 accept
ip6 daddr @dns6 tcp dport 53 accept
ip daddr @database4 tcp dport { 3306, 6379 } accept
ip6 daddr @database6 tcp dport { 3306, 6379 } accept
# 端口按实际服务配置调整;IP 集合包含 RPC、执行器、回调、OAuth 等业务目标。
ip daddr @business4 tcp dport { 80, 443, 50051, 50061 } accept
ip6 daddr @business6 tcp dport { 80, 443, 50051, 50061 } accept
limit rate 5/second log prefix "usdt-egress-denied "
counter reject
}
}
+5
View File
@@ -0,0 +1,5 @@
# 复制到 /etc/nginx/snippets/usdt-admin-allow.conf。
# 仅在此处添加实际管理员公网 IP / VPN 网段;不要放行 0.0.0.0/0。
allow 127.0.0.1;
allow ::1;
deny all;
+16
View File
@@ -0,0 +1,16 @@
# 合并到现有对外 server 中。使用 /prod-api 前缀的若依部署与直接路径均覆盖。
# 必须放在其他正则 location 前,且不能被现有 ^~ /prod-api/ 或精确 location 绕过。
# 合并后使用 nginx -T 核对实际命中的 location,再 nginx -t。
# 若前面还有 CDN/LB,仅对可信代理设置 real_ip;禁止信任全网的转发头。
location ~ ^/(?:prod-api/)?(?:monitor/(?:job|jobLog)|druid)(?:[/.;]|$) {
include /etc/nginx/snippets/usdt-admin-allow.conf;
# 与现有网关相同的 URI 去前缀行为,保留查询串。
rewrite ^/prod-api/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 如需整个管理站仅限 VPN,在独立管理域名的 server 级 include 上面的 allow 文件;
# 对外支付 API / OAuth 回调 / Telegram webhook 继续放在原公共 server,避免误封业务。
+4 -2
View File
@@ -3,8 +3,10 @@
## 当前结论与证据边界
`grpc.nile.trongrid.io` 的 AWS ELB CNAME 属于已有 Nile 查询链路。
两个 `*.run.pinggy-free.link` 域名的 DNS 记录不能直接确定 Java 调用者,
也不能凭 NXDOMAIN 断言已经成功连接或外传信息。
最初的 DNS 记录不能直接确定 Java 调用者;后续实际调用栈和数据库记录已确认:
`sys_job` 8/12 的恶意任务通过 Quartz → Yaml.load → ScriptEngineManager → URLClassLoader
触发两个 Pinggy 域名的远程 JAR 加载尝试。是否成功下载、执行或外传仍需主机证据。
修复和部署步骤见[安全加固](security-hardening.md)。
已检查的本地动态插件 JAR 和 `D:/configs/license.dll` 中未命中目标域名的明文、
UTF-16 或 Base64 内容。此前识别到 `org.json:json:19970182` 含授权代码,
+117
View File
@@ -0,0 +1,117 @@
# Quartz 入侵链修复与网络隔离部署
## 本轮实现
`sys_job` 的恶意调用链为 Quartz → 任意类反射 → SnakeYAML → 远程 JAR。
修复作用于后续执行,不能证明已被入侵的操作系统恢复可信,也不删除数据库中的取证记录。
1. Quartz 仅能调用已有 Spring Bean 上标记 `@AllowedJobMethod` 的 public、非 static、void 方法,
并精确匹配参数类型。禁止完整类名实例化、继承的通用对象方法、表达式及非标量参数。
新增、修改、恢复、立即运行、创建调度和最终执行均校验;最终执行检查不能通过直接改库绕过。
2. 启动发现非法任务只记录 jobId 并跳过,不修改原记录、不阻止合法任务启动。
因此历史恶意记录仍可能显示“正常”,但不会被本轮版本加载执行。
3. 两个根 POM 统一锁定 SnakeYAML 2.3。`SafeYamlPropertySourceLoader` 在 Spring 启动前注册,
适配 Boot 2.2,使用 SafeConstructor、禁止重复键、限制别名 50、嵌套 50 层及 3 Mi 字符输入。
展开阶段拒绝循环别名,限制展开节点 100000;保留普通 Map/列表、占位符、Unicode、多文档 profile
选择与简单锚点;不打印配置 Map。
适配器返回标准属性源,不提供旧 OriginTrackedYamlLoader 的逐字段行号元数据。
4. Java 入口增加 `/monitor/job`、`/monitor/jobLog`、`/druid` 来源 CIDR 检查(包含子路径及旧 MVC 后缀)。
默认仅允许回环对端,不读取 X-Forwarded-For;来源通过后仍须原有认证/权限检查。
支付 API、回调、OAuth、WebSocket 及 `@Scheduled` 调度不在该限制范围。
## 现有任务兼容
当前已授权的专用任务入口:
| Bean | 方法 |
| --- | --- |
| ryTask | ryNoParams、ryParams(String)、ryMultipleParams(String,Boolean,Long,Double,Integer) |
| dmPlayerentOnlineStatusTask | execute |
| paymentLedgerReconciliationTask | reconcile |
| paymentOrderExpireTask | expireOrders |
| payoutConfirmationTask | confirm |
| tronPaymentTask | scan |
| usdtConfigBalanceRefreshTask | refresh |
| walletSnapshotRefreshTask | produce |
原有无参 `bean.method` / `bean.method()` 和单引号字符串、Boolean、Long(L)、Double(D)、Integer
调用格式保留;正常支付、归集和钱包派生逻辑没有改写。
数据库无法从本机连接,因此部署前仍须核对真实库内其他合法 Quartz 任务。
如有表外自定义任务,应审查对应专用 Bean 及方法后在源码加注解并测试,不能放行任意包或通用 Service。
`UsdtAggregationExecutorTask` 当前不是 Spring Bean,也没有启用调度;本次没有额外启用该旧执行器。
## 构建与更新范围
两个项目是独立 Maven reactor,Quartz 来自兄弟目录,必须先构建它:
```powershell
cd D:/myprojects/usdt/ruoyi-common
mvn -pl ruoyi-quartz -am install
cd ../myEpusdt
mvn clean package -DskipTests
```
外置 lib 部署使用新的干净发布目录,包含新 `ruoyi-admin.jar`、`ruoyi-system-3.4.0.jar`、
`ruoyi-quartz-3.4.0.jar`、`snakeyaml-2.3.jar` 及本轮依赖清单中的其他 JAR。
不要往旧 lib 叠加文件;旧 `snakeyaml-1.*.jar`、旧 Quartz 或旧 system 不能留在同一 classpath。
保留原部署目录用于取证/恢复配置;不能通过回滚到有漏洞的旧程序恢复运行。
若独立链上执行器也部署,使用本轮构建的执行器制品,避免继续携带旧 YAML 依赖。
## 管理来源和代理配置
**同机 Nginx:** 保留当前 profiles 并追加 `hardening`(例如 `prod,rental,hardening`),
使 Java 只监听 127.0.0.1。Nginx 的所有业务上游需指向该回环端口;该 profile 不应直接用于跨主机代理。
`deploy/security/nginx-admin-allow.conf` 加入实际管理员公网 IP/VPN CIDR 后复制到
`/etc/nginx/snippets/usdt-admin-allow.conf`,把 `nginx-management.conf` 合入现有 server。
按实际 Java 端口及前端 API 前缀调整模板,不替换原 TLS、公共 API、WebSocket 配置。
模板默认只允许回环,不含虚构的管理员 IP。
已有 `^~ /prod-api/`、更早的正则或精确 location 可能使安全 location 失效,必须用 `nginx -T`
核查优先级;必要时把相同 allow 规则直接合并到现有管理 location。
若前面还有 CDN/LB,仅信任明确代理网段的 real_ip 配置,不能信任客户端转发头。
Java 默认只能看到同机代理地址,所以**代理层来源控制不可省略**。
跨主机代理/管理员直连时,用外部配置设置:
```text
SECURITY_MANAGEMENT_ALLOWED_CIDRS=10.8.0.0/24,192.0.2.10/32
```
上述地址仅为格式示例,必须换成真实可信网段;跨主机 Java 应绑定私网地址,主机安全组仅允许代理访问。
如需整个管理站只限 VPN,使用独立管理域名并在 server 层 include 来源规则;原公共支付域名继续提供
商户 API、支付/租赁回调、OAuth 回调、Telegram webhook 和节点 WebSocket,不能直接对公共 server 全面 deny。
先执行 `nginx -t`,再 reload;验证可信来源能管理任务,不可信来源返回 403,伪造 X-Forwarded-For 仍拒绝。
确认公网不能直接访问 Java、3306 和 6379;MySQL/Redis 若在独立主机上,用其安全组仅放行业务私网来源。
## 出站控制
`deploy/security/egress.nft.example` 是专用服务 UID 的 IPv4/IPv6 出站允许列表模板,未在本机或服务器加载。
先用真实服务用户 UID 替换 99999,并填充 dns、database、business 地址集合及实际端口。
不能以 root 运行服务后对整个 root UID 套用该规则;容器需在其实际网络命名空间/转发链上配置等价策略。
业务清单至少核实:MySQL、Redis、DNS、TRON 主网/Nile 的 HTTP/gRPC、TronGrid/TronScan、
链上执行器、资源租赁供应商、商户支付/代付/租赁回调、Google OAuth、Telegram、OSS/MinIO 及启用的插件外联。
动态域名的 IP 变更和 IPv6 必须一并维护;任意公网商户回调应经受控出站代理动态审批,不能使用固定
IP 模板后假定所有回调可用。不要通过允许所有 443 来“修复”连接失败,这会放回恶意 HTTPS 下载。
先在隔离测试环境核对业务目标,使用 `nft -c -f <配置文件>` 校验后再安排实际部署。
表名为 `usdt_egress`,不执行 `flush ruleset`;回退时只移除该专用表,不清空其他防火墙。
模板保留 established/related,部署切换需重启应用以断开旧恶意连接。
默认空集合会拒绝未登记的业务外联,因此不能原样应用。
本机是 Windows,未提供远程 Linux 会话,不能宣称已完成 Nginx/nftables 的线上生效验证。
## 发布后核验
本地验证:Quartz 安全测试 6 项、安全 YAML 6 项、管理来源过滤 4 项、当前全部配置兼容 1 项,
合计 17 项全通过;另有原业务/诊断回归 91 项,0 失败、1 项真实转账测试跳过。
最终制品 classpath 的 11 项 YAML/来源测试复测通过;已核对外置 lib 仅含 SnakeYAML 2.3,
Quartz 源码制品与发布依赖的 SHA256 相同,执行器也包含更新后的 YAML/system。
本地未启动连接真实数据库和链上的完整业务应用;以下线上核验需在部署环境完成。
- 日志中的任务 8/12 等非法 jobId 被拒绝加载;其他合法任务按期运行。
- 数据库任务管理的新增、修改、恢复和立即执行均拒绝非法目标,且没有发起网络解析。
- 支付创建/查询、入账扫描、回调、资源租赁及执行器调用在隔离环境分别验证。
- 核对实际加载的 SnakeYAML 只有 2.3,启动没有 NoSuchMethodError。
- 保留 `[NETWORK-TRACE]` 观察窗口,确认不再由恶意任务触发 Pinggy 外联。
+7
View File
@@ -16,6 +16,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<snakeyaml.version>2.3</snakeyaml.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<druid.version>1.2.4</druid.version>
<bitwalker.version>1.21</bitwalker.version>
@@ -45,6 +46,12 @@
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- 2.x 默认拒绝任意 Java 类型;Boot 2.2 的 YAML 加载由安全适配器兼容。 -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<!-- SpringBoot的依赖配置-->
<dependency>
@@ -18,6 +18,7 @@ public class DmPlayerentOnlineStatusTask {
private IDmPlayerentService dmPlayerentService;
@Scheduled(cron = "0/5 * * * * ?")
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void execute() {
// com.license.LicenseBootstrap.init();
LambdaQueryWrapper<DmPlayerentPlus> queryWrapper = new LambdaQueryWrapper<>();
@@ -38,4 +39,4 @@ public class DmPlayerentOnlineStatusTask {
int count = dmPlayerentService.count(queryWrapper);
System.setProperty("globalCount", count+"");
}
}
}
@@ -20,6 +20,7 @@ public class PaymentLedgerReconciliationTask {
}
@org.springframework.scheduling.annotation.Scheduled(fixedDelay = 30000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void reconcile() {
List<Long> orderIds = ledgerPostingService.findOrderIdsRequiringSettlement(BATCH_SIZE);
for (Long orderId : orderIds) {
@@ -15,6 +15,7 @@ public class PaymentOrderExpireTask {
@Autowired private IUsdtOrdersService orders;
@Scheduled(fixedDelay = 10000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void expireOrders() {
LambdaQueryWrapper<UsdtOrdersPlus> query = new LambdaQueryWrapper<UsdtOrdersPlus>()
.eq(UsdtOrdersPlus::getStatus, 1)
@@ -16,6 +16,7 @@ public class PayoutConfirmationTask {
}
@Scheduled(fixedDelay = 30000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void confirm() {
service.confirmPending();
}
@@ -39,6 +39,7 @@ public class TronPaymentTask {
private TronChainDataClient chainDataClient;
@Scheduled(fixedDelay = 10000L)
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void scan() {
ITronService tron = null;
try {
@@ -32,6 +32,7 @@ public class UsdtConfigBalanceRefreshTask {
/** 默认每 30 秒刷新一次,完成上一轮后再计算间隔,防止慢查询堆积。 */
@Scheduled(fixedDelayString = "${payment.usdt-config-balance.refresh-delay-ms:15000}")
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void refresh() {
UsdtConfigPlus config = usdtConfigMapper.selectOne(new LambdaQueryWrapper<UsdtConfigPlus>()
.select(UsdtConfigPlus::getId, UsdtConfigPlus::getTokenAddress)
@@ -13,6 +13,7 @@ public class WalletSnapshotRefreshTask {
/** 每轮按更新时间投递五个钱包。 */
@Scheduled(fixedDelayString = "${payment.wallet-snapshot.producer-delay-ms:10000}")
@com.ruoyi.quartz.annotation.AllowedJobMethod
public void produce() {
walletSnapshotRefreshService.enqueueScheduledBatch();
}
@@ -0,0 +1,64 @@
package com.ruoyi.web.core.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.web.util.matcher.IpAddressMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* 调度管理/数据库监控的额外来源限制,不替代原有登录与权限检查。
* 只信任 TCP 对端地址,绝不采信客户端可伪造的 X-Forwarded-For。
* 使用本机反向代理时必须同时启用代理层来源限制,否则应用只看得到代理地址。
* 默认仅回环访问;跨主机代理或直连管理员通过受控外部配置加入明确 CIDR。
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
public class ManagementSourceFilter extends OncePerRequestFilter {
private final List<IpAddressMatcher> allowed = new ArrayList<>();
public ManagementSourceFilter(@Value("${security.management.allowed-cidrs:127.0.0.1/32,::1/128}")
String cidrs) {
for (String value : cidrs.split(",")) {
String cidr = value.trim();
// 地址必须为数值格式,配置错误时启动失败,避免把主机名交给 DNS 解析。
if (!cidr.matches("[0-9a-fA-F:.]+(?:/[0-9]{1,3})?")) {
throw new IllegalArgumentException("管理来源配置必须是数值 IP/CIDR");
}
allowed.add(new IpAddressMatcher(cidr));
}
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
// servletPath 来自容器映射,避免使用带 contextPath/查询串的原始请求 URI。
String path = request.getServletPath();
if (protectedPath(path)) {
boolean permitted = false;
for (IpAddressMatcher matcher : allowed) {
if (matcher.matches(request)) { permitted = true; break; }
}
if (!permitted) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":403,\"msg\":\"管理接口来源不允许\"}");
return;
}
}
chain.doFilter(request, response);
}
private boolean protectedPath(String path) {
// 同时覆盖旧 MVC 的后缀匹配和分号路径参数,不能靠 .json 绕过来源检查。
return path.matches("/(?:monitor/(?:job|jobLog)|druid)(?:[/.;].*)?");
}
}
@@ -0,0 +1,9 @@
# 仅在同机 Nginx 部署时追加 hardening profile;原 prod/rental 等 profile 保留。
# 所有公共 API 仍由 Nginx 转发,不再允许绕过代理直接访问 Java 端口。
# 跨主机代理需将 address 改成实际私网地址,并由主机防火墙只放行代理来源。
server:
address: 127.0.0.1
security:
management:
allowed-cidrs: ${SECURITY_MANAGEMENT_ALLOWED_CIDRS:127.0.0.1/32,::1/128}
@@ -0,0 +1,18 @@
package com.ruoyi.web.core.filter;
import com.ruoyi.system.security.SafeYamlPropertySourceLoader;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import static org.junit.Assert.*;
/** 只解析当前项目配置,不启动应用、不连接数据库,且不打印配置中的秘密。 */
public class ExistingYamlCompatibilityTest {
@Test
public void allShippedConfigurationFilesRemainReadable() throws Exception {
SafeYamlPropertySourceLoader loader = new SafeYamlPropertySourceLoader();
for (String name : new String[] {"application.yml", "application-prod.yml", "application-local.yml",
"application-druid.yml", "application-rental.yml", "application-hardening.yml"}) {
assertFalse(name, loader.load(name, new ClassPathResource(name)).isEmpty());
}
}
}
@@ -0,0 +1,49 @@
package com.ruoyi.web.core.filter;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.junit.Assert.*;
public class ManagementSourceFilterTest {
private boolean invoke(String path, String remote, String forwarded, String cidrs) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath(path);
request.setRemoteAddr(remote);
request.addHeader("X-Forwarded-For", forwarded);
MockHttpServletResponse response = new MockHttpServletResponse();
AtomicBoolean passed = new AtomicBoolean();
new ManagementSourceFilter(cidrs).doFilter(request, response,
(req, res) -> passed.set(true));
if (!passed.get()) assertEquals(403, response.getStatus());
return passed.get();
}
@Test
public void directPublicClientCannotSpoofLoopback() throws Exception {
for (String path : new String[] {"/monitor/job", "/monitor/job/run", "/monitor/jobLog/list",
"/monitor/job.json", "/monitor/job;id=1", "/druid/"}) {
assertFalse(invoke(path, "203.0.113.10", "127.0.0.1", "127.0.0.1/32,::1/128"));
}
}
@Test
public void trustedIpv4AndIpv6CanReachOriginalAuthenticationChain() throws Exception {
assertTrue(invoke("/monitor/job/list", "10.8.0.10", "203.0.113.10", "10.8.0.0/24"));
assertTrue(invoke("/monitor/job/list", "::1", "203.0.113.10", "::1/128"));
}
@Test
public void paymentCallbackAndOtherBusinessRoutesRemainUnchanged() throws Exception {
for (String path : new String[] {"/api/v1/order/query", "/api/rental/payment/notify/1",
"/api/telegram/webhook", "/node/v1/socket", "/login", "/system/wallet/list"}) {
assertTrue(invoke(path, "203.0.113.10", "203.0.113.10", "127.0.0.1/32"));
}
}
@Test(expected = IllegalArgumentException.class)
public void invalidHostnameFailsClosedWithoutDns() {
new ManagementSourceFilter("example.invalid");
}
}
@@ -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