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
310 changes: 300 additions & 10 deletions keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
package io.keploy.dedup;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.net.URI;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -184,10 +188,27 @@ final class ServerEntries implements ClassFileTransformer {
// only when an async response invokes suspend() or setSuspendTimeout().
addLatchOnCall("org/glassfish/jersey/server/internal/JerseyRequestTimeoutHandler",
"jersey-async-timeout", "suspend", "setSuspendTimeout");
// - logback-classic ConfigurationAction (1.2.x) and
// ConfigurationModelHandlerFull (1.3.x-1.5.x): loaded whenever an app
// configures Logback via XML (logback.xml / logback-spring.xml), even
// without scan="true". Both unconditionally enter processScanAttrib /
// detachedPostProcess and return early unless scan is enabled, so hook
// their dispatch call sites (ScheduledExecutorService.scheduleAtFixedRate,
// etc.) instead of method entry: XML configs without scan stay clean,
// while scan="true" latches asyncExecutors=false the moment the reload
// task is actually scheduled.
addLatchOnDispatchCall("ch/qos/logback/classic/joran/action/ConfigurationAction",
"logback-scan-reload");
addLatchOnDispatchCall("ch/qos/logback/classic/model/processor/ConfigurationModelHandlerFull",
"logback-scan-reload");
}

private static void addLatchOnCall(String className, String label, String... methods) {
LATCH_ON_CALL.put(className, new LatchEntry(label, new HashSet<>(Arrays.asList(methods))));
LATCH_ON_CALL.put(className, new LatchEntry(label, new HashSet<>(Arrays.asList(methods)), false));
}

private static void addLatchOnDispatchCall(String className, String label) {
LATCH_ON_CALL.put(className, new LatchEntry(label, Collections.<String>emptySet(), true));
}

// Server-owned executor/scheduler sinks whose internal queues bypass JDK
Expand Down Expand Up @@ -593,16 +614,51 @@ private static Map<String, Set<String>> buildDispatchPrimitiveMethods() {
"org/springframework/util/ConcurrentLruCache",
// Logback (logback-core, AsyncAppenderBase.java): Dropwizard's default
// async logging wrapper; Worker.run() drains BlockingQueue<E> of logging
// events into AppenderAttachableImpl.appendLoopOnAppenders only (same
// logging-only sink category as Tomcat AsyncFileHandler$LoggerExecutorService
// and Jetty AsyncRequestLogWriter$WriterThread).
// events into AppenderAttachableImpl.appendLoopOnAppenders only. Safe to
// allowlist ONLY when no app-included class extends or implements any
// ch/qos/logback/ type (appender, encoder, layout, converter, filter,
// discriminator, ...) — otherwise inspectLogbackAsyncExtension fails
// closed on asyncExecutors=false.
"ch/qos/logback/core/AsyncAppenderBase",
"ch/qos/logback/core/AsyncAppenderBase$Worker")));

static Set<String> allowlistedDispatchClasses() {
return ALLOWLISTED_DISPATCH_CLASSES;
}

private static final String LOGBACK_ASYNC_APPENDER_BASE = "ch/qos/logback/core/AsyncAppenderBase";
private static final String LOGBACK_ASYNC_APPENDER_WORKER = "ch/qos/logback/core/AsyncAppenderBase$Worker";
private static final String LOGBACK_CLASSIC_ASYNC_APPENDER = "ch/qos/logback/classic/AsyncAppender";

// Logback plugin types reach AsyncAppenderBase$Worker through
// AppenderAttachableImpl.appendLoopOnAppenders(): appenders, encoders,
// layouts, converters, filters, evaluators, discriminators (SiftingAppender),
// throwable renderers, status listeners, rolling/triggering policies, and any
// SPI a future Logback adds. An enumerated list of them fails open on the one
// it leaves out, so an app-included class is a Logback extension when ANY of
// its supertypes, directly or transitively, is a ch/qos/logback/ type. When
// one coexists with AsyncAppenderBase in the JVM, its lines can run after END
// or bleed across concurrent request windows: fail closed
// (asyncExecutors=false) instead of tracking put() so coverage never
// under-reports or cross-contaminates.
private static final String LOGBACK_PACKAGE = "ch/qos/logback/";

