添加提示
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', '_');
|
||||
}
|
||||
}
|
||||
@@ -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("本地域名解析失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user