Search code examples
javaagent

java.lang.SecurityException when injecting java agent


I am trying to create a dynamic java agent, but when the agent is loaded this error is thrown:

com.sun.tools.attach.AgentInitializationException: Agent JAR loaded but agent failed to initialize
    at jdk.attach/sun.tools.attach.HotSpotVirtualMachine.loadAgent(HotSpotVirtualMachine.java:165)
    at jdk.attach/com.sun.tools.attach.VirtualMachine.loadAgent(VirtualMachine.java:538)
    at injector.main(injector.java:20)

And this is the error that is shown on the target application:

java.lang.SecurityException: class "agent"'s signer information does not match signer information of other classes in the same package
  at java.base/java.lang.ClassLoader.checkCerts(ClassLoader.java:1151)
  at java.base/java.lang.ClassLoader.preDefineClass(ClassLoader.java:906)
  at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1015)
  at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
  at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:821)
  at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:719)
  at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:642)
  at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:600)
  at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
  at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
  at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:431)
  at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallAgentmain(InstrumentationImpl.java:535)

The agent has no code that could possibly trigger the error because right now it is a single System.out.println statement for testing. I use this code to inject the agent:

VirtualMachine vm = VirtualMachine.attach(vmd);
vm.loadAgent("myagentpath");
vm.detach();

The target application is running a normal distribution of java. I do not believe that it is an issue with my code. Does anyone know what could be causing this?


Solution

  • signer information does not match signer information of other classes in the same package

    This happens when classes belonging to the same package are loaded from different JAR files present on the classpath, and those JAR files have signatures signed with different certificates - or, perhaps more often, at least one is signed and one or more others are not. So either make sure all JARs (or at least those which contain classes from the same packages) are signed using the same certificate or remove the signatures from the manifest of JAR files with overlapping packages.