DLL Injection Part 3 — Creating remote thread

This is the third 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 know how to inject a DLL into process using registry or hooks. With the former approach we cannot control the moment of injection (because it usually happens when the process is starting) whilst with the latter approach we cannot choose the target process (since our library is called to every process). Today we will see yet another method. This time we will be able to precisely choose the target process and the time of injection.

Loading library

In order to load library during runtime we can call LoadLibrary or LoadLibraryEx method and pass it a path to the library. What if we could do the same but in another process? Fortunately, Windows gives us an option to execute code in other process using CreateRemoteThread function. Basically, we are able to start a thread in other process.

Every thread requires a thread function: a piece of code which newly spawned thread will execute. This method can accept at most one parameter. How can we use this to inject DLL? Well, we can create remote thread and point its thread function to LoadLibrary in target process. However, we need to be able to pass a path to the library as a parameter. We cannot simply allocate memory using malloc because this method allocates memory in our process.

There is a method which is able to allocate memory in other process: VirtualAllocEx. We can use it to allocate some bytes in target address space and write there a DLL path using WriteProcessMemory function. This should work good.

So the plan looks as follows: we allocate memory in the target process and fill it with the path to the DLL. Next, we get the address of LoadLibrary function and use it as a thread function for thread created in remote process. Let’s see some code.

Code

The code should be pretty obvious:

Summary

We are now able to inject DLL into the process we choose and when we decide. Next time we will use this method to inject managed (.NET) DLL.