This is the seventh part of the DLL Injection series. For your convenience you can find other parts in the table of contents in Part 1 – Registry

We already injected native code into target, managed code into default application domain, and managed code into specific application domain. Today we are going to inject Java code into C# application. Let’s begin.

IKVM

How can we execute Java code? The obvious way is to spin up the JVM but we won’t use this approach. Instead, we will convert the Java bytecode to IL and inject it instead. To do that, we will use IKVM project.

Unfortunately, this project is abandoned and not supported anymore, but it still works reliably and can be widely used. You can either execute the bytecode directly (from a jar file) or recompile it to DLL and use from C#. We will use the latter approach, load IKVM into process and execute the code.

Java part

This is pretty easy:

public class Program {
    public static void main(String... args) throws InterruptedException {
        System.out.println("Hello from Java!");
    }
}

Take this code, compile in any way and bundle into single jar called bundle.jar. Next, run the following command:

ikvmc -target:library -out:bundle.dll bundle.jar

This will create bundle.dll file containing IL code representing Java bytecode.

C# part

Now create a class library with the following code:

using System;

namespace Exceptionhandler
{
    public class Class1
    {
       public static int AddHandler(string arg)
       {
            Console.WriteLine("Starting");

            Program.main(new String[0]);
            return 5;
       }
    }
}

Add necessary references to bundle.dll and other IKVM libraries which you need to use. Compile and follow the same path as in Injecting managed DLL. The C# code you just built is just a different Exceptionhandler. Do not forget to have IKVM libraries on the PATH (ideally the same directory as the target application) as they need to be loaded with the Exceptionhandler. You could split this into multiple class libraries and load IKVM dynamically though.

Result

Here is the result:

Java DLL Injection

As you can see, there is a line printed out by the Java code.