Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;

/**
* Generates glue bytecode for a {@link BiFunction} around {@code ClassLoader.defineClass} that
Expand All @@ -37,6 +38,8 @@
final class DefineClassGlueGenerator {
// our glue must be located inside the java.lang namespace for accessibility reasons
private static final String DEFINECLASSGLUE_CLASS = "java/lang/$Datadog$DefineClassGlue";
private static final String LOOKUPGLUE_CLASS =
"datadog/instrument/glue/$Datadog$ClassLoaderLookup";

private static final String OBJECT_CLASS = "java/lang/Object";
private static final String CLASS_CLASS = "java/lang/Class";
Expand All @@ -50,6 +53,8 @@ final class DefineClassGlueGenerator {
private static final String BYTE_ARRAY = "[B";

private static final String CLASSLOADER_CLASS = "java/lang/ClassLoader";
private static final String CONSTRUCTOR_CLASS = "java/lang/reflect/Constructor";
private static final String LOOKUP_CLASS = "java/lang/invoke/MethodHandles$Lookup";
private static final String PROTECTIONDOMAIN_CLASS = "java/security/ProtectionDomain";
private static final String BIFUNCTION_CLASS = "java/util/function/BiFunction";

Expand Down Expand Up @@ -106,10 +111,58 @@ public static void generateGlue(Path resourcePath, Path javaPath) throws IOExcep
lines.add(" /** Packed Java 9+ bytecode */");
lines.add(" String V9 =");
packBytecode(lines, generateBytecode("jdk/internal/misc"));
lines.add(" /** Lookup helper */");
lines.add(" String LOOKUP =");
packBytecode(lines, generateLookup());
lines.add("}");
Files.write(defineClassGlue, lines, StandardCharsets.UTF_8);
}

/** Generates a static factory for a full-privilege ClassLoader lookup. */
static byte[] generateLookup() {
ClassWriter cw = new ClassWriter(0);
cw.visit(
V1_8, ACC_PUBLIC | ACC_FINAL | ACC_SYNTHETIC, LOOKUPGLUE_CLASS, null, OBJECT_CLASS, null);

// privateLookupIn across modules drops MODULE access and cannot define hidden classes.
MethodVisitor mv =
cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "lookup", "()Ljava/lang/Object;", null, null);
mv.visitCode();
mv.visitLdcInsn(Type.getObjectType(LOOKUP_CLASS));
mv.visitInsn(ICONST_1);
mv.visitTypeInsn(ANEWARRAY, CLASS_CLASS);
mv.visitInsn(DUP);
mv.visitInsn(ICONST_0);
mv.visitLdcInsn(Type.getObjectType(CLASS_CLASS));
mv.visitInsn(AASTORE);
mv.visitMethodInsn(
INVOKEVIRTUAL,
CLASS_CLASS,
"getDeclaredConstructor",
"([L" + CLASS_CLASS + ";)L" + CONSTRUCTOR_CLASS + ";",
false);
mv.visitInsn(DUP);
mv.visitInsn(ICONST_1);
mv.visitMethodInsn(INVOKEVIRTUAL, CONSTRUCTOR_CLASS, "setAccessible", "(Z)V", false);
mv.visitInsn(ICONST_1);
mv.visitTypeInsn(ANEWARRAY, OBJECT_CLASS);
mv.visitInsn(DUP);
mv.visitInsn(ICONST_0);
mv.visitLdcInsn(Type.getObjectType(CLASSLOADER_CLASS));
mv.visitInsn(AASTORE);
mv.visitMethodInsn(
INVOKEVIRTUAL,
CONSTRUCTOR_CLASS,
"newInstance",
"([Ljava/lang/Object;)Ljava/lang/Object;",
false);
mv.visitInsn(ARETURN);
mv.visitMaxs(5, 0);
mv.visitEnd();
cw.visitEnd();
return cw.toByteArray();
}

