Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
60 changes: 60 additions & 0 deletions docs/JVM_PROBE.md
Original file line number Diff line number Diff line change
@@ -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 `<init>`, 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 |
Original file line number Diff line number Diff line change
@@ -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");
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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");
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
});
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}
50 changes: 50 additions & 0 deletions jvm/secfoo-agent/examples/servlet-sample/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.secfoo.examples</groupId>
<artifactId>servlet-sample</artifactId>
<version>0.1.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<jetty.version>11.0.24</jetty.version>
</properties>

<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>servlet-sample</finalName>
<createDependencyReducedPom>false</createDependencyReducedPom>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.secfoo.examples.servlet.ServletSampleApp</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Loading