From 6805588d8a9549533f7439ea89661617990d3f30 Mon Sep 17 00:00:00 2001 From: Sanjai Gopal Date: Thu, 3 Dec 2026 12:36:33 +0530 Subject: [PATCH] feat(jvm-probe): add JVM -javaagent runtime probe for Java, Kotlin, and Scala (#74) --- .gitignore | 4 + docs/JVM_PROBE.md | 60 ++ .../secfoo/conformance/ConformanceApp.java | 62 ++ .../secfoo/conformance/OverheadBenchmark.java | 35 ++ .../secfoo/conformance/RetransformApp.java | 42 ++ .../com/secfoo/conformance/SecondAgent.java | 32 + .../com/secfoo/conformance/Vulnerable.java | 13 + .../logging/log4j/core/lookup/JndiLookup.java | 14 + .../examples/servlet-sample/pom.xml | 50 ++ .../examples/servlet/ServletSampleApp.java | 123 ++++ .../logging/log4j/core/lookup/JndiLookup.java | 13 + .../examples/spring-boot-sample/pom.xml | 36 ++ .../examples/springboot/SpringSampleApp.java | 116 ++++ .../logging/log4j/core/lookup/JndiLookup.java | 13 + jvm/secfoo-agent/pom.xml | 87 +++ .../com/secfoo/probe/InventoryExtractor.java | 287 +++++++++ .../main/java/com/secfoo/probe/MiniJson.java | 315 ++++++++++ .../java/com/secfoo/probe/ProbeConfig.java | 162 +++++ .../java/com/secfoo/probe/ProbeRuntime.java | 552 ++++++++++++++++++ .../java/com/secfoo/probe/RouteContext.java | 207 +++++++ .../java/com/secfoo/probe/RouteHooks.java | 406 +++++++++++++ .../java/com/secfoo/probe/SecfooAgent.java | 47 ++ .../java/com/secfoo/probe/SecfooContext.java | 52 ++ .../com/secfoo/probe/SecfooTransformer.java | 506 ++++++++++++++++ .../main/java/com/secfoo/probe/Transport.java | 511 ++++++++++++++++ .../com/secfoo/probe/WatchlistManager.java | 241 ++++++++ .../java/com/secfoo/probe/ProbeCoreTest.java | 154 +++++ .../secfoo/probe/RouteAndTransformTest.java | 252 ++++++++ tests/test_sensor/test_jvm_probe.py | 307 ++++++++++ 29 files changed, 4699 insertions(+) create mode 100644 docs/JVM_PROBE.md create mode 100644 jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/ConformanceApp.java create mode 100644 jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/OverheadBenchmark.java create mode 100644 jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/RetransformApp.java create mode 100644 jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/SecondAgent.java create mode 100644 jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/Vulnerable.java create mode 100644 jvm/secfoo-agent/examples/conformance-app/src/org/apache/logging/log4j/core/lookup/JndiLookup.java create mode 100644 jvm/secfoo-agent/examples/servlet-sample/pom.xml create mode 100644 jvm/secfoo-agent/examples/servlet-sample/src/main/java/com/secfoo/examples/servlet/ServletSampleApp.java create mode 100644 jvm/secfoo-agent/examples/servlet-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java create mode 100644 jvm/secfoo-agent/examples/spring-boot-sample/pom.xml create mode 100644 jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/com/secfoo/examples/springboot/SpringSampleApp.java create mode 100644 jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java create mode 100644 jvm/secfoo-agent/pom.xml create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/InventoryExtractor.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/MiniJson.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeConfig.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeRuntime.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteContext.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteHooks.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooAgent.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooContext.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooTransformer.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/Transport.java create mode 100644 jvm/secfoo-agent/src/main/java/com/secfoo/probe/WatchlistManager.java create mode 100644 jvm/secfoo-agent/src/test/java/com/secfoo/probe/ProbeCoreTest.java create mode 100644 jvm/secfoo-agent/src/test/java/com/secfoo/probe/RouteAndTransformTest.java create mode 100644 tests/test_sensor/test_jvm_probe.py diff --git a/.gitignore b/.gitignore index a0ee705..500de06 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,7 @@ node_modules/ # uv writes a lockfile when you `uv run` inside the checkout; the project # does not pin dependencies that way. uv.lock + +# JVM probe Maven build artifacts +jvm/**/target/ +jvm/**/*.jar diff --git a/docs/JVM_PROBE.md b/docs/JVM_PROBE.md new file mode 100644 index 0000000..666b1f1 --- /dev/null +++ b/docs/JVM_PROBE.md @@ -0,0 +1,60 @@ +# JVM Runtime Probe (`-javaagent`) + +The JVM probe (`jvm/secfoo-agent`) instruments Java, Kotlin, and Scala +applications running on Java 8+ (including Java 21 virtual threads) using +`java.lang.instrument` and shaded ASM (`com.secfoo.probe.shaded.asm`), without +requiring application code changes. + +## Usage + +```sh +JAVA_TOOL_OPTIONS="-javaagent:/opt/secfoo/probe/jvm/secfoo-agent.jar" java -jar app.jar +``` + +By default the agent is completely inert unless `SECFOO_SENSOR=1` is set +(Rule 0): no class transformer, background thread, file, or socket is created. + +## Building + +```sh +cd jvm/secfoo-agent +mvn -B test package +``` + +This builds `jvm/secfoo-agent/target/secfoo-agent.jar` with ASM relocated under +`com.secfoo.probe.shaded.asm` so it does not conflict with application or APM +agent dependencies. + +## Capabilities + +- **Watched method hits (`#52` / `#53`):** Matches Maven watchlist symbols + (`pkg.Class#method`, inner classes `$`, constructors ``, Kotlin `*Kt`, + Scala `$`) and injects a lock-free entry counter (`LongAdder`) plus a + first-hit trimmed `file:line` stack sample. Watchlist updates reload via + `Instrumentation.retransformClasses`. +- **Package inventory (`#68`):** Extracts Maven coordinates from + `META-INF/maven/**/pom.properties` across standard JARs, Spring Boot fat JARs + (`BOOT-INF/lib/*.jar`, including `nested:` URLs), and WAR archives + (`WEB-INF/lib/*.jar`), marking relocated/uber-jar packages as `shaded`. +- **Route & auth attribution (`#69`):** Reflectively hooks `javax.servlet` and + `jakarta.servlet` `HttpServlet.service`, Spring MVC + `HandlerMapping.bestMatchingPattern`, Spring WebFlux `DispatcherHandler` / + `InvocableHandlerMethod`, and JAX-RS `@Path` endpoints. Context is held per + thread in `ThreadLocal` (compatible with platform threads and Java 21 virtual + threads). Argument values, query strings, request bodies, and credentials are + never read or sent. +- **Agent coexistence:** Uses resource-based bytecode class hierarchy resolution + in `SafeClassWriter` instead of `Class.forName`, avoiding eager class loading + and initialization order changes alongside other `-javaagent` tools. + +## Conformance & Overhead + +Verified against the `#73` conformance kit (`secfoo sensor conformance`) on +pure-JDK, embedded Jetty Jakarta Servlet (`examples/servlet-sample`), and +Spring Boot 3 (`examples/spring-boot-sample`) applications: + +| Target | Checks | Marginal call overhead | Startup/exit delta | +|---|---:|---:|---:| +| Pure JDK conformance app | 6/6 pass | 0.49 µs/call (budget 50 µs) | 0.25 s (budget 5 s) | +| Jetty Servlet sample | 6/6 pass | 0.36 µs/call | 0.39 s | +| Spring Boot 3 sample | 6/6 pass | 0.32 µs/call | 0.19 s | diff --git a/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/ConformanceApp.java b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/ConformanceApp.java new file mode 100644 index 0000000..e964804 --- /dev/null +++ b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/ConformanceApp.java @@ -0,0 +1,62 @@ +package com.secfoo.conformance; + +import com.secfoo.probe.SecfooContext; +import org.apache.logging.log4j.core.lookup.JndiLookup; + +/** + * Pure-JDK sample app implementing the #73 conformance contract. + */ +public final class ConformanceApp { + private ConformanceApp() {} + + public static volatile int sink; + + public static void main(String[] args) throws Exception { + String step = System.getenv("SECFOO_CONFORMANCE_STEP"); + if (step == null || step.isEmpty()) { + step = "call"; + } + final String sentinel = System.getenv("SECFOO_CONFORMANCE_SENTINEL"); + final String secret = sentinel != null ? sentinel : ""; + final JndiLookup jndi = new JndiLookup(); + + if ("call".equals(step)) { + for (int i = 0; i < 3; i++) { + sink += Vulnerable.parse("payload").length(); + } + } else if ("nocall".equals(step)) { + for (int i = 0; i < 3; i++) { + sink += Vulnerable.safe("payload").length(); + } + } else if ("request".equals(step)) { + final String concretePath = "/users/8675309?token=" + secret; + final String authHeader = "Bearer " + secret; + SecfooContext.runWithRoute("GET", "/users/{id}", "authenticated", new Runnable() { + @Override + public void run() { + sink += Vulnerable.parse(concretePath + authHeader).length(); + sink += jndi.lookup("${jndi:ldap://127.0.0.1/" + secret + "}").length(); + } + }); + } else if ("slow".equals(step)) { + long deadline = System.nanoTime() + 1_500_000_000L; + while (System.nanoTime() < deadline) { + sink += Vulnerable.parse("payload").length(); + Thread.sleep(50L); + } + } else if ("loop".equals(step)) { + String nRaw = System.getenv("SECFOO_CONFORMANCE_N"); + int n = (nRaw != null && !nRaw.isEmpty()) ? Integer.parseInt(nRaw) : 100000; + int acc = 0; + for (int i = 0; i < n; i++) { + acc += Vulnerable.parse("payload").length(); + } + sink = acc; + } else { + System.err.println("unknown step: " + step); + System.exit(2); + return; + } + System.out.println("conformance step " + step + " ok"); + } +} diff --git a/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/OverheadBenchmark.java b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/OverheadBenchmark.java new file mode 100644 index 0000000..82ab185 --- /dev/null +++ b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/OverheadBenchmark.java @@ -0,0 +1,35 @@ +package com.secfoo.conformance; + +/** + * Standalone overhead microbenchmark measuring per-call latency of a watched JVM method. + */ +public final class OverheadBenchmark { + public static volatile int sink = 0; + + private OverheadBenchmark() {} + + public static void main(String[] args) { + int warmup = 50_000; + int small = 200_000; + int large = 1_000_000; + + for (int i = 0; i < warmup; i++) { + sink += Vulnerable.parse("payload").length(); + } + + long t0 = System.nanoTime(); + for (int i = 0; i < small; i++) { + sink += Vulnerable.parse("payload").length(); + } + long t1 = System.nanoTime(); + + long t2 = System.nanoTime(); + for (int i = 0; i < large; i++) { + sink += Vulnerable.parse("payload").length(); + } + long t3 = System.nanoTime(); + + double marginalNs = (double) ((t3 - t2) - (t1 - t0)) / (large - small); + System.out.printf("marginal_us=%.4f%n", marginalNs / 1000.0); + } +} diff --git a/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/RetransformApp.java b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/RetransformApp.java new file mode 100644 index 0000000..de2c9c6 --- /dev/null +++ b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/RetransformApp.java @@ -0,0 +1,42 @@ +package com.secfoo.conformance; + +import org.apache.logging.log4j.core.lookup.JndiLookup; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Verifies Instrumentation.retransformClasses when SECFOO_WATCHLIST updates after + * the watched class has already been loaded (#74). + */ +public final class RetransformApp { + private RetransformApp() {} + + public static void main(String[] args) throws Exception { + // Load JndiLookup BEFORE it appears in the watchlist. + JndiLookup jndi = new JndiLookup(); + jndi.lookup("before-reload"); + + String wlPathStr = System.getenv("SECFOO_WATCHLIST"); + if (wlPathStr == null || wlPathStr.isEmpty()) { + throw new IllegalStateException("SECFOO_WATCHLIST must be set"); + } + Path wlPath = Paths.get(wlPathStr); + String updated = "{\"version\":1,\"generated_at\":\"2026-12-03T00:00:00Z\",\"entries\":[{" + + "\"finding_fingerprint\":\"fp-retransform\",\"ecosystem\":\"Maven\"," + + "\"package\":\"org.apache.logging.log4j:log4j-core\",\"version\":\"2.14.1\"," + + "\"granularity\":\"symbol\",\"symbols\":[\"org.apache.logging.log4j.core.lookup.JndiLookup#lookup\"]" + + "}]}"; + Thread.sleep(50L); + Files.write(wlPath, updated.getBytes(StandardCharsets.UTF_8)); + + // Wait for the background flusher to reload the watchlist and retransform JndiLookup. + Thread.sleep(500L); + + jndi.lookup("after-reload-1"); + jndi.lookup("after-reload-2"); + System.out.println("retransform ok"); + } +} diff --git a/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/SecondAgent.java b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/SecondAgent.java new file mode 100644 index 0000000..afceefa --- /dev/null +++ b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/SecondAgent.java @@ -0,0 +1,32 @@ +package com.secfoo.conformance; + +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.Instrumentation; +import java.security.ProtectionDomain; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Minimal second -javaagent used in tests to prove coexistence with other agents (#74). + */ +public final class SecondAgent { + public static final AtomicInteger TRANSFORMED_COUNT = new AtomicInteger(0); + + private SecondAgent() {} + + public static void premain(String args, Instrumentation inst) { + inst.addTransformer(new ClassFileTransformer() { + @Override + public byte[] transform( + ClassLoader loader, + String className, + Class classBeingRedefined, + ProtectionDomain protectionDomain, + byte[] classfileBuffer) { + if (className != null && className.startsWith("com/secfoo/conformance/")) { + TRANSFORMED_COUNT.incrementAndGet(); + } + return null; + } + }); + } +} diff --git a/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/Vulnerable.java b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/Vulnerable.java new file mode 100644 index 0000000..633e226 --- /dev/null +++ b/jvm/secfoo-agent/examples/conformance-app/src/com/secfoo/conformance/Vulnerable.java @@ -0,0 +1,13 @@ +package com.secfoo.conformance; + +public final class Vulnerable { + private Vulnerable() {} + + public static String parse(String text) { + return text == null ? "" : text.toUpperCase(); + } + + public static String safe(String text) { + return text == null ? "" : text; + } +} diff --git a/jvm/secfoo-agent/examples/conformance-app/src/org/apache/logging/log4j/core/lookup/JndiLookup.java b/jvm/secfoo-agent/examples/conformance-app/src/org/apache/logging/log4j/core/lookup/JndiLookup.java new file mode 100644 index 0000000..30f81b6 --- /dev/null +++ b/jvm/secfoo-agent/examples/conformance-app/src/org/apache/logging/log4j/core/lookup/JndiLookup.java @@ -0,0 +1,14 @@ +package org.apache.logging.log4j.core.lookup; + +/** + * Sample vulnerable lookup class matching #52 Maven notation: + * org.apache.logging.log4j.core.lookup.JndiLookup#lookup + */ +public class JndiLookup { + public String lookup(String key) { + if (key == null) { + return ""; + } + return "resolved:" + key.length(); + } +} diff --git a/jvm/secfoo-agent/examples/servlet-sample/pom.xml b/jvm/secfoo-agent/examples/servlet-sample/pom.xml new file mode 100644 index 0000000..21639fc --- /dev/null +++ b/jvm/secfoo-agent/examples/servlet-sample/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + com.secfoo.examples + servlet-sample + 0.1.0 + + + UTF-8 + 11 + 11 + 11.0.24 + + + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + servlet-sample + false + + + com.secfoo.examples.servlet.ServletSampleApp + + + + + + + + + diff --git a/jvm/secfoo-agent/examples/servlet-sample/src/main/java/com/secfoo/examples/servlet/ServletSampleApp.java b/jvm/secfoo-agent/examples/servlet-sample/src/main/java/com/secfoo/examples/servlet/ServletSampleApp.java new file mode 100644 index 0000000..358c69a --- /dev/null +++ b/jvm/secfoo-agent/examples/servlet-sample/src/main/java/com/secfoo/examples/servlet/ServletSampleApp.java @@ -0,0 +1,123 @@ +package com.secfoo.examples.servlet; + +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.logging.log4j.core.lookup.JndiLookup; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * Plain Servlet sample app (embedded Jetty + Jakarta Servlet) implementing the #73 + * conformance contract and Log4Shell-style route attribution (#74). + */ +public final class ServletSampleApp { + public static volatile int sink = 0; + + private ServletSampleApp() {} + + public static final class LookupServlet extends HttpServlet { + private final transient JndiLookup jndi = new JndiLookup(); + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + req.setAttribute("secfoo.route", "/users/{id}"); + String auth = req.getHeader("Authorization"); + String token = req.getParameter("token"); + String result = jndi.lookup(String.valueOf(token) + ":" + String.valueOf(auth)); + sink += result.length(); + resp.setStatus(HttpServletResponse.SC_OK); + resp.getWriter().write("ok"); + } + } + + public static final class SafeServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + sink += 1; + resp.setStatus(HttpServletResponse.SC_OK); + resp.getWriter().write("safe"); + } + } + + public static void main(String[] args) throws Exception { + String step = System.getenv("SECFOO_CONFORMANCE_STEP"); + if (step == null || step.isEmpty()) { + step = "call"; + } + String sentinel = System.getenv("SECFOO_CONFORMANCE_SENTINEL"); + String secret = sentinel != null ? sentinel : ""; + JndiLookup jndi = new JndiLookup(); + + if ("call".equals(step)) { + for (int i = 0; i < 3; i++) { + sink += jndi.lookup("payload").length(); + } + } else if ("nocall".equals(step)) { + Server server = startServer(); + try { + int port = ((ServerConnector) server.getConnectors()[0]).getLocalPort(); + httpGet("http://127.0.0.1:" + port + "/safe", null); + } finally { + server.stop(); + } + } else if ("request".equals(step)) { + Server server = startServer(); + try { + int port = ((ServerConnector) server.getConnectors()[0]).getLocalPort(); + httpGet("http://127.0.0.1:" + port + "/users/8675309?token=" + secret, "Bearer " + secret); + } finally { + server.stop(); + } + } else if ("slow".equals(step)) { + long deadline = System.nanoTime() + 1_500_000_000L; + while (System.nanoTime() < deadline) { + sink += jndi.lookup("payload").length(); + Thread.sleep(50L); + } + } else if ("loop".equals(step)) { + String nRaw = System.getenv("SECFOO_CONFORMANCE_N"); + int n = (nRaw != null && !nRaw.isEmpty()) ? Integer.parseInt(nRaw) : 100000; + int acc = 0; + for (int i = 0; i < n; i++) { + acc += jndi.lookup("payload").length(); + } + sink = acc; + } else { + System.err.println("unknown step: " + step); + System.exit(2); + return; + } + System.out.println("conformance step " + step + " ok"); + } + + private static Server startServer() throws Exception { + Server server = new Server(0); + ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); + ctx.setContextPath("/"); + ctx.addServlet(new ServletHolder(new LookupServlet()), "/users/*"); + ctx.addServlet(new ServletHolder(new SafeServlet()), "/safe"); + server.setHandler(ctx); + server.start(); + return server; + } + + private static void httpGet(String urlStr, String authHeader) throws IOException { + HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection(); + conn.setRequestMethod("GET"); + if (authHeader != null) { + conn.setRequestProperty("Authorization", authHeader); + } + int code = conn.getResponseCode(); + conn.disconnect(); + if (code != 200) { + throw new IOException("Unexpected HTTP status " + code); + } + } +} diff --git a/jvm/secfoo-agent/examples/servlet-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java b/jvm/secfoo-agent/examples/servlet-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java new file mode 100644 index 0000000..1e19856 --- /dev/null +++ b/jvm/secfoo-agent/examples/servlet-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java @@ -0,0 +1,13 @@ +package org.apache.logging.log4j.core.lookup; + +/** + * Sample Log4Shell-style vulnerable class for Servlet and Spring Boot conformance checks (#74). + */ +public class JndiLookup { + public String lookup(String key) { + if (key == null) { + return ""; + } + return "jndi:" + key.length(); + } +} diff --git a/jvm/secfoo-agent/examples/spring-boot-sample/pom.xml b/jvm/secfoo-agent/examples/spring-boot-sample/pom.xml new file mode 100644 index 0000000..268821f --- /dev/null +++ b/jvm/secfoo-agent/examples/spring-boot-sample/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.1 + + + + com.secfoo.examples + spring-boot-sample + 0.1.0 + + + 17 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + spring-boot-sample + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/com/secfoo/examples/springboot/SpringSampleApp.java b/jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/com/secfoo/examples/springboot/SpringSampleApp.java new file mode 100644 index 0000000..78bbfec --- /dev/null +++ b/jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/com/secfoo/examples/springboot/SpringSampleApp.java @@ -0,0 +1,116 @@ +package com.secfoo.examples.springboot; + +import org.apache.logging.log4j.core.lookup.JndiLookup; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +/** + * Spring Boot sample app verifying Spring MVC BEST_MATCHING_PATTERN_ATTRIBUTE + * route attribution, BOOT-INF/lib inventory extraction, and #73 conformance (#74). + */ +@SpringBootApplication +@RestController +public class SpringSampleApp { + public static volatile int sink = 0; + private final JndiLookup jndi = new JndiLookup(); + + @GetMapping("/users/{id}") + public String getUser( + @PathVariable("id") String id, + @RequestParam(value = "token", required = false, defaultValue = "") String token, + @RequestHeader(value = "Authorization", required = false, defaultValue = "") String auth) { + String out = jndi.lookup(id + ":" + token + ":" + auth); + sink += out.length(); + return "ok"; + } + + @GetMapping("/safe") + public String safe() { + sink += 1; + return "safe"; + } + + public static void main(String[] args) throws Exception { + String step = System.getenv("SECFOO_CONFORMANCE_STEP"); + if (step == null || step.isEmpty()) { + step = "call"; + } + String sentinel = System.getenv("SECFOO_CONFORMANCE_SENTINEL"); + String secret = sentinel != null ? sentinel : ""; + + if ("loop".equals(step)) { + JndiLookup direct = new JndiLookup(); + String nRaw = System.getenv("SECFOO_CONFORMANCE_N"); + int n = (nRaw != null && !nRaw.isEmpty()) ? Integer.parseInt(nRaw) : 100000; + int acc = 0; + for (int i = 0; i < n; i++) { + acc += direct.lookup("payload").length(); + } + sink = acc; + System.out.println("conformance step " + step + " ok"); + return; + } + + SpringApplication app = new SpringApplication(SpringSampleApp.class); + Map props = new HashMap(); + props.put("server.port", "0"); + props.put("logging.level.root", "WARN"); + props.put("spring.main.banner-mode", "off"); + app.setDefaultProperties(props); + + ConfigurableApplicationContext ctx = app.run(args); + try { + int port = ((ServletWebServerApplicationContext) ctx).getWebServer().getPort(); + JndiLookup direct = new JndiLookup(); + + if ("call".equals(step)) { + for (int i = 0; i < 3; i++) { + sink += direct.lookup("payload").length(); + } + } else if ("nocall".equals(step)) { + httpGet("http://127.0.0.1:" + port + "/safe", null); + } else if ("request".equals(step)) { + httpGet("http://127.0.0.1:" + port + "/users/8675309?token=" + secret, "Bearer " + secret); + } else if ("slow".equals(step)) { + long deadline = System.nanoTime() + 1_500_000_000L; + while (System.nanoTime() < deadline) { + sink += direct.lookup("payload").length(); + Thread.sleep(50L); + } + } else { + System.err.println("unknown step: " + step); + System.exit(2); + return; + } + System.out.println("conformance step " + step + " ok"); + } finally { + SpringApplication.exit(ctx, () -> 0); + } + } + + private static void httpGet(String urlStr, String authHeader) throws IOException { + HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection(); + conn.setRequestMethod("GET"); + if (authHeader != null) { + conn.setRequestProperty("Authorization", authHeader); + } + int code = conn.getResponseCode(); + conn.disconnect(); + if (code != 200) { + throw new IOException("Unexpected HTTP status " + code); + } + } +} diff --git a/jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java b/jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java new file mode 100644 index 0000000..b4554b5 --- /dev/null +++ b/jvm/secfoo-agent/examples/spring-boot-sample/src/main/java/org/apache/logging/log4j/core/lookup/JndiLookup.java @@ -0,0 +1,13 @@ +package org.apache.logging.log4j.core.lookup; + +/** + * Sample Log4Shell-style vulnerable class for Spring Boot conformance checks (#74). + */ +public class JndiLookup { + public String lookup(String key) { + if (key == null) { + return ""; + } + return "jndi:" + key.length(); + } +} diff --git a/jvm/secfoo-agent/pom.xml b/jvm/secfoo-agent/pom.xml new file mode 100644 index 0000000..d013903 --- /dev/null +++ b/jvm/secfoo-agent/pom.xml @@ -0,0 +1,87 @@ + + 4.0.0 + + com.secfoo + secfoo-agent + 0.1.0 + jar + + secfoo-agent + In-process JVM runtime probe (-javaagent) for Secfoo runtime reachability (#74). + + + UTF-8 + 8 + 8 + 9.7 + 5.11.3 + + + + + org.ow2.asm + asm + ${asm.version} + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + + + secfoo-agent + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + true + false + + + org.ow2.asm:asm + + module-info.class + + + + + + org.objectweb.asm + com.secfoo.probe.shaded.asm + + + + + + com.secfoo.probe.SecfooAgent + com.secfoo.probe.SecfooAgent + true + true + + + + + + + + + + diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/InventoryExtractor.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/InventoryExtractor.java new file mode 100644 index 0000000..68eea33 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/InventoryExtractor.java @@ -0,0 +1,287 @@ +package com.secfoo.probe; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.security.CodeSource; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * Extracts Maven package coordinates (#68) from loaded CodeSource locations. + * Supports standard JARs, Spring Boot fat JARs (BOOT-INF/lib, including Spring Boot 3.2+ + * nested: URLs), WAR archives (WEB-INF/lib), and shaded/relocated package detection. + */ +public final class InventoryExtractor { + private static final Pattern JAR_NAME_VERSION = + Pattern.compile("^([A-Za-z0-9._-]+?)-([0-9][A-Za-z0-9._-]*)\\.jar$"); + private static final String[] SHADED_MARKERS = { + ".shaded.", ".shadow.", ".repackaged.", ".relocated." + }; + + private final ConcurrentHashMap seenLocations = new ConcurrentHashMap(); + + public static final class PackageInfo { + public final String ecosystem = "Maven"; + public final String packageName; + public final String version; + public final String path; + public final boolean shaded; + + public PackageInfo(String packageName, String version, String path, boolean shaded) { + this.packageName = packageName; + this.version = version; + this.path = path; + this.shaded = shaded; + } + } + + public List inspectProtectionDomain(ProtectionDomain pd, String classInternalName) { + if (pd == null) { + return Collections.emptyList(); + } + CodeSource cs = pd.getCodeSource(); + if (cs == null || cs.getLocation() == null) { + return Collections.emptyList(); + } + URL location = cs.getLocation(); + String key = location.toString(); + if (seenLocations.putIfAbsent(key, Boolean.TRUE) != null) { + return Collections.emptyList(); + } + return inspectLocation(location, classInternalName); + } + + public static List inspectLocation(URL location, String classInternalName) { + if (location == null) { + return Collections.emptyList(); + } + String raw = location.toString(); + try { + if ("file".equalsIgnoreCase(location.getProtocol())) { + File file = new File(location.toURI()); + if (file.isFile() && file.getName().endsWith(".jar")) { + return inspectJarFile(file, raw, classInternalName); + } + return Collections.emptyList(); + } + if ("jar".equalsIgnoreCase(location.getProtocol())) { + // jar:file:/app/app.jar!/BOOT-INF/lib/foo-1.0.jar!/ + String inner = raw.substring("jar:".length()); + int firstBang = inner.indexOf("!/"); + if (firstBang > 0) { + String outerUrl = inner.substring(0, firstBang); + String nestedEntry = inner.substring(firstBang + 2); + if (nestedEntry.endsWith("!/")) { + nestedEntry = nestedEntry.substring(0, nestedEntry.length() - 2); + } + File outerFile = fileFromFileUrl(outerUrl); + if (outerFile != null && outerFile.isFile()) { + if (nestedEntry.isEmpty() || !nestedEntry.endsWith(".jar")) { + return inspectJarFile(outerFile, raw, classInternalName); + } + return inspectNestedJar(outerFile, nestedEntry, raw, classInternalName); + } + } + } + if ("nested".equalsIgnoreCase(location.getProtocol())) { + // Spring Boot 3.2+: nested:/app/app.jar/!BOOT-INF/lib/foo-1.0.jar + String rest = raw.substring("nested:".length()); + int sep = rest.indexOf("/!"); + if (sep > 0) { + String outerPath = rest.substring(0, sep); + String nestedEntry = rest.substring(sep + 2); + if (nestedEntry.endsWith("/!")) { + nestedEntry = nestedEntry.substring(0, nestedEntry.length() - 2); + } + File outerFile = new File(URI.create("file:" + (outerPath.startsWith("/") ? "" : "/") + outerPath)); + if (outerFile.isFile() && nestedEntry.endsWith(".jar")) { + return inspectNestedJar(outerFile, nestedEntry, raw, classInternalName); + } + } + } + } catch (Throwable ignored) { + // fail-open: never disrupt class loading + } + return Collections.emptyList(); + } + + static List inspectJarFile(File jarFile, String locationPath, String classInternalName) throws IOException { + List poms = new ArrayList(); + Manifest manifest = null; + JarFile jf = new JarFile(jarFile); + try { + Enumeration entries = jf.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String name = entry.getName(); + if (!entry.isDirectory() && name.startsWith("META-INF/maven/") && name.endsWith("/pom.properties")) { + InputStream is = jf.getInputStream(entry); + try { + Properties props = new Properties(); + props.load(is); + if (props.getProperty("groupId") != null && props.getProperty("artifactId") != null) { + poms.add(props); + } + } finally { + is.close(); + } + } + } + manifest = jf.getManifest(); + } finally { + jf.close(); + } + return buildPackages(poms, manifest, jarFile.getName(), locationPath, classInternalName); + } + + static List inspectNestedJar( + File outerFile, String nestedEntry, String locationPath, String classInternalName) throws IOException { + List poms = new ArrayList(); + Manifest manifest = null; + ZipFile zf = new ZipFile(outerFile); + try { + ZipEntry entry = zf.getEntry(nestedEntry); + if (entry == null) { + return Collections.emptyList(); + } + InputStream rawStream = zf.getInputStream(entry); + JarInputStream jis = new JarInputStream(rawStream); + try { + manifest = jis.getManifest(); + JarEntry inner; + while ((inner = jis.getNextJarEntry()) != null) { + String name = inner.getName(); + if (!inner.isDirectory() && name.startsWith("META-INF/maven/") && name.endsWith("/pom.properties")) { + Properties props = new Properties(); + props.load(jis); + if (props.getProperty("groupId") != null && props.getProperty("artifactId") != null) { + poms.add(props); + } + } + jis.closeEntry(); + } + } finally { + jis.close(); + } + } finally { + zf.close(); + } + String fileName = nestedEntry.contains("/") ? nestedEntry.substring(nestedEntry.lastIndexOf('/') + 1) : nestedEntry; + return buildPackages(poms, manifest, fileName, locationPath, classInternalName); + } + + private static List buildPackages( + List poms, + Manifest manifest, + String jarFileName, + String locationPath, + String classInternalName) { + List out = new ArrayList(); + String classDotName = classInternalName == null ? "" : classInternalName.replace('/', '.'); + boolean relocatedClass = isRelocatedPackage(classDotName); + boolean multiPom = poms.size() > 1; + + if (!poms.isEmpty()) { + for (Properties props : poms) { + String groupId = props.getProperty("groupId", "").trim(); + String artifactId = props.getProperty("artifactId", "").trim(); + String version = props.getProperty("version", "").trim(); + if (groupId.isEmpty() || artifactId.isEmpty() || version.isEmpty()) { + continue; + } + boolean shaded = relocatedClass || (multiPom && !matchesGroupPrefix(classDotName, groupId)); + String coord = groupId + ":" + artifactId; + String displayPath = shaded ? locationPath + " [shaded]" : locationPath; + out.add(new PackageInfo(coord, version, displayPath, shaded)); + } + if (!out.isEmpty()) { + return out; + } + } + + if (manifest != null) { + Attributes attrs = manifest.getMainAttributes(); + String symbolic = trimOrNull(attrs.getValue("Bundle-SymbolicName")); + if (symbolic != null && symbolic.contains(";")) { + symbolic = symbolic.substring(0, symbolic.indexOf(';')).trim(); + } + String title = firstNonEmpty(symbolic, attrs.getValue("Implementation-Title")); + String version = firstNonEmpty(attrs.getValue("Bundle-Version"), attrs.getValue("Implementation-Version")); + if (title != null && version != null) { + String displayPath = relocatedClass ? locationPath + " [shaded]" : locationPath; + out.add(new PackageInfo(title, version, displayPath, relocatedClass)); + return out; + } + } + + Matcher m = JAR_NAME_VERSION.matcher(jarFileName); + if (m.matches()) { + String displayPath = relocatedClass ? locationPath + " [shaded]" : locationPath; + out.add(new PackageInfo(m.group(1), m.group(2), displayPath, relocatedClass)); + } + return out; + } + + static boolean isRelocatedPackage(String classDotName) { + if (classDotName == null || classDotName.isEmpty()) { + return false; + } + String low = classDotName.toLowerCase(Locale.ROOT); + for (String marker : SHADED_MARKERS) { + if (low.contains(marker)) { + return true; + } + } + return false; + } + + private static boolean matchesGroupPrefix(String classDotName, String groupId) { + if (classDotName == null || classDotName.isEmpty() || groupId == null || groupId.isEmpty()) { + return true; + } + String normalizedGroup = groupId.replace('-', '.'); + return classDotName.startsWith(normalizedGroup + ".") || classDotName.startsWith(groupId + "."); + } + + private static File fileFromFileUrl(String url) { + try { + if (url.startsWith("file:")) { + return new File(URI.create(url)); + } + } catch (Exception ignored) { + // fall through + } + return null; + } + + private static String firstNonEmpty(String a, String b) { + String va = trimOrNull(a); + return va != null ? va : trimOrNull(b); + } + + private static String trimOrNull(String value) { + if (value == null) { + return null; + } + String t = value.trim(); + return t.isEmpty() ? null : t; + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/MiniJson.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/MiniJson.java new file mode 100644 index 0000000..7de31e2 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/MiniJson.java @@ -0,0 +1,315 @@ +package com.secfoo.probe; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Minimal zero-dependency JSON parser and serializer for #52 watchlists and #73 protocol lines. + */ +public final class MiniJson { + private final String src; + private int pos; + + private MiniJson(String src) { + this.src = src; + } + + public static Object parse(String json) { + if (json == null) { + throw new IllegalArgumentException("null json"); + } + if (!json.isEmpty() && json.charAt(0) == '\uFEFF') { + json = json.substring(1); + } + MiniJson parser = new MiniJson(json); + Object value = parser.readValue(); + parser.skipWhitespace(); + if (parser.pos != parser.src.length()) { + throw new IllegalArgumentException("trailing characters at offset " + parser.pos); + } + return value; + } + + @SuppressWarnings("unchecked") + public static Map parseObject(String json) { + Object val = parse(json); + if (!(val instanceof Map)) { + throw new IllegalArgumentException("expected JSON object"); + } + return (Map) val; + } + + public static String stringify(Object value) { + StringBuilder sb = new StringBuilder(128); + appendValue(sb, value); + return sb.toString(); + } + + private static void appendValue(StringBuilder sb, Object value) { + if (value == null) { + sb.append("null"); + } else if (value instanceof Boolean || value instanceof Number) { + sb.append(value); + } else if (value instanceof String) { + appendString(sb, (String) value); + } else if (value instanceof Map) { + sb.append('{'); + boolean first = true; + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!first) { + sb.append(','); + } + first = false; + appendString(sb, String.valueOf(entry.getKey())); + sb.append(':'); + appendValue(sb, entry.getValue()); + } + sb.append('}'); + } else if (value instanceof Iterable) { + sb.append('['); + boolean first = true; + for (Object item : (Iterable) value) { + if (!first) { + sb.append(','); + } + first = false; + appendValue(sb, item); + } + sb.append(']'); + } else { + appendString(sb, String.valueOf(value)); + } + } + + private static void appendString(StringBuilder sb, String s) { + sb.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + if (c < 0x20 || Character.isSurrogate(c)) { + sb.append(String.format("\\u%04x", (int) c)); + } else { + sb.append(c); + } + break; + } + } + sb.append('"'); + } + + private Object readValue() { + skipWhitespace(); + if (pos >= src.length()) { + throw new IllegalArgumentException("unexpected end of JSON"); + } + char c = src.charAt(pos); + switch (c) { + case '{': + return readObject(); + case '[': + return readArray(); + case '"': + return readString(); + case 't': + expectLiteral("true"); + return Boolean.TRUE; + case 'f': + expectLiteral("false"); + return Boolean.FALSE; + case 'n': + expectLiteral("null"); + return null; + default: + if (c == '-' || (c >= '0' && c <= '9')) { + return readNumber(); + } + throw new IllegalArgumentException("unexpected char '" + c + "' at offset " + pos); + } + } + + private Map readObject() { + pos++; + Map map = new LinkedHashMap(); + skipWhitespace(); + if (pos < src.length() && src.charAt(pos) == '}') { + pos++; + return map; + } + while (pos < src.length()) { + skipWhitespace(); + if (pos >= src.length() || src.charAt(pos) != '"') { + throw new IllegalArgumentException("expected object key at offset " + pos); + } + String key = readString(); + skipWhitespace(); + if (pos >= src.length() || src.charAt(pos) != ':') { + throw new IllegalArgumentException("expected ':' at offset " + pos); + } + pos++; + Object val = readValue(); + map.put(key, val); + skipWhitespace(); + if (pos >= src.length()) { + break; + } + char next = src.charAt(pos++); + if (next == '}') { + return map; + } + if (next != ',') { + throw new IllegalArgumentException("expected ',' or '}' at offset " + (pos - 1)); + } + } + throw new IllegalArgumentException("unterminated JSON object"); + } + + private List readArray() { + pos++; + List list = new ArrayList(); + skipWhitespace(); + if (pos < src.length() && src.charAt(pos) == ']') { + pos++; + return list; + } + while (pos < src.length()) { + list.add(readValue()); + skipWhitespace(); + if (pos >= src.length()) { + break; + } + char next = src.charAt(pos++); + if (next == ']') { + return list; + } + if (next != ',') { + throw new IllegalArgumentException("expected ',' or ']' at offset " + (pos - 1)); + } + } + throw new IllegalArgumentException("unterminated JSON array"); + } + + private String readString() { + pos++; + StringBuilder sb = new StringBuilder(); + while (pos < src.length()) { + char c = src.charAt(pos++); + if (c == '"') { + return sb.toString(); + } + if (c == '\\') { + if (pos >= src.length()) { + throw new IllegalArgumentException("unterminated escape"); + } + char esc = src.charAt(pos++); + switch (esc) { + case '"': + case '\\': + case '/': + sb.append(esc); + break; + case 'b': + sb.append('\b'); + break; + case 'f': + sb.append('\f'); + break; + case 'n': + sb.append('\n'); + break; + case 'r': + sb.append('\r'); + break; + case 't': + sb.append('\t'); + break; + case 'u': + if (pos + 4 > src.length()) { + throw new IllegalArgumentException("short \\u escape"); + } + int code = Integer.parseInt(src.substring(pos, pos + 4), 16); + sb.append((char) code); + pos += 4; + break; + default: + throw new IllegalArgumentException("invalid escape \\" + esc); + } + } else { + sb.append(c); + } + } + throw new IllegalArgumentException("unterminated string"); + } + + private Number readNumber() { + int start = pos; + if (src.charAt(pos) == '-') { + pos++; + } + boolean isFloat = false; + while (pos < src.length()) { + char c = src.charAt(pos); + if (c >= '0' && c <= '9') { + pos++; + } else if (c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-') { + if (c == '-' && pos == start + 1) { + break; + } + isFloat = true; + pos++; + } else { + break; + } + } + String raw = src.substring(start, pos); + if (isFloat) { + return Double.valueOf(raw); + } + try { + return Long.valueOf(raw); + } catch (NumberFormatException e) { + return Double.valueOf(raw); + } + } + + private void expectLiteral(String literal) { + if (!src.startsWith(literal, pos)) { + throw new IllegalArgumentException("expected " + literal + " at offset " + pos); + } + pos += literal.length(); + } + + private void skipWhitespace() { + while (pos < src.length()) { + char c = src.charAt(pos); + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { + pos++; + } else { + break; + } + } + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeConfig.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeConfig.java new file mode 100644 index 0000000..252ce4b --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeConfig.java @@ -0,0 +1,162 @@ +package com.secfoo.probe; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Immutable configuration resolved from environment variables and optional agent arguments. + */ +public final class ProbeConfig { + public static final String PROBE_VERSION = "0.1.0"; + public static final double DEFAULT_FLUSH_SECONDS = 10.0; + public static final double MIN_FLUSH_SECONDS = 0.05; + public static final double MAX_FLUSH_SECONDS = 3600.0; + public static final long WATCHLIST_RECHECK_MS = 30_000L; + + public final boolean enabled; + public final String sensorAddr; + public final String eventsOut; + public final String watchlistPath; + public final double flushSeconds; + public final String sensorKey; + public final String apiKey; + public final String project; + public final String app; + public final String env; + public final String appRoot; + public final long watchlistRecheckMs; + + private ProbeConfig( + boolean enabled, + String sensorAddr, + String eventsOut, + String watchlistPath, + double flushSeconds, + String sensorKey, + String apiKey, + String project, + String app, + String env, + String appRoot, + long watchlistRecheckMs) { + this.enabled = enabled; + this.sensorAddr = sensorAddr; + this.eventsOut = eventsOut; + this.watchlistPath = watchlistPath; + this.flushSeconds = flushSeconds; + this.sensorKey = sensorKey; + this.apiKey = apiKey; + this.project = project; + this.app = app; + this.env = env; + this.appRoot = appRoot; + this.watchlistRecheckMs = watchlistRecheckMs; + } + + public static ProbeConfig fromEnv(String agentArgs) { + return fromMap(System.getenv(), agentArgs); + } + + static ProbeConfig fromMap(Map envMap, String agentArgs) { + Map args = parseAgentArgs(agentArgs); + boolean enabled = "1".equals(trimOrNull(envMap.get("SECFOO_SENSOR"))); + String sensorAddr = firstNonEmpty(envMap.get("SECFOO_SENSOR_ADDR"), args.get("addr")); + String eventsOut = firstNonEmpty(envMap.get("SECFOO_EVENTS_OUT"), args.get("out")); + String watchlist = firstNonEmpty(envMap.get("SECFOO_WATCHLIST"), args.get("watchlist")); + double flush = parseFlushSeconds(firstNonEmpty(envMap.get("SECFOO_FLUSH_INTERVAL"), args.get("flush"))); + String sensorKey = trimOrNull(envMap.get("SECFOO_SENSOR_KEY")); + String apiKey = resolveApiKey(envMap); + String project = firstNonEmpty(envMap.get("SECFOO_PROJECT"), args.get("project")); + String app = firstNonEmpty(envMap.get("SECFOO_APP"), args.get("app")); + String deployEnv = firstNonEmpty(envMap.get("SECFOO_ENV"), args.get("env")); + String appRoot = firstNonEmpty(envMap.get("SECFOO_APP_ROOT"), System.getProperty("user.dir")); + long recheckMs = parseRecheckMs(trimOrNull(envMap.get("SECFOO_WATCHLIST_RECHECK_SECONDS"))); + return new ProbeConfig( + enabled, sensorAddr, eventsOut, watchlist, flush, sensorKey, apiKey, project, app, deployEnv, appRoot, + recheckMs); + } + + private static long parseRecheckMs(String raw) { + if (raw == null) { + return WATCHLIST_RECHECK_MS; + } + try { + double secs = Double.parseDouble(raw); + if (Double.isNaN(secs) || Double.isInfinite(secs) || secs <= 0.0) { + return WATCHLIST_RECHECK_MS; + } + return Math.max(50L, (long) (secs * 1000.0)); + } catch (NumberFormatException e) { + return WATCHLIST_RECHECK_MS; + } + } + + public static double clampFlushSeconds(double value) { + if (Double.isNaN(value) || Double.isInfinite(value) || value <= 0.0) { + return DEFAULT_FLUSH_SECONDS; + } + return Math.min(Math.max(value, MIN_FLUSH_SECONDS), MAX_FLUSH_SECONDS); + } + + private static double parseFlushSeconds(String raw) { + if (raw == null) { + return DEFAULT_FLUSH_SECONDS; + } + try { + return clampFlushSeconds(Double.parseDouble(raw)); + } catch (NumberFormatException e) { + return DEFAULT_FLUSH_SECONDS; + } + } + + private static String resolveApiKey(Map envMap) { + String file = trimOrNull(envMap.get("SECFOO_API_KEY_FILE")); + if (file != null) { + try { + Path path = Paths.get(file); + if (Files.isRegularFile(path)) { + String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8).trim(); + if (!content.isEmpty()) { + return content; + } + } + } catch (IOException ignored) { + // Fail-open: fall back to SECFOO_API_KEY + } + } + return trimOrNull(envMap.get("SECFOO_API_KEY")); + } + + private static Map parseAgentArgs(String agentArgs) { + if (agentArgs == null || agentArgs.trim().isEmpty()) { + return Collections.emptyMap(); + } + Map out = new HashMap(); + for (String part : agentArgs.split(",")) { + int eq = part.indexOf('='); + if (eq > 0 && eq < part.length() - 1) { + out.put(part.substring(0, eq).trim(), part.substring(eq + 1).trim()); + } + } + return out; + } + + private static String firstNonEmpty(String a, String b) { + String va = trimOrNull(a); + return va != null ? va : trimOrNull(b); + } + + private static String trimOrNull(String value) { + if (value == null) { + return null; + } + String trimmed = value.trim(); + return trimmed.isEmpty() ? null : trimmed; + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeRuntime.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeRuntime.java new file mode 100644 index 0000000..378c1f0 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/ProbeRuntime.java @@ -0,0 +1,552 @@ +package com.secfoo.probe; + +import java.lang.instrument.Instrumentation; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.LongAdder; + +/** + * Runtime state, lock-free hit aggregation, first-hit stack sampling, + * inventory buffering, and background daemon flusher (#73/#74). + */ +public final class ProbeRuntime implements Transport.ControlListener { + public static final int MAX_STACK_FRAMES = 10; + public static final int MAX_PENDING_LOADS = 2048; + public static final long SHUTDOWN_DRAIN_MS = 200L; + private static final int FAST_TABLE_CAPACITY = 4096; + + private static volatile ProbeRuntime activeInstance; + + private final ProbeConfig config; + private final Instrumentation instrumentation; + private final WatchlistManager watchlist; + private final InventoryExtractor inventory = new InventoryExtractor(); + private final Transport transport; + + private final String sessionId = UUID.randomUUID().toString(); + private final String startedAt = Instant.now().toString(); + + private final AtomicBoolean active = new AtomicBoolean(false); + private final AtomicBoolean broken = new AtomicBoolean(false); + private final AtomicBoolean stopped = new AtomicBoolean(false); + private final Object flushLock = new Object(); + + private volatile double flushSeconds; + private volatile int sampleEvery = 1; + private final AtomicInteger sampleCounter = new AtomicInteger(0); + private final LongAdder droppedBatches = new LongAdder(); + + // Ultra-fast unattributed path (no active request context): zero allocation, zero Map lookup + private final LongAdder[] fastCounts = new LongAdder[FAST_TABLE_CAPACITY]; + private final AtomicBoolean[] fastStackCaptured = new AtomicBoolean[FAST_TABLE_CAPACITY]; + private final String[] fastFirstSeen = new String[FAST_TABLE_CAPACITY]; + private final String[] fastLastSeen = new String[FAST_TABLE_CAPACITY]; + private final String[] fastEntryFrame = new String[FAST_TABLE_CAPACITY]; + private final List[] fastStackSample = createStackArray(FAST_TABLE_CAPACITY); + + // Attributed / overflow hits keyed by (symbolId, route, auth) + private final ConcurrentHashMap attributedHits = new ConcurrentHashMap(); + private final ConcurrentHashMap routesSeen = new ConcurrentHashMap(); + private final ConcurrentLinkedQueue pendingLoads = + new ConcurrentLinkedQueue(); + private final AtomicInteger pendingLoadCount = new AtomicInteger(0); + private final List recordedLoads = + Collections.synchronizedList(new ArrayList()); + + private Thread flushThread; + + @SuppressWarnings("unchecked") + private static List[] createStackArray(int size) { + return (List[]) new List[size]; + } + + static final class HitKey { + final int symbolId; + final String route; + final String auth; + + HitKey(int symbolId, String route, String auth) { + this.symbolId = symbolId; + this.route = route; + this.auth = auth; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof HitKey)) { + return false; + } + HitKey other = (HitKey) o; + return symbolId == other.symbolId && route.equals(other.route) && auth.equals(other.auth); + } + + @Override + public int hashCode() { + int h = symbolId; + h = 31 * h + route.hashCode(); + h = 31 * h + auth.hashCode(); + return h; + } + } + + static final class HitStats { + final LongAdder count = new LongAdder(); + final AtomicBoolean stackCaptured = new AtomicBoolean(false); + volatile String firstSeen; + volatile String lastSeen; + volatile String entryFrame; + volatile List stackSample; + } + + public ProbeRuntime(ProbeConfig config, Instrumentation instrumentation, WatchlistManager watchlist, Transport transport) { + this.config = config; + this.instrumentation = instrumentation; + this.watchlist = watchlist; + this.transport = transport; + this.flushSeconds = config.flushSeconds; + for (int i = 0; i < FAST_TABLE_CAPACITY; i++) { + fastCounts[i] = new LongAdder(); + fastStackCaptured[i] = new AtomicBoolean(false); + } + } + + public static ProbeRuntime current() { + return activeInstance; + } + + public void start() { + try { + activeInstance = this; + watchlist.reloadIfNeeded(true); + active.set(true); + flushThread = new Thread(new Runnable() { + @Override + public void run() { + runFlushLoop(); + } + }, "secfoo-probe-flush"); + flushThread.setDaemon(true); + flushThread.start(); + Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { + @Override + public void run() { + stop(); + } + }, "secfoo-probe-shutdown")); + } catch (Throwable t) { + disable(t); + } + } + + public void stop() { + if (!stopped.compareAndSet(false, true)) { + return; + } + active.set(false); + if (flushThread != null) { + flushThread.interrupt(); + try { + flushThread.join(SHUTDOWN_DRAIN_MS); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + } + try { + if (!broken.get()) { + synchronized (flushLock) { + flushNow(true); + } + } + } catch (Throwable ignored) { + // fail-open on shutdown + } finally { + try { + transport.close(); + } catch (Throwable ignored) { + // ignore + } + if (activeInstance == this) { + activeInstance = null; + } + } + } + + /** + * Bytecode entry hook invoked at the start of every watched method. + * Must NEVER throw into application code. + */ + public static void recordHit(int symbolId) { + ProbeRuntime rt = activeInstance; + if (rt == null || !rt.active.get() || rt.broken.get()) { + return; + } + try { + rt.onHit(symbolId); + } catch (Throwable t) { + rt.disable(t); + } + } + + public static void recordRoute(String route) { + ProbeRuntime rt = activeInstance; + if (rt == null || !rt.active.get() || rt.broken.get() || route == null) { + return; + } + if ("unknown".equals(route) || "startup".equals(route) || route.startsWith("job:")) { + return; + } + try { + LongAdder counter = rt.routesSeen.get(route); + if (counter == null) { + if (rt.routesSeen.size() >= 1024) { + return; // bounded memory (#73 §5) + } + LongAdder fresh = new LongAdder(); + LongAdder prev = rt.routesSeen.putIfAbsent(route, fresh); + counter = prev != null ? prev : fresh; + } + counter.increment(); + } catch (Throwable t) { + rt.disable(t); + } + } + + public void recordCodeSource(java.security.ProtectionDomain pd, String classInternalName) { + if (!active.get() || broken.get()) { + return; + } + try { + List pkgs = inventory.inspectProtectionDomain(pd, classInternalName); + for (InventoryExtractor.PackageInfo pkg : pkgs) { + if (pendingLoadCount.incrementAndGet() <= MAX_PENDING_LOADS) { + pendingLoads.add(pkg); + } else { + pendingLoadCount.decrementAndGet(); + break; + } + } + } catch (Throwable ignored) { + // fail-open + } + } + + void onHit(int symbolId) { + int factor = sampleEvery; + if (factor > 1) { + int seq = sampleCounter.incrementAndGet(); + if ((seq % factor) != 0) { + return; + } + } + + RouteContext.Frame frame = RouteContext.peek(); + if (frame == null && symbolId >= 0 && symbolId < FAST_TABLE_CAPACITY) { + fastCounts[symbolId].increment(); + if (fastStackCaptured[symbolId].compareAndSet(false, true)) { + String now = Instant.now().toString(); + fastFirstSeen[symbolId] = now; + fastLastSeen[symbolId] = now; + StackSample sample = captureStackSample(watchlist.byId(symbolId)); + fastEntryFrame[symbolId] = sample.entryFrame; + fastStackSample[symbolId] = sample.frames; + } else { + fastLastSeen[symbolId] = Instant.now().toString(); + } + return; + } + + RouteContext.Snapshot snap = RouteContext.currentSnapshot(); + HitKey key = new HitKey(symbolId, snap.route, snap.auth); + HitStats stats = attributedHits.get(key); + if (stats == null) { + if (attributedHits.size() >= 8192) { + return; // bounded memory + } + HitStats fresh = new HitStats(); + HitStats prev = attributedHits.putIfAbsent(key, fresh); + stats = prev != null ? prev : fresh; + } + stats.count.increment(); + String now = Instant.now().toString(); + if (stats.stackCaptured.compareAndSet(false, true)) { + stats.firstSeen = now; + stats.lastSeen = now; + StackSample sample = captureStackSample(watchlist.byId(symbolId)); + stats.entryFrame = sample.entryFrame; + stats.stackSample = sample.frames; + } else { + stats.lastSeen = now; + } + } + + private void runFlushLoop() { + while (active.get() && !broken.get()) { + long sleepMs = Math.max(50L, (long) (flushSeconds * 1000.0)); + try { + Thread.sleep(sleepMs); + } catch (InterruptedException ie) { + if (!active.get()) { + break; + } + } + if (!active.get() || broken.get()) { + break; + } + try { + checkWatchlistReload(); + synchronized (flushLock) { + flushNow(false); + } + } catch (Throwable t) { + disable(t); + break; + } + } + } + + private void checkWatchlistReload() { + Set addedClasses = watchlist.reloadIfNeeded(false); + if (addedClasses.isEmpty() || instrumentation == null || !instrumentation.isRetransformClassesSupported()) { + return; + } + List> toRetransform = new ArrayList>(); + for (Class loaded : instrumentation.getAllLoadedClasses()) { + if (loaded == null || !instrumentation.isModifiableClass(loaded)) { + continue; + } + String internal = loaded.getName().replace('.', '/'); + if (addedClasses.contains(internal)) { + toRetransform.add(loaded); + } + } + if (!toRetransform.isEmpty()) { + try { + instrumentation.retransformClasses(toRetransform.toArray(new Class[0])); + } catch (Throwable ignored) { + // fail-open + } + } + } + + public boolean flushNow(boolean ended) { + drainPendingLoads(); + List> batch = buildEvents(ended); + if (batch.isEmpty()) { + return true; + } + boolean ok = transport.send(batch, this); + if (!ok) { + droppedBatches.increment(); + } + return ok; + } + + private void drainPendingLoads() { + InventoryExtractor.PackageInfo info; + while ((info = pendingLoads.poll()) != null) { + pendingLoadCount.decrementAndGet(); + recordedLoads.add(info); + } + } + + List> buildEvents(boolean ended) { + List> events = new ArrayList>(); + events.add(buildSessionEvent(ended)); + + synchronized (recordedLoads) { + String now = Instant.now().toString(); + for (InventoryExtractor.PackageInfo pkg : recordedLoads) { + Map load = new LinkedHashMap(); + load.put("type", "load"); + load.put("session", sessionId); + load.put("ecosystem", pkg.ecosystem); + load.put("package", pkg.packageName); + load.put("version", pkg.version); + if (pkg.path != null && !pkg.path.isEmpty()) { + load.put("path", pkg.path); + } + if (pkg.shaded) { + load.put("shaded", Boolean.TRUE); + } + load.put("first_seen", now); + events.add(load); + } + } + + WatchlistManager.Snapshot wl = watchlist.current(); + for (int i = 0; i < wl.byId.size() && i < FAST_TABLE_CAPACITY; i++) { + long count = fastCounts[i].sum(); + if (count > 0) { + WatchlistManager.WatchedSymbol sym = wl.byId.get(i); + emitHitEvents(events, sym, "unknown", "unknown", count, + fastFirstSeen[i], fastLastSeen[i], fastEntryFrame[i], fastStackSample[i]); + } + } + + for (Map.Entry entry : attributedHits.entrySet()) { + long count = entry.getValue().count.sum(); + if (count <= 0) { + continue; + } + HitKey key = entry.getKey(); + WatchlistManager.WatchedSymbol sym = watchlist.byId(key.symbolId); + if (sym == null) { + continue; + } + HitStats st = entry.getValue(); + emitHitEvents(events, sym, key.route, key.auth, count, + st.firstSeen, st.lastSeen, st.entryFrame, st.stackSample); + } + + return events; + } + + private void emitHitEvents( + List> events, + WatchlistManager.WatchedSymbol sym, + String route, + String auth, + long count, + String firstSeen, + String lastSeen, + String entryFrame, + List stackSample) { + for (String fp : sym.fingerprints) { + Map hit = new LinkedHashMap(); + hit.put("type", "hit"); + hit.put("session", sessionId); + hit.put("finding_fingerprint", fp); + hit.put("symbol", sym.symbol); + hit.put("route", route); + hit.put("auth", auth); + hit.put("count", count); + if (firstSeen != null) { + hit.put("first_seen", firstSeen); + } + if (lastSeen != null) { + hit.put("last_seen", lastSeen); + } + if (entryFrame != null) { + hit.put("entry_frame", entryFrame); + } + if (stackSample != null && !stackSample.isEmpty()) { + hit.put("stack_sample", stackSample); + } + events.add(hit); + } + } + + private Map buildSessionEvent(boolean ended) { + Map session = new LinkedHashMap(); + session.put("type", "session"); + session.put("id", sessionId); + session.put("language", "jvm"); + session.put("runtime", System.getProperty("java.version", "unknown")); + session.put("source", "sensor"); + if (config.app != null) { + session.put("app", config.app); + } + if (config.env != null) { + session.put("env", config.env); + } + session.put("instance", Transport.resolveHostname()); + session.put("sensor_version", ProbeConfig.PROBE_VERSION); + session.put("started_at", startedAt); + if (ended) { + session.put("ended_at", Instant.now().toString()); + } + if (!routesSeen.isEmpty()) { + Map routesMap = new LinkedHashMap(); + for (Map.Entry e : routesSeen.entrySet()) { + long c = e.getValue().sum(); + if (c > 0) { + routesMap.put(e.getKey(), c); + } + } + if (!routesMap.isEmpty()) { + session.put("routes_seen", routesMap); + } + } + return session; + } + + @Override + public void onWelcome(double flushIntervalSeconds) { + this.flushSeconds = flushIntervalSeconds; + } + + @Override + public void onSlow(int sampleEvery) { + this.sampleEvery = Math.max(1, sampleEvery); + } + + public long getDroppedBatches() { + return droppedBatches.sum(); + } + + private void disable(Throwable t) { + if (broken.compareAndSet(false, true)) { + active.set(false); + System.err.println("[secfoo-jvm-probe] disabled (fail-open): " + t); + } + } + + private static final class StackSample { + final String entryFrame; + final List frames; + + StackSample(String entryFrame, List frames) { + this.entryFrame = entryFrame; + this.frames = frames; + } + } + + private static StackSample captureStackSample(WatchlistManager.WatchedSymbol sym) { + StackTraceElement[] elements = Thread.currentThread().getStackTrace(); + List frames = new ArrayList(MAX_STACK_FRAMES); + String watchedClassDot = sym != null ? sym.classInternalName.replace('/', '.') : ""; + String entryFrame = null; + + for (StackTraceElement el : elements) { + String cls = el.getClassName(); + if (cls.startsWith("com.secfoo.probe.") + || cls.startsWith("java.lang.Thread") + || cls.startsWith("jdk.internal.") + || cls.startsWith("sun.reflect.")) { + continue; + } + int line = el.getLineNumber(); + if (line <= 0) { + continue; + } + String file = el.getFileName(); + if (file == null || file.trim().isEmpty() || file.indexOf(' ') >= 0) { + file = cls.replace('.', '/') + ".java"; + } + String frame = file + ":" + line; + if (frames.size() < MAX_STACK_FRAMES) { + frames.add(frame); + } + if (entryFrame == null && !cls.equals(watchedClassDot)) { + entryFrame = frame; + } + } + if (entryFrame == null && !frames.isEmpty()) { + entryFrame = frames.get(0); + } + return new StackSample(entryFrame, frames); + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteContext.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteContext.java new file mode 100644 index 0000000..312a579 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteContext.java @@ -0,0 +1,207 @@ +package com.secfoo.probe; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Per-thread (platform and Java 21 virtual thread) request, job, and auth context (#69). + * + * Strictly stores only sanitized route templates and coarse auth classification + * ("authenticated", "anonymous", "unknown") — never header values, cookie values, + * query strings, concrete URLs, or user identifiers. + */ +public final class RouteContext { + private static final Set HTTP_METHODS = new HashSet( + Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE")); + private static final Set SESSION_COOKIE_NAMES = new HashSet(Arrays.asList( + "jsessionid", "session", "sessionid", "session_id", "sid", + "connect.sid", "phpsessid", "auth", "auth_token", "access_token", + "jwt", "_session")); + private static final Pattern UNSAFE_ROUTE = Pattern.compile("://|[?#\\r\\n\\t]"); + private static final Pattern ANGLE_PARAM = Pattern.compile("<(?:[A-Za-z_]\\w*:)?([A-Za-z_]\\w*)>"); + private static final Pattern COLON_PARAM = Pattern.compile("/:[A-Za-z_]\\w*"); + private static final Pattern JOB_UNSAFE = Pattern.compile("[^A-Za-z0-9._:/-]+"); + + private static final ThreadLocal> CURRENT = new ThreadLocal>(); + + private RouteContext() {} + + public static final class Frame { + public volatile String route; + public volatile String auth; + public volatile Object requestCarrier; + public volatile boolean resolved; + + Frame(String route, String auth, Object requestCarrier, boolean resolved) { + this.route = route; + this.auth = auth; + this.requestCarrier = requestCarrier; + this.resolved = resolved; + } + } + + public static final class Snapshot { + public final String route; + public final String auth; + + Snapshot(String route, String auth) { + this.route = route; + this.auth = auth; + } + } + + public static void push(String route, String auth, Object requestCarrier) { + Deque stack = CURRENT.get(); + if (stack == null) { + stack = new ArrayDeque(4); + CURRENT.set(stack); + } + String sanitized = (route != null && !route.isEmpty()) ? route : "unknown"; + String safeAuth = normalizeAuth(auth); + stack.push(new Frame(sanitized, safeAuth, requestCarrier, requestCarrier == null)); + } + + public static void updateCurrent(String route, String auth) { + Deque stack = CURRENT.get(); + if (stack == null || stack.isEmpty()) { + return; + } + Frame frame = stack.peek(); + if (route != null && !route.isEmpty() && !"unknown".equals(route)) { + frame.route = route; + } + if (auth != null && !"unknown".equals(auth)) { + frame.auth = normalizeAuth(auth); + } + } + + public static Frame pop() { + Deque stack = CURRENT.get(); + if (stack == null || stack.isEmpty()) { + return null; + } + Frame popped = stack.pop(); + if (stack.isEmpty()) { + CURRENT.remove(); + } + return popped; + } + + public static Frame peek() { + Deque stack = CURRENT.get(); + return (stack == null || stack.isEmpty()) ? null : stack.peek(); + } + + public static Snapshot currentSnapshot() { + Frame frame = peek(); + if (frame == null) { + return new Snapshot("unknown", "unknown"); + } + if (!frame.resolved && frame.requestCarrier != null) { + RouteHooks.resolveFrame(frame); + } + return new Snapshot(frame.route, frame.auth); + } + + public static void clear() { + CURRENT.remove(); + } + + public static String sanitizeRouteTemplate(String method, String template) { + if (template == null) { + return "unknown"; + } + String raw = template.trim(); + if (raw.isEmpty() || raw.length() > 512 || UNSAFE_ROUTE.matcher(raw).find()) { + return "unknown"; + } + String normalized = ANGLE_PARAM.matcher(raw).replaceAll("{$1}"); + Matcher colonMatcher = COLON_PARAM.matcher(normalized); + StringBuffer sb = new StringBuffer(); + while (colonMatcher.find()) { + String param = colonMatcher.group().substring(2); + colonMatcher.appendReplacement(sb, "/{" + param + "}"); + } + colonMatcher.appendTail(sb); + normalized = sb.toString(); + + if (!normalized.startsWith("/")) { + int i = 0; + while (i < normalized.length() && normalized.charAt(i) == '/') { + i++; + } + normalized = "/" + normalized.substring(i); + } + if (normalized.length() > 1 && normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + if (normalized.indexOf(' ') >= 0) { + return "unknown"; + } + String verb = normalizeMethod(method); + return verb.isEmpty() ? normalized : verb + " " + normalized; + } + + public static String sanitizeJobName(String name) { + if (name == null) { + return "job:unknown"; + } + String cleaned = JOB_UNSAFE.matcher(name.trim()).replaceAll("_"); + while (cleaned.startsWith("_") || cleaned.startsWith(".")) { + cleaned = cleaned.substring(1); + } + if (cleaned.isEmpty()) { + cleaned = "unknown"; + } + if (cleaned.length() > 200) { + cleaned = cleaned.substring(0, 200); + } + return cleaned.startsWith("job:") ? cleaned : "job:" + cleaned; + } + + public static boolean isSessionCookieName(String name) { + if (name == null) { + return false; + } + String low = name.trim().toLowerCase(Locale.ROOT); + return !low.isEmpty() && (SESSION_COOKIE_NAMES.contains(low) || low.contains("session")); + } + + public static boolean hasSessionCookieInHeader(String rawCookieHeader) { + if (rawCookieHeader == null || rawCookieHeader.isEmpty()) { + return false; + } + for (String part : rawCookieHeader.split(";")) { + int eq = part.indexOf('='); + if (eq > 0 && eq < part.length() - 1) { + String name = part.substring(0, eq).trim(); + String val = part.substring(eq + 1).trim(); + if (!val.isEmpty() && isSessionCookieName(name)) { + return true; + } + } + } + return false; + } + + static String normalizeMethod(String method) { + if (method == null) { + return ""; + } + String up = method.trim().toUpperCase(Locale.ROOT); + return HTTP_METHODS.contains(up) ? up : ""; + } + + static String normalizeAuth(String auth) { + if ("authenticated".equals(auth) || "anonymous".equals(auth)) { + return auth; + } + return "unknown"; + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteHooks.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteHooks.java new file mode 100644 index 0000000..9c7352a --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/RouteHooks.java @@ -0,0 +1,406 @@ +package com.secfoo.probe; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Reflective route and auth extraction for Servlet (javax + jakarta), Spring MVC, + * Spring WebFlux, and JAX-RS (#69). Uses zero compile-time framework dependencies + * so the agent works across any framework version without linkage conflicts. + */ +public final class RouteHooks { + public static final String SPRING_MVC_PATTERN_ATTR = + "org.springframework.web.servlet.HandlerMapping.bestMatchingPattern"; + public static final String SPRING_WEBFLUX_PATTERN_ATTR = + "org.springframework.web.reactive.HandlerMapping.bestMatchingPattern"; + public static final String SECFOO_ROUTE_ATTR = "secfoo.route"; + + private static final ConcurrentHashMap, Class> METHOD_CACHE = new ConcurrentHashMap, Class>(); + + private RouteHooks() {} + + // ---------- Servlet / Spring MVC hooks (called from instrumented HttpServlet.service / Filter.doFilter) ---------- + + public static void enterServlet(Object request) { + try { + if (request == null) { + RouteContext.push("unknown", "unknown", null); + return; + } + String method = safeString(invokeNoArg(request, "getMethod")); + String auth = detectServletAuth(request); + String initialRoute = extractServletRoute(request, method); + RouteContext.push(initialRoute, auth, request); + } catch (Throwable ignored) { + RouteContext.push("unknown", "unknown", null); + } + } + + public static void exitServlet() { + try { + RouteContext.Frame frame = RouteContext.peek(); + if (frame != null) { + if (!frame.resolved && frame.requestCarrier != null) { + resolveFrame(frame); + } + if (frame.route != null && !"unknown".equals(frame.route)) { + ProbeRuntime.recordRoute(frame.route); + } + } + } catch (Throwable ignored) { + // fail-open + } finally { + RouteContext.pop(); + } + } + + // ---------- Spring WebFlux hook (called from instrumented DispatcherHandler.handle) ---------- + + public static void enterWebFlux(Object exchange) { + try { + if (exchange == null) { + RouteContext.push("unknown", "unknown", null); + return; + } + String route = extractWebFluxRoute(exchange); + String auth = detectWebFluxAuth(exchange); + RouteContext.push(route, auth, exchange); + } catch (Throwable ignored) { + RouteContext.push("unknown", "unknown", null); + } + } + + public static void exitWebFlux() { + exitServlet(); + } + + // ---------- JAX-RS hook (called from instrumented @Path resource methods or ContainerRequestFilter) ---------- + + public static void enterJaxRs(Object resourceOrContext, String httpMethod, String classPath, String methodPath) { + try { + String template = joinPaths(classPath, methodPath); + String route = RouteContext.sanitizeRouteTemplate(httpMethod, template); + String auth = "unknown"; + if (resourceOrContext != null && hasMethod(resourceOrContext.getClass(), "getHeaderString", String.class)) { + route = extractJaxRsContextRoute(resourceOrContext, route); + auth = detectJaxRsAuth(resourceOrContext); + } + RouteContext.push(route, auth, null); + if (!"unknown".equals(route)) { + ProbeRuntime.recordRoute(route); + } + } catch (Throwable ignored) { + RouteContext.push("unknown", "unknown", null); + } + } + + public static void exitJaxRs() { + RouteContext.pop(); + } + + public static void resolveFrame(RouteContext.Frame frame) { + if (frame == null || frame.resolved) { + return; + } + frame.resolved = true; + Object carrier = frame.requestCarrier; + if (carrier == null) { + return; + } + try { + if (hasMethod(carrier.getClass(), "getAttribute", String.class)) { + String method = safeString(invokeNoArg(carrier, "getMethod")); + String route = extractServletRoute(carrier, method); + if (!"unknown".equals(route)) { + frame.route = route; + } + String auth = detectServletAuth(carrier); + if (!"unknown".equals(auth)) { + frame.auth = auth; + } + } else if (hasMethod(carrier.getClass(), "getAttributes")) { + String route = extractWebFluxRoute(carrier); + if (!"unknown".equals(route)) { + frame.route = route; + } + } + } catch (Throwable ignored) { + // fail-open + } + } + + // ---------- Servlet + Spring MVC extraction ---------- + + static String extractServletRoute(Object request, String method) { + // 1. Spring MVC bestMatchingPattern attribute (set by DispatcherServlet) + Object bestPattern = invokeOneArg(request, "getAttribute", String.class, SPRING_MVC_PATTERN_ATTR); + if (bestPattern != null) { + String candidate = RouteContext.sanitizeRouteTemplate(method, String.valueOf(bestPattern)); + if (!"unknown".equals(candidate)) { + return candidate; + } + } + // 2. Explicit secfoo.route attribute if present + Object explicit = invokeOneArg(request, "getAttribute", String.class, SECFOO_ROUTE_ATTR); + if (explicit != null) { + String candidate = RouteContext.sanitizeRouteTemplate(method, String.valueOf(explicit)); + if (!"unknown".equals(candidate)) { + return candidate; + } + } + // 3. Servlet 4.0+ / Jakarta HttpServletMapping.getPattern() (returns route pattern, never query/IDs) + Object mapping = invokeNoArg(request, "getHttpServletMapping"); + if (mapping != null) { + String pattern = safeString(invokeNoArg(mapping, "getPattern")); + if (pattern != null && !pattern.isEmpty() && !"/*".equals(pattern) && !"/".equals(pattern)) { + String candidate = RouteContext.sanitizeRouteTemplate(method, pattern); + if (!"unknown".equals(candidate)) { + return candidate; + } + } + } + // 4. Servlet mapping prefix (getServletPath is the matched servlet mapping, never pathInfo/queryString) + String servletPath = safeString(invokeNoArg(request, "getServletPath")); + if (servletPath != null && !servletPath.isEmpty() && !looksNumericSegment(servletPath)) { + return RouteContext.sanitizeRouteTemplate(method, servletPath); + } + return "unknown"; + } + + static String detectServletAuth(Object request) { + try { + Object principal = invokeNoArg(request, "getUserPrincipal"); + if (principal != null) { + return "authenticated"; + } + String authHeader = safeString(invokeOneArg(request, "getHeader", String.class, "Authorization")); + if (authHeader != null && !authHeader.trim().isEmpty()) { + return "authenticated"; + } + Object cookiesObj = invokeNoArg(request, "getCookies"); + if (cookiesObj instanceof Object[]) { + for (Object cookie : (Object[]) cookiesObj) { + if (cookie == null) { + continue; + } + String name = safeString(invokeNoArg(cookie, "getName")); + if (RouteContext.isSessionCookieName(name)) { + return "authenticated"; + } + } + } + String cookieHeader = safeString(invokeOneArg(request, "getHeader", String.class, "Cookie")); + if (RouteContext.hasSessionCookieInHeader(cookieHeader)) { + return "authenticated"; + } + if (hasMethod(request.getClass(), "getHeader", String.class)) { + return "anonymous"; + } + } catch (Throwable ignored) { + // fail-open + } + return "unknown"; + } + + // ---------- Spring WebFlux extraction ---------- + + @SuppressWarnings("unchecked") + static String extractWebFluxRoute(Object exchange) { + Object request = invokeNoArg(exchange, "getRequest"); + String method = request != null ? extractReactiveMethod(request) : null; + Object attrsObj = invokeNoArg(exchange, "getAttributes"); + if (attrsObj instanceof Map) { + Map attrs = (Map) attrsObj; + Object pattern = attrs.get(SPRING_WEBFLUX_PATTERN_ATTR); + if (pattern != null) { + String patternStr = safeString(invokeNoArg(pattern, "getPatternString")); + if (patternStr == null) { + patternStr = String.valueOf(pattern); + } + String candidate = RouteContext.sanitizeRouteTemplate(method, patternStr); + if (!"unknown".equals(candidate)) { + return candidate; + } + } + } + return "unknown"; + } + + static String detectWebFluxAuth(Object exchange) { + try { + Object request = invokeNoArg(exchange, "getRequest"); + if (request == null) { + return "unknown"; + } + Object headers = invokeNoArg(request, "getHeaders"); + if (headers != null) { + String auth = safeString(invokeOneArg(headers, "getFirst", String.class, "Authorization")); + if (auth != null && !auth.trim().isEmpty()) { + return "authenticated"; + } + String cookie = safeString(invokeOneArg(headers, "getFirst", String.class, "Cookie")); + if (RouteContext.hasSessionCookieInHeader(cookie)) { + return "authenticated"; + } + return "anonymous"; + } + } catch (Throwable ignored) { + // fail-open + } + return "unknown"; + } + + private static String extractReactiveMethod(Object request) { + Object methodObj = invokeNoArg(request, "getMethod"); + if (methodObj != null) { + String name = safeString(invokeNoArg(methodObj, "name")); + if (name != null) { + return name; + } + return methodObj.toString(); + } + return safeString(invokeNoArg(request, "getMethodValue")); + } + + // ---------- JAX-RS extraction ---------- + + static String extractJaxRsContextRoute(Object containerRequestContext, String fallback) { + String method = safeString(invokeNoArg(containerRequestContext, "getMethod")); + Object uriInfo = invokeNoArg(containerRequestContext, "getUriInfo"); + if (uriInfo != null) { + Object templates = invokeNoArg(uriInfo, "getMatchedTemplates"); + if (templates instanceof List && !((List) templates).isEmpty()) { + List list = (List) templates; + StringBuilder combined = new StringBuilder(); + for (int i = list.size() - 1; i >= 0; i--) { + Object tpl = list.get(i); + String str = safeString(invokeNoArg(tpl, "getTemplate")); + if (str == null && tpl != null) { + str = tpl.toString(); + } + if (str != null && !str.isEmpty()) { + if (!str.startsWith("/")) { + combined.append('/'); + } + combined.append(str); + } + } + String candidate = RouteContext.sanitizeRouteTemplate(method, combined.toString()); + if (!"unknown".equals(candidate)) { + return candidate; + } + } + } + return fallback; + } + + static String detectJaxRsAuth(Object containerRequestContext) { + Object secCtx = invokeNoArg(containerRequestContext, "getSecurityContext"); + if (secCtx != null && invokeNoArg(secCtx, "getUserPrincipal") != null) { + return "authenticated"; + } + String auth = safeString(invokeOneArg(containerRequestContext, "getHeaderString", String.class, "Authorization")); + if (auth != null && !auth.trim().isEmpty()) { + return "authenticated"; + } + String cookie = safeString(invokeOneArg(containerRequestContext, "getHeaderString", String.class, "Cookie")); + if (RouteContext.hasSessionCookieInHeader(cookie)) { + return "authenticated"; + } + return "anonymous"; + } + + public static String readJaxRsAnnotationPath(Annotation[] annotations) { + if (annotations == null) { + return null; + } + for (Annotation ann : annotations) { + String name = ann.annotationType().getName(); + if ("javax.ws.rs.Path".equals(name) || "jakarta.ws.rs.Path".equals(name)) { + return safeString(invokeNoArg(ann, "value")); + } + } + return null; + } + + static String joinPaths(String classPath, String methodPath) { + String a = classPath == null ? "" : classPath.trim(); + String b = methodPath == null ? "" : methodPath.trim(); + if (a.isEmpty() && b.isEmpty()) { + return ""; + } + if (a.isEmpty()) { + return b; + } + if (b.isEmpty()) { + return a; + } + if (a.endsWith("/") && b.startsWith("/")) { + return a + b.substring(1); + } + if (!a.endsWith("/") && !b.startsWith("/")) { + return a + "/" + b; + } + return a + b; + } + + private static boolean looksNumericSegment(String path) { + for (String seg : path.split("/")) { + if (!seg.isEmpty()) { + boolean allDigits = true; + for (int i = 0; i < seg.length(); i++) { + if (!Character.isDigit(seg.charAt(i))) { + allDigits = false; + break; + } + } + if (allDigits) { + return true; + } + } + } + return false; + } + + private static boolean hasMethod(Class cls, String name, Class... params) { + try { + cls.getMethod(name, params); + return true; + } catch (NoSuchMethodException e) { + return false; + } + } + + private static Object invokeNoArg(Object target, String methodName) { + if (target == null) { + return null; + } + try { + Method m = target.getClass().getMethod(methodName); + m.setAccessible(true); + return m.invoke(target); + } catch (Throwable ignored) { + return null; + } + } + + private static Object invokeOneArg(Object target, String methodName, Class paramType, Object arg) { + if (target == null) { + return null; + } + try { + Method m = target.getClass().getMethod(methodName, paramType); + m.setAccessible(true); + return m.invoke(target, arg); + } catch (Throwable ignored) { + return null; + } + } + + private static String safeString(Object obj) { + return obj == null ? null : String.valueOf(obj); + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooAgent.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooAgent.java new file mode 100644 index 0000000..ef032bf --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooAgent.java @@ -0,0 +1,47 @@ +package com.secfoo.probe; + +import java.lang.instrument.Instrumentation; + +/** + * JVM -javaagent entry point (#74). + * + * Rule 0: completely inert unless SECFOO_SENSOR=1 is set in the environment. + * Zero threads, zero ClassFileTransformers, zero sockets, and zero files are + * created when disabled. + */ +public final class SecfooAgent { + private static volatile boolean initialized = false; + + private SecfooAgent() {} + + public static void premain(String agentArgs, Instrumentation inst) { + bootstrap(agentArgs, inst); + } + + public static void agentmain(String agentArgs, Instrumentation inst) { + bootstrap(agentArgs, inst); + } + + private static synchronized void bootstrap(String agentArgs, Instrumentation inst) { + if (initialized) { + return; + } + try { + ProbeConfig config = ProbeConfig.fromEnv(agentArgs); + if (!config.enabled) { + return; + } + initialized = true; + WatchlistManager watchlist = new WatchlistManager(config.watchlistPath, config.watchlistRecheckMs); + watchlist.reloadIfNeeded(true); + Transport transport = Transport.fromConfig(config); + ProbeRuntime runtime = new ProbeRuntime(config, inst, watchlist, transport); + SecfooTransformer transformer = new SecfooTransformer(watchlist, runtime); + inst.addTransformer(transformer, inst.isRetransformClassesSupported()); + runtime.start(); + } catch (Throwable t) { + // Fail-open: never abort JVM startup + System.err.println("[secfoo-jvm-probe] init failed (fail-open): " + t); + } + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooContext.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooContext.java new file mode 100644 index 0000000..c694abb --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooContext.java @@ -0,0 +1,52 @@ +package com.secfoo.probe; + +import java.util.concurrent.Callable; + +/** + * Optional public API for manual or async route/job attribution (#69). + * Standard Servlet, Spring MVC, Spring WebFlux, and JAX-RS apps are + * instrumented automatically by the agent without using this class. + */ +public final class SecfooContext { + private SecfooContext() {} + + public static void runWithRoute(String method, String template, String auth, Runnable action) { + String route = RouteContext.sanitizeRouteTemplate(method, template); + RouteContext.push(route, auth, null); + ProbeRuntime.recordRoute(route); + try { + action.run(); + } finally { + RouteContext.pop(); + } + } + + public static T callWithRoute(String method, String template, String auth, Callable action) throws Exception { + String route = RouteContext.sanitizeRouteTemplate(method, template); + RouteContext.push(route, auth, null); + ProbeRuntime.recordRoute(route); + try { + return action.call(); + } finally { + RouteContext.pop(); + } + } + + public static void runWithJob(String jobName, Runnable action) { + String job = RouteContext.sanitizeJobName(jobName); + RouteContext.push(job, "unknown", null); + try { + action.run(); + } finally { + RouteContext.pop(); + } + } + + public static String currentRoute() { + return RouteContext.currentSnapshot().route; + } + + public static String currentAuth() { + return RouteContext.currentSnapshot().auth; + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooTransformer.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooTransformer.java new file mode 100644 index 0000000..80015d2 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/SecfooTransformer.java @@ -0,0 +1,506 @@ +package com.secfoo.probe; + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.lang.instrument.ClassFileTransformer; +import java.security.ProtectionDomain; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * ASM ClassFileTransformer (#74). + * + * Design invariants: + * - Never calls Class.forName or COMPUTE_FRAMES (zero eager class loading, safe alongside APM/coverage agents). + * - Only parses/rewrites classes that contain watched #52 symbols or supported route entry points. + * - Never reads arguments, return values, or object fields. + */ +public final class SecfooTransformer implements ClassFileTransformer { + private static final int ASM_API = Opcodes.ASM9; + private static final String RUNTIME_INTERNAL = "com/secfoo/probe/ProbeRuntime"; + private static final String HOOKS_INTERNAL = "com/secfoo/probe/RouteHooks"; + + private final WatchlistManager watchlist; + private final ProbeRuntime runtime; + + public SecfooTransformer(WatchlistManager watchlist, ProbeRuntime runtime) { + this.watchlist = watchlist; + this.runtime = runtime; + } + + @Override + public byte[] transform( + ClassLoader loader, + String className, + Class classBeingRedefined, + ProtectionDomain protectionDomain, + byte[] classfileBuffer) { + if (className == null || classfileBuffer == null) { + return null; + } + if (className.startsWith("com/secfoo/probe/")) { + return null; + } + try { + if (!isBootstrapJdkInternal(className)) { + runtime.recordCodeSource(protectionDomain, className); + } + WatchlistManager.Snapshot snap = watchlist.current(); + boolean isWatched = snap.isWatchedClass(className); + boolean isRouteHookTarget = isFrameworkRouteTarget(className); + boolean maybeJaxRs = !isBootstrapJdkInternal(className) && !isWatched && !isRouteHookTarget + && hasJaxRsAnnotationHint(classfileBuffer); + + if (!isWatched && !isRouteHookTarget && !maybeJaxRs) { + return null; + } + + ClassReader cr = new ClassReader(classfileBuffer); + boolean needsFrames = (isRouteHookTarget || maybeJaxRs) && (readClassMajorVersion(classfileBuffer) >= Opcodes.V1_6); + int writerFlags = needsFrames ? (ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES) : ClassWriter.COMPUTE_MAXS; + ClassWriter cw = new SafeClassWriter(cr, writerFlags, loader); + ProbingClassVisitor cv = new ProbingClassVisitor(cw, className, snap, isWatched, isRouteHookTarget, maybeJaxRs); + cr.accept(cv, ClassReader.EXPAND_FRAMES); + return cv.modified ? cw.toByteArray() : null; + } catch (Throwable ignored) { + // Fail-open: never break class loading + return null; + } + } + + private static int readClassMajorVersion(byte[] bytes) { + if (bytes.length < 8) { + return 0; + } + return ((bytes[6] & 0xFF) << 8) | (bytes[7] & 0xFF); + } + + /** + * ClassWriter that resolves common superclasses by reading .class bytecode resources + * instead of calling Class.forName, preventing eager class loading/initialization (#74). + */ + private static final class SafeClassWriter extends ClassWriter { + private final ClassLoader loader; + + SafeClassWriter(ClassReader cr, int flags, ClassLoader loader) { + super(cr, flags); + this.loader = loader; + } + + @Override + protected String getCommonSuperClass(String type1, String type2) { + if (type1.equals(type2)) { + return type1; + } + if ("java/lang/Object".equals(type1) || "java/lang/Object".equals(type2)) { + return "java/lang/Object"; + } + TypeInfo info1 = readTypeInfo(type1); + TypeInfo info2 = readTypeInfo(type2); + if (info1 == null || info2 == null) { + return "java/lang/Object"; + } + if (isAssignableFrom(info1, type2)) { + return type1; + } + if (isAssignableFrom(info2, type1)) { + return type2; + } + if (info1.isInterface || info2.isInterface) { + return "java/lang/Object"; + } + String cur = info1.superName; + while (cur != null && !"java/lang/Object".equals(cur)) { + TypeInfo curInfo = readTypeInfo(cur); + if (curInfo == null) { + return "java/lang/Object"; + } + if (isAssignableFrom(curInfo, type2)) { + return cur; + } + cur = curInfo.superName; + } + return "java/lang/Object"; + } + + private boolean isAssignableFrom(TypeInfo targetInfo, String candidate) { + String cur = candidate; + int depth = 0; + while (cur != null && depth++ < 32) { + if (cur.equals(targetInfo.name)) { + return true; + } + TypeInfo info = readTypeInfo(cur); + if (info == null) { + return false; + } + if (targetInfo.isInterface && info.interfaces != null) { + for (String iface : info.interfaces) { + if (iface.equals(targetInfo.name)) { + return true; + } + } + } + cur = info.superName; + } + return false; + } + + private TypeInfo readTypeInfo(String internalName) { + String resource = internalName + ".class"; + java.io.InputStream is = null; + try { + if (loader != null) { + is = loader.getResourceAsStream(resource); + } + if (is == null) { + is = ClassLoader.getSystemResourceAsStream(resource); + } + if (is == null) { + return null; + } + ClassReader reader = new ClassReader(is); + return new TypeInfo( + reader.getClassName(), + reader.getSuperName(), + reader.getInterfaces(), + (reader.getAccess() & Opcodes.ACC_INTERFACE) != 0); + } catch (Throwable ignored) { + return null; + } finally { + if (is != null) { + try { + is.close(); + } catch (java.io.IOException ignored) { + // ignore + } + } + } + } + } + + private static final class TypeInfo { + final String name; + final String superName; + final String[] interfaces; + final boolean isInterface; + + TypeInfo(String name, String superName, String[] interfaces, boolean isInterface) { + this.name = name; + this.superName = superName; + this.interfaces = interfaces; + this.isInterface = isInterface; + } + } + + private static boolean isBootstrapJdkInternal(String internalName) { + return internalName.startsWith("java/") + || internalName.startsWith("sun/") + || internalName.startsWith("jdk/") + || internalName.startsWith("com/sun/") + || (internalName.startsWith("javax/") && !internalName.startsWith("javax/servlet/") && !internalName.startsWith("javax/ws/rs/")); + } + + private static boolean isFrameworkRouteTarget(String internalName) { + return "javax/servlet/http/HttpServlet".equals(internalName) + || "jakarta/servlet/http/HttpServlet".equals(internalName) + || "org/springframework/web/reactive/DispatcherHandler".equals(internalName) + || "org/springframework/web/reactive/result/method/InvocableHandlerMethod".equals(internalName); + } + + private static boolean hasJaxRsAnnotationHint(byte[] bytes) { + return containsAscii(bytes, "ws/rs/Path"); + } + + private static boolean containsAscii(byte[] haystack, String needle) { + byte[] n = needle.getBytes(java.nio.charset.StandardCharsets.US_ASCII); + outer: + for (int i = 0; i <= haystack.length - n.length; i++) { + for (int j = 0; j < n.length; j++) { + if (haystack[i + j] != n[j]) { + continue outer; + } + } + return true; + } + return false; + } + + private static final class ProbingClassVisitor extends ClassVisitor { + private final String className; + private final WatchlistManager.Snapshot snapshot; + private final boolean isWatched; + private final boolean isRouteHookTarget; + private final boolean maybeJaxRs; + boolean modified = false; + private String jaxRsClassPath = null; + + ProbingClassVisitor( + ClassVisitor cv, + String className, + WatchlistManager.Snapshot snapshot, + boolean isWatched, + boolean isRouteHookTarget, + boolean maybeJaxRs) { + super(ASM_API, cv); + this.className = className; + this.snapshot = snapshot; + this.isWatched = isWatched; + this.isRouteHookTarget = isRouteHookTarget; + this.maybeJaxRs = maybeJaxRs; + } + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + AnnotationVisitor av = super.visitAnnotation(descriptor, visible); + if (maybeJaxRs && ("Ljavax/ws/rs/Path;".equals(descriptor) || "Ljakarta/ws/rs/Path;".equals(descriptor))) { + return new AnnotationVisitor(ASM_API, av) { + @Override + public void visit(String name, Object value) { + if ("value".equals(name) && value instanceof String) { + jaxRsClassPath = (String) value; + } + super.visit(name, value); + } + }; + } + return av; + } + + @Override + public MethodVisitor visitMethod( + int access, String name, String descriptor, String signature, String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); + if (mv == null || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) { + return mv; + } + + List watched = isWatched + ? snapshot.matchMethod(className, name, descriptor) + : java.util.Collections.emptyList(); + + boolean hookServlet = isRouteHookTarget + && ("javax/servlet/http/HttpServlet".equals(className) + || "jakarta/servlet/http/HttpServlet".equals(className)) + && "service".equals(name) + && ("(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V".equals(descriptor) + || "(Ljakarta/servlet/ServletRequest;Ljakarta/servlet/ServletResponse;)V".equals(descriptor)); + + boolean hookWebFlux = isRouteHookTarget + && (("org/springframework/web/reactive/DispatcherHandler".equals(className) + && "handle".equals(name) + && descriptor.startsWith("(Lorg/springframework/web/server/ServerWebExchange;)")) + || ("org/springframework/web/reactive/result/method/InvocableHandlerMethod".equals(className) + && "invoke".equals(name) + && descriptor.startsWith("(Lorg/springframework/web/server/ServerWebExchange;"))); + + if (!watched.isEmpty()) { + modified = true; + mv = new WatchedMethodVisitor(mv, watched); + } + if (hookServlet) { + modified = true; + mv = new TryFinallyRouteVisitor(mv, HOOKS_INTERNAL, "enterServlet", "(Ljava/lang/Object;)V", "exitServlet", 1); + } else if (hookWebFlux) { + modified = true; + mv = new TryFinallyRouteVisitor(mv, HOOKS_INTERNAL, "enterWebFlux", "(Ljava/lang/Object;)V", "exitWebFlux", 1); + } else if (maybeJaxRs && (access & Opcodes.ACC_PUBLIC) != 0 && !"".equals(name) && !"".equals(name)) { + mv = new JaxRsMethodVisitor(mv, jaxRsClassPath, (access & Opcodes.ACC_STATIC) == 0, this); + } + return mv; + } + } + + private static final class WatchedMethodVisitor extends MethodVisitor { + private final List watched; + + WatchedMethodVisitor(MethodVisitor mv, List watched) { + super(ASM_API, mv); + this.watched = watched; + } + + @Override + public void visitCode() { + super.visitCode(); + for (WatchlistManager.WatchedSymbol sym : watched) { + pushInt(mv, sym.id); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, RUNTIME_INTERNAL, "recordHit", "(I)V", false); + } + } + } + + private static final class TryFinallyRouteVisitor extends MethodVisitor { + private final String hooksClass; + private final String enterMethod; + private final String enterDesc; + private final String exitMethod; + private final int argIndex; + private final Label tryStart = new Label(); + private final Label tryEnd = new Label(); + private final Label catchHandler = new Label(); + + TryFinallyRouteVisitor( + MethodVisitor mv, + String hooksClass, + String enterMethod, + String enterDesc, + String exitMethod, + int argIndex) { + super(ASM_API, mv); + this.hooksClass = hooksClass; + this.enterMethod = enterMethod; + this.enterDesc = enterDesc; + this.exitMethod = exitMethod; + this.argIndex = argIndex; + } + + @Override + public void visitCode() { + super.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, argIndex); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, hooksClass, enterMethod, enterDesc, false); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + mv.visitLabel(tryStart); + } + + @Override + public void visitInsn(int opcode) { + if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) { + mv.visitMethodInsn(Opcodes.INVOKESTATIC, hooksClass, exitMethod, "()V", false); + } + super.visitInsn(opcode); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + mv.visitLabel(tryEnd); + mv.visitLabel(catchHandler); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, hooksClass, exitMethod, "()V", false); + mv.visitInsn(Opcodes.ATHROW); + super.visitMaxs(maxStack, maxLocals); + } + } + + private static final class JaxRsMethodVisitor extends MethodVisitor { + private static final Map HTTP_ANNOTATIONS = new HashMap(); + static { + String[] verbs = {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}; + for (String v : verbs) { + HTTP_ANNOTATIONS.put("Ljavax/ws/rs/" + v + ";", v); + HTTP_ANNOTATIONS.put("Ljakarta/ws/rs/" + v + ";", v); + } + } + + private final String classPath; + private final boolean isInstance; + private final ProbingClassVisitor owner; + private String methodPath; + private String httpMethod; + private boolean isEndpoint = false; + private final Label tryStart = new Label(); + private final Label tryEnd = new Label(); + private final Label catchHandler = new Label(); + + JaxRsMethodVisitor(MethodVisitor mv, String classPath, boolean isInstance, ProbingClassVisitor owner) { + super(ASM_API, mv); + this.classPath = classPath; + this.isInstance = isInstance; + this.owner = owner; + } + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + AnnotationVisitor av = super.visitAnnotation(descriptor, visible); + String verb = HTTP_ANNOTATIONS.get(descriptor); + if (verb != null) { + this.httpMethod = verb; + this.isEndpoint = true; + return av; + } + if ("Ljavax/ws/rs/Path;".equals(descriptor) || "Ljakarta/ws/rs/Path;".equals(descriptor)) { + this.isEndpoint = true; + return new AnnotationVisitor(ASM_API, av) { + @Override + public void visit(String name, Object value) { + if ("value".equals(name) && value instanceof String) { + methodPath = (String) value; + } + super.visit(name, value); + } + }; + } + return av; + } + + @Override + public void visitCode() { + super.visitCode(); + if (!isEndpoint) { + return; + } + owner.modified = true; + if (isInstance) { + mv.visitVarInsn(Opcodes.ALOAD, 0); + } else { + mv.visitInsn(Opcodes.ACONST_NULL); + } + pushStringOrNull(mv, httpMethod); + pushStringOrNull(mv, classPath); + pushStringOrNull(mv, methodPath); + mv.visitMethodInsn( + Opcodes.INVOKESTATIC, + HOOKS_INTERNAL, + "enterJaxRs", + "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", + false); + mv.visitTryCatchBlock(tryStart, tryEnd, catchHandler, null); + mv.visitLabel(tryStart); + } + + @Override + public void visitInsn(int opcode) { + if (isEndpoint && ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW)) { + mv.visitMethodInsn(Opcodes.INVOKESTATIC, HOOKS_INTERNAL, "exitJaxRs", "()V", false); + } + super.visitInsn(opcode); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + if (isEndpoint) { + mv.visitLabel(tryEnd); + mv.visitLabel(catchHandler); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, HOOKS_INTERNAL, "exitJaxRs", "()V", false); + mv.visitInsn(Opcodes.ATHROW); + } + super.visitMaxs(maxStack, maxLocals); + } + } + + private static void pushInt(MethodVisitor mv, int value) { + if (value >= -1 && value <= 5) { + mv.visitInsn(Opcodes.ICONST_0 + value); + } else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + mv.visitIntInsn(Opcodes.BIPUSH, value); + } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { + mv.visitIntInsn(Opcodes.SIPUSH, value); + } else { + mv.visitLdcInsn(value); + } + } + + private static void pushStringOrNull(MethodVisitor mv, String value) { + if (value == null) { + mv.visitInsn(Opcodes.ACONST_NULL); + } else { + mv.visitLdcInsn(value); + } + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/Transport.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/Transport.java new file mode 100644 index 0000000..320e974 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/Transport.java @@ -0,0 +1,511 @@ +package com.secfoo.probe; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.lang.management.ManagementFactory; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.URI; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.zip.GZIPOutputStream; + +/** + * #73 protocol transport client for the JVM probe. + * Supports tcp:// (loopback only), unix://, npipe://, file://, https:// (direct mode), + * and SECFOO_EVENTS_OUT fallback. Never throws into caller code. + */ +public abstract class Transport { + public static final int PROTOCOL_VERSION = 1; + public static final int SOCKET_TIMEOUT_MS = 1000; + public static final int DIRECT_TIMEOUT_MS = 200; + public static final int MAX_LINE_BYTES = 64 * 1024; + + public interface ControlListener { + void onWelcome(double flushIntervalSeconds); + void onSlow(int sampleEvery); + } + + public abstract boolean send(List> events, ControlListener listener); + + public abstract void close(); + + public static Transport fromConfig(ProbeConfig config) { + String addr = config.sensorAddr; + if (addr == null || addr.isEmpty()) { + if (config.eventsOut != null && !config.eventsOut.isEmpty()) { + return new FileTransport(config.eventsOut); + } + String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT); + if (os.contains("win")) { + addr = "npipe:////./pipe/secfoo-sensor"; + } else { + addr = "unix:///var/run/secfoo/sensor.sock"; + } + } + if (addr.startsWith("tcp://")) { + return TcpTransport.parse(addr, config.sensorKey); + } + if (addr.startsWith("unix://")) { + return new UnixTransport(addr.substring("unix://".length()), config.sensorKey); + } + if (addr.startsWith("npipe://")) { + return new NamedPipeTransport(addr.substring("npipe://".length())); + } + if (addr.startsWith("file://")) { + return new FileTransport(addr.substring("file://".length())); + } + if (addr.startsWith("https://")) { + return new DirectHttpsTransport(addr, config); + } + throw new IllegalArgumentException("Unsupported SECFOO_SENSOR_ADDR scheme: " + addr); + } + + public static Map buildHello() { + Map hello = new LinkedHashMap(); + hello.put("type", "hello"); + hello.put("protocol", PROTOCOL_VERSION); + hello.put("runtime", "jvm"); + hello.put("runtime_version", System.getProperty("java.version", "unknown")); + hello.put("probe_version", ProbeConfig.PROBE_VERSION); + hello.put("pid", currentPid()); + hello.put("host", resolveHostname()); + return hello; + } + + static byte[] encodeLines(List> messages) { + StringBuilder sb = new StringBuilder(messages.size() * 192); + for (Map msg : messages) { + String line = MiniJson.stringify(msg); + if (line.getBytes(StandardCharsets.UTF_8).length >= MAX_LINE_BYTES) { + continue; + } + sb.append(line).append('\n'); + } + return sb.toString().getBytes(StandardCharsets.UTF_8); + } + + static long currentPid() { + String jvmName = ManagementFactory.getRuntimeMXBean().getName(); + int at = jvmName.indexOf('@'); + if (at > 0) { + try { + long pid = Long.parseLong(jvmName.substring(0, at)); + if (pid > 0) { + return pid; + } + } catch (NumberFormatException ignored) { + // fall back + } + } + return 1L; + } + + static String resolveHostname() { + String envHost = System.getenv("HOSTNAME"); + if (envHost != null && !envHost.trim().isEmpty()) { + return envHost.trim(); + } + try { + String host = InetAddress.getLocalHost().getHostName(); + if (host != null && !host.trim().isEmpty()) { + return host.trim(); + } + } catch (Exception ignored) { + // fall back + } + return "localhost"; + } + + static void dispatchControlLine(String line, ControlListener listener) { + if (listener == null || line == null || line.trim().isEmpty()) { + return; + } + try { + Map msg = MiniJson.parseObject(line.trim()); + Object type = msg.get("type"); + if ("welcome".equals(type)) { + Object interval = msg.get("flush_interval"); + if (interval instanceof Number) { + listener.onWelcome(ProbeConfig.clampFlushSeconds(((Number) interval).doubleValue())); + } + } else if ("slow".equals(type)) { + Object factor = msg.get("sample_every"); + if (factor instanceof Number) { + int n = ((Number) factor).intValue(); + if (n >= 1) { + listener.onSlow(n); + } + } + } + } catch (RuntimeException ignored) { + // ignore malformed control line + } + } + + // ---------- file:// and SECFOO_EVENTS_OUT ---------- + + public static final class FileTransport extends Transport { + private final Path path; + + public FileTransport(String rawPath) { + String expanded = rawPath.replace("{pid}", String.valueOf(currentPid())); + if (expanded.startsWith("/") && expanded.length() > 2 && expanded.charAt(2) == ':' + && System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) { + // Strip leading slash from file:///C:/... on Windows + expanded = expanded.substring(1); + } + this.path = Paths.get(expanded); + } + + @Override + public synchronized boolean send(List> events, ControlListener listener) { + if (events.isEmpty()) { + return true; + } + try { + Path parent = path.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + byte[] bytes = encodeLines(events); + Files.write(path, bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE); + return true; + } catch (IOException e) { + return false; + } + } + + @Override + public void close() {} + } + + // ---------- tcp:// (loopback only) ---------- + + public static final class TcpTransport extends Transport { + private final String host; + private final int port; + private final String sensorKey; + private Socket socket; + private OutputStream out; + private InputStream in; + private final ByteArrayOutputStream readBuf = new ByteArrayOutputStream(); + + TcpTransport(String host, int port, String sensorKey) { + this.host = host; + this.port = port; + this.sensorKey = sensorKey; + } + + static TcpTransport parse(String addr, String sensorKey) { + URI uri = URI.create(addr); + String host = uri.getHost(); + int port = uri.getPort(); + if (host == null || host.isEmpty() || port <= 0 || port > 65535) { + throw new IllegalArgumentException("Invalid tcp:// address: " + addr); + } + try { + InetAddress resolved = InetAddress.getByName(host); + if (!resolved.isLoopbackAddress()) { + throw new IllegalArgumentException( + "SECFOO_SENSOR_ADDR tcp:// must target a loopback address, got: " + host); + } + } catch (IOException e) { + throw new IllegalArgumentException("Cannot resolve tcp:// loopback host: " + host, e); + } + return new TcpTransport(host, port, sensorKey); + } + + @Override + public synchronized boolean send(List> events, ControlListener listener) { + try { + boolean fresh = false; + if (socket == null || socket.isClosed()) { + connect(); + fresh = true; + } + if (fresh) { + out.write(encodeLines(java.util.Collections.singletonList(buildHello()))); + if (sensorKey != null && !sensorKey.isEmpty()) { + Map auth = new LinkedHashMap(); + auth.put("type", "auth"); + auth.put("key", sensorKey); + out.write(encodeLines(java.util.Collections.singletonList(auth))); + } + out.flush(); + } + if (!events.isEmpty()) { + out.write(encodeLines(events)); + out.flush(); + } + drainControlLines(listener, fresh ? 100 : 0); + return true; + } catch (IOException e) { + close(); + return false; + } + } + + private void connect() throws IOException { + Socket s = new Socket(); + s.connect(new InetSocketAddress(host, port), SOCKET_TIMEOUT_MS); + s.setSoTimeout(SOCKET_TIMEOUT_MS); + s.setTcpNoDelay(true); + this.socket = s; + this.out = s.getOutputStream(); + this.in = s.getInputStream(); + this.readBuf.reset(); + } + + private void drainControlLines(ControlListener listener, int briefWaitMs) throws IOException { + if (in == null) { + return; + } + if (briefWaitMs > 0 && in.available() == 0) { + long deadline = System.currentTimeMillis() + briefWaitMs; + while (in.available() == 0 && System.currentTimeMillis() < deadline) { + try { + Thread.sleep(10L); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + break; + } + } + } + while (in.available() > 0) { + int avail = Math.min(in.available(), 4096); + byte[] chunk = new byte[avail]; + int n = in.read(chunk); + if (n <= 0) { + break; + } + for (int i = 0; i < n; i++) { + byte b = chunk[i]; + if (b == '\n') { + String line = new String(readBuf.toByteArray(), StandardCharsets.UTF_8); + readBuf.reset(); + dispatchControlLine(line, listener); + } else if (readBuf.size() < MAX_LINE_BYTES) { + readBuf.write(b); + } + } + } + } + + @Override + public synchronized void close() { + if (socket != null) { + try { + socket.close(); + } catch (IOException ignored) { + // ignore + } + socket = null; + out = null; + in = null; + } + } + } + + // ---------- unix:// (Java 16+ UnixDomainSocketAddress via reflection for Java 8 bytecode) ---------- + + public static final class UnixTransport extends Transport { + private final String socketPath; + private final String sensorKey; + private SocketChannel channel; + + public UnixTransport(String socketPath, String sensorKey) { + this.socketPath = socketPath; + this.sensorKey = sensorKey; + } + + @Override + public synchronized boolean send(List> events, ControlListener listener) { + try { + boolean fresh = false; + if (channel == null || !channel.isOpen()) { + openChannel(); + fresh = true; + } + if (fresh) { + writeAll(encodeLines(java.util.Collections.singletonList(buildHello()))); + if (sensorKey != null && !sensorKey.isEmpty()) { + Map auth = new LinkedHashMap(); + auth.put("type", "auth"); + auth.put("key", sensorKey); + writeAll(encodeLines(java.util.Collections.singletonList(auth))); + } + } + if (!events.isEmpty()) { + writeAll(encodeLines(events)); + } + return true; + } catch (Throwable e) { + close(); + return false; + } + } + + private void openChannel() throws Exception { + Class addrClass = Class.forName("java.net.UnixDomainSocketAddress"); + Method ofMethod = addrClass.getMethod("of", String.class); + SocketAddress addr = (SocketAddress) ofMethod.invoke(null, socketPath); + SocketChannel ch = SocketChannel.open(addr); + ch.configureBlocking(true); + this.channel = ch; + } + + private void writeAll(byte[] data) throws IOException { + ByteBuffer buf = ByteBuffer.wrap(data); + while (buf.hasRemaining()) { + channel.write(buf); + } + } + + @Override + public synchronized void close() { + if (channel != null) { + try { + channel.close(); + } catch (IOException ignored) { + // ignore + } + channel = null; + } + } + } + + // ---------- npipe:// (Windows named pipe) ---------- + + public static final class NamedPipeTransport extends Transport { + private final String pipePath; + private RandomAccessFile pipe; + + public NamedPipeTransport(String rawPath) { + this.pipePath = rawPath.replace('/', '\\'); + } + + @Override + public synchronized boolean send(List> events, ControlListener listener) { + try { + boolean fresh = false; + if (pipe == null) { + pipe = new RandomAccessFile(pipePath, "rw"); + fresh = true; + } + if (fresh) { + pipe.write(encodeLines(java.util.Collections.singletonList(buildHello()))); + } + if (!events.isEmpty()) { + pipe.write(encodeLines(events)); + } + return true; + } catch (IOException e) { + close(); + return false; + } + } + + @Override + public synchronized void close() { + if (pipe != null) { + try { + pipe.close(); + } catch (IOException ignored) { + // ignore + } + pipe = null; + } + } + } + + // ---------- https:// (direct mode, gzipped NDJSON, hard 200ms timeout) ---------- + + public static final class DirectHttpsTransport extends Transport { + private final String endpointUrl; + private final String apiKey; + + public DirectHttpsTransport(String baseUrl, ProbeConfig config) { + String trimmed = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + this.endpointUrl = trimmed + "/api/runtime/v1/events" + + "?project=" + urlEncode(config.project) + + "&app=" + urlEncode(config.app) + + "&env=" + urlEncode(config.env); + this.apiKey = config.apiKey; + } + + @Override + public boolean send(List> events, ControlListener listener) { + if (events.isEmpty() || apiKey == null || apiKey.isEmpty()) { + return false; + } + HttpURLConnection conn = null; + try { + byte[] plain = encodeLines(events); + ByteArrayOutputStream gzOut = new ByteArrayOutputStream(plain.length); + GZIPOutputStream gz = new GZIPOutputStream(gzOut); + try { + gz.write(plain); + } finally { + gz.close(); + } + byte[] body = gzOut.toByteArray(); + + conn = (HttpURLConnection) new URL(endpointUrl).openConnection(); + conn.setRequestMethod("POST"); + conn.setConnectTimeout(DIRECT_TIMEOUT_MS); + conn.setReadTimeout(DIRECT_TIMEOUT_MS); + conn.setDoOutput(true); + conn.setRequestProperty("Content-Type", "application/x-ndjson"); + conn.setRequestProperty("Content-Encoding", "gzip"); + conn.setRequestProperty("Authorization", "Bearer " + apiKey); + OutputStream os = conn.getOutputStream(); + try { + os.write(body); + } finally { + os.close(); + } + int code = conn.getResponseCode(); + return code >= 200 && code < 300; + } catch (IOException e) { + return false; + } finally { + if (conn != null) { + conn.disconnect(); + } + } + } + + @Override + public void close() {} + + private static String urlEncode(String val) { + if (val == null) { + return ""; + } + try { + return URLEncoder.encode(val, "UTF-8"); + } catch (IOException e) { + return ""; + } + } + } +} diff --git a/jvm/secfoo-agent/src/main/java/com/secfoo/probe/WatchlistManager.java b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/WatchlistManager.java new file mode 100644 index 0000000..fa92708 --- /dev/null +++ b/jvm/secfoo-agent/src/main/java/com/secfoo/probe/WatchlistManager.java @@ -0,0 +1,241 @@ +package com.secfoo.probe; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Loads and reloads #52 watchlists in Maven notation (`pkg.Class#method`). + * Supports Java, Kotlin, and Scala class/method names including inner classes ($), + * constructors (), and optional JVM descriptors. + */ +public final class WatchlistManager { + private static final Pattern MAVEN_SYMBOL = + Pattern.compile("^([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)#([A-Za-z_$<][\\w$>]*)(\\(.*\\))?$"); + + public static final class WatchedSymbol { + public final int id; + public final String symbol; + public final String classInternalName; + public final String methodName; + public final String methodDescriptor; // optional + public final List fingerprints; + + WatchedSymbol( + int id, + String symbol, + String classInternalName, + String methodName, + String methodDescriptor, + List fingerprints) { + this.id = id; + this.symbol = symbol; + this.classInternalName = classInternalName; + this.methodName = methodName; + this.methodDescriptor = methodDescriptor; + this.fingerprints = Collections.unmodifiableList(fingerprints); + } + } + + public static final class Snapshot { + public final List byId; + public final Map>> byClassAndMethod; + + Snapshot(List byId, Map>> byClassAndMethod) { + this.byId = Collections.unmodifiableList(byId); + this.byClassAndMethod = Collections.unmodifiableMap(byClassAndMethod); + } + + public boolean isWatchedClass(String internalName) { + return byClassAndMethod.containsKey(internalName); + } + + public List matchMethod(String internalName, String methodName, String descriptor) { + Map> methods = byClassAndMethod.get(internalName); + if (methods == null) { + return Collections.emptyList(); + } + List candidates = methods.get(methodName); + if (candidates == null || candidates.isEmpty()) { + return Collections.emptyList(); + } + List matched = new ArrayList(candidates.size()); + for (WatchedSymbol sym : candidates) { + if (sym.methodDescriptor == null || sym.methodDescriptor.equals(descriptor)) { + matched.add(sym); + } + } + return matched; + } + } + + private final Path watchlistPath; + private final long recheckMs; + private volatile long lastMtime = Long.MIN_VALUE; + private volatile long lastCheckedMs = 0L; + private volatile Snapshot snapshot = new Snapshot( + Collections.emptyList(), + Collections.>>emptyMap()); + + // Preserve assigned symbol IDs across hot reloads so active LongAdders stay valid. + private final Map symbolIds = new HashMap(); + private final List idTable = new ArrayList(); + + public WatchlistManager(String path) { + this(path, ProbeConfig.WATCHLIST_RECHECK_MS); + } + + public WatchlistManager(String path, long recheckMs) { + this.watchlistPath = (path != null && !path.trim().isEmpty()) ? Paths.get(path.trim()) : null; + this.recheckMs = Math.max(50L, recheckMs); + } + + public Snapshot current() { + return snapshot; + } + + public WatchedSymbol byId(int id) { + Snapshot s = snapshot; + return (id >= 0 && id < s.byId.size()) ? s.byId.get(id) : null; + } + + /** + * Reloads the watchlist if its mtime changed (checked at most every 30s unless forced). + * Returns newly added internal class names that may require Instrumentation.retransformClasses. + */ + public synchronized Set reloadIfNeeded(boolean force) { + if (watchlistPath == null) { + return Collections.emptySet(); + } + long now = System.currentTimeMillis(); + if (!force && (now - lastCheckedMs) < recheckMs) { + return Collections.emptySet(); + } + lastCheckedMs = now; + try { + if (!Files.isRegularFile(watchlistPath)) { + return Collections.emptySet(); + } + long mtime = Files.getLastModifiedTime(watchlistPath).toMillis(); + if (!force && mtime == lastMtime) { + return Collections.emptySet(); + } + String content = new String(Files.readAllBytes(watchlistPath), StandardCharsets.UTF_8); + Snapshot next = parseWatchlist(content); + Set prevClasses = snapshot.byClassAndMethod.keySet(); + Set added = new HashSet(); + for (String cls : next.byClassAndMethod.keySet()) { + if (!prevClasses.contains(cls)) { + added.add(cls); + } + } + snapshot = next; + lastMtime = mtime; + return added; + } catch (IOException | RuntimeException ignored) { + // Fail-open: malformed or missing watchlist never disrupts the app + return Collections.emptySet(); + } + } + + @SuppressWarnings("unchecked") + private Snapshot parseWatchlist(String jsonText) { + Map root = MiniJson.parseObject(jsonText); + Object entriesObj = root.get("entries"); + if (!(entriesObj instanceof List)) { + return snapshot; + } + Map> symbolToFingerprints = new HashMap>(); + for (Object itemObj : (List) entriesObj) { + if (!(itemObj instanceof Map)) { + continue; + } + Map entry = (Map) itemObj; + String ecosystem = asString(entry.get("ecosystem")); + if (ecosystem != null && !ecosystem.isEmpty() && !"Maven".equalsIgnoreCase(ecosystem)) { + continue; + } + String fp = asString(entry.get("finding_fingerprint")); + if (fp == null || fp.isEmpty()) { + continue; + } + Object symbolsObj = entry.get("symbols"); + if (!(symbolsObj instanceof List)) { + continue; + } + for (Object symObj : (List) symbolsObj) { + String sym = asString(symObj); + if (sym == null) { + continue; + } + Matcher m = MAVEN_SYMBOL.matcher(sym.trim()); + if (!m.matches()) { + continue; + } + Set fps = symbolToFingerprints.get(sym.trim()); + if (fps == null) { + fps = new HashSet(); + symbolToFingerprints.put(sym.trim(), fps); + } + fps.add(fp); + } + } + + Map>> byClass = + new HashMap>>(); + for (Map.Entry> e : symbolToFingerprints.entrySet()) { + String sym = e.getKey(); + Matcher m = MAVEN_SYMBOL.matcher(sym); + if (!m.matches()) { + continue; + } + String internalClass = m.group(1).replace('.', '/'); + String methodName = m.group(2); + String desc = m.group(3); + List fps = new ArrayList(e.getValue()); + Collections.sort(fps); + + Integer idObj = symbolIds.get(sym); + int id; + WatchedSymbol ws; + if (idObj == null) { + id = idTable.size(); + ws = new WatchedSymbol(id, sym, internalClass, methodName, desc, fps); + symbolIds.put(sym, id); + idTable.add(ws); + } else { + id = idObj.intValue(); + ws = new WatchedSymbol(id, sym, internalClass, methodName, desc, fps); + idTable.set(id, ws); + } + + Map> methods = byClass.get(internalClass); + if (methods == null) { + methods = new HashMap>(); + byClass.put(internalClass, methods); + } + List list = methods.get(methodName); + if (list == null) { + list = new ArrayList(1); + methods.put(methodName, list); + } + list.add(ws); + } + return new Snapshot(new ArrayList(idTable), byClass); + } + + private static String asString(Object obj) { + return obj instanceof String ? (String) obj : null; + } +} diff --git a/jvm/secfoo-agent/src/test/java/com/secfoo/probe/ProbeCoreTest.java b/jvm/secfoo-agent/src/test/java/com/secfoo/probe/ProbeCoreTest.java new file mode 100644 index 0000000..a7afb2e --- /dev/null +++ b/jvm/secfoo-agent/src/test/java/com/secfoo/probe/ProbeCoreTest.java @@ -0,0 +1,154 @@ +package com.secfoo.probe; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +import static org.junit.jupiter.api.Assertions.*; + +class ProbeCoreTest { + + @Test + void ruleZeroInertWithoutSecfooSensor(@TempDir Path tmp) { + ProbeConfig disabled = ProbeConfig.fromMap(Collections.emptyMap(), null); + assertFalse(disabled.enabled); + + ProbeConfig enabled = ProbeConfig.fromMap( + Collections.singletonMap("SECFOO_SENSOR", "1"), null); + assertTrue(enabled.enabled); + } + + @Test + void loopbackRequiredForTcpTransport() { + ProbeConfig bad = ProbeConfig.fromMap( + new java.util.HashMap() {{ + put("SECFOO_SENSOR", "1"); + put("SECFOO_SENSOR_ADDR", "tcp://8.8.8.8:7461"); + }}, + null); + assertThrows(IllegalArgumentException.class, () -> Transport.fromConfig(bad)); + + ProbeConfig good = ProbeConfig.fromMap( + new java.util.HashMap() {{ + put("SECFOO_SENSOR", "1"); + put("SECFOO_SENSOR_ADDR", "tcp://127.0.0.1:7461"); + }}, + null); + assertTrue(Transport.fromConfig(good) instanceof Transport.TcpTransport); + } + + @Test + void routeSanitizationAndPrivacy() { + assertEquals("GET /users/{id}", RouteContext.sanitizeRouteTemplate("get", "/users/{id}")); + assertEquals("POST /users/{id}", RouteContext.sanitizeRouteTemplate("POST", "/users//")); + assertEquals("GET /items/{itemId}", RouteContext.sanitizeRouteTemplate("GET", "/items/:itemId")); + assertEquals("unknown", RouteContext.sanitizeRouteTemplate("GET", "/users/8675309?token=secret")); + assertEquals("unknown", RouteContext.sanitizeRouteTemplate("GET", "https://evil.example/users/1")); + assertEquals("unknown", RouteContext.sanitizeRouteTemplate("GET", "/users/1#frag")); + assertEquals("unknown", RouteContext.sanitizeRouteTemplate("GET", "/a b")); + + assertTrue(RouteContext.hasSessionCookieInHeader("theme=dark; JSESSIONID=xyz123")); + assertFalse(RouteContext.hasSessionCookieInHeader("theme=dark; lang=en")); + } + + @Test + void watchlistParsesMavenNotationAndHotReloads(@TempDir Path tmp) throws IOException { + Path wlPath = tmp.resolve("watchlist.json"); + String json = "{\"version\":1,\"generated_at\":\"2026-12-03T00:00:00Z\",\"entries\":[" + + "{\"finding_fingerprint\":\"fp-log4j\",\"ecosystem\":\"Maven\"," + + "\"package\":\"org.apache.logging.log4j:log4j-core\",\"version\":\"2.14.1\"," + + "\"granularity\":\"symbol\",\"symbols\":[\"org.apache.logging.log4j.core.lookup.JndiLookup#lookup\"]}" + + "]}"; + java.nio.file.Files.write(wlPath, json.getBytes(StandardCharsets.UTF_8)); + + WatchlistManager manager = new WatchlistManager(wlPath.toString()); + java.util.Set initial = manager.reloadIfNeeded(true); + assertTrue(initial.contains("org/apache/logging/log4j/core/lookup/JndiLookup")); + + WatchlistManager.Snapshot snap = manager.current(); + assertTrue(snap.isWatchedClass("org/apache/logging/log4j/core/lookup/JndiLookup")); + List matched = snap.matchMethod( + "org/apache/logging/log4j/core/lookup/JndiLookup", "lookup", "(Ljava/lang/String;)Ljava/lang/String;"); + assertEquals(1, matched.size()); + assertEquals("fp-log4j", matched.get(0).fingerprints.get(0)); + } + + @Test + void inventoryExtractsRegularBootInfWebInfAndShadedJars(@TempDir Path tmp) throws IOException { + // 1. Standard Maven JAR + File regularJar = tmp.resolve("log4j-core-2.14.1.jar").toFile(); + writeMavenJar(regularJar, "org.apache.logging.log4j", "log4j-core", "2.14.1"); + List reg = InventoryExtractor.inspectLocation( + regularJar.toURI().toURL(), "org/apache/logging/log4j/core/lookup/JndiLookup"); + assertEquals(1, reg.size()); + assertEquals("org.apache.logging.log4j:log4j-core", reg.get(0).packageName); + assertEquals("2.14.1", reg.get(0).version); + assertFalse(reg.get(0).shaded); + + // 2. Shaded/relocated class inside JAR + List shaded = InventoryExtractor.inspectLocation( + regularJar.toURI().toURL(), "com/example/shaded/org/apache/logging/log4j/JndiLookup"); + assertEquals(1, shaded.size()); + assertTrue(shaded.get(0).shaded); + assertTrue(shaded.get(0).path.contains("[shaded]")); + + // 3. Spring Boot fat JAR with BOOT-INF/lib/*.jar + byte[] nestedBytes = buildMavenJarBytes("com.fasterxml.jackson.core", "jackson-databind", "2.13.0"); + File bootJar = tmp.resolve("app.jar").toFile(); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(bootJar))) { + JarEntry entry = new JarEntry("BOOT-INF/lib/jackson-databind-2.13.0.jar"); + jos.putNextEntry(entry); + jos.write(nestedBytes); + jos.closeEntry(); + } + URL bootUrl = new URL("jar:" + bootJar.toURI().toURL() + "!/BOOT-INF/lib/jackson-databind-2.13.0.jar!/"); + List bootPkgs = InventoryExtractor.inspectLocation( + bootUrl, "com/fasterxml/jackson/databind/ObjectMapper"); + assertEquals(1, bootPkgs.size()); + assertEquals("com.fasterxml.jackson.core:jackson-databind", bootPkgs.get(0).packageName); + assertEquals("2.13.0", bootPkgs.get(0).version); + + // 4. WAR archive with WEB-INF/lib/*.jar + File warFile = tmp.resolve("app.war").toFile(); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(warFile))) { + JarEntry entry = new JarEntry("WEB-INF/lib/jackson-databind-2.13.0.jar"); + jos.putNextEntry(entry); + jos.write(nestedBytes); + jos.closeEntry(); + } + URL warUrl = new URL("jar:" + warFile.toURI().toURL() + "!/WEB-INF/lib/jackson-databind-2.13.0.jar!/"); + List warPkgs = InventoryExtractor.inspectLocation( + warUrl, "com/fasterxml/jackson/databind/ObjectMapper"); + assertEquals(1, warPkgs.size()); + assertEquals("com.fasterxml.jackson.core:jackson-databind", warPkgs.get(0).packageName); + } + + private static void writeMavenJar(File target, String groupId, String artifactId, String version) throws IOException { + try (FileOutputStream fos = new FileOutputStream(target)) { + fos.write(buildMavenJarBytes(groupId, artifactId, version)); + } + } + + private static byte[] buildMavenJarBytes(String groupId, String artifactId, String version) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (JarOutputStream jos = new JarOutputStream(baos)) { + String path = "META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties"; + jos.putNextEntry(new JarEntry(path)); + String content = "groupId=" + groupId + "\nartifactId=" + artifactId + "\nversion=" + version + "\n"; + jos.write(content.getBytes(StandardCharsets.UTF_8)); + jos.closeEntry(); + } + return baos.toByteArray(); + } +} diff --git a/jvm/secfoo-agent/src/test/java/com/secfoo/probe/RouteAndTransformTest.java b/jvm/secfoo-agent/src/test/java/com/secfoo/probe/RouteAndTransformTest.java new file mode 100644 index 0000000..93b3d22 --- /dev/null +++ b/jvm/secfoo-agent/src/test/java/com/secfoo/probe/RouteAndTransformTest.java @@ -0,0 +1,252 @@ +package com.secfoo.probe; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.Principal; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.junit.jupiter.api.Assertions.*; + +class RouteAndTransformTest { + + // Minimal fake ServletRequest / WebFlux ServerWebExchange / JAX-RS ContainerRequestContext + public static final class FakeServletRequest { + private final String method; + private final Map attrs; + private final Map headers; + private final Principal principal; + + FakeServletRequest(String method, Map attrs, Map headers, Principal principal) { + this.method = method; + this.attrs = attrs; + this.headers = headers; + this.principal = principal; + } + + public String getMethod() { return method; } + public Object getAttribute(String name) { return attrs.get(name); } + public String getHeader(String name) { return headers.get(name); } + public Principal getUserPrincipal() { return principal; } + public String getServletPath() { return "/users/8675309"; } + public Object[] getCookies() { return null; } + } + + public static final class FakeWebFluxExchange { + private final FakeReactiveRequest request; + private final Map attributes; + + FakeWebFluxExchange(FakeReactiveRequest request, Map attributes) { + this.request = request; + this.attributes = attributes; + } + + public FakeReactiveRequest getRequest() { return request; } + public Map getAttributes() { return attributes; } + } + + public static final class FakeReactiveRequest { + private final String method; + private final FakeHttpHeaders headers; + + FakeReactiveRequest(String method, FakeHttpHeaders headers) { + this.method = method; + this.headers = headers; + } + + public String getMethodValue() { return method; } + public FakeHttpHeaders getHeaders() { return headers; } + } + + public static final class FakeHttpHeaders { + private final Map map; + + FakeHttpHeaders(Map map) { this.map = map; } + + public String getFirst(String name) { return map.get(name); } + } + + public static final class FakeUriInfo { + private final List templates; + + FakeUriInfo(List templates) { this.templates = templates; } + + public List getMatchedTemplates() { return templates; } + } + + public static final class FakeJaxRsContext { + private final String method; + private final FakeUriInfo uriInfo; + private final Map headers; + + FakeJaxRsContext(String method, FakeUriInfo uriInfo, Map headers) { + this.method = method; + this.uriInfo = uriInfo; + this.headers = headers; + } + + public String getMethod() { return method; } + public FakeUriInfo getUriInfo() { return uriInfo; } + public String getHeaderString(String name) { return headers.get(name); } + } + + @Test + void springMvcBestMatchingPatternAndAuthExtraction() { + Map attrs = Collections.singletonMap( + RouteHooks.SPRING_MVC_PATTERN_ATTR, "/users/{id}"); + Map headers = Collections.singletonMap("Authorization", "Bearer s3cr3t-SENTINEL-73"); + FakeServletRequest req = new FakeServletRequest("GET", attrs, headers, null); + + RouteHooks.enterServlet(req); + try { + RouteContext.Snapshot snap = RouteContext.currentSnapshot(); + assertEquals("GET /users/{id}", snap.route); + assertEquals("authenticated", snap.auth); + } finally { + RouteHooks.exitServlet(); + } + assertNull(RouteContext.peek()); + } + + @Test + void springWebFluxPatternAndAnonymousAuthExtraction() { + FakeHttpHeaders headers = new FakeHttpHeaders(Collections.emptyMap()); + FakeReactiveRequest req = new FakeReactiveRequest("POST", headers); + Map attrs = Collections.singletonMap( + RouteHooks.SPRING_WEBFLUX_PATTERN_ATTR, "/orders/{orderId}"); + FakeWebFluxExchange exchange = new FakeWebFluxExchange(req, attrs); + + RouteHooks.enterWebFlux(exchange); + try { + RouteContext.Snapshot snap = RouteContext.currentSnapshot(); + assertEquals("POST /orders/{orderId}", snap.route); + assertEquals("anonymous", snap.auth); + } finally { + RouteHooks.exitWebFlux(); + } + } + + @Test + void jaxRsMatchedTemplatesExtraction() { + FakeUriInfo uriInfo = new FakeUriInfo(java.util.Arrays.asList("/{id}", "/accounts")); + FakeJaxRsContext ctx = new FakeJaxRsContext( + "DELETE", uriInfo, Collections.singletonMap("Cookie", "JSESSIONID=secret-session")); + + RouteHooks.enterJaxRs(ctx, "DELETE", "/accounts", "/{id}"); + try { + RouteContext.Snapshot snap = RouteContext.currentSnapshot(); + assertEquals("DELETE /accounts/{id}", snap.route); + assertEquals("authenticated", snap.auth); + } finally { + RouteHooks.exitJaxRs(); + } + } + + @Test + void transformerInstrumentsWatchedMethodWithBranchesWithoutLoadingClasses(@TempDir Path tmp) throws Exception { + Path wl = tmp.resolve("watchlist.json"); + String json = "{\"version\":1,\"generated_at\":\"2026-12-03T00:00:00Z\",\"entries\":[{" + + "\"finding_fingerprint\":\"fp-asm\",\"ecosystem\":\"Maven\"," + + "\"package\":\"com.example:demo\",\"version\":\"1.0.0\"," + + "\"granularity\":\"symbol\",\"symbols\":[\"com.example.TargetKt#compute\"]" + + "}]}"; + Files.write(wl, json.getBytes(StandardCharsets.UTF_8)); + + WatchlistManager manager = new WatchlistManager(wl.toString()); + manager.reloadIfNeeded(true); + ProbeConfig cfg = ProbeConfig.fromMap(Collections.emptyMap(), null); + ProbeRuntime rt = new ProbeRuntime(cfg, null, manager, new Transport.FileTransport(tmp.resolve("out.ndjson").toString())); + SecfooTransformer transformer = new SecfooTransformer(manager, rt); + + byte[] original = generateBranchingTargetClass("com/example/TargetKt"); + byte[] transformed = transformer.transform( + getClass().getClassLoader(), "com/example/TargetKt", null, null, original); + assertNotNull(transformed); + + ClassLoader loader = new ClassLoader(getClass().getClassLoader()) { + @Override + protected Class findClass(String name) { + if ("com.example.TargetKt".equals(name)) { + return defineClass(name, transformed, 0, transformed.length); + } + throw new RuntimeException("unexpected class load: " + name); + } + }; + Class cls = loader.loadClass("com.example.TargetKt"); + Method m = cls.getMethod("compute", int.class); + assertEquals(11, ((Integer) m.invoke(null, 10)).intValue()); + assertEquals(0, ((Integer) m.invoke(null, -1)).intValue()); + } + + @Test + void concurrentThreadsKeepIndependentRouteContext() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(4); + try { + Future f1 = pool.submit(new Callable() { + @Override + public String call() throws Exception { + return SecfooContext.callWithRoute("GET", "/a/{id}", "authenticated", new Callable() { + @Override + public String call() throws Exception { + Thread.sleep(20L); + return SecfooContext.currentRoute() + "|" + SecfooContext.currentAuth(); + } + }); + } + }); + Future f2 = pool.submit(new Callable() { + @Override + public String call() throws Exception { + return SecfooContext.callWithRoute("POST", "/b/{id}", "anonymous", new Callable() { + @Override + public String call() throws Exception { + Thread.sleep(20L); + return SecfooContext.currentRoute() + "|" + SecfooContext.currentAuth(); + } + }); + } + }); + assertEquals("GET /a/{id}|authenticated", f1.get()); + assertEquals("POST /b/{id}|anonymous", f2.get()); + } finally { + pool.shutdownNow(); + } + } + + private static byte[] generateBranchingTargetClass(String internalName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, internalName, null, "java/lang/Object", null); + MethodVisitor mv = cw.visitMethod( + Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "compute", "(I)I", null, null); + mv.visitCode(); + Label elseLabel = new Label(); + mv.visitVarInsn(Opcodes.ILOAD, 0); + mv.visitJumpInsn(Opcodes.IFLE, elseLabel); + mv.visitVarInsn(Opcodes.ILOAD, 0); + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IADD); + mv.visitInsn(Opcodes.IRETURN); + mv.visitLabel(elseLabel); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitInsn(Opcodes.IRETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } +} diff --git a/tests/test_sensor/test_jvm_probe.py b/tests/test_sensor/test_jvm_probe.py new file mode 100644 index 0000000..29350bf --- /dev/null +++ b/tests/test_sensor/test_jvm_probe.py @@ -0,0 +1,307 @@ +"""#74: JVM runtime probe (-javaagent) tests and #73 conformance.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess # nosec B404 -- runs JVM conformance and agent tests +import zipfile +from pathlib import Path + +import pytest + +from secfoo.runtime.conformance.kit import run_kit +from secfoo.runtime.evidence import ingest_events +from secfoo.storage.repository import RunRepository + +ROOT = Path(__file__).resolve().parents[2] +JVM_DIR = ROOT / "jvm" / "secfoo-agent" +AGENT_JAR = JVM_DIR / "target" / "secfoo-agent.jar" +CONFORMANCE_SRC = JVM_DIR / "examples" / "conformance-app" / "src" +SERVLET_JAR = JVM_DIR / "examples" / "servlet-sample" / "target" / "servlet-sample.jar" +SPRING_JAR = JVM_DIR / "examples" / "spring-boot-sample" / "target" / "spring-boot-sample.jar" + + +def _find_tool(name: str, env_override: str | None = None) -> str | None: + if env_override: + candidate = os.environ.get(env_override) + if candidate and Path(candidate).is_file(): + return candidate + return shutil.which(name) + + +JAVA_BIN = _find_tool("java") +JAVAC_BIN = _find_tool("javac") +MVN_BIN = _find_tool("mvn", "SECFOO_MAVEN_BIN") + +requires_jdk = pytest.mark.skipif(not (JAVA_BIN and JAVAC_BIN), reason="java/javac not installed on PATH") +requires_maven = pytest.mark.skipif(not (JAVA_BIN and JAVAC_BIN and MVN_BIN), reason="maven/jdk not installed") + + +@pytest.fixture(scope="module") +def built_agent_jar() -> Path: + if AGENT_JAR.is_file() and os.environ.get("SECFOO_JVM_REBUILD") != "1": + return AGENT_JAR + if not MVN_BIN: + pytest.skip("mvn not installed and secfoo-agent.jar not prebuilt") + proc = subprocess.run( # nosec B603 + [MVN_BIN, "-B", "package"], + cwd=JVM_DIR, + capture_output=True, + text=True, + timeout=180, + check=False, + ) + assert proc.returncode == 0, proc.stdout + "\n" + proc.stderr + assert AGENT_JAR.is_file() + return AGENT_JAR + + +@pytest.fixture(scope="module") +def compiled_conformance(tmp_path_factory, built_agent_jar: Path) -> Path: + out_dir = tmp_path_factory.mktemp("jvm-conformance-classes") + sources = [str(p) for p in sorted(CONFORMANCE_SRC.rglob("*.java"))] + proc = subprocess.run( # nosec B603 + [JAVAC_BIN, "-cp", str(built_agent_jar), "-d", str(out_dir), *sources], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert proc.returncode == 0, proc.stdout + "\n" + proc.stderr + return out_dir + + +def _build_second_agent_jar(classes_dir: Path, dest_jar: Path) -> Path: + manifest = "Manifest-Version: 1.0\r\nPremain-Class: com.secfoo.conformance.SecondAgent\r\n\r\n" + class_rel = Path("com/secfoo/conformance/SecondAgent.class") + class_rel_inner = Path("com/secfoo/conformance/SecondAgent$1.class") + with zipfile.ZipFile(dest_jar, "w") as zf: + zf.writestr("META-INF/MANIFEST.MF", manifest) + for rel in (class_rel, class_rel_inner): + full = classes_dir / rel + if full.is_file(): + zf.write(full, rel.as_posix()) + return dest_jar + + +@requires_maven +def test_maven_junit_suite_passes(): + proc = subprocess.run( # nosec B603 + [MVN_BIN, "-B", "test"], + cwd=JVM_DIR, + capture_output=True, + text=True, + timeout=180, + check=False, + ) + assert proc.returncode == 0, proc.stdout + "\n" + proc.stderr + assert "Failures: 0, Errors: 0" in proc.stdout + + +@requires_jdk +def test_jvm_probe_passes_conformance_kit(built_agent_jar: Path, compiled_conformance: Path): + cmd = [ + JAVA_BIN, + f"-javaagent:{built_agent_jar}", + "-cp", + str(compiled_conformance), + "com.secfoo.conformance.ConformanceApp", + ] + results = run_kit( + cmd, + symbol="com.secfoo.conformance.Vulnerable#parse", + ecosystem="Maven", + loop_calls=200_000, + ) + failures = [f"{r.name}: {r.detail}" for r in results if not r.passed] + assert not failures, "\n".join(failures) + + +@requires_jdk +def test_jvm_events_ingest_and_route_attribution(built_agent_jar: Path, compiled_conformance: Path, tmp_path: Path): + watchlist = tmp_path / "watchlist.json" + watchlist.write_text( + json.dumps( + { + "version": 1, + "generated_at": "2026-12-03T00:00:00Z", + "entries": [ + { + "finding_fingerprint": "fp-log4j", + "advisory": "CVE-2021-44228", + "ecosystem": "Maven", + "package": "org.apache.logging.log4j:log4j-core", + "version": "2.14.1", + "granularity": "symbol", + "symbols": ["org.apache.logging.log4j.core.lookup.JndiLookup#lookup"], + "source": "osv", + } + ], + } + ), + encoding="utf-8", + ) + events_file = tmp_path / "events.ndjson" + env = { + **os.environ, + "SECFOO_SENSOR": "1", + "SECFOO_WATCHLIST": str(watchlist), + "SECFOO_EVENTS_OUT": str(events_file), + "SECFOO_CONFORMANCE_STEP": "request", + "SECFOO_CONFORMANCE_SENTINEL": "s3cr3t-SENTINEL-73", + } + env.pop("SECFOO_SENSOR_ADDR", None) + + proc = subprocess.run( # nosec B603 + [ + JAVA_BIN, + f"-javaagent:{built_agent_jar}", + "-cp", + str(compiled_conformance), + "com.secfoo.conformance.ConformanceApp", + ], + env=env, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert proc.returncode == 0, proc.stderr + raw_text = events_file.read_text(encoding="utf-8") + assert "s3cr3t-SENTINEL-73" not in raw_text + assert "/users/8675309" not in raw_text + + lines = [line for line in raw_text.splitlines() if line.strip()] + with RunRepository(db_path=tmp_path / "db.sqlite") as repo: + pid = repo.upsert_project("/app", "jvm-app", "local") + run_id = repo.get_run( + repo.create_run( + project_id=pid, + skill_id="sca-reachability", + skill_name="SCA", + agent_id="claude", + confluence_urls=[], + ) + ).id + repo.upsert_sca_finding( + project_id=pid, + fingerprint="fp-log4j", + run_id=run_id, + current_ref="D1", + package="org.apache.logging.log4j:log4j-core", + severity="Critical", + ) + report = ingest_events(repo.connection, pid, lines) + assert report.skipped == [] + assert report.hits == 1 + row = repo.connection.execute( + "SELECT symbol, route, auth, count FROM runtime_evidence WHERE finding_fingerprint = 'fp-log4j'" + ).fetchone() + assert tuple(row) == ("org.apache.logging.log4j.core.lookup.JndiLookup#lookup", "GET /users/{id}", "authenticated", 1) + + +@requires_jdk +def test_dual_agent_coexistence(built_agent_jar: Path, compiled_conformance: Path, tmp_path: Path): + second_jar = _build_second_agent_jar(compiled_conformance, tmp_path / "second-agent.jar") + watchlist = tmp_path / "watchlist.json" + watchlist.write_text( + json.dumps( + { + "version": 1, + "generated_at": "2026-12-03T00:00:00Z", + "entries": [ + { + "finding_fingerprint": "fp-dual", + "ecosystem": "Maven", + "package": "com.secfoo.conformance:app", + "version": "1.0", + "granularity": "symbol", + "symbols": ["com.secfoo.conformance.Vulnerable#parse"], + } + ], + } + ), + encoding="utf-8", + ) + + for order in ( + [f"-javaagent:{second_jar}", f"-javaagent:{built_agent_jar}"], + [f"-javaagent:{built_agent_jar}", f"-javaagent:{second_jar}"], + ): + events_file = tmp_path / f"events-{len(order)}-{order[0].endswith('second-agent.jar')}.ndjson" + env = { + **os.environ, + "SECFOO_SENSOR": "1", + "SECFOO_WATCHLIST": str(watchlist), + "SECFOO_EVENTS_OUT": str(events_file), + "SECFOO_CONFORMANCE_STEP": "call", + } + env.pop("SECFOO_SENSOR_ADDR", None) + proc = subprocess.run( # nosec B603 + [JAVA_BIN, *order, "-cp", str(compiled_conformance), "com.secfoo.conformance.ConformanceApp"], + env=env, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert proc.returncode == 0, proc.stderr + events = [json.loads(line) for line in events_file.read_text(encoding="utf-8").splitlines() if line.strip()] + hits = [e for e in events if e.get("type") == "hit"] + assert hits and hits[-1]["count"] == 3 + + +@requires_jdk +def test_watchlist_hot_reload_retransforms_loaded_class( + built_agent_jar: Path, compiled_conformance: Path, tmp_path: Path +): + watchlist = tmp_path / "watchlist.json" + watchlist.write_text(json.dumps({"version": 1, "generated_at": "2026-12-03T00:00:00Z", "entries": []}), encoding="utf-8") + events_file = tmp_path / "events.ndjson" + env = { + **os.environ, + "SECFOO_SENSOR": "1", + "SECFOO_WATCHLIST": str(watchlist), + "SECFOO_WATCHLIST_RECHECK_SECONDS": "0.05", + "SECFOO_FLUSH_INTERVAL": "0.05", + "SECFOO_EVENTS_OUT": str(events_file), + } + env.pop("SECFOO_SENSOR_ADDR", None) + + proc = subprocess.run( # nosec B603 + [ + JAVA_BIN, + f"-javaagent:{built_agent_jar}", + "-cp", + str(compiled_conformance), + "com.secfoo.conformance.RetransformApp", + ], + env=env, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert proc.returncode == 0, proc.stderr + assert "retransform ok" in proc.stdout + events = [json.loads(line) for line in events_file.read_text(encoding="utf-8").splitlines() if line.strip()] + hits = [e for e in events if e.get("type") == "hit" and e.get("finding_fingerprint") == "fp-retransform"] + assert hits and hits[-1]["count"] == 2 + + +@requires_jdk +@pytest.mark.parametrize("sample_jar", [SERVLET_JAR, SPRING_JAR], ids=["servlet", "spring-boot"]) +def test_framework_sample_apps_pass_conformance_when_built(built_agent_jar: Path, sample_jar: Path): + if not sample_jar.is_file(): + pytest.skip(f"{sample_jar.name} not built") + cmd = [JAVA_BIN, f"-javaagent:{built_agent_jar}", "-jar", str(sample_jar)] + results = run_kit( + cmd, + symbol="org.apache.logging.log4j.core.lookup.JndiLookup#lookup", + ecosystem="Maven", + loop_calls=200_000, + ) + failures = [f"{r.name}: {r.detail}" for r in results if not r.passed] + assert not failures, "\n".join(failures)