private static volatile boolean seenLogbackAsyncAppender;
// Non-Logback classes (framework or app) seen to extend a Logback type, so an
// app subclass of one (e.g. of Spring Boot's ColorConverter) is found
// without re-reading its supertypes.
private static final Set<String> KNOWN_LOGBACK_EXTENSION_TYPES = ConcurrentHashMap.newKeySet();
// Bounded negative cache of resolved non-Logback supertypes so large apps do
// not re-read the same .class resources on every app class load.
private static final int MAX_KNOWN_NON_LOGBACK_TYPES = 32_768;
private static final Set<String> KNOWN_NON_LOGBACK_TYPES = ConcurrentHashMap.newKeySet();
private static final Set<String> SEEN_APP_LOGBACK_EXTENSIONS = ConcurrentHashMap.newKeySet();

private static boolean isLogbackExtensionType(String internalName) {
return internalName != null
&& (internalName.startsWith(LOGBACK_PACKAGE) || KNOWN_LOGBACK_EXTENSION_TYPES.contains(internalName));
}

// JDK classes whose subclasses dispatch work through inherited JDK code (scanned like Thread).
private static final Set<String> JDK_DISPATCH_SUPERCLASSES = Collections.unmodifiableSet(new HashSet<>(
Arrays.asList(
Expand Down Expand Up @@ -1075,6 +1131,203 @@ static void setHookStatusForTests(boolean serverFailed, boolean listenerFailed,
appRewriteFailed = rewriteFailed;
SEEN_UNHOOKED_CONSUMERS.clear();
SEEN_UNHOOKED_ASYNC_DISPATCHERS.clear();
seenLogbackAsyncAppender = false;
SEEN_APP_LOGBACK_EXTENSIONS.clear();
KNOWN_LOGBACK_EXTENSION_TYPES.clear();
KNOWN_NON_LOGBACK_TYPES.clear();
}

/**
* Records that Logback's {@code AsyncAppenderBase} has loaded or started its
* worker thread. Returns {@code true} only if no app-included class extends
* or implements a Logback appender/encoder/layout/converter/filter; when one
* does, latches {@code asyncExecutors=false} fail-closed and returns
* {@code false}.
*/
static boolean noteLogbackAsyncAppenderAndCheckSafe() {
seenLogbackAsyncAppender = true;
if (SEEN_APP_LOGBACK_EXTENSIONS.isEmpty()) {
return true;
}
for (String ext : SEEN_APP_LOGBACK_EXTENSIONS) {
recordUnhookedAsyncDispatcher("logback-async-app-extension", ext);
}
return false;
}

private void inspectLogbackAsyncExtension(ClassLoader loader, String className, byte[] classfile) {
if (className == null || classfile == null || classfile.length < 16) {
return;
}
if (LOGBACK_ASYNC_APPENDER_BASE.equals(className)
|| LOGBACK_ASYNC_APPENDER_WORKER.equals(className)
|| LOGBACK_CLASSIC_ASYNC_APPENDER.equals(className)) {
noteLogbackAsyncAppenderAndCheckSafe();
return;
}
if (isSdkOrJdkInternalClass(className)) {
return;
}
try {
ClassReader reader = new ClassReader(classfile);
String superName = reader.getSuperName();
String[] interfaces = reader.getInterfaces();
boolean isLogbackExt = isKnownLogbackExtension(superName, interfaces);
boolean appIncluded = isAppIncludedLogbackExtension(className);
if (!isLogbackExt && appIncluded) {
isLogbackExt = inheritsLogbackExtensionViaResources(loader, superName, interfaces);
}
if (!isLogbackExt) {
return;
}
if (!className.startsWith(LOGBACK_PACKAGE)) {
KNOWN_LOGBACK_EXTENSION_TYPES.add(className);
KNOWN_NON_LOGBACK_TYPES.remove(className);
}
if (appIncluded) {
SEEN_APP_LOGBACK_EXTENSIONS.add(className);
if (seenLogbackAsyncAppender) {
recordUnhookedAsyncDispatcher("logback-async-app-extension", className);
}
}
} catch (Throwable ignored) {
// Read-only classification must never interfere with class loading.
}
}

private static boolean isKnownLogbackExtension(String superName, String[] interfaces) {
if (isLogbackExtensionType(superName)) {
return true;
}
if (interfaces != null) {
for (String iface : interfaces) {
if (isLogbackExtensionType(iface)) {
return true;
}
}
}
return false;
}

// Walks superclass/interface .class resources (read-only, zero class loading)
// for app-included classes in case an intermediate framework/app base class
// was loaded before ServerEntries was registered. Superclasses are explored
// before interfaces so a wide interface list cannot crowd out a deep class
// hierarchy, and fully resolved non-Logback supertypes are negatively cached.
private static boolean inheritsLogbackExtensionViaResources(ClassLoader loader, String superName,
String[] interfaces) {
Deque<String> queue = new ArrayDeque<>();
Set<String> visited = new HashSet<>();
List<String> resolvedNonLogback = new ArrayList<>();
if (superName != null && !"java/lang/Object".equals(superName)) {
queue.addFirst(superName);
}
if (interfaces != null) {
for (String iface : interfaces) {
if (iface != null) {
queue.addLast(iface);
}
}
}
int steps = 0;
boolean complete = true;
while (!queue.isEmpty() && steps < 64) {
String current = queue.pollFirst();
if (current == null || !visited.add(current) || isSdkOrJdkInternalClass(current)) {
continue;
}
if (isLogbackExtensionType(current)) {
return true;
}
if (KNOWN_NON_LOGBACK_TYPES.contains(current)) {
continue;
}
steps++;
byte[] bytes = readClassResource(loader, current);
if (bytes == null || bytes.length < 16) {
complete = false;
continue;
}
try {
ClassReader cr = new ClassReader(bytes);
String nextSuper = cr.getSuperName();
String[] nextIfaces = cr.getInterfaces();
if (isKnownLogbackExtension(nextSuper, nextIfaces)) {
KNOWN_LOGBACK_EXTENSION_TYPES.add(current);
return true;
}
resolvedNonLogback.add(current);
if (nextSuper != null && !"java/lang/Object".equals(nextSuper)) {
queue.addFirst(nextSuper);
}
if (nextIfaces != null) {
for (String iface : nextIfaces) {
if (iface != null) {
queue.addLast(iface);
}
}
}
} catch (Throwable ignored) {
complete = false;
// Ignore unreadable class bytes and keep walking remaining parents.
}
}
if (complete && queue.isEmpty() && !resolvedNonLogback.isEmpty()
&& KNOWN_NON_LOGBACK_TYPES.size() < MAX_KNOWN_NON_LOGBACK_TYPES) {
for (String nonLogback : resolvedNonLogback) {
if (KNOWN_NON_LOGBACK_TYPES.size() >= MAX_KNOWN_NON_LOGBACK_TYPES) {
break;
}
KNOWN_NON_LOGBACK_TYPES.add(nonLogback);
}
}
return false;
}

private static byte[] readClassResource(ClassLoader loader, String internalName) {
String resource = internalName + ".class";
InputStream in = loader != null
? loader.getResourceAsStream(resource)
: ClassLoader.getSystemResourceAsStream(resource);
if (in == null) {
return null;
}
try (InputStream stream = in) {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] buf = new byte[1024];
int n;
while ((n = stream.read(buf)) != -1) {
out.write(buf, 0, n);
}
return out.toByteArray();
} catch (Throwable ignored) {
return null;
}
}

private static boolean isSdkOrJdkInternalClass(String className) {
return className.startsWith("java/")
|| className.startsWith("javax/")
|| className.startsWith("sun/")
|| className.startsWith("jdk/")
|| className.startsWith("com/sun/")
|| className.startsWith("io/keploy/dedup/")
|| className.startsWith("io/keploy/servlet/")
|| className.startsWith("org/jacoco/")
|| className.startsWith("org/newsclub/");
}

private boolean isAppIncludedLogbackExtension(String className) {
if (className == null || className.startsWith("ch/qos/logback/")) {
return false;
}
if (!appClasses.isEmpty()) {
return appClasses.contains(className);
}
if (appPackagePrefix != null && !appPackagePrefix.isEmpty()) {
return className.startsWith(appPackagePrefix) && !isShadedOrRelocated(className);
}
return isRewriteAllowedPackage(className) && !className.startsWith("io/dropwizard/");
}

// uncounted names the servers whose requests do not count that the app
Expand Down Expand Up @@ -1114,6 +1367,7 @@ public byte[] transform(ClassLoader loader, String className, Class<?> classBein
SEEN_UNHOOKED_CONSUMERS.add(unhookedConsumer);
}
byte[] currentBytes = classfileBuffer;
inspectLogbackAsyncExtension(loader, className, currentBytes);
boolean hookedAsyncContext = false;
boolean hookedSessionListener = false;
if (className != null && !isInternalOrAgentClass(className)) {
Expand Down Expand Up @@ -2376,12 +2630,14 @@ private byte[] hookLatchOnCall(ClassLoader loader, String className, ProtectionD
byte[] wrapped = wrapLatchOnCall(classfileBuffer, latchEntry);
if (wrapped == null) {
// Only fail closed if this class version actually references a
// dispatch primitive without exposing the expected methods (e.g.
// Spring 5.3 ConcurrentMapCache has no async retrieve method).
// dispatch primitive without exposing the expected methods or call
// sites (e.g. Spring 5.3 ConcurrentMapCache has no async retrieve).
if (hasDispatchPrimitiveReference(classfileBuffer)) {
asyncHookFailed = true;
LOGGER.log(Level.WARNING, "Keploy dedup cannot hook " + name
+ ": none of " + latchEntry.methods + " found");
+ (latchEntry.dispatchCallSites
? ": no dispatch call sites found"
: ": none of " + latchEntry.methods + " found"));
}
return null;
}
Expand Down Expand Up @@ -2411,8 +2667,40 @@ static byte[] wrapLatchOnCall(byte[] classfile, final LatchEntry latchEntry) {
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
|| !latchEntry.matches(name, descriptor)) {
if (mv == null || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) {
return mv;
}
if (latchEntry.dispatchCallSites) {
return new MethodVisitor(Opcodes.ASM9, mv) {
private boolean methodHooked;

@Override
public void visitMethodInsn(int opcode, String owner, String mname, String desc,
boolean isInterface) {
if (opcode == Opcodes.INVOKESTATIC && GATE.equals(owner)
&& "noteRuntimeUntrackedDispatch".equals(mname)) {
alreadyHooked[0] = true;
super.visitMethodInsn(opcode, owner, mname, desc, isInterface);
return;
}
Set<String> dispatchMethods = DISPATCH_PRIMITIVE_METHODS.get(owner);
if (dispatchMethods != null && dispatchMethods.contains(mname)) {
found[0] = true;
methodHooked = true;
super.visitLdcInsn(latchEntry.label + ":" + owner.replace('/', '.') + "." + mname);
super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE,
"noteRuntimeUntrackedDispatch", "(Ljava/lang/String;)V", false);
}
super.visitMethodInsn(opcode, owner, mname, desc, isInterface);
}

@Override
public void visitMaxs(int maxStack, int maxLocals) {
super.visitMaxs(methodHooked ? maxStack + 1 : maxStack, maxLocals);
}
};
}
if (!latchEntry.matches(name, descriptor)) {
return mv;
}
found[0] = true;
Expand Down Expand Up @@ -3508,10 +3796,12 @@ static final class LatchEntry {

final String label;
final Set<String> methods;
final boolean dispatchCallSites;

private LatchEntry(String label, Set<String> methods) {
private LatchEntry(String label, Set<String> methods, boolean dispatchCallSites) {
this.label = label;
this.methods = Collections.unmodifiableSet(methods);
this.dispatchCallSites = dispatchCallSites;
}

boolean matches(String name, String descriptor) {
Expand Down
Loading