Monday, December 13, 2010

Use agents to screw with non-protected JVMs

The title is mostly for shock value, but it is true that you can do some pretty awesome stuff to any un-protected JVM.

I ran across this little piece of information as I was reading the source code for JConsole to see how it managed to monitor any JVM running on your box (assuming you have user permissions).  It's an extension of the java.lang.instrument agent functionality added in Java 1.5.  NOTE: This example is specifically for Java 6 and later.

So in Java 6, the Attach API was introduced, and it provided a new way to add agents to JVM: after the JVM already started running.

So let's start by creating a simple little app:

And let's start this app with: java SomeThreadedApp  No special arguments, just typical start.

Now, the JVM is running.  But now we want to modify the JVM in flight: I wanted to kill some threads in the running JVM.  With the agent Attach API, we can inject any code we want into a running JVM that isn't protected by a SecurityManager:


The agent code needs to be in a JAR with a MANIFEST.MF entry for "Agent-Class" set to the class that defines the public static void agentmain method.  More info can be found on the Oracle Java Instrumentation page.

And the last step to actually get the agent code into the target JVM, so the agent code actually run on the target JVM, I use a little JRuby:



No comments:

Post a Comment