添加提示
This commit is contained in:
1 parent
4c4fd99fc4
commit
1daf477899
10 files changed
+562
No files matched your search
@@ -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', '_');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user