/**
* Generates glue bytecode to access {@code ClassLoader.defineClass}.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.security.ProtectionDomain;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -167,18 +166,22 @@ public static void enableClassInjection(Instrumentation inst) {
*/
@SuppressWarnings("Since15")
private static BiFunction injectViaLookup(Instrumentation inst) throws Exception {
// privateLookupIn across modules drops MODULE access and cannot define hidden classes
// this means we need to reflectively construct the lookup to enable defineHiddenClass
Constructor<Lookup> ctor = Lookup.class.getDeclaredConstructor(Class.class);
Class<?> lookupGlue =
new ClassLoader(null) {
Class<?> defineLookupGlue() {
byte[] bytecode = DefineClassGlue.LOOKUP.getBytes(ISO_8859_1);
return defineClass(
null, bytecode, 0, bytecode.length, ClassInjector.class.getProtectionDomain());
}
}.defineLookupGlue();
inst.redefineModule(
ClassLoader.class.getModule(),
emptySet(),
emptyMap(),
singletonMap("java.lang.invoke", singleton(ClassInjector.class.getModule())),
singletonMap("java.lang.invoke", singleton(lookupGlue.getModule())),
emptySet(),
emptyMap());
ctor.setAccessible(true);
Lookup lookup = ctor.newInstance(ClassLoader.class);
Lookup lookup = (Lookup) lookupGlue.getMethod("lookup").invoke(null);
byte[] bytecode = DefineClassGlue.V9.getBytes(ISO_8859_1);
Class<?> glueClass = lookup.defineHiddenClass(bytecode, false).lookupClass();
return (BiFunction) glueClass.getConstructor().newInstance();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package datadog.instrument.classinject;

import static datadog.instrument.classinject.ClassInjectorTestSupport.observeRetransforms;
import static datadog.instrument.classinject.ClassInjectorTestSupport.sampleClass;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.ReflectPermission;
import java.security.CodeSource;
import java.security.Permission;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressWarnings("removal")
public class ClassInjectorSecurityManagerProbe {
public static void premain(String arguments, Instrumentation inst) {
AtomicInteger retransforms = new AtomicInteger();
ClassFileTransformer observer = observeRetransforms(retransforms);
inst.addTransformer(observer, true);
Policy.setPolicy(
new Policy() {
@Override
public boolean implies(ProtectionDomain domain, Permission permission) {
CodeSource source = domain.getCodeSource();
if (source == null || source.getLocation() == null) {
return false;
}
String name = permission.getName();
return (permission instanceof ReflectPermission && name.equals("suppressAccessChecks"))
|| (permission instanceof RuntimePermission
&& (name.equals("createClassLoader")
|| name.equals("getProtectionDomain")
|| name.equals("accessDeclaredMembers")));
}
});
System.setSecurityManager(new SecurityManager());
try {
ClassInjector.enableClassInjection(inst);
} finally {
inst.removeTransformer(observer);
}
if (retransforms.get() != 0) {
throw new AssertionError("Lookup failed and used the transformation fallback");
}
}

public static void main(String[] args) throws Exception {
if (System.getSecurityManager() == null) {
throw new AssertionError("SecurityManager is not installed");
}
ClassLoader target = new ClassLoader(null) {};
ProtectionDomain domain = new ProtectionDomain(null, null, target, null);
String name = "datadog.injected.SecurityManagerSample";
Class<?> injected = ClassInjector.injectClass(name, sampleClass(name), domain);
if (injected.getProtectionDomain() != domain) {
throw new AssertionError("Injected class has the wrong protection domain");
}
if (!Integer.valueOf(42).equals(injected.getMethod("value").invoke(null))) {
throw new AssertionError("Injected class did not execute correctly");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package datadog.instrument.classinject;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import datadog.instrument.utils.JVM;
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.List;
import java.util.concurrent.TimeUnit;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class ClassInjectorSecurityManagerTest {
private static final int TIMEOUT_SECONDS = 20;

@TempDir Path temporary;

@Test
void enablesLookupFromAgentWithSecurityManager() throws Exception {
assumeTrue(JVM.atLeastJava(15) && !JVM.atLeastJava(24));
Path agent = temporary.resolve("security-manager-agent.jar");
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.putValue("Manifest-Version", "1.0");
attributes.putValue("Premain-Class", ClassInjectorSecurityManagerProbe.class.getName());
attributes.putValue("Can-Retransform-Classes", "true");
try (JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(agent), manifest)) {}

List<String> command = new ArrayList<>();
command.add(Paths.get(System.getProperty("java.home"), "bin", "java").toString());
command.add("-Djava.security.manager=allow");
command.add("-javaagent:" + agent);
command.add("-cp");
command.add(System.getProperty("java.class.path"));
command.add(ClassInjectorSecurityManagerProbe.class.getName());

Path output = temporary.resolve("security-manager.log");
Process process =
new ProcessBuilder(command)
.redirectErrorStream(true)
.redirectOutput(output.toFile())
.start();
try {
assertThat(process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS))
.withFailMessage("Child JVM timed out after %ds", TIMEOUT_SECONDS)
.isTrue();
String log = new String(Files.readAllBytes(output), StandardCharsets.UTF_8);
assertThat(process.exitValue()).withFailMessage(log).isZero();
} finally {
process.destroyForcibly();
process.waitFor(5, TimeUnit.SECONDS);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package datadog.instrument.classinject;

import static datadog.instrument.classinject.ClassInjectorTestSupport.observeRetransforms;
import static datadog.instrument.classinject.ClassInjectorTestSupport.sampleClass;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.objectweb.asm.Opcodes.*;
Expand All @@ -9,6 +11,7 @@
import datadog.instrument.utils.JVM;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
Expand All @@ -18,7 +21,9 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
Expand Down Expand Up @@ -103,21 +108,64 @@ void fallsBackWhenModuleOpeningFails() throws Exception {
}

@Test
@SuppressWarnings("Since15")
void onlyJavaLangInvokeIsOpenedToTheInjectorsModule() throws Exception {
@SuppressWarnings({"Since15", "unchecked"})
void onlyJavaLangInvokeIsOpenedToTheLookupHelpersModule() throws Exception {
if (JVM.atLeastJava(17)) {
AtomicReference<Module> helperModule = new AtomicReference<>();
AtomicInteger retransforms = new AtomicInteger();
Instrumentation inst = TestAgent.getInstrumentation();
Instrumentation observingModuleOpen =
(Instrumentation)
Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] {Instrumentation.class},
(proxy, method, args) -> {
if (method.getName().equals("redefineModule")) {
assertThat(args[0]).isSameAs(Object.class.getModule());
Map<String, Set<Module>> extraOpens = (Map<String, Set<Module>>) args[3];
assertThat(extraOpens).containsOnlyKeys("java.lang.invoke");
assertThat(extraOpens.get("java.lang.invoke")).hasSize(1);
helperModule.set(extraOpens.get("java.lang.invoke").iterator().next());
} else if (method.getName().equals("retransformClasses")) {
retransforms.incrementAndGet();
}
try {
return method.invoke(inst, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
});
try (URLClassLoader copy = isolatedLibrary();
URLClassLoader unrelated = URLClassLoader.newInstance(new URL[0], null)) {
Class<?> injector = copy.loadClass(ClassInjector.class.getName());
injector
.getMethod("enableClassInjection", Instrumentation.class)
.invoke(null, TestAgent.getInstrumentation());
assertThat(Object.class.getModule().isOpen("java.lang.invoke", injector.getModule()))
.invoke(null, observingModuleOpen);
assertThat(retransforms.get()).isZero();
assertThat(helperModule.get()).isNotNull().isNotSameAs(injector.getModule());
ClassLoader helperLoader = helperModule.get().getClassLoader();
assertThat(helperLoader).isNotNull().isNotSameAs(copy);
assertThat(helperLoader.getParent()).isNull();
assertThat(Object.class.getModule().isOpen("java.lang.invoke", helperModule.get()))
.isTrue();
assertThat(Object.class.getModule().isOpen("java.lang.invoke", injector.getModule()))
.isFalse();
assertThat(Object.class.getModule().isOpen("java.lang.invoke", getClass().getModule()))
.isFalse();
assertThat(
Object.class.getModule().isOpen("java.lang.invoke", unrelated.getUnnamedModule()))
.isFalse();
assertThat(Object.class.getModule().isOpen("java.lang", injector.getModule())).isFalse();
assertThat(Object.class.getModule().isOpen("java.lang", helperModule.get())).isFalse();
assertThat(Lookup.class.getDeclaredConstructor(Class.class).trySetAccessible()).isFalse();

Class<?> helper =
helperLoader.loadClass("datadog.instrument.glue.$Datadog$ClassLoaderLookup");
assertThat(helper.getProtectionDomain()).isSameAs(injector.getProtectionDomain());
assertThat(helper.getDeclaredConstructors()).isEmpty();
Lookup lookup = (Lookup) helper.getMethod("lookup").invoke(null);
assertThat(lookup.lookupClass()).isSameAs(ClassLoader.class);
assertThat(lookup.hasFullPrivilegeAccess()).isTrue();
assertThat(injectSample(injector)).isEqualTo(42);
}
}
}
Expand Down Expand Up @@ -225,24 +273,6 @@ void injectsClassesThatReferenceEachOther() throws Exception {
assertThat(injectedClasses.get(0).getMethod("value").invoke(null)).isEqualTo(42);
}

private static ClassFileTransformer observeRetransforms(AtomicInteger retransforms) {
return new ClassFileTransformer() {
@Override
public byte[] transform(
ClassLoader loader,
String name,
Class<?> redefined,
ProtectionDomain domain,
byte[] bytecode) {
if (redefined != null
&& ("java/lang/ClassLoader".equals(name) || "java/lang/Class".equals(name))) {
retransforms.incrementAndGet();
}
return null;
}
};
}

private static URLClassLoader isolatedLibrary() {
return new URLClassLoader(
new URL[] {
Expand Down Expand Up @@ -273,20 +303,6 @@ private static ClassLoader newCL() {
return new ClassLoader(null) {};
}

/** Generates a class with a static {@code value()} method that returns 42. */
private static byte[] sampleClass(String name) {
ClassWriter writer = new ClassWriter(0);
writer.visit(V1_8, ACC_PUBLIC, name.replace('.', '/'), null, "java/lang/Object", null);
MethodVisitor method = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "value", "()I", null, null);
method.visitCode();
method.visitIntInsn(BIPUSH, 42);
method.visitInsn(IRETURN);
method.visitMaxs(1, 0);
method.visitEnd();
writer.visitEnd();
return writer.toByteArray();
}

/** Generates a class with a static {@code value()} method that delegates to the target. */
private static byte[] delegatingClass(String name, String target) {
ClassWriter writer = new ClassWriter(0);
Expand Down
Loading