Skip to content

Commit f495171

Browse files
authored
[Entitlements] Add an option to perform bytecode verification during instrumentation (#124404) (#125226)
Using ASM CheckClassAdapter was key to diagnose the issue we had with incorrect signatures for some check methods. In this PR I polished up the code I used to pinpoint the issue, and made it available via a system property so it can be turned on if we need it (and it's always on for Entitlements IT tests too). It is also turned on in case we get VerifyErrors during retransformClasses early in the Entitlement agent bootstrap: retransformClasses runs in the native part of the JVM, so the VerifyError it produces is not so readable (e.g. it lacks a full stack trace and a description); in case this happens, we re-apply the transformation with verification turned on to get a meaningful error before dying.
1 parent e0c689b commit f495171

File tree

8 files changed

+111
-12
lines changed

8 files changed

+111
-12
lines changed

libs/entitlement/asm-provider/build.gradle

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,15 @@ dependencies {
1414
compileOnly project(':libs:core')
1515
compileOnly project(':libs:logging')
1616
implementation 'org.ow2.asm:asm:9.7.1'
17+
implementation 'org.ow2.asm:asm-util:9.7.1'
18+
implementation 'org.ow2.asm:asm-tree:9.7.1'
19+
implementation 'org.ow2.asm:asm-analysis:9.7.1'
1720
testImplementation project(":test:framework")
1821
testImplementation project(":libs:entitlement:bridge")
19-
testImplementation 'org.ow2.asm:asm-util:9.7.1'
22+
}
23+
24+
tasks.named("dependencyLicenses").configure {
25+
mapping from: /asm-.*/, to: 'asm'
2026
}
2127

2228
tasks.named('test').configure {

libs/entitlement/asm-provider/src/main/java/module-info.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
module org.elasticsearch.entitlement.instrumentation {
1414
requires org.objectweb.asm;
15+
requires org.objectweb.asm.util;
1516
requires org.elasticsearch.entitlement;
1617

1718
requires static org.elasticsearch.base; // for SuppressForbidden

libs/entitlement/asm-provider/src/main/java/org/elasticsearch/entitlement/instrumentation/impl/InstrumenterImpl.java

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
package org.elasticsearch.entitlement.instrumentation.impl;
1111

12+
import org.elasticsearch.core.Strings;
1213
import org.elasticsearch.entitlement.instrumentation.CheckMethod;
1314
import org.elasticsearch.entitlement.instrumentation.EntitlementInstrumented;
1415
import org.elasticsearch.entitlement.instrumentation.Instrumenter;
@@ -24,9 +25,12 @@
2425
import org.objectweb.asm.Opcodes;
2526
import org.objectweb.asm.RecordComponentVisitor;
2627
import org.objectweb.asm.Type;
28+
import org.objectweb.asm.util.CheckClassAdapter;
2729

2830
import java.io.IOException;
2931
import java.io.InputStream;
32+
import java.io.PrintWriter;
33+
import java.io.StringWriter;
3034
import java.util.Map;
3135
import java.util.stream.Stream;
3236

@@ -63,6 +67,7 @@ public class InstrumenterImpl implements Instrumenter {
6367
}
6468

6569
public static InstrumenterImpl create(Class<?> checkerClass, Map<MethodKey, CheckMethod> checkMethods) {
70+
6671
Type checkerClassType = Type.getType(checkerClass);
6772
String handleClass = checkerClassType.getInternalName() + "Handle";
6873
String getCheckerClassMethodDescriptor = Type.getMethodDescriptor(checkerClassType);
@@ -82,13 +87,54 @@ static ClassFileInfo getClassFileInfo(Class<?> clazz) throws IOException {
8287
return new ClassFileInfo(fileName, originalBytecodes);
8388
}
8489

90+
private enum VerificationPhase {
91+
BEFORE_INSTRUMENTATION,
92+
AFTER_INSTRUMENTATION
93+
}
94+
95+
private static String verify(byte[] classfileBuffer) {
96+
ClassReader reader = new ClassReader(classfileBuffer);
97+
StringWriter stringWriter = new StringWriter();
98+
PrintWriter printWriter = new PrintWriter(stringWriter);
99+
CheckClassAdapter.verify(reader, false, printWriter);
100+
return stringWriter.toString();
101+
}
102+
103+
private static void verifyAndLog(byte[] classfileBuffer, String className, VerificationPhase phase) {
104+
try {
105+
String result = verify(classfileBuffer);
106+
if (result.isEmpty() == false) {
107+
logger.error(Strings.format("Bytecode verification (%s) for class [%s] failed: %s", phase, className, result));
108+
} else {
109+
logger.info("Bytecode verification ({}) for class [{}] passed", phase, className);
110+
}
111+
} catch (ClassCircularityError e) {
112+
// Apparently, verification during instrumentation is challenging for class resolution and loading
113+
// Treat this not as an error, but as "inconclusive"
114+
logger.warn(Strings.format("Cannot perform bytecode verification (%s) for class [%s]", phase, className), e);
115+
} catch (IllegalArgumentException e) {
116+
// The ASM CheckClassAdapter in some cases throws this instead of printing the error
117+
logger.error(Strings.format("Bytecode verification (%s) for class [%s] failed", phase, className), e);
118+
}
119+
}
120+
85121
@Override
86-
public byte[] instrumentClass(String className, byte[] classfileBuffer) {
122+
public byte[] instrumentClass(String className, byte[] classfileBuffer, boolean verify) {
123+
if (verify) {
124+
verifyAndLog(classfileBuffer, className, VerificationPhase.BEFORE_INSTRUMENTATION);
125+
}
126+
87127
ClassReader reader = new ClassReader(classfileBuffer);
88128
ClassWriter writer = new ClassWriter(reader, COMPUTE_FRAMES | COMPUTE_MAXS);
89129
ClassVisitor visitor = new EntitlementClassVisitor(Opcodes.ASM9, writer, className);
90130
reader.accept(visitor, 0);
91-
return writer.toByteArray();
131+
var outBytes = writer.toByteArray();
132+
133+
if (verify) {
134+
verifyAndLog(outBytes, className, VerificationPhase.AFTER_INSTRUMENTATION);
135+
}
136+
137+
return outBytes;
92138
}
93139

94140
class EntitlementClassVisitor extends ClassVisitor {

libs/entitlement/asm-provider/src/test/java/org/elasticsearch/entitlement/instrumentation/impl/InstrumenterTests.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -226,9 +226,9 @@ public void testNotInstrumentedTwice() throws Exception {
226226
var instrumenter = createInstrumenter(Map.of("checkSomeStaticMethod", targetMethod));
227227

228228
var loader1 = instrumentTestClass(instrumenter);
229-
byte[] instrumentedTwiceBytecode = instrumenter.instrumentClass(TestClassToInstrument.class.getName(), loader1.testClassBytes);
230-
logger.trace(() -> Strings.format("Bytecode after 2nd instrumentation:\n%s", bytecode2text(instrumentedTwiceBytecode)));
231-
var loader2 = new TestLoader(TestClassToInstrument.class.getName(), instrumentedTwiceBytecode);
229+
byte[] instrumentedTwiceBytes = instrumenter.instrumentClass(TestClassToInstrument.class.getName(), loader1.testClassBytes, true);
230+
logger.trace(() -> Strings.format("Bytecode after 2nd instrumentation:\n%s", bytecode2text(instrumentedTwiceBytes)));
231+
var loader2 = new TestLoader(TestClassToInstrument.class.getName(), instrumentedTwiceBytes);
232232

233233
assertStaticMethodThrows(loader2, targetMethod, 123);
234234
assertEquals(1, TestEntitlementCheckerHolder.checkerInstance.checkSomeStaticMethodIntCallCount);
@@ -306,7 +306,7 @@ private static InstrumenterImpl createInstrumenter(Map<String, Executable> metho
306306
private static TestLoader instrumentTestClass(InstrumenterImpl instrumenter) throws IOException {
307307
var clazz = TestClassToInstrument.class;
308308
ClassFileInfo initial = getClassFileInfo(clazz);
309-
byte[] newBytecode = instrumenter.instrumentClass(Type.getInternalName(clazz), initial.bytecodes());
309+
byte[] newBytecode = instrumenter.instrumentClass(Type.getInternalName(clazz), initial.bytecodes(), true);
310310
if (logger.isTraceEnabled()) {
311311
logger.trace("Bytecode after instrumentation:\n{}", bytecode2text(newBytecode));
312312
}

libs/entitlement/qa/src/javaRestTest/java/org/elasticsearch/entitlement/qa/EntitlementsTestRule.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ protected void before() throws Throwable {
8484
.module("entitled", spec -> buildEntitlements(spec, "org.elasticsearch.entitlement.qa.entitled", ENTITLED_POLICY))
8585
.module(ENTITLEMENT_TEST_PLUGIN_NAME, spec -> setupEntitlements(spec, modular, policyBuilder))
8686
.systemProperty("es.entitlements.enabled", "true")
87+
.systemProperty("es.entitlements.verify_bytecode", "true")
8788
.systemProperty("es.entitlements.testdir", () -> testDir.getRoot().getAbsolutePath())
8889
.systemProperties(spec -> tempDirSystemPropertyProvider.get(testDir.getRoot().toPath()))
8990
.setting("xpack.security.enabled", "false")

libs/entitlement/src/main/java/org/elasticsearch/entitlement/initialization/EntitlementInitialization.java

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@ public static void initialize(Instrumentation inst) throws Exception {
102102
manager = initChecker();
103103

104104
var latestCheckerInterface = getVersionSpecificCheckerClass(EntitlementChecker.class, Runtime.version().feature());
105+
var verifyBytecode = Booleans.parseBoolean(System.getProperty("es.entitlements.verify_bytecode", "false"));
106+
107+
if (verifyBytecode) {
108+
ensureClassesSensitiveToVerificationAreInitialized();
109+
}
105110

106111
Map<MethodKey, CheckMethod> checkMethods = new HashMap<>(INSTRUMENTATION_SERVICE.lookupMethods(latestCheckerInterface));
107112
Stream.of(
@@ -124,8 +129,23 @@ public static void initialize(Instrumentation inst) throws Exception {
124129
var classesToTransform = checkMethods.keySet().stream().map(MethodKey::className).collect(Collectors.toSet());
125130

126131
Instrumenter instrumenter = INSTRUMENTATION_SERVICE.newInstrumenter(latestCheckerInterface, checkMethods);
127-
inst.addTransformer(new Transformer(instrumenter, classesToTransform), true);
128-
inst.retransformClasses(findClassesToRetransform(inst.getAllLoadedClasses(), classesToTransform));
132+
var transformer = new Transformer(instrumenter, classesToTransform, verifyBytecode);
133+
inst.addTransformer(transformer, true);
134+
135+
var classesToRetransform = findClassesToRetransform(inst.getAllLoadedClasses(), classesToTransform);
136+
try {
137+
inst.retransformClasses(classesToRetransform);
138+
} catch (VerifyError e) {
139+
// Turn on verification and try to retransform one class at the time to get detailed diagnostic
140+
transformer.enableClassVerification();
141+
142+
for (var classToRetransform : classesToRetransform) {
143+
inst.retransformClasses(classToRetransform);
144+
}
145+
146+
// We should have failed already in the loop above, but just in case we did not, rethrow.
147+
throw e;
148+
}
129149
}
130150

131151
private static Class<?>[] findClassesToRetransform(Class<?>[] loadedClasses, Set<String> classesToTransform) {
@@ -456,6 +476,24 @@ private static Stream<InstrumentationService.InstrumentationInfo> pathChecks() {
456476
});
457477
}
458478

479+
/**
480+
* If bytecode verification is enabled, ensure these classes get loaded before transforming/retransforming them.
481+
* For these classes, the order in which we transform and verify them matters. Verification during class transformation is at least an
482+
* unforeseen (if not unsupported) scenario: we are loading a class, and while we are still loading it (during transformation) we try
483+
* to verify it. This in turn leads to more classes loading (for verification purposes), which could turn into those classes to be
484+
* transformed and undergo verification. In order to avoid circularity errors as much as possible, we force a partial order.
485+
*/
486+
private static void ensureClassesSensitiveToVerificationAreInitialized() {
487+
var classesToInitialize = Set.of("sun.net.www.protocol.http.HttpURLConnection");
488+
for (String className : classesToInitialize) {
489+
try {
490+
Class.forName(className);
491+
} catch (ClassNotFoundException unexpected) {
492+
throw new AssertionError(unexpected);
493+
}
494+
}
495+
}
496+
459497
/**
460498
* Returns the "most recent" checker class compatible with the current runtime Java version.
461499
* For checkers, we have (optionally) version specific classes, each with a prefix (e.g. Java23).

libs/entitlement/src/main/java/org/elasticsearch/entitlement/instrumentation/Instrumenter.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,5 @@
1010
package org.elasticsearch.entitlement.instrumentation;
1111

1212
public interface Instrumenter {
13-
byte[] instrumentClass(String className, byte[] classfileBuffer);
13+
byte[] instrumentClass(String className, byte[] classfileBuffer, boolean verify);
1414
}

libs/entitlement/src/main/java/org/elasticsearch/entitlement/instrumentation/Transformer.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,19 @@ public class Transformer implements ClassFileTransformer {
2020
private final Instrumenter instrumenter;
2121
private final Set<String> classesToTransform;
2222

23-
public Transformer(Instrumenter instrumenter, Set<String> classesToTransform) {
23+
private boolean verifyClasses;
24+
25+
public Transformer(Instrumenter instrumenter, Set<String> classesToTransform, boolean verifyClasses) {
2426
this.instrumenter = instrumenter;
2527
this.classesToTransform = classesToTransform;
28+
this.verifyClasses = verifyClasses;
2629
// TODO: Should warn if any MethodKey doesn't match any methods
2730
}
2831

32+
public void enableClassVerification() {
33+
this.verifyClasses = true;
34+
}
35+
2936
@Override
3037
public byte[] transform(
3138
ClassLoader loader,
@@ -36,7 +43,7 @@ public byte[] transform(
3643
) {
3744
if (classesToTransform.contains(className)) {
3845
// System.out.println("Transforming " + className);
39-
return instrumenter.instrumentClass(className, classfileBuffer);
46+
return instrumenter.instrumentClass(className, classfileBuffer, verifyClasses);
4047
} else {
4148
// System.out.println("Not transforming " + className);
4249
return classfileBuffer;

0 commit comments

Comments
 (0)