Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63a9df5e79 | ||
|
|
65a793efcc | ||
|
|
606c50139c | ||
|
|
4d656ef63c | ||
|
|
c12b777a42 | ||
|
|
f3b4d171d7 | ||
|
|
fee0c3243b | ||
|
|
4dbc3e767b | ||
|
|
98657ace5b | ||
|
|
1daf477899 |
No files matched your search
@@ -4,6 +4,7 @@
|
||||
.gradle
|
||||
/build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
.planning
|
||||
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# 当前证据
|
||||
实施: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 关联。
|
||||
当前 RuoYiApplication 启动扫描 com.ruoyi、com.luqj 和 org.code.modules.plugins,插件目录来自 plugin.base.dir。独立执行器有另一个启动入口,也应支持同一诊断。
|
||||
当前没有运行中的业务 Java 服务,仅有 IDEA Maven JVM,无法直接取得正在复现异常的 Java 调用栈。
|
||||
对本地 D:/luqj-plugins 插件 JAR 和 D:/configs/license.dll 扫描明文、UTF-16 与 Base64 字符串,未命中目标域名。
|
||||
主入口原本仅经本地 ruoyi-framework 间接依赖 ruoyi-system,Maven reactor 先编译 admin,新增诊断引用因此读取旧本地 system JAR。需要显式依赖 system 保证使用本轮编译的源码。
|
||||
@@ -0,0 +1,11 @@
|
||||
# 排查进度
|
||||
最终安全测试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 历史查询。
|
||||
计划使用 JDK 8 SecurityManager 的 checkConnect 观察 DNS/连接;默认关闭,已存在安全管理器时拒绝覆盖,仅记录指定域名及调用来源,不能作为沙箱。
|
||||
4 个独立 JVM 测试全部通过:默认关闭、保留原安全管理器、本地真实 DNS 的动态 JAR 来源、域名边界和 200 事件输出上限。测试无可疑域名外联。
|
||||
首次全模块编译因 admin 在 system 之前构建而找不到新类;以显式依赖修复构建顺序,不修改业务。
|
||||
@@ -0,0 +1,15 @@
|
||||
# Pinggy 异常外联定位
|
||||
## Next Step
|
||||
本地实现、测试及打包完成;按安全部署文档在实际环境配置可信来源/出站目标并切换新制品。
|
||||
### Phase 1: 当前调用链与证据检查
|
||||
**Status:** complete
|
||||
### Phase 2: 定位代码与隔离验证
|
||||
**Status:** complete
|
||||
### Phase 3: 扩展扫描、文档与结果交付
|
||||
**Status:** complete
|
||||
## Boundaries
|
||||
不改业务逻辑,不主动请求可疑域名,不启动带真实数据库及链上调度的完整服务。
|
||||
### Phase 4: 安全修复与兼容性核查
|
||||
**Status:** complete
|
||||
### Phase 5: 安全回归与部署交付
|
||||
**Status:** complete
|
||||
@@ -1,5 +1,12 @@
|
||||
## 平台简介
|
||||
|
||||
支付和租赁应用支持[外部 API 来源 IP 白名单](docs/app-ip-whitelist.md)。升级先执行 [增量 SQL](sql/app_ip_whitelist_upgrade.sql),并为现有应用配置允许来源;空白名单拒绝全部请求,独立 `*` 显式允许全部来源。
|
||||
|
||||
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 编译。
|
||||
|
||||
归集、代付支持可选的[双平台资源租赁](docs/resource-rental.md):人工确认租赁后等待链上资源到账,再输入密码广播;独立执行器自动异步准备资源。默认关闭,启用前执行增量SQL并配置加密的平台凭据。
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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,避免误封业务。
|
||||
@@ -0,0 +1,44 @@
|
||||
# 管理后台全局接口 IP 白名单
|
||||
|
||||
## 部署
|
||||
|
||||
1. 执行 `sql/admin_access_whitelist.sql`(增量建表,无默认放行规则)。
|
||||
2. 通过管理接口或 SQL 配置允许访问的路径/IP,必须包含管理员访问的 `/login`、`/captchaImage`、`/getInfo`、`/getRouters` 等实际调用路径;固定管理员 IP 可配置 `/**`。
|
||||
3. 在后台 application 配置添加以下内容,重启启用:
|
||||
|
||||
```yaml
|
||||
admin:
|
||||
access-whitelist:
|
||||
enabled: true # 默认 false,部署前先配置规则
|
||||
refresh-delay-ms: 30000
|
||||
```
|
||||
|
||||
全局过滤覆盖此后台服务所有入口,包括登录、退出、匿名开放 API、回调和静态资源,没有隐式豁免,也不会绕过原有签名、登录和业务权限。公共支付/回调接口如需对任意 IP 开放,可显式配置该路径与 `*`。空规则、全部停用、首次加载失败时,启用状态下均拒绝访问。关闭开关需要修改配置并重启,可用于规则误配后的恢复。
|
||||
|
||||
## 规则
|
||||
|
||||
每行 `pathPattern` 与 `ipPattern` 同时匹配即放行,多行取或。路径采用 Ant 规则:`*` 为单段、`**` 为多段、`?` 为单字符;`/system/**` 匹配系统接口。IP 支持精确 IPv4/IPv6 以及 `*`、`?`,如 `192.168.*.*`,不是 CIDR。IPv6 按文本匹配,使用实际连接地址表示形式。
|
||||
|
||||
仅匹配应用内路径,不含 context-path、查询串;使用 Servlet 路径解码/分号移除规则。IP 从 `request.getRemoteAddr()` 读取,不直接读取 X-Forwarded-For 或 X-Real-IP。反向代理部署时它默认是代理地址:需要在容器层仅对受信代理做地址还原,且禁止客户端绕过该代理直连后台;否则这里只能限制代理本身。不要配置无边界信任所有代理头。
|
||||
|
||||
## 管理接口
|
||||
|
||||
基路径 `/system/accessWhitelist`,沿用 `system:config:*` 权限,并保留若依操作审计。
|
||||
|
||||
| 方法 | 路径 | 权限 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/list` | list | 获取全部规则 |
|
||||
| POST | 基路径 | add | 新建 |
|
||||
| PUT | `/{id}` | edit | 更新、启停 |
|
||||
| DELETE | `/{id}` | remove | 删除 |
|
||||
| POST | `/refresh` | edit | 触发当前节点刷新 |
|
||||
|
||||
新增/更新请求示例:
|
||||
|
||||
```json
|
||||
{"pathPattern":"/**","ipPattern":"192.168.1.*","enabled":true,"remark":"管理网络"}
|
||||
```
|
||||
|
||||
更改写入数据库,正常情况下约 30 秒后生效(刷新间隔不含查询耗时);各后台实例独立定时拉取,可调用刷新接口提前更新当前实例。每次刷新完整构建后原子替换快照,请求线程不查库;数据库故障或规则无效会保留最后成功快照并输出不含配置内容的错误日志。首次初始化后调度持续重试。刷新接口返回刷新成功或失败信息。
|
||||
|
||||
本次仅新增后台配置 API,未添加前端管理页面。
|
||||
@@ -0,0 +1,30 @@
|
||||
# 支付与租赁应用 IP 白名单
|
||||
|
||||
`apps.ip_whitelist` 和 `rent_app.ip_whitelist` 使用 `VARCHAR(2048) NOT NULL DEFAULT ''`。
|
||||
支付应用 JSON 字段为 `ipWhitelist`,租赁工作台 JSON 字段为 `ip_whitelist`。
|
||||
|
||||
## 规则
|
||||
|
||||
- 空值或空白:拒绝此应用全部外部 API 请求。不会影响后台 JWT 管理页面,仍可登录修改白名单。
|
||||
- 精确 IPv4 / IPv6:例如 `203.0.113.10`、`2001:db8::1`。
|
||||
- IPv4 完整地址段通配:例如 `192.168.*.*`、`10.*.1.*`。`*` 不能匹配半个地址段,不支持 CIDR、主机名或 URL。
|
||||
- 独立 `*`:显式允许所有来源,签名及原有鉴权仍必须通过。
|
||||
- 多条使用换行、逗号、分号或空白分隔;保存时去重,最多2048字符。
|
||||
|
||||
支付覆盖所有调用 `ApiSecurityService` 的创建订单、查询、代付和钱包开放接口。
|
||||
租赁覆盖 `/api/rental/v1/{operation}` 和 `/api/rental/v1/address-onchain/{operation}`。
|
||||
供应节点 Agent、后台管理、链上扫描和平台接收回调不属于应用商户调用,不套用本规则。
|
||||
拒绝响应为原 JSON 协议的 `code=403`,签名、密钥及抗重放逻辑继续保留。
|
||||
|
||||
## 真实来源与反向代理
|
||||
|
||||
默认取 Servlet `request.getRemoteAddr()`,不直接使用 `X-Forwarded-For`、`X-Real-IP` 或 `Forwarded`,防止调用者伪造来源。
|
||||
直接部署填写客户端实际 IP。反向代理部署须由运维在可信代理/容器层配置来源地址恢复,并且只信任确定的代理地址、限制直连后端和覆盖外部转发头;未配置时服务看到的是代理 IP。
|
||||
不要仅把所有用户共用的反向代理地址加入名单后将其当作按客户端隔离。
|
||||
|
||||
## 部署
|
||||
|
||||
1. 先在业务库执行 `sql/app_ip_whitelist_upgrade.sql`,可重复执行,不重建、不删除已有表。新租赁库的 `rent_init.sql` 已包含该列。
|
||||
2. 按每个应用配置实际来源 IP;旧记录默认空白,新版上线后会拒绝其 API 请求,必须提前配置。
|
||||
3. 编译部署前后端并重启服务。支付应用在创建/编辑对话框维护;租赁商户在应用详情保存,运营在应用列表的“IP 白名单”操作维护。
|
||||
4. 使用名单内、名单外和伪造转发头的请求验证。测试不广播任何链上交易。
|
||||
@@ -0,0 +1,126 @@
|
||||
# Pinggy 外联调用来源定位
|
||||
|
||||
## 当前结论与证据边界
|
||||
|
||||
`grpc.nile.trongrid.io` 的 AWS ELB CNAME 属于已有 Nile 查询链路。
|
||||
最初的 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` 含授权代码,
|
||||
但没有把它与这两个 Pinggy 域名关联的调用栈;暂不能认定是该包引入。
|
||||
实际部署目录、数据库、运行环境可能与本机不同,需要在复现进程中采样。
|
||||
|
||||
## 开启方式
|
||||
|
||||
该功能针对本项目 JDK 8,默认关闭。管理后端和独立执行器均已在 `main` 的
|
||||
Spring 启动之前调用 `NetworkRequestTrace.installIfEnabled()`,不需要修改业务配置。
|
||||
|
||||
IDEA 的 Run/Debug Configuration → VM options 加入:
|
||||
|
||||
```text
|
||||
-Dnetwork.trace.enabled=true
|
||||
```
|
||||
|
||||
部署环境也可以设置 `NETWORK_TRACE_ENABLED=true`。JVM 参数优先于环境变量。
|
||||
必须重启实际出现异常的 Java 进程,修改当前终端变量不会影响已经启动的进程。
|
||||
无需把开关放进 `application.yml`;这里是在 Spring 读取 YAML 之前安装。
|
||||
|
||||
现有 `java -jar` 启动命令把开关放在 `-jar` 之前,例如:
|
||||
|
||||
```bash
|
||||
java -Dnetwork.trace.enabled=true -jar ruoyi-admin.jar
|
||||
```
|
||||
|
||||
默认匹配 `pinggy-free.link` 和它的子域名。如果只需这两个域名,可以设置:
|
||||
|
||||
```text
|
||||
-Dnetwork.trace.hosts=wzndf-185-244-148-229.run.pinggy-free.link,lmdpj-185-244-148-229.run.pinggy-free.link
|
||||
```
|
||||
|
||||
环境变量等效项为 `NETWORK_TRACE_HOSTS`。需要顺便对照 Nile 调用时,可以把
|
||||
`grpc.nile.trongrid.io` 加入逗号分隔的列表。不要使用 URL、密码或查询串作为过滤值。
|
||||
|
||||
更新主程序时,必须同时更新本轮构建的 `ruoyi-system` JAR;外置 `lib` 部署不能只更新
|
||||
`ruoyi-admin.jar`,也不能把旧 `ruoyi-system` 留在同一 classpath 中。
|
||||
主模块已显式声明系统模块依赖,完整 Maven 构建会先编译当前系统模块。
|
||||
|
||||
## 查看结果
|
||||
|
||||
启动控制台首先应显示:
|
||||
|
||||
```text
|
||||
[NETWORK-TRACE] ENABLED java=1.8... hosts=pinggy-free.link maxEvents=200 output=stderr observation-only
|
||||
```
|
||||
|
||||
日志直接写入标准错误输出,覆盖日志框架尚未初始化的时段。
|
||||
IDEA 控制台、systemd journal 或容器日志一般会收集 stderr;只看业务 `info.log`
|
||||
可能看不到。自行启动时可以在原命令后追加 `2>network-trace.log` 收集诊断。
|
||||
|
||||
目标域名被解析时,输出形式如下(以下为格式示意,并非已经捕获的可疑调用):
|
||||
|
||||
```text
|
||||
[NETWORK-TRACE] BEGIN event=1 timeMillis=... threadId=... operation=DNS host=lmdpj-185-244-148-229.run.pinggy-free.link port=-1
|
||||
origin com.example.CallbackWorker source=file:/srv/app/lib/example.jar
|
||||
at java.net.InetAddress.getAllByName(...)
|
||||
at com.example.CallbackWorker.send(CallbackWorker.java:123)
|
||||
[NETWORK-TRACE] END event=1
|
||||
```
|
||||
|
||||
`origin` 显示实际执行类的 CodeSource,而非根据类名推测 JAR;`at` 显示方法和行号。
|
||||
结合类名与相应栈帧,判断请求来自业务回调、依赖授权逻辑或动态插件。
|
||||
若栈帧是异步 DNS 工作线程,它只能说明当前解析任务的执行者,仍需沿上游任务入口追查。
|
||||
|
||||
重点判读:
|
||||
|
||||
| 栈上的业务类 | 后续核查 |
|
||||
| --- | --- |
|
||||
| `PaymentCallbackWorker` | `orders.notify_url`、订单 ID、回调次数 |
|
||||
| `PayoutCallbackService` | `usdt_payout_order.notify_url` |
|
||||
| `RentalWorkers` | `rent_order.notify_url`、`rent_webhook` 对应明细;域名校验本身也可能触发 DNS |
|
||||
| `com.license.*` | 日志中实际加载的 JAR、部署环境的授权地址配置及本地 DLL |
|
||||
| 其他库或插件类 | 以 `origin source=` 指向的实际 JAR 为准,核对该部署文件的哈希及来源 |
|
||||
|
||||
## 同步检查数据库中的旧回调地址
|
||||
|
||||
当前本机无法连接配置中的数据库,所以没有假定数据库里不存在目标域名。
|
||||
可以在复现服务实际连接的数据库中执行以下只读查询,只返回记录 ID 和状态,
|
||||
不返回完整 URL、请求参数、API Key 或私钥。没有租赁表的库跳过相应查询。
|
||||
|
||||
```sql
|
||||
SELECT id, status, callback_num, callback_confirm
|
||||
FROM orders WHERE LOWER(notify_url) LIKE '%pinggy-free.link%' LIMIT 100;
|
||||
|
||||
SELECT id, status, callback_num, callback_confirm
|
||||
FROM usdt_payout_order WHERE LOWER(notify_url) LIKE '%pinggy-free.link%' LIMIT 100;
|
||||
|
||||
SELECT id, status
|
||||
FROM rent_order WHERE LOWER(notify_url) LIKE '%pinggy-free.link%' LIMIT 100;
|
||||
|
||||
SELECT id, status
|
||||
FROM rent_app WHERE LOWER(notify_url) LIKE '%pinggy-free.link%' LIMIT 100;
|
||||
```
|
||||
|
||||
命中仅代表存在配置,不代表该行正被定时任务执行;需要结合调用栈和任务状态确认。
|
||||
不要直接删除订单、修改回调状态或清空队列作为定位手段。
|
||||
|
||||
## 诊断边界与关闭
|
||||
|
||||
- 该钩子基于 JDK 8 `SecurityManager.checkConnect`。`port=-1` 表示解析前检查,
|
||||
不是 HTTP 已成功发出。诊断本身不访问目标域名,也不改变 DNS 缓存、代理或连接结果。
|
||||
- 只记录域名、时间、线程 ID、栈帧和类来源,不采集完整 URL、请求头、正文或钱包数据。
|
||||
- 已存在安全管理器时输出 `NOT_INSTALLED existing-security-manager`,不会覆盖已有策略。
|
||||
这是观察工具,不是安全沙箱。部分较新 JDK 已禁用此机制,应使用项目 JDK 8。
|
||||
- 最多输出 200 条事件;出现 `LIMIT_REACHED` 后仍正常执行网络操作,但停止打印。
|
||||
- JNI、自建 DNS 解析器、原生库、子进程和其他服务的请求不一定经过本钩子。
|
||||
一直没有日志时,应先核对 `ENABLED`、进程、部署 JAR、事件上限,再用操作系统工具关联 PID。
|
||||
- 定位后删除 VM 参数/环境变量并重启,或显式设置 `-Dnetwork.trace.enabled=false`。
|
||||
现有业务任务、回调及链上逻辑均不因该开关而被禁用。
|
||||
|
||||
## 验证
|
||||
|
||||
`NetworkRequestTraceTest` 在独立 JVM 中验证默认关闭、保留原安全管理器、
|
||||
通过本地 `localhost` 真实解析记录动态 JAR 来源、域名边界、敏感 URL 拒绝输出和事件上限。
|
||||
测试不解析 Pinggy 域名,也不启动真实数据库或链上调度。
|
||||
@@ -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 外联。
|
||||
+11
-6
@@ -1,6 +1,8 @@
|
||||
# Google Authenticator 动态码登录
|
||||
# Google Authenticator 登录二次验证
|
||||
|
||||
保留原密码登录和 Google OAuth 登录,新增独立的“账号 + 六位动态码 + 图形验证码”登录方式。动态码登录不是强制双因素验证,不改变其他登录方式的认证规则。
|
||||
仅提供密码登录和 Google OAuth 登录,不提供独立动态码登录。已绑定 Google 账号或 Google Authenticator 的账号,在密码登录(含 `/simple-login`)及 Google 登录交换票据时,必须提供有效且未使用的六位授权码 `totpCode`,否则不签发令牌。两者均未绑定的账号无需填写。
|
||||
|
||||
Google 身份绑定与 Authenticator 绑定分别记录在 `sys_user_google_oauth` 和 `sys_user_totp`。仅有 Google 身份绑定、缺少 Authenticator 凭据的旧账号会拒绝登录,需通过已有会话完成认证器绑定或联系管理员核实处理;不会自动生成密钥或仅检查输入非空后放行。
|
||||
|
||||
## 部署
|
||||
|
||||
@@ -21,22 +23,25 @@ $totpRng.Dispose()
|
||||
|
||||
## 使用
|
||||
|
||||
- Google 和 Authenticator 均未绑定的账号可直接使用密码及图形验证码登录。登录成功后提示前往账号安全完成绑定;选择“稍后处理”或关闭提示可直接进入系统。建议先绑定 Authenticator,再绑定 Google,防止下次登录因缺少动态码凭据被拒绝。
|
||||
- 先用密码或已绑定 Google 账号登录,打开“个人中心 → 账号安全 → Google Authenticator 动态码”。
|
||||
- 输入本地密码生成二维码;用 Google Authenticator 扫码,或手动输入页面展示的设置密钥,再输入手机六位动态码确认绑定。二维码在浏览器本地生成。
|
||||
- 临时绑定十分钟过期,未经验证不会启用。确认绑定所用码已消费,等手机刷新下一组码后再用于登录。
|
||||
- 登录页切换“动态码登录”,输入本地用户名、六位动态码和图形验证码。前导零必须保留。
|
||||
- 解绑需要本地密码及未使用过的动态码。遗失认证器时可用原密码或已绑定 Google 登录;需要重置绑定时由管理员核实身份后通过受控流程处理,系统不公开免验证重置接口。
|
||||
- 密码登录需输入本地用户名、密码和图形验证码;已绑定账号同时填写六位授权码,前导零必须保留。授权码不能单独作为登录凭据。
|
||||
- 密码登录时,已绑定用户必须填写授权码。Google 授权返回后填写授权码并继续;票据只有 60 秒有效且仅能交换一次,验证失败或过期需重新发起 Google 登录。
|
||||
- 解绑需要本地密码及未使用过的动态码。遗失认证器时,密码或 Google 身份均不能绕过授权码;需要重置绑定时由管理员核实身份后通过受控流程处理,系统不公开免验证重置接口。
|
||||
|
||||
## API
|
||||
|
||||
| 方法 / 路径 | 认证 / 请求 |
|
||||
| --- | --- |
|
||||
| `POST /auth/totp/login` | 匿名;`username, totpCode, code, uuid`,其中 code 是图形验证码;返回原有 `token` 字段 |
|
||||
| `POST /login`、`POST /simple-login` | 原登录参数增加 `totpCode`,已绑定用户必填 |
|
||||
| `POST /auth/google/exchange` | `ticket, totpCode`,已绑定用户必填授权码;失败后票据不可复用 |
|
||||
| `GET /auth/totp/binding` | 当前 JWT;返回 `data.enabled`、`data.bound`,不返回密钥 |
|
||||
| `POST /auth/totp/setup` | 当前 JWT + `password`;返回 `data.secret`、`data.otpauthUrl`,禁止缓存或记录响应 |
|
||||
| `POST /auth/totp/bind` | 当前 JWT + `password, totpCode` |
|
||||
| `POST /auth/totp/unbind` | 当前 JWT + `password, totpCode` |
|
||||
|
||||
时间步为 30 秒,SHA-1,6 位,容忍前后各一个时间步。数据库 CAS 原子消费时间步,包含绑定确认在内的同一时间步不可重复成功,也不能倒退使用旧码。账号每五分钟最多十次动态码登录尝试,管理操作另计十次;连接来源每五分钟最多五十次登录尝试。反向代理部署下连接来源按代理地址计数,可另在代理层对真实来源限流,不信任任意客户端传入的转发头。
|
||||
时间步为 30 秒,SHA-1,6 位,容忍前后各一个时间步。数据库 CAS 原子消费时间步,包含绑定确认在内的同一时间步不可重复成功,也不能倒退使用旧码。账号每五分钟最多十次登录授权码验证尝试,管理操作另计十次。可在反向代理层对真实来源增加限流,不信任任意客户端传入的转发头。
|
||||
|
||||
凭据使用 AES-256-GCM 加密,绑定用户 ID 为附加认证数据。密钥不加入用户实体、常规响应或 JWT。数据库、Redis 异常时拒绝认证。不要在网关、APM 或应用中开启登录请求体和绑定响应体采集。
|
||||
@@ -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>
|
||||
|
||||
@@ -24,6 +24,11 @@
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- 启动入口直接使用系统模块的诊断类,显式声明以保证多模块构建先编译当前源码。 -->
|
||||
<dependency>
|
||||
<groupId>com.ruoyi</groupId>
|
||||
<artifactId>ruoyi-system</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.ruoyi;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.ruoyi.framework.config.MybatisPlusInterceptor;
|
||||
import com.ruoyi.system.diagnostics.NetworkRequestTrace;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -20,6 +21,7 @@ import org.springframework.context.annotation.Bean;
|
||||
})
|
||||
public class RuoYiApplication {
|
||||
public static void main(String[] args) {// System.setProperty("spring.devtools.restart.enabled", "false");
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
SpringApplication.run(RuoYiApplication.class, args);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<>();
|
||||
|
||||
@@ -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,49 @@
|
||||
package com.ruoyi.web.access;
|
||||
|
||||
import java.io.IOException;
|
||||
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.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.util.UrlPathHelper;
|
||||
|
||||
/** 全局入口过滤,早于认证链;白名单不赋予匿名访问或业务权限。 */
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class AdminAccessConfiguration {
|
||||
@Bean
|
||||
public FilterRegistrationBean<OncePerRequestFilter> adminAccessFilter(
|
||||
AdminAccessWhitelist whitelist,
|
||||
@Value("${admin.access-whitelist.enabled:false}") boolean enabled) {
|
||||
OncePerRequestFilter filter = new OncePerRequestFilter() {
|
||||
private final UrlPathHelper paths = new UrlPathHelper();
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
// 仅使用 TCP 对端地址,绝不直接信任客户端可伪造的 X-Forwarded-For/X-Real-IP。
|
||||
String remoteAddress = request.getRemoteAddr();
|
||||
if (!enabled || whitelist.allows(paths.getPathWithinApplication(request), remoteAddress)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":403,\"msg\":\"来源 IP "
|
||||
+ remoteAddress + " 不在接口访问白名单中\"}");
|
||||
}
|
||||
};
|
||||
FilterRegistrationBean<OncePerRequestFilter> registration = new FilterRegistrationBean<>(filter);
|
||||
registration.setName("adminAccessWhitelistFilter");
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 20);
|
||||
return registration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.ruoyi.web.access;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/** 白名单管理接口,复用系统参数管理权限;数据库写入使用绑定参数。 */
|
||||
@RestController
|
||||
@RequestMapping("/system/accessWhitelist")
|
||||
public class AdminAccessController {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final AdminAccessWhitelist whitelist;
|
||||
|
||||
public AdminAccessController(JdbcTemplate jdbc, AdminAccessWhitelist whitelist) {
|
||||
this.jdbc = jdbc;
|
||||
this.whitelist = whitelist;
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
@PreAuthorize("@ss.hasPermi('system:config:list')")
|
||||
public AjaxResult list() {
|
||||
return AjaxResult.success(jdbc.queryForList("select id, path_pattern as pathPattern, "
|
||||
+ "ip_pattern as ipPattern, enabled, remark, created_at, updated_at "
|
||||
+ "from sys_admin_access_whitelist order by id"));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("@ss.hasPermi('system:config:add')")
|
||||
@Log(title = "全局接口访问白名单", businessType = BusinessType.INSERT)
|
||||
public AjaxResult add(@Valid @RequestBody AdminAccessRule rule) {
|
||||
int count = jdbc.update("insert into sys_admin_access_whitelist "
|
||||
+ "(path_pattern, ip_pattern, enabled, remark) values (?, ?, ?, ?)",
|
||||
rule.getPathPattern(), rule.getIpPattern(), rule.getEnabled(), rule.getRemark());
|
||||
return AjaxResult.success(count);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@PreAuthorize("@ss.hasPermi('system:config:edit')")
|
||||
@Log(title = "全局接口访问白名单", businessType = BusinessType.UPDATE)
|
||||
public AjaxResult edit(@PathVariable Long id, @Valid @RequestBody AdminAccessRule rule) {
|
||||
return AjaxResult.success(jdbc.update("update sys_admin_access_whitelist set "
|
||||
+ "path_pattern=?, ip_pattern=?, enabled=?, remark=? where id=?",
|
||||
rule.getPathPattern(), rule.getIpPattern(), rule.getEnabled(), rule.getRemark(), id));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("@ss.hasPermi('system:config:remove')")
|
||||
@Log(title = "全局接口访问白名单", businessType = BusinessType.DELETE)
|
||||
public AjaxResult remove(@PathVariable Long id) {
|
||||
return AjaxResult.success(jdbc.update("delete from sys_admin_access_whitelist where id=?", id));
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
@PreAuthorize("@ss.hasPermi('system:config:edit')")
|
||||
@Log(title = "刷新全局接口访问白名单", businessType = BusinessType.UPDATE)
|
||||
public AjaxResult refresh() {
|
||||
whitelist.refresh();
|
||||
return whitelist.isLastRefreshSuccessful() ? AjaxResult.success("刷新成功")
|
||||
: AjaxResult.error("刷新失败,已保留上一版本,请检查服务日志");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ruoyi.web.access;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Pattern;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
/** 管理后台全局访问规则;一行中的路径和 IP 必须同时匹配。 */
|
||||
public class AdminAccessRule {
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(max = 255)
|
||||
@Pattern(regexp = "/[^\\s?#;\\\\]*", message = "路径须以 / 开头,且不能包含空白、查询串、分号或反斜杠")
|
||||
private String pathPattern;
|
||||
@NotBlank
|
||||
@Size(max = 64)
|
||||
@Pattern(regexp = "[0-9a-fA-F:.*?]+", message = "IP 仅支持数字地址及 *、? 通配符")
|
||||
private String ipPattern;
|
||||
@NotNull
|
||||
private Boolean enabled;
|
||||
@Size(max = 255)
|
||||
private String remark;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getPathPattern() { return pathPattern; }
|
||||
public void setPathPattern(String pathPattern) { this.pathPattern = pathPattern; }
|
||||
public String getIpPattern() { return ipPattern; }
|
||||
public void setIpPattern(String ipPattern) { this.ipPattern = ipPattern; }
|
||||
public Boolean getEnabled() { return enabled; }
|
||||
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
|
||||
public String getRemark() { return remark; }
|
||||
public void setRemark(String remark) { this.remark = remark; }
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.ruoyi.web.access;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.annotation.PostConstruct;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
/**
|
||||
* 数据库规则的进程内快照。请求线程不访问数据库;完整加载成功后一次性发布快照,
|
||||
* 刷新失败保留最近成功版本。首次加载失败时快照为空,启用拦截后默认拒绝。
|
||||
*/
|
||||
@Service
|
||||
public class AdminAccessWhitelist {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AdminAccessWhitelist.class);
|
||||
private final JdbcTemplate jdbc;
|
||||
private final AntPathMatcher paths = new AntPathMatcher();
|
||||
private volatile List<CompiledRule> snapshot = Collections.emptyList();
|
||||
private volatile boolean lastRefreshSuccessful;
|
||||
|
||||
public AdminAccessWhitelist(JdbcTemplate jdbc) { this.jdbc = jdbc; }
|
||||
|
||||
@PostConstruct
|
||||
@Scheduled(fixedDelayString = "${admin.access-whitelist.refresh-delay-ms:30000}")
|
||||
public synchronized void refresh() {
|
||||
try {
|
||||
List<CompiledRule> next = jdbc.query(
|
||||
"select path_pattern, ip_pattern from sys_admin_access_whitelist where enabled = 1",
|
||||
(rs, row) -> new CompiledRule(rs.getString(1), rs.getString(2)));
|
||||
snapshot = Collections.unmodifiableList(new ArrayList<>(next));
|
||||
lastRefreshSuccessful = true;
|
||||
} catch (RuntimeException ex) {
|
||||
lastRefreshSuccessful = false;
|
||||
// 不记录配置值或数据库异常正文,避免日志泄漏连接信息。
|
||||
LOG.error("管理后台访问白名单刷新失败,保留上一版本,异常类型: {}", ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isLastRefreshSuccessful() { return lastRefreshSuccessful; }
|
||||
|
||||
public boolean allows(String path, String ip) {
|
||||
if (path == null || ip == null) { return false; }
|
||||
for (CompiledRule rule : snapshot) {
|
||||
if (paths.match(rule.path, path) && rule.ip.matcher(ip.toLowerCase(Locale.ROOT)).matches()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 仅 * 和 ? 具有特殊意义,其他字符逐个转义,禁止将数据库内容作为任意正则执行。 */
|
||||
static Pattern compileIp(String value) {
|
||||
if (value == null || value.length() > 64 || !value.matches("[0-9a-fA-F:.*?]+")) {
|
||||
throw new IllegalArgumentException("无效 IP 规则");
|
||||
}
|
||||
StringBuilder regex = new StringBuilder();
|
||||
for (char c : value.toLowerCase(Locale.ROOT).toCharArray()) {
|
||||
regex.append(c == '*' ? ".*" : c == '?' ? "." : Pattern.quote(String.valueOf(c)));
|
||||
}
|
||||
return Pattern.compile(regex.toString());
|
||||
}
|
||||
|
||||
private static final class CompiledRule {
|
||||
private final String path;
|
||||
private final Pattern ip;
|
||||
private CompiledRule(String path, String ip) {
|
||||
if (path == null || !path.startsWith("/") || path.length() > 255) {
|
||||
throw new IllegalArgumentException("无效接口规则");
|
||||
}
|
||||
this.path = path;
|
||||
this.ip = compileIp(ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -59,7 +59,7 @@ public class GoogleOauthController {
|
||||
@PostMapping("/exchange")
|
||||
public AjaxResult exchange(@RequestBody Map<String, String> request) {
|
||||
AjaxResult result = AjaxResult.success();
|
||||
result.put(Constants.TOKEN, googleOauthService.exchangeTicket(request.get("ticket")));
|
||||
result.put(Constants.TOKEN, googleOauthService.exchangeTicket(request.get("ticket"), request.get("totpCode")));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ public class SysLoginController
|
||||
AjaxResult ajax = AjaxResult.success();
|
||||
// 生成令牌
|
||||
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
|
||||
loginBody.getUuid(),true);
|
||||
loginBody.getUuid(),true, loginBody.getTotpCode());
|
||||
ajax.put(Constants.TOKEN, token);
|
||||
return ajax;
|
||||
}
|
||||
@@ -61,7 +61,7 @@ public class SysLoginController
|
||||
AjaxResult ajax = AjaxResult.success();
|
||||
// 生成令牌
|
||||
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), null,
|
||||
loginBody.getUuid(),false);
|
||||
loginBody.getUuid(),false, loginBody.getTotpCode());
|
||||
ajax.put(Constants.TOKEN, token);
|
||||
return ajax;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
package com.ruoyi.web.controller.system;
|
||||
|
||||
import com.ruoyi.common.constant.Constants;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.core.domain.model.LoginBody;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.framework.web.service.TotpAuthService;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
@@ -13,7 +11,7 @@ import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** Authenticator 六位动态码;只有 login 匿名开放,管理接口使用当前 JWT 用户 ID。 */
|
||||
/** Authenticator 绑定管理;所有接口使用当前 JWT 用户 ID,不提供独立动态码登录。 */
|
||||
@RestController
|
||||
@RequestMapping("/auth/totp")
|
||||
public class TotpAuthController {
|
||||
@@ -47,21 +45,7 @@ public class TotpAuthController {
|
||||
return AjaxResult.success("Authenticator 已解绑");
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AjaxResult login(@RequestBody TotpRequest request, HttpServletRequest servletRequest,
|
||||
HttpServletResponse response) {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
AjaxResult result = AjaxResult.success();
|
||||
result.put(Constants.TOKEN, service.login(request.getUsername(), request.getTotpCode(),
|
||||
request.getCode(), request.getUuid(), servletRequest.getRemoteAddr()));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 禁止生成包含密码、动态码的 toString;动态码与图形验证码分开传输。 */
|
||||
public static class TotpRequest extends LoginBody {
|
||||
private String totpCode;
|
||||
|
||||
public String getTotpCode() { return totpCode; }
|
||||
public void setTotpCode(String totpCode) { this.totpCode = totpCode; }
|
||||
}
|
||||
}
|
||||
@@ -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,29 @@
|
||||
package com.ruoyi.system.rental;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static com.ruoyi.system.rental.RentalValues.map;
|
||||
|
||||
/** 白名单保存必须依据持久化应用归属鉴权,且只写归一化后的配置(复用 admin 测试依赖)。 */
|
||||
public class RentalAppIpWhitelistTest {
|
||||
@Test
|
||||
public void ownerCanSaveNormalizedRules() {
|
||||
RentalStore store = mock(RentalStore.class);
|
||||
when(store.get("app", 7L, true)).thenReturn(map("user_id", 9L));
|
||||
new RentalProvisioning(store, mock(RentalOrders.class))
|
||||
.updateAppIpWhitelist(7L, "192.168.*.* , 203.0.113.1", 9L);
|
||||
verify(store).update("app", 7L, map("ip_whitelist", "192.168.*.*\n203.0.113.1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void otherOwnerCannotChangeWhitelist() {
|
||||
RentalStore store = mock(RentalStore.class);
|
||||
when(store.get("app", 7L, true)).thenReturn(map("user_id", 9L));
|
||||
try {
|
||||
new RentalProvisioning(store, mock(RentalOrders.class)).updateAppIpWhitelist(7L, "*", 10L);
|
||||
org.junit.Assert.fail("其他商户不得修改白名单");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
verify(store, never()).update(anyString(), anyLong(), anyMap());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.ruoyi.web.access;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.util.Collections;
|
||||
import javax.servlet.FilterChain;
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** 隔离数据库和 Servlet 链,覆盖规则配对、快照替换、故障保留及真实响应。 */
|
||||
public class AdminAccessWhitelistTest {
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public void refreshPublishesWholeSnapshotAndRetainsItOnDatabaseFailure() throws Exception {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.query(anyString(), any(RowMapper.class))).thenAnswer(call -> {
|
||||
ResultSet rs = mock(ResultSet.class);
|
||||
when(rs.getString(1)).thenReturn("/system/**");
|
||||
when(rs.getString(2)).thenReturn("192.168.*.*");
|
||||
return Collections.singletonList(((RowMapper) call.getArgument(1)).mapRow(rs, 0));
|
||||
});
|
||||
AdminAccessWhitelist whitelist = new AdminAccessWhitelist(jdbc);
|
||||
assertFalse(whitelist.allows("/system/user", "192.168.1.2"));
|
||||
whitelist.refresh();
|
||||
assertTrue(whitelist.allows("/system/user/list", "192.168.1.2"));
|
||||
assertFalse(whitelist.allows("/login", "192.168.1.2"));
|
||||
assertFalse(whitelist.allows("/system/user/list", "192x168.1.2"));
|
||||
when(jdbc.query(anyString(), any(RowMapper.class))).thenThrow(new IllegalStateException());
|
||||
whitelist.refresh();
|
||||
assertTrue(whitelist.allows("/system/user/list", "192.168.1.2"));
|
||||
when(jdbc.query(anyString(), any(RowMapper.class))).thenReturn(Collections.emptyList());
|
||||
whitelist.refresh();
|
||||
assertFalse(whitelist.allows("/system/user/list", "192.168.1.2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsSpoofedForwardingHeaderAndAllowsDisabledMode() throws Exception {
|
||||
AdminAccessWhitelist whitelist = mock(AdminAccessWhitelist.class);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/system/user/list");
|
||||
request.setRemoteAddr("203.0.113.9");
|
||||
request.addHeader("X-Forwarded-For", "127.0.0.1");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
new AdminAccessConfiguration().adminAccessFilter(whitelist, true).getFilter()
|
||||
.doFilter(request, response, chain);
|
||||
assertEquals(403, response.getStatus());
|
||||
assertTrue(response.getContentAsString().contains("来源 IP 203.0.113.9 不在接口访问白名单中"));
|
||||
assertFalse(response.getContentAsString().contains("127.0.0.1"));
|
||||
verify(whitelist).allows("/system/user/list", "203.0.113.9");
|
||||
verifyZeroInteractions(chain);
|
||||
new AdminAccessConfiguration().adminAccessFilter(whitelist, false).getFilter()
|
||||
.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
verify(chain).doFilter(eq(request), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowedRequestContinuesThroughOriginalChain() throws Exception {
|
||||
AdminAccessWhitelist whitelist = mock(AdminAccessWhitelist.class);
|
||||
when(whitelist.allows("/login", "127.0.0.1")).thenReturn(true);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/admin/login");
|
||||
request.setContextPath("/admin");
|
||||
request.setRemoteAddr("127.0.0.1");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
new AdminAccessConfiguration().adminAccessFilter(whitelist, true).getFilter()
|
||||
.doFilter(request, response, chain);
|
||||
verify(chain).doFilter(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wildcardMatchesEntireIpAndSupportsIpv6() {
|
||||
assertTrue(AdminAccessWhitelist.compileIp("2001:db8:*").matcher("2001:db8::1").matches());
|
||||
assertTrue(AdminAccessWhitelist.compileIp("10.0.0.?").matcher("10.0.0.1").matches());
|
||||
assertFalse(AdminAccessWhitelist.compileIp("10.0.0.?").matcher("10.0.0.12").matches());
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.ruoyi.web.controller.system;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import com.ruoyi.system.domain.AppApiKeysPlus;
|
||||
import com.ruoyi.system.domain.Apps;
|
||||
import com.ruoyi.system.domain.dto.EncryptedRequest;
|
||||
import com.ruoyi.system.mapper.AppsMapper;
|
||||
import com.ruoyi.system.rental.*;
|
||||
import com.ruoyi.system.service.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** 使用可控凭证和请求,验证两套真实API入口不会因伪造转发头而绕过白名单。 */
|
||||
public class AppIpWhitelistSecurityTest {
|
||||
@After
|
||||
public void clearRequest() { RequestContextHolder.resetRequestAttributes(); }
|
||||
|
||||
@Test
|
||||
public void paymentRejectsNonWhitelistedPeerBeforeDecrypting() {
|
||||
ApiSecurityService service = new ApiSecurityService();
|
||||
IAppApiKeysService keys = mock(IAppApiKeysService.class);
|
||||
AppsMapper apps = mock(AppsMapper.class);
|
||||
AppPrivateKeyCipher cipher = mock(AppPrivateKeyCipher.class);
|
||||
AppApiKeysPlus credential = new AppApiKeysPlus();
|
||||
credential.setAppId(7L); credential.setUserId(8L);
|
||||
Apps app = new Apps();
|
||||
app.setId(7L); app.setUserId(8L); app.setStatus(1); app.setIpWhitelist("203.0.113.*");
|
||||
when(keys.getOne(any())).thenReturn(credential);
|
||||
when(apps.selectAppsById(7L)).thenReturn(app);
|
||||
ReflectionTestUtils.setField(service, "apiKeysService", keys);
|
||||
ReflectionTestUtils.setField(service, "appsMapper", apps);
|
||||
ReflectionTestUtils.setField(service, "privateKeyCipher", cipher);
|
||||
MockHttpServletRequest request = request("198.51.100.1");
|
||||
request.addHeader("X-Forwarded-For", "203.0.113.10");
|
||||
request.addHeader("X-Real-IP", "203.0.113.10");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
EncryptedRequest encrypted = new EncryptedRequest();
|
||||
encrypted.setApiKey("key"); encrypted.setTimestamp(System.currentTimeMillis()); encrypted.setNonce("nonce");
|
||||
encrypted.setEncryptedKey("key"); encrypted.setIv("iv"); encrypted.setData("data"); encrypted.setHmac("hmac");
|
||||
denied(() -> service.decryptAndVerify(encrypted));
|
||||
app.setIpWhitelist("");
|
||||
denied(() -> service.decryptAndVerify(encrypted));
|
||||
verifyNoInteractions(cipher);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rentalEnforcesApplicationWhitelistAcrossOperations() throws Exception {
|
||||
RentalIdentity identity = mock(RentalIdentity.class);
|
||||
RentalStore store = mock(RentalStore.class);
|
||||
RentalOrders orders = mock(RentalOrders.class);
|
||||
Map<String, Object> credential = new HashMap<>(); credential.put("owner_id", 7L);
|
||||
Map<String, Object> app = new HashMap<>(); app.put("status", "ACTIVE"); app.put("user_id", 8L);
|
||||
app.put("ip_whitelist", "203.0.113.*");
|
||||
when(identity.authenticate(anyString(), eq("APP"), eq("API"), anyLong(), anyString(), eq("POST"), anyString(), anyString(), anyString())).thenReturn(credential);
|
||||
when(store.get("app", 7L, false)).thenReturn(app);
|
||||
RentalApiController controller = new RentalApiController(identity, store, orders, new ObjectMapper());
|
||||
for (String operation : Arrays.asList("create", "query", "quote", "packages")) {
|
||||
MockHttpServletRequest request = request("198.51.100.1");
|
||||
request.addHeader("X-Forwarded-For", "203.0.113.10");
|
||||
try {
|
||||
controller.execute(operation, request);
|
||||
fail("非白名单来源不能调用租赁API");
|
||||
} catch (CustomException expected) { assertEquals(Integer.valueOf(403), expected.getCode()); }
|
||||
}
|
||||
controller.execute("packages", request("203.0.113.10"));
|
||||
try {
|
||||
controller.executeOnchain("quote", request("198.51.100.1"));
|
||||
fail("地址上链入口同样需要白名单");
|
||||
} catch (CustomException expected) { assertEquals(Integer.valueOf(403), expected.getCode()); }
|
||||
verifyNoInteractions(orders);
|
||||
}
|
||||
|
||||
private MockHttpServletRequest request(String ip) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/rental/v1/packages");
|
||||
request.setRemoteAddr(ip);
|
||||
request.setContent("{\"network\":\"NILE\"}".getBytes(StandardCharsets.UTF_8));
|
||||
request.addHeader("X-Rent-Key", "key"); request.addHeader("X-Rent-Timestamp", "1");
|
||||
request.addHeader("X-Rent-Nonce", "nonce"); request.addHeader("X-Rent-Signature", "signature");
|
||||
return request;
|
||||
}
|
||||
|
||||
private void denied(Runnable operation) {
|
||||
try { operation.run(); fail("必须拒绝白名单以外的IP"); }
|
||||
catch (CustomException expected) { assertEquals(Integer.valueOf(403), expected.getCode()); }
|
||||
}
|
||||
}
|
||||
+47
-3
@@ -1,12 +1,14 @@
|
||||
package com.ruoyi.web.controller.system;
|
||||
|
||||
import com.ruoyi.common.core.domain.entity.SysUser;
|
||||
import com.ruoyi.common.core.domain.model.LoginUser;
|
||||
import com.ruoyi.common.core.redis.RedisCache;
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.common.utils.TotpUtils;
|
||||
import com.ruoyi.framework.web.service.TotpAuthService;
|
||||
import com.ruoyi.framework.web.service.SysLoginService;
|
||||
import com.ruoyi.framework.web.service.TokenService;
|
||||
import com.ruoyi.framework.web.service.TotpAuthService;
|
||||
import com.ruoyi.framework.web.service.TotpSecretCipher;
|
||||
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
|
||||
import com.ruoyi.system.mapper.SysUserTotpMapper;
|
||||
@@ -21,6 +23,8 @@ import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -50,8 +54,7 @@ public class TotpBindingServiceTest {
|
||||
user.setPassword(SecurityUtils.encryptPassword("test-only-password"));
|
||||
when(users.selectUserById(7L)).thenReturn(user);
|
||||
cipher = new TotpSecretCipher(Base64.getEncoder().encodeToString(new byte[32]));
|
||||
service = new TotpAuthService(mapper, cipher, redis, users, mock(UserDetailsServiceImpl.class),
|
||||
mock(TokenService.class), mock(SysLoginService.class));
|
||||
service = new TotpAuthService(mapper, cipher, redis, users, mock(UserDetailsServiceImpl.class));
|
||||
ReflectionTestUtils.setField(service, "issuer", "USDT PAY");
|
||||
secret = TotpUtils.newSecret();
|
||||
encrypted = cipher.encrypt(7L, secret);
|
||||
@@ -114,6 +117,47 @@ public class TotpBindingServiceTest {
|
||||
expectFailure(() -> service.setup(7L, "test-only-password"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unboundUserDoesNotRequireSecondFactor() {
|
||||
service.verifyBoundUser(7L, null);
|
||||
verify(mapper, never()).consume(anyLong(), anyString(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticatorBoundUserMustProvideValidUnusedAuthenticatorCode() {
|
||||
when(mapper.selectSecret(7L)).thenReturn(encrypted);
|
||||
expectFailure(() -> service.verifyBoundUser(7L, null));
|
||||
expectFailure(() -> service.verifyBoundUser(7L, ""));
|
||||
expectFailure(() -> service.verifyBoundUser(7L, currentCode()));
|
||||
when(mapper.consume(eq(7L), eq(encrypted), anyLong())).thenReturn(1);
|
||||
service.verifyBoundUser(7L, currentCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void boundUserRequiresSixDigitsAndAtomicConsumption() {
|
||||
when(mapper.selectSecret(7L)).thenReturn(encrypted);
|
||||
expectFailure(() -> service.verifyBoundUser(7L, null));
|
||||
expectFailure(() -> service.verifyBoundUser(7L, ""));
|
||||
expectFailure(() -> service.verifyBoundUser(7L, "12345"));
|
||||
expectFailure(() -> service.verifyBoundUser(7L, "abcdef"));
|
||||
verify(mapper, never()).consume(anyLong(), anyString(), anyLong());
|
||||
// 正确动态码仍必须原子消费成功;重复或并发消费失败不能登录。
|
||||
expectFailure(() -> service.verifyBoundUser(7L, currentCode()));
|
||||
when(mapper.consume(eq(7L), eq(encrypted), anyLong())).thenReturn(1);
|
||||
service.verifyBoundUser(7L, currentCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void boundUserCannotLoginWhenCredentialStoreFails() {
|
||||
when(mapper.selectSecret(7L)).thenThrow(new IllegalStateException("database unavailable"));
|
||||
try {
|
||||
service.verifyBoundUser(7L, null);
|
||||
fail("数据库异常不能跳过第二因素");
|
||||
} catch (IllegalStateException expected) {
|
||||
verify(mapper, never()).consume(anyLong(), anyString(), anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
private String currentCode() {
|
||||
return TotpUtils.generate(secret, Instant.now().getEpochSecond() / 30);
|
||||
}
|
||||
|
||||
+18
@@ -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,206 @@
|
||||
package com.ruoyi.system.diagnostics;
|
||||
|
||||
import java.net.URL;
|
||||
import java.security.CodeSource;
|
||||
import java.security.Permission;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* JDK 8 临时外联诊断:在 DNS 解析/连接之前记录调用栈与实际加载的 JAR 来源。
|
||||
*
|
||||
* <p>默认关闭,必须在 Spring 启动前调用。仅观察,不拒绝连接,不改变 DNS 缓存或
|
||||
* 代理配置,不读取请求 URL、请求参数、正文、环境变量清单或钱包数据。
|
||||
* 不是安全沙箱,也不能代替操作系统抓包;JNI、自建 DNS 客户端和其他进程可能绕过此钩子。</p>
|
||||
*/
|
||||
public final class NetworkRequestTrace extends SecurityManager {
|
||||
private static final String ENABLED_PROPERTY = "network.trace.enabled";
|
||||
private static final String HOSTS_PROPERTY = "network.trace.hosts";
|
||||
private static final String DEFAULT_HOSTS = "pinggy-free.link";
|
||||
/** 限制整个进程的诊断输出量,避免定时重试刷满日志;重启可重新采集。 */
|
||||
private static final int MAX_EVENTS = 200;
|
||||
private static final int MAX_FRAMES = 80;
|
||||
private final String[] watchedHosts;
|
||||
private final AtomicInteger events = new AtomicInteger();
|
||||
private final ThreadLocal<Boolean> recording = new ThreadLocal<Boolean>();
|
||||
|
||||
private NetworkRequestTrace(String[] watchedHosts) {
|
||||
this.watchedHosts = watchedHosts;
|
||||
}
|
||||
|
||||
/**
|
||||
* -Dnetwork.trace.enabled=true 或 NETWORK_TRACE_ENABLED=true 启用。
|
||||
* 只接受 JVM 参数/环境变量,因为 application.yml 在这个启动阶段还未加载。
|
||||
* 已有安全管理器时不替换,避免降低原有安全策略。
|
||||
*/
|
||||
public static synchronized void installIfEnabled() {
|
||||
try {
|
||||
installConfigured();
|
||||
} catch (SecurityException | UnsupportedOperationException ex) {
|
||||
// 读取开关也可能被现有策略拒绝,不能因诊断逻辑阻止原服务启动。
|
||||
System.err.println("[NETWORK-TRACE] NOT_INSTALLED " + ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
private static void installConfigured() {
|
||||
String enabled = System.getProperty(ENABLED_PROPERTY);
|
||||
if (enabled == null) {
|
||||
enabled = System.getenv("NETWORK_TRACE_ENABLED");
|
||||
}
|
||||
if (!Boolean.parseBoolean(enabled)) {
|
||||
return;
|
||||
}
|
||||
if (System.getSecurityManager() instanceof NetworkRequestTrace) {
|
||||
return;
|
||||
}
|
||||
if (System.getSecurityManager() != null) {
|
||||
System.err.println("[NETWORK-TRACE] NOT_INSTALLED existing-security-manager");
|
||||
return;
|
||||
}
|
||||
String configured = System.getProperty(HOSTS_PROPERTY);
|
||||
if (configured == null) {
|
||||
configured = System.getenv("NETWORK_TRACE_HOSTS");
|
||||
}
|
||||
String[] hosts = parseHosts(configured == null ? DEFAULT_HOSTS : configured);
|
||||
if (hosts.length == 0) {
|
||||
System.err.println("[NETWORK-TRACE] NOT_INSTALLED invalid-host-filter");
|
||||
return;
|
||||
}
|
||||
System.setSecurityManager(new NetworkRequestTrace(hosts));
|
||||
System.err.println("[NETWORK-TRACE] ENABLED java="
|
||||
+ safe(System.getProperty("java.version")) + " hosts="
|
||||
+ String.join(",", hosts) + " maxEvents=" + MAX_EVENTS
|
||||
+ " output=stderr observation-only");
|
||||
}
|
||||
|
||||
/** 不引入权限限制:安装前没有 SecurityManager,安装后仍允许原有操作。 */
|
||||
@Override
|
||||
public void checkPermission(Permission permission) {
|
||||
// Observation only.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPermission(Permission permission, Object context) {
|
||||
// Observation only.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkConnect(String host, int port) {
|
||||
record(host, port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkConnect(String host, int port, Object context) {
|
||||
record(host, port);
|
||||
}
|
||||
|
||||
private void record(String host, int port) {
|
||||
if (Boolean.TRUE.equals(recording.get()) || !matches(host)) {
|
||||
return;
|
||||
}
|
||||
recording.set(Boolean.TRUE);
|
||||
try {
|
||||
int sequence = events.incrementAndGet();
|
||||
if (sequence > MAX_EVENTS) {
|
||||
return;
|
||||
}
|
||||
StringBuilder output = new StringBuilder(4096);
|
||||
output.append("[NETWORK-TRACE] BEGIN event=").append(sequence)
|
||||
.append(" timeMillis=").append(System.currentTimeMillis())
|
||||
.append(" threadId=").append(Thread.currentThread().getId())
|
||||
.append(" operation=").append(port == -1 ? "DNS" : "CONNECT")
|
||||
.append(" host=").append(normalizeHost(host)).append(" port=").append(port)
|
||||
.append('\n');
|
||||
// Class 对象来自真实执行栈;不根据类名反射加载其他类,避免触发静态初始化。
|
||||
Class<?>[] context = getClassContext();
|
||||
for (int i = 0; i < context.length && i < MAX_FRAMES; i++) {
|
||||
Class<?> type = context[i];
|
||||
if (type != NetworkRequestTrace.class) {
|
||||
output.append(" origin ").append(safe(type.getName()))
|
||||
.append(" source=").append(sourceOf(type)).append('\n');
|
||||
}
|
||||
}
|
||||
StackTraceElement[] stack = new Throwable().getStackTrace();
|
||||
for (int i = 0; i < stack.length && i < MAX_FRAMES; i++) {
|
||||
// 只打印栈帧元数据,不打印业务异常消息或参数。
|
||||
output.append(" at ").append(safe(stack[i].toString())).append('\n');
|
||||
}
|
||||
if (sequence == MAX_EVENTS) {
|
||||
output.append("[NETWORK-TRACE] LIMIT_REACHED restart-to-capture-more\n");
|
||||
}
|
||||
output.append("[NETWORK-TRACE] END event=").append(sequence);
|
||||
// 一次写入防止并发事件互相穿插。使用 stderr,覆盖日志框架初始化前的调用。
|
||||
System.err.println(output.toString());
|
||||
} catch (RuntimeException | LinkageError ex) {
|
||||
// 来源信息不可用或类加载失败时,仅放弃本次诊断,原网络操作继续。
|
||||
} finally {
|
||||
recording.remove();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matches(String host) {
|
||||
String normalized = normalizeHost(host);
|
||||
if (normalized == null) {
|
||||
return false;
|
||||
}
|
||||
for (String watched : watchedHosts) {
|
||||
if (normalized.equals(watched) || normalized.endsWith("." + watched)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String[] parseHosts(String configured) {
|
||||
List<String> hosts = new ArrayList<String>();
|
||||
for (String value : configured.split(",")) {
|
||||
String normalized = normalizeHost(value.trim());
|
||||
if (normalized != null && hosts.size() < 32) {
|
||||
hosts.add(normalized);
|
||||
}
|
||||
}
|
||||
return hosts.toArray(new String[hosts.size()]);
|
||||
}
|
||||
|
||||
/** 仅接受域名/IP 字符,避免 URL 中的密码、查询参数及日志换行进入诊断输出。 */
|
||||
private static String normalizeHost(String host) {
|
||||
if (host == null || host.isEmpty() || host.length() > 253) {
|
||||
return null;
|
||||
}
|
||||
String normalized = host.toLowerCase(Locale.ROOT);
|
||||
if (normalized.endsWith(".")) {
|
||||
normalized = normalized.substring(0, normalized.length() - 1);
|
||||
}
|
||||
if (normalized.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < normalized.length(); i++) {
|
||||
char value = normalized.charAt(i);
|
||||
if (!(value >= 'a' && value <= 'z') && !(value >= '0' && value <= '9')
|
||||
&& value != '.' && value != '-' && value != ':' && value != '[' && value != ']') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String sourceOf(Class<?> type) {
|
||||
CodeSource source = type.getProtectionDomain().getCodeSource();
|
||||
if (source == null || source.getLocation() == null) {
|
||||
return "[JDK-or-unavailable]";
|
||||
}
|
||||
URL location = source.getLocation();
|
||||
String external = location.toExternalForm();
|
||||
// 不输出远程类加载器地址中的认证信息;普通 JAR、目录和 Spring Boot 嵌套 JAR 可显示。
|
||||
if (!external.startsWith("file:") && !external.startsWith("jar:file:")) {
|
||||
return "[non-file-code-source]";
|
||||
}
|
||||
return safe(external.split("[?#]", 2)[0]);
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
return value == null ? "[unknown]" : value.replace('\r', '_').replace('\n', '_').replace('\t', '_');
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,11 @@ public class Apps extends BaseEntity
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 外部 API 来源 IP 白名单,空值拒绝,支持 IPv4 整段通配符。 */
|
||||
private String ipWhitelist;
|
||||
public String getIpWhitelist() { return ipWhitelist; }
|
||||
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
|
||||
|
||||
/** 主键 */
|
||||
private Long id;
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ public class AppsPlus implements Serializable
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 外部 API 来源 IP 白名单。 */
|
||||
private String ipWhitelist;
|
||||
public String getIpWhitelist() { return ipWhitelist; }
|
||||
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
|
||||
|
||||
/** 主键 */
|
||||
private Long id;
|
||||
/** 用户ID */
|
||||
|
||||
@@ -17,6 +17,11 @@ public class RentApp extends BaseEntity
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 外部 API 来源 IP 白名单,空值拒绝,支持 IPv4 整段通配符。 */
|
||||
private String ipWhitelist;
|
||||
public String getIpWhitelist() { return ipWhitelist; }
|
||||
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
|
||||
|
||||
/** 记录主键 */
|
||||
private Long id;
|
||||
|
||||
|
||||
@@ -20,6 +20,11 @@ public class RentAppPlus implements Serializable
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 外部 API 来源 IP 白名单。 */
|
||||
private String ipWhitelist;
|
||||
public String getIpWhitelist() { return ipWhitelist; }
|
||||
public void setIpWhitelist(String ipWhitelist) { this.ipWhitelist = ipWhitelist; }
|
||||
|
||||
/** 记录主键 */
|
||||
private Long id;
|
||||
/** 所有者sys_user.user_id */
|
||||
|
||||
@@ -88,6 +88,8 @@ public class RentalApiController {
|
||||
request.getHeader("X-Rent-Signature"));
|
||||
Map<String, Object> app = store.get("app", number(credential, "owner_id"), false);
|
||||
require("ACTIVE".equals(text(app, "status")), "应用已禁用");
|
||||
// 与支付应用使用相同策略;商户查询、报价、套餐、下单和地址上链均不可绕过。
|
||||
com.ruoyi.system.security.AppIpWhitelist.requireAllowed(text(app, "ip_whitelist"), request.getRemoteAddr());
|
||||
Map<String, Object> data =
|
||||
json.readValue(body, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
|
||||
@@ -121,7 +121,7 @@ public class RentalController {
|
||||
@PreAuthorize("@ss.hasPermi('rent:portal:view')")
|
||||
public AjaxResult appDetail(@PathVariable long id) {
|
||||
Map<String, Object> app = store.one(
|
||||
"SELECT id,name,status,notify_url,created_at,updated_at FROM rent_app WHERE id=? AND user_id=?",
|
||||
"SELECT id,name,status,notify_url,ip_whitelist,created_at,updated_at FROM rent_app WHERE id=? AND user_id=?",
|
||||
id, user());
|
||||
require(app != null, "应用不存在或无权访问");
|
||||
// DATETIME(3) 约定存服务器本地时间;统一输出毫秒,避免驱动返回 Timestamp/LocalDateTime 的差异。
|
||||
@@ -143,6 +143,24 @@ public class RentalController {
|
||||
return AjaxResult.success(map("app", app, "credentials", credentials));
|
||||
}
|
||||
|
||||
/** 商户只能维护本人应用,白名单不是商户外部API,避免配置错误后无法修复。 */
|
||||
@PostMapping("/app/{id}/ip-whitelist")
|
||||
@PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:app:create') or @ss.hasPermi('rent:app:edit')")
|
||||
public AjaxResult updateAppIpWhitelist(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
require(body.containsKey("ip_whitelist"), "缺少IP白名单配置");
|
||||
provisioning.updateAppIpWhitelist(id, text(body, "ip_whitelist"), user());
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
/** 运营配置入口与商户入口分离,不能通过提交应用ID越权。 */
|
||||
@PostMapping("/manage/app/{id}/ip-whitelist")
|
||||
@PreAuthorize("@ss.hasPermi('rent:manage:audit')")
|
||||
public AjaxResult manageAppIpWhitelist(@PathVariable long id, @RequestBody Map<String, Object> body) {
|
||||
require(body.containsKey("ip_whitelist"), "缺少IP白名单配置");
|
||||
provisioning.updateAppIpWhitelist(id, text(body, "ip_whitelist"), null);
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
/** 仅允许删除本人未产生业务关联的空应用。 */
|
||||
@DeleteMapping("/app/{id}")
|
||||
@PreAuthorize("@ss.hasPermi('rent:portal:register') or @ss.hasPermi('rent:app:remove')")
|
||||
|
||||
@@ -25,6 +25,16 @@ public class RentalProvisioning {
|
||||
this.orders = orders;
|
||||
}
|
||||
|
||||
/** actor=null 仅由已校验运营权限的入口传入;商户入口必须校验持久化归属,不能信任请求 user_id。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void updateAppIpWhitelist(long appId, String whitelist, Long actor) {
|
||||
String normalized = com.ruoyi.system.security.AppIpWhitelist.normalize(whitelist);
|
||||
Map<String, Object> app = store.get("app", appId, true);
|
||||
require(actor == null || number(app, "user_id") == actor, "应用不存在或无权访问");
|
||||
store.update("app", appId, map("ip_whitelist", normalized));
|
||||
store.event("APP", appId, "UPDATE_IP_WHITELIST", actor == null ? 0 : actor, "更新外部API来源IP白名单");
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除未使用的应用。actor 为 null 仅供已有运营权限校验的内部入口使用。
|
||||
* 与下单和凭证签发使用相同父行锁,保证检查与删除之间不会插入新关联。
|
||||
@@ -63,6 +73,7 @@ public class RentalProvisioning {
|
||||
"ACTIVE",
|
||||
"notify_url",
|
||||
url.isEmpty() ? null : url);
|
||||
row.put("ip_whitelist", com.ruoyi.system.security.AppIpWhitelist.normalize(text(request, "ip_whitelist")));
|
||||
} else if ("node".equals(type)) {
|
||||
row =
|
||||
map(
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.ruoyi.system.security;
|
||||
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import java.net.InetAddress;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 商户应用共用的来源 IP 白名单。只解析 IP 字面量,不做 DNS 查询,不接受 URL、主机名或正则。
|
||||
* IPv4 的 * 匹配一个完整地址段;独立 * 显式允许所有来源。空配置和非法配置一律拒绝。
|
||||
*/
|
||||
public final class AppIpWhitelist {
|
||||
public static final int MAX_LENGTH = 2048;
|
||||
|
||||
private AppIpWhitelist() { }
|
||||
|
||||
/** 保存前校验并归一化。多条可使用逗号、分号、空白或换行分隔。 */
|
||||
public static String normalize(String value) {
|
||||
if (value == null || value.trim().isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
if (value.length() > MAX_LENGTH) {
|
||||
throw new CustomException("IP 白名单不能超过2048个字符");
|
||||
}
|
||||
Set<String> rules = new LinkedHashSet<>();
|
||||
for (String rule : value.trim().split("[,;\\s]+")) {
|
||||
if (!validRule(rule)) {
|
||||
throw new CustomException("IP 白名单格式错误:支持IP地址、IPv4整段通配符(如192.168.*.*)或独立*");
|
||||
}
|
||||
rules.add(rule);
|
||||
}
|
||||
return String.join("\n", rules);
|
||||
}
|
||||
|
||||
public static void requireAllowed(String whitelist, String sourceIp) {
|
||||
if (!isAllowed(whitelist, sourceIp)) {
|
||||
throw new CustomException("来源 IP 不在应用白名单中", 403);
|
||||
}
|
||||
}
|
||||
|
||||
/** 运行时也完整校验配置,防止直接改库写入非法规则后意外放行。 */
|
||||
public static boolean isAllowed(String whitelist, String sourceIp) {
|
||||
String normalized;
|
||||
try {
|
||||
normalized = normalize(whitelist);
|
||||
} catch (CustomException exception) {
|
||||
return false;
|
||||
}
|
||||
byte[] source = address(sourceIp);
|
||||
if (normalized.isEmpty() || source == null) {
|
||||
return false;
|
||||
}
|
||||
for (String rule : normalized.split("\n")) {
|
||||
if ("*".equals(rule)) {
|
||||
return true;
|
||||
}
|
||||
if (rule.indexOf('*') >= 0) {
|
||||
if (source.length != 4) {
|
||||
continue;
|
||||
}
|
||||
String[] parts = rule.split("\\.");
|
||||
boolean matches = true;
|
||||
for (int index = 0; index < 4; index++) {
|
||||
if (!"*".equals(parts[index]) && Integer.parseInt(parts[index]) != (source[index] & 255)) {
|
||||
matches = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matches) {
|
||||
return true;
|
||||
}
|
||||
} else if (java.util.Arrays.equals(source, address(rule))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean validRule(String rule) {
|
||||
if ("*".equals(rule)) {
|
||||
return true;
|
||||
}
|
||||
if (rule.indexOf('*') < 0) {
|
||||
return address(rule) != null;
|
||||
}
|
||||
String[] parts = rule.split("\\.", -1);
|
||||
if (parts.length != 4) {
|
||||
return false;
|
||||
}
|
||||
for (String part : parts) {
|
||||
if (!"*".equals(part) && !octet(part)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean octet(String value) {
|
||||
return value.matches("0|[1-9][0-9]{0,2}") && Integer.parseInt(value) <= 255;
|
||||
}
|
||||
|
||||
/** IPv6 先限定字符集并要求冒号,避免 InetAddress 对任意字符串发起域名解析。 */
|
||||
private static byte[] address(String value) {
|
||||
if (value == null || value.length() > 45) {
|
||||
return null;
|
||||
}
|
||||
if (value.indexOf(':') >= 0) {
|
||||
if (!value.matches("[0-9a-fA-F:.]+")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return InetAddress.getByName(value).getAddress();
|
||||
} catch (Exception exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
String[] parts = value.split("\\.", -1);
|
||||
if (parts.length != 4) {
|
||||
return null;
|
||||
}
|
||||
byte[] result = new byte[4];
|
||||
for (int index = 0; index < 4; index++) {
|
||||
if (!octet(parts[index])) {
|
||||
return null;
|
||||
}
|
||||
result[index] = (byte) Integer.parseInt(parts[index]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+109
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,10 @@ public class ApiSecurityService {
|
||||
|| !Objects.equals(credential.getUserId(), app.getUserId())) {
|
||||
throw new CustomException("API 凭证无效");
|
||||
}
|
||||
// 只使用连接对端地址,不信任调用者可伪造的 X-Forwarded-For / X-Real-IP。
|
||||
javax.servlet.http.HttpServletRequest httpRequest = com.ruoyi.common.utils.ServletUtils.getRequest();
|
||||
com.ruoyi.system.security.AppIpWhitelist.requireAllowed(app.getIpWhitelist(),
|
||||
httpRequest == null ? null : httpRequest.getRemoteAddr());
|
||||
|
||||
byte[] aesKey = null;
|
||||
try {
|
||||
|
||||
@@ -395,6 +395,7 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int insertApps(Apps apps, boolean isUser) {
|
||||
validateAppForCreate(apps, isUser);
|
||||
apps.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(apps.getIpWhitelist()));
|
||||
Long ownerUserId = isUser ? SecurityUtils.getUserId() : apps.getUserId();
|
||||
if (ownerUserId == null || appsMapper.lockUserById(ownerUserId) == null) {
|
||||
throw new CustomException("所属用户不存在");
|
||||
@@ -447,6 +448,9 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
|
||||
update.setId(current.getId());
|
||||
update.setName(apps.getName().trim());
|
||||
update.setDescription(apps.getDescription());
|
||||
if (apps.getIpWhitelist() != null) {
|
||||
update.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(apps.getIpWhitelist()));
|
||||
}
|
||||
update.setStatus(apps.getStatus());
|
||||
update.setUpdatedAt(DateUtils.getNowDate());
|
||||
if (!isUser) {
|
||||
|
||||
@@ -215,6 +215,7 @@ public class RentAppServiceImpl extends ServiceImpl<RentAppMapper, RentAppPlus>
|
||||
@Override
|
||||
public int insertRentApp(RentApp rentApp,boolean isUser)
|
||||
{
|
||||
rentApp.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(rentApp.getIpWhitelist()));
|
||||
rentApp.setCreatedAt(DateUtils.getNowDate());
|
||||
rentApp.setUpdatedAt(DateUtils.getNowDate());
|
||||
if(isUser){
|
||||
@@ -232,9 +233,18 @@ public class RentAppServiceImpl extends ServiceImpl<RentAppMapper, RentAppPlus>
|
||||
@Override
|
||||
public int updateRentApp(RentApp rentApp,boolean isUser)
|
||||
{
|
||||
if (rentApp.getIpWhitelist() != null) {
|
||||
rentApp.setIpWhitelist(com.ruoyi.system.security.AppIpWhitelist.normalize(rentApp.getIpWhitelist()));
|
||||
}
|
||||
rentApp.setUpdatedAt(DateUtils.getNowDate());
|
||||
if (isUser) {
|
||||
checkUser(rentApp);
|
||||
// 必须依据数据库归属鉴权,禁止通过请求中的 userId 修改其他商户的安全配置。
|
||||
RentApp persisted = rentAppMapper.selectRentAppById(rentApp.getId());
|
||||
Long actor = SecurityUtils.getUserId();
|
||||
if (persisted == null || actor == null || !actor.equals(persisted.getUserId())) {
|
||||
throw new com.ruoyi.common.exception.CustomException("应用不存在或无权访问", 403);
|
||||
}
|
||||
rentApp.setUserId(persisted.getUserId());
|
||||
}
|
||||
return rentAppMapper.updateRentApp(rentApp);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# Boot 2.2 的默认 YAML loader 依赖 SnakeYAML 1.x 已删除的无参构造器。
|
||||
# 工厂优先级确保配置加载时选择本安全适配器,不需要升级整套 Spring。
|
||||
org.springframework.boot.env.PropertySourceLoader=\
|
||||
com.ruoyi.system.security.SafeYamlPropertySourceLoader
|
||||
@@ -10,6 +10,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</update>
|
||||
|
||||
<resultMap type="Apps" id="AppsResult">
|
||||
<result property="ipWhitelist" column="ip_whitelist" />
|
||||
<result property="id" column="id" />
|
||||
<result property="userId" column="user_id" />
|
||||
<result property="name" column="name" />
|
||||
@@ -33,7 +34,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectAppsVo">
|
||||
select id, user_id, name, description, status, created_at, updated_at, deleted_at, trx_balance, usdt_balance, usdt_frozen_balance, trx_frozen_balance, public_key, private_key, credit_limit, google_sub, google_email, google_name, google_picture, dist_token_address from apps
|
||||
select id, ip_whitelist, user_id, name, description, status, created_at, updated_at, deleted_at, trx_balance, usdt_balance, usdt_frozen_balance, trx_frozen_balance, public_key, private_key, credit_limit, google_sub, google_email, google_name, google_picture, dist_token_address from apps
|
||||
</sql>
|
||||
|
||||
<select id="lockUserById" resultType="Long">
|
||||
@@ -104,6 +105,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<insert id="insertApps" parameterType="Apps" useGeneratedKeys="true" keyProperty="id">
|
||||
insert into apps
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="ipWhitelist != null">ip_whitelist,</if>
|
||||
<if test="userId != null">user_id,</if>
|
||||
<if test="name != null and name != ''">name,</if>
|
||||
<if test="description != null">description,</if>
|
||||
@@ -125,6 +127,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="distTokenAddress != null">dist_token_address,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="ipWhitelist != null">#{ipWhitelist},</if>
|
||||
<if test="userId != null">#{userId},</if>
|
||||
<if test="name != null and name != ''">#{name},</if>
|
||||
<if test="description != null">#{description},</if>
|
||||
@@ -150,6 +153,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<update id="updateApps" parameterType="Apps">
|
||||
update apps
|
||||
<trim prefix="SET" suffixOverrides=",">
|
||||
<if test="ipWhitelist != null">ip_whitelist = #{ipWhitelist},</if>
|
||||
<if test="userId != null">user_id = #{userId},</if>
|
||||
<if test="name != null and name != ''">name = #{name},</if>
|
||||
<if test="description != null">description = #{description},</if>
|
||||
|
||||
@@ -5,6 +5,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<mapper namespace="com.ruoyi.system.mapper.RentAppMapper">
|
||||
|
||||
<resultMap type="RentApp" id="RentAppResult">
|
||||
<result property="ipWhitelist" column="ip_whitelist" />
|
||||
<result property="id" column="id" />
|
||||
<result property="userId" column="user_id" />
|
||||
<result property="name" column="name" />
|
||||
@@ -16,7 +17,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectRentAppVo">
|
||||
select id, user_id, name, status, notify_url, version, created_at, updated_at from rent_app
|
||||
select id, ip_whitelist, user_id, name, status, notify_url, version, created_at, updated_at from rent_app
|
||||
</sql>
|
||||
|
||||
<select id="selectRentAppList" parameterType="RentApp" resultMap="RentAppResult">
|
||||
@@ -34,6 +35,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<insert id="insertRentApp" parameterType="RentApp" useGeneratedKeys="true" keyProperty="id">
|
||||
insert into rent_app
|
||||
<trim prefix="(" suffix=")" suffixOverrides=",">
|
||||
<if test="ipWhitelist != null">ip_whitelist,</if>
|
||||
<if test="userId != null">user_id,</if>
|
||||
<if test="name != null and name != ''">name,</if>
|
||||
<if test="status != null and status != ''">status,</if>
|
||||
@@ -43,6 +45,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="updatedAt != null">updated_at,</if>
|
||||
</trim>
|
||||
<trim prefix="values (" suffix=")" suffixOverrides=",">
|
||||
<if test="ipWhitelist != null">#{ipWhitelist},</if>
|
||||
<if test="userId != null">#{userId},</if>
|
||||
<if test="name != null and name != ''">#{name},</if>
|
||||
<if test="status != null and status != ''">#{status},</if>
|
||||
@@ -56,6 +59,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<update id="updateRentApp" parameterType="RentApp">
|
||||
update rent_app
|
||||
<trim prefix="SET" suffixOverrides=",">
|
||||
<if test="ipWhitelist != null">ip_whitelist = #{ipWhitelist},</if>
|
||||
<if test="userId != null">user_id = #{userId},</if>
|
||||
<if test="name != null and name != ''">name = #{name},</if>
|
||||
<if test="status != null and status != ''">status = #{status},</if>
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.ruoyi.system.diagnostics;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.Permission;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/** 每个场景使用独立 JVM,防止临时 SecurityManager 污染其他支付测试。 */
|
||||
public class NetworkRequestTraceTest {
|
||||
@Test
|
||||
public void disabledByDefault() throws Exception {
|
||||
String output = runProbe("disabled");
|
||||
assertTrue(output.contains("DISABLED_OK"));
|
||||
assertFalse(output.contains("[NETWORK-TRACE]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void existingSecurityPolicyIsNeverReplaced() throws Exception {
|
||||
String output = runProbe("existing");
|
||||
assertTrue(output.contains("NOT_INSTALLED existing-security-manager"));
|
||||
assertTrue(output.contains("EXISTING_OK"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deniedDiagnosticPropertyDoesNotPreventApplicationStartup() throws Exception {
|
||||
String output = runProbe("denied");
|
||||
assertTrue(output, output.contains("NOT_INSTALLED SecurityException"));
|
||||
assertTrue(output, output.contains("DENIED_OK"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void realLocalDnsShowsStackAndDynamicallyLoadedJar() throws Exception {
|
||||
String output = runProbe("enabled");
|
||||
assertTrue(output, output.contains("operation=DNS host=localhost port=-1"));
|
||||
assertTrue(output, output.contains("origin " + JarCaller.class.getName() + " source=file:"));
|
||||
assertTrue(output, output.contains("probe-caller.jar"));
|
||||
assertTrue(output, output.contains("JarCaller.lookup("));
|
||||
assertTrue(output, output.contains("LOOKUP_OK"));
|
||||
assertFalse(output, output.contains("not-localhost.example"));
|
||||
assertFalse(output, output.contains("secret-query-marker"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultFilterMatchesOnlyPinggyDomainBoundaryAndCapsLogs() throws Exception {
|
||||
String output = runProbe("filter");
|
||||
assertTrue(output, output.contains("host=test.pinggy-free.link"));
|
||||
assertFalse(output, output.contains("evilpinggy-free.link"));
|
||||
assertFalse(output, output.contains("pinggy-free.link.example"));
|
||||
assertTrue(output, output.contains("LIMIT_REACHED"));
|
||||
assertFalse(output, output.contains("BEGIN event=201"));
|
||||
assertTrue(output, output.contains("FILTER_OK"));
|
||||
}
|
||||
|
||||
private String runProbe(String mode) throws Exception {
|
||||
String java = Paths.get(System.getProperty("java.home"), "bin", "java").toString();
|
||||
String classpath = System.getProperty("surefire.test.class.path",
|
||||
System.getProperty("java.class.path"));
|
||||
List<String> command = new ArrayList<String>();
|
||||
command.add(java);
|
||||
command.add("-cp");
|
||||
command.add(classpath);
|
||||
command.add(Probe.class.getName());
|
||||
command.add(mode);
|
||||
Path output = Files.createTempFile("network-trace-test-", ".log");
|
||||
try {
|
||||
Process child = new ProcessBuilder(command).redirectErrorStream(true)
|
||||
.redirectOutput(output.toFile()).start();
|
||||
try {
|
||||
assertTrue("诊断子进程超时", child.waitFor(20, TimeUnit.SECONDS));
|
||||
String text = new String(Files.readAllBytes(output), StandardCharsets.UTF_8);
|
||||
assertEquals(text, 0, child.exitValue());
|
||||
return text;
|
||||
} finally {
|
||||
if (child.isAlive()) {
|
||||
child.destroyForcibly().waitFor(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(output);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Probe {
|
||||
public static void main(String[] args) throws Exception {
|
||||
// 无论宿主环境如何配置,先显式关闭,验证安装入口不会受测试机环境污染。
|
||||
System.setProperty("network.trace.enabled", "false");
|
||||
if ("disabled".equals(args[0])) {
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
require(System.getSecurityManager() == null);
|
||||
System.out.println("DISABLED_OK");
|
||||
return;
|
||||
}
|
||||
System.setProperty("network.trace.enabled", "true");
|
||||
if ("denied".equals(args[0])) {
|
||||
SecurityManager original = new SecurityManager() {
|
||||
@Override public void checkPermission(Permission permission) {
|
||||
if ("network.trace.enabled".equals(permission.getName())) {
|
||||
throw new SecurityException("diagnostic-property-denied");
|
||||
}
|
||||
}
|
||||
};
|
||||
System.setSecurityManager(original);
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
require(System.getSecurityManager() == original);
|
||||
System.out.println("DENIED_OK");
|
||||
return;
|
||||
}
|
||||
if ("existing".equals(args[0])) {
|
||||
SecurityManager original = new SecurityManager() {
|
||||
@Override public void checkPermission(Permission permission) { }
|
||||
};
|
||||
System.setSecurityManager(original);
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
require(System.getSecurityManager() == original);
|
||||
System.out.println("EXISTING_OK");
|
||||
return;
|
||||
}
|
||||
if ("filter".equals(args[0])) {
|
||||
System.setProperty("network.trace.hosts", "pinggy-free.link");
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
SecurityManager manager = System.getSecurityManager();
|
||||
// 直接调用钩子验证过滤,不执行这些可疑域名的真实 DNS 查询。
|
||||
manager.checkConnect("evilpinggy-free.link", -1);
|
||||
manager.checkConnect("pinggy-free.link.example", -1);
|
||||
manager.checkConnect("https://test.pinggy-free.link/?secret-query-marker", -1);
|
||||
for (int i = 0; i < 205; i++) {
|
||||
manager.checkConnect("TEST.PINGGY-FREE.LINK.", -1);
|
||||
}
|
||||
System.out.println("FILTER_OK");
|
||||
return;
|
||||
}
|
||||
System.setProperty("network.trace.hosts", "localhost");
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
SecurityManager installed = System.getSecurityManager();
|
||||
require(installed instanceof NetworkRequestTrace);
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
require(System.getSecurityManager() == installed);
|
||||
installed.checkConnect("not-localhost.example", -1);
|
||||
installed.checkConnect("https://localhost/?secret-query-marker", -1);
|
||||
|
||||
// 把调用者放到单独 JAR,并用独立类加载器加载,验证来源来自实际 Class 而非猜测。
|
||||
Path directory = Files.createTempDirectory("network-trace-origin-");
|
||||
Path jar = directory.resolve("probe-caller.jar");
|
||||
String resource = JarCaller.class.getName().replace('.', '/') + ".class";
|
||||
try {
|
||||
try (JarOutputStream stream = new JarOutputStream(Files.newOutputStream(jar));
|
||||
InputStream input = Probe.class.getClassLoader().getResourceAsStream(resource)) {
|
||||
require(input != null);
|
||||
stream.putNextEntry(new JarEntry(resource));
|
||||
byte[] buffer = new byte[4096];
|
||||
int count;
|
||||
while ((count = input.read(buffer)) != -1) {
|
||||
stream.write(buffer, 0, count);
|
||||
}
|
||||
stream.closeEntry();
|
||||
}
|
||||
try (URLClassLoader loader = new URLClassLoader(new URL[] {jar.toUri().toURL()}, null)) {
|
||||
Class<?> caller = loader.loadClass(JarCaller.class.getName());
|
||||
caller.getMethod("lookup").invoke(null);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(jar);
|
||||
Files.deleteIfExists(directory);
|
||||
}
|
||||
System.out.println("LOOKUP_OK");
|
||||
}
|
||||
|
||||
private static void require(boolean condition) {
|
||||
if (!condition) {
|
||||
throw new IllegalStateException("诊断探针断言失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 该类只依赖 JDK,能从独立 JAR 加载;只解析本地回环域名。 */
|
||||
public static class JarCaller {
|
||||
public static void lookup() throws Exception {
|
||||
if (InetAddress.getAllByName("localhost").length == 0) {
|
||||
throw new IllegalStateException("本地域名解析失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.ruoyi.system.security;
|
||||
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/** 不连接网络:验证精确匹配、整段通配、非法配置失败关闭及 IPv6 规范化。 */
|
||||
public class AppIpWhitelistTest {
|
||||
@Test
|
||||
public void emptyAndInvalidConfigurationsDeny() {
|
||||
for (String value : new String[] {null, "", " ", "192.168.*", "*\nexample.com", "999.1.1.1"}) {
|
||||
assertFalse(AppIpWhitelist.isAllowed(value, "192.168.1.2"));
|
||||
}
|
||||
assertFalse(AppIpWhitelist.isAllowed("*", null));
|
||||
assertFalse(AppIpWhitelist.isAllowed("*", "203.0.113.1,127.0.0.1"));
|
||||
assertFalse(AppIpWhitelist.isAllowed("*", "example.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesWholeIpv4OctetsOnly() {
|
||||
assertTrue(AppIpWhitelist.isAllowed("192.168.*.*", "192.168.0.255"));
|
||||
assertFalse(AppIpWhitelist.isAllowed("192.168.*.*", "192.169.0.1"));
|
||||
assertFalse(AppIpWhitelist.isAllowed("203.0.113.1", "203.0.113.10"));
|
||||
assertTrue(AppIpWhitelist.isAllowed("10.*.1.*", "10.255.1.0"));
|
||||
assertTrue(AppIpWhitelist.isAllowed("*", "203.0.113.10"));
|
||||
assertFalse(AppIpWhitelist.isAllowed("192.168.*.*", "2001:db8::1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsMultipleRulesAndIpv6Literals() {
|
||||
assertEquals("203.0.113.1\n192.168.*.*", AppIpWhitelist.normalize("203.0.113.1, 192.168.*.*;203.0.113.1"));
|
||||
assertTrue(AppIpWhitelist.isAllowed("203.0.113.1\n2001:db8::1", "2001:0db8:0:0:0:0:0:1"));
|
||||
assertTrue(AppIpWhitelist.isAllowed("203.0.113.1", "::ffff:203.0.113.1"));
|
||||
assertFalse(AppIpWhitelist.isAllowed("2001:db8::1", "2001:db8::2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsAmbiguousAndUnboundedInputBeforeSave() {
|
||||
for (String value : new String[] {"192.168.1*.*", "1.2.3.256", "01.2.3.4", "1.2.3.4/24", "localhost", "::1%lo", "[::1]"}) {
|
||||
try {
|
||||
AppIpWhitelist.normalize(value);
|
||||
fail("必须拒绝非法规则: " + value);
|
||||
} catch (CustomException expected) { }
|
||||
}
|
||||
try {
|
||||
AppIpWhitelist.normalize(new String(new char[2049]).replace('\0', '*'));
|
||||
fail("必须限制配置长度");
|
||||
} catch (CustomException expected) { }
|
||||
}
|
||||
}
|
||||
+102
@@ -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
|
||||
@@ -0,0 +1,12 @@
|
||||
-- 增量初始化,不修改或删除现有业务表;不插入允许任意来源的默认规则。
|
||||
CREATE TABLE IF NOT EXISTS sys_admin_access_whitelist (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '规则 ID',
|
||||
path_pattern VARCHAR(255) NOT NULL COMMENT 'Ant 接口路径,如 /system/**',
|
||||
ip_pattern VARCHAR(64) NOT NULL COMMENT 'IP 通配规则,如 192.168.*.*',
|
||||
enabled TINYINT NOT NULL DEFAULT 1 COMMENT '1 启用,0 停用',
|
||||
remark VARCHAR(255) DEFAULT NULL COMMENT '备注',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_admin_access_enabled (enabled)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理后台全局接口 IP 访问白名单';
|
||||
@@ -0,0 +1,26 @@
|
||||
-- 将全局接口白名单页面加入系统管理;重复执行不会创建重复菜单。
|
||||
INSERT INTO sys_menu
|
||||
(menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type,
|
||||
visible, status, perms, icon, create_by, create_time, remark)
|
||||
SELECT '接口白名单', menu_id, 8, 'accessWhitelist', 'system/accessWhitelist/index', 1, 0, 'C',
|
||||
'0', '0', 'system:config:list', 'lock', 'admin', NOW(), '管理后台全局接口 IP 访问白名单'
|
||||
FROM sys_menu parent
|
||||
WHERE parent.menu_name = '系统管理' AND parent.menu_type = 'M'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_menu existing
|
||||
WHERE existing.component = 'system/accessWhitelist/index'
|
||||
)
|
||||
LIMIT 1;
|
||||
|
||||
-- 已拥有参数设置查询权限的角色可看到页面;新增、编辑、删除继续沿用该角色已有的 config 权限。
|
||||
INSERT INTO sys_role_menu (role_id, menu_id)
|
||||
SELECT DISTINCT permission.role_id, whitelist.menu_id
|
||||
FROM sys_role_menu permission
|
||||
JOIN sys_menu config_menu ON config_menu.menu_id = permission.menu_id
|
||||
JOIN sys_menu whitelist ON whitelist.component = 'system/accessWhitelist/index'
|
||||
WHERE config_menu.perms = 'system:config:list'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sys_role_menu current_permission
|
||||
WHERE current_permission.role_id = permission.role_id
|
||||
AND current_permission.menu_id = whitelist.menu_id
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
-- 支付及租赁应用共用来源IP白名单。先执行迁移,再部署新代码。
|
||||
-- 可重复执行,兼容已在 rent_init.sql 中创建该列的新库;不修改任何已有业务行。
|
||||
-- 空白名单拒绝外部API访问,请在启用新版前按应用填写实际来源IP。
|
||||
SET @ip_ddl = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='apps' AND COLUMN_NAME='ip_whitelist')=0,
|
||||
'ALTER TABLE apps ADD COLUMN ip_whitelist VARCHAR(2048) NOT NULL DEFAULT '''' COMMENT ''API来源IP白名单;空拒绝,支持IPv4整段通配''', 'SELECT 1');
|
||||
PREPARE ip_stmt FROM @ip_ddl;
|
||||
EXECUTE ip_stmt;
|
||||
DEALLOCATE PREPARE ip_stmt;
|
||||
SET @ip_ddl = IF((SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='rent_app' AND COLUMN_NAME='ip_whitelist')=0,
|
||||
'ALTER TABLE rent_app ADD COLUMN ip_whitelist VARCHAR(2048) NOT NULL DEFAULT '''' COMMENT ''API来源IP白名单;空拒绝,支持IPv4整段通配''', 'SELECT 1');
|
||||
PREPARE ip_stmt FROM @ip_ddl;
|
||||
EXECUTE ip_stmt;
|
||||
DEALLOCATE PREPARE ip_stmt;
|
||||
@@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS `rent_app` (
|
||||
`name` VARCHAR(100) NOT NULL COMMENT '应用名称',
|
||||
`status` VARCHAR(32) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE启用、DISABLED禁用',
|
||||
`notify_url` VARCHAR(512) NULL COMMENT '默认HTTPS回调地址,必须检查SSRF',
|
||||
`ip_whitelist` VARCHAR(2048) NOT NULL DEFAULT '' COMMENT 'API来源IP白名单;空拒绝,*允许全部,IPv4整段通配',
|
||||
`version` BIGINT NOT NULL DEFAULT 0 COMMENT 'CAS乐观锁版本,更新须条件递增;追加记录保持0',
|
||||
`created_at` DATETIME(3) NOT NULL COMMENT '创建服务器本地时间,应用显式写入',
|
||||
`updated_at` DATETIME(3) NOT NULL COMMENT '更新服务器本地时间,追加记录与创建时间相同',
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.ruoyi.executor;
|
||||
|
||||
import com.ruoyi.system.chain.ChainCommandExecutor;
|
||||
import com.ruoyi.system.chain.ChainExecutionStore;
|
||||
import com.ruoyi.system.diagnostics.NetworkRequestTrace;
|
||||
import com.ruoyi.system.mapper.UsdtConfigMapper;
|
||||
import com.ruoyi.system.service.TronChainDataClient;
|
||||
import com.ruoyi.system.service.TronServiceProvider;
|
||||
@@ -40,6 +41,7 @@ public class ChainExecutorApplication {
|
||||
private static final Logger log = LoggerFactory.getLogger(ChainExecutorApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
NetworkRequestTrace.installIfEnabled();
|
||||
// 配置错误只输出固定提示;Spring 启动异常可能包含 JDBC URL 等配置,不打印异常对象。
|
||||
try {
|
||||
log.info("USDT链上执行器正在启动,运行模式=独立内网执行进程");
|
||||
|
||||
Reference in new issue
Block a user