In this tutorial i'll try to cover all of the known methods(or at least, those that I know =p) of injecting dll's into a process.
Dll injection is incredibly useful for TONS of stuff(game hacking, function hooking, code patching, keygenning, unpacking, etc..).
Though there are scattered tutorials on these techniques available throughout the web, I have yet to see any complete tutorials detailing
all of them(there may even be more out there than I have here, of course), and comparing their respective strength's and weakness's.
This is precisely what i'll attempt to do for you in this paper. You are free to reproduce or copy this paper, so long as proper
credit is given and you don't modify it without speaking to me first.

The CreateRemoteThread method

I've used this in tons of stuff, and I only recently realized that a lot of people have never seen it, or know how to do it.
I can't take credit for thinking it up...I got it from an article on codeproject, but it's a neat trick that I think more
people should know how to use.

The trick is simple, and elegant. The windows API provides us with a function called CreateRemoteThread(). This allows you
to start a thread in another process. For our purposes, i'll assume you know how threading works, and how to use functions like
CreateThread(if not, you can go here ). The main disadvantage of this method is that it will work only on windows NT and above.
To prevent it from crashing, you should use this function to check to make sure you're on an NT-based system(thanks to CatID for
pointing this out):

So, it's essentially CreateThread, with an hProcess argument, so that we can tell it in which process to create the new thread.Now, normally we would want to start the thread executing on some internal function of the process that we are interacting with. However, to inject a dll, we have to do something a little bit different.

This code, calls CreateRemoteThread() with a lpStartAddress of LoadLibrary(). So, it starts a new thread in the remote process and executes the LoadLibrary() function. Luckily for us, this function takes only one argument, the name of the dll to load. We can pass this in the arg field of CreateRemoteThread(). However, there is a minor dilemma. Since this thread will not be executing in our address space, it won't be able to refer to strings(such as the name of the dll) that are in our address space. So, before callingCreateRemoteThread(), we have to allocate space in the other process, using VirtualAllocEx(), and write our string there. Finally, we pass the pointer to the string inside the remote process in the single arg field of CreateRemoteThread(), and voila...Our dll is now loaded and running smoothly within the remote process. This is the generic loader program I use whenever I need to load a dll.

The SetWindowsHookEx method

The SetWindowsHookEx method is a little bit more intrusive than the first, and creates more of a commotion in the injected process, which we normally don't want. However, it is a little bit easier to use than the first, and does have it's own advantages(like being able to inject into every process on the system in one shot). The SetWindowsHookEx() function is designed to allow you to "hook" windows messages for a given thread. This requires that you inject a dll into that process's address space, so SetWindowsHookEx() handles all that for us. The dll must have a function for the hook that it created though, otherwise it will crash.

idHook is just that, the ID of the message that we want to hook. There are many of them(for a complete list, gohere ), however we'll want to use one that's as unintrusive as possible, and has the least likelihood of causing alarm bells togo off in any AV software(SetWindowsHookEx is the staple of all ring3 keyloggers). The WH_CBT message seems innocuous enough.

Quote:

WH_CBT Installs a hook procedure that receives notifications useful to a computer-based training (CBT) application. For more information, see the CBTProc hook procedure.

--MSDN

So, we'll need to create a placebo CBT hook proc in our dll, so that when the hook is called, we can handle it properly.

All we're doing is calling the next hook in the chain of hooks that exist for this message. Getting back to the SetWindowsHookEx()function, the next parameter we see is lpfn. lpfn is exactly as it sounds "long pointer to function". That's a pointer to our CBT hook proc function. So, to get this, we'll have to either hardcode the address, or load the dll first ourselves. Hardcoding anythingis a bad idea, so we'll load the dll using LoadLibrary(), and use GetProcAddress() to get the address of our function.

Now, in cbtProcAddr we have the address of our function. Parameter 3, of SetWindowsHookEx() is a handle to our dll, we've already obtained this in the process of getting the address of CBTProc(hDll is a handle to our dll, returned by LoadLibrary). Now,there is only one parameter left in the SetWindowsHookEx() function, the dwThreadId parameter. If you want to inject your dll into every process on the system(useful for global function hooks, keyloggers, trojans, rootkits, etc..) you can simply specify 0 for this parameter. If you want to target a specific process, you'll need to get the ID of one of it's threads. There are many ways of doing this, and i'll try to enumerate as many as I can think of in Appendix B. So,to put it all together into one neat little function:

Instead of exploiting a windows API function to force the process to load our Dll, this time we'll allocate a little chunk memory inside the target application, and inject a little stub that loads our dll. The advantage of this approach is that itwill work on any version of windows, and it's also the least detectable of any of the methods mentioned thus far. Our stub willlook like this:

0xDEADBEEF is just there to mark addresses that we can't know beforehand, and have to patch-in at runtime. Ok, let's make a listof the things that we need to do to make this work:

- Allocate space for the stub- Allocate space for the name of the dll - Suspend the main thread of our target - Get the address of the next instruction to be executed(need this for the next step) - Patch the proper address to return to in the stub - Patch the address of the dll name - Patch the address of LoadLibrary - Set the address of the next instruction to be executed in our target's thread, to the address of the beginning of our stub - Resume the target's thread

To allocate space inside the target, we'll use VirtualAllocEx(). We'll need to open a handle to the processwith the VM_OPERATION privelege specified, in order to do this. For our dllName string, we'll only need read and write priveleges. For the stub however, we'll need read, write, and execute priveleges. Then we'll write in our dllName string, so that we can referenceit from the stub once it's inserted.

Now, we need to pause the thread in order to get it's "context". The context of a thread is the current state of all of it'sregisters, as well as other peripheral information. However, we're mostly concerned with the EIP register, which points to the next instruction to be executed. So, if we don't suspend the thread before retrieving its context information, it'll continue executing and by the time we get the information, it'll be invalid. Once we've paused the thread, we'll retrieve it's context information using the GetThreadContext() function. We'll grab the value of the current next instruction to be executed, so that we know where our stub should return to. Then it's just a matter of patching up the stub to have all of the proper pointers, and forcing the thread to execute it:

WriteProcessMemory(hProcess, stub, loadDll, stubLen, NULL); //Write the stub into the target//Set the new context of the target's threadSetThreadContext(hThread, &ctx);//Let the target thread continue execution, starting at our stubResumeThread(hThread);

All that's left now, is to cleanup the evidence. Before we do that though, we should pause the injector for a bit, to be surethat the target has time to execute our stub(don't want any nasty race conditions). We'll use Sleep() to pause for 8 seconds beforeunmapping the memory that we allocated, and exiting the injector.

This method should work on any version of windows, and should be the least likely to trigger any A/V alarms or cause the program to malfunction. If you can understand it and implement it properly, this is definitely the best of the three methods.

Appendix A - Methods of obtaining a process ID

If the process you're targeting has a window, you can use the FindWindow function, in conjunction with GetWindowThreadProcessId,as shown here:

//I could just use PROCESS_ALL_ACCESS but it's always best to use the absolute bare minimum of priveleges, so that your code works in as //many circumstances as possible.#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)

Very nice tutorial, the CreateRemoteThread method is actually the one im using now...My code is very similar to your example.(i gave credit to you for the Injection Code and CatID for the IsWindowsNT function, which works wonders btw) Thank You Again!

Hello. I'm using the CreateRemoteThread method, and I have a slight problem. I'd like to UN-inject this DLL, if possible. I have a game I'm writing the DLL for, and I really don't want to close/reopen the game every single time I want to make a change. Friends have suggested FreeLibrary..... but I have no handle from LoadLibrary... I think.

I'm testing on Minesweeper. I launch a copy of Minesweeper, and then run my launcher program. I exported an UnjectMyself DLL function, which calls FreeLibrary. Then before my launcher quits, I call UnjectMyself. Then, if I try to rebuild, it fails. However, if I quit Minesweeper, then I am able to build just fine.

The eventual goal of this program is to inject a DLL into an online game, which takes a long time to load. It will be very painstaking to close/reopen the game at every single build.

I'm testing on Minesweeper. I launch a copy of Minesweeper, and then run my launcher program. I exported an UnjectMyself DLL function, which calls FreeLibrary. Then before my launcher quits, I call UnjectMyself. Then, if I try to rebuild, it fails. However, if I quit Minesweeper, then I am able to build just fine.

The eventual goal of this program is to inject a DLL into an online game, which takes a long time to load. It will be very painstaking to close/reopen the game at every single build.

Is there any other way to do this?

There are two ways that I can think of right now that would allow you to unload your module. The first one is to unload your module using FreeLibrary from an external process with the CreateRemoteThread function. This method is almost identical to dll injection except it is calling FreeLibrary.

The other way that I can think of is to unload and exit the thread at the same time:

Just pass the module handle to it and it will unload itself. Make sure you know what thread it is closing, though. Examples:
-If you close while in DllMain while your module is still loading, you will be closing the injection thread, meaning that it loads and unloads all with one thread.
-Almost everything else will be part of of the program you are injected to. Create a new thread (with CreateThread) and then Uninject.
-If you want to unload for anti-detection reasons, you will need a different function because using CreateThread would cause a race issue.

DllMain creates the WaitForUnload thread, which just blocks on the global event object. When you want to unload, your external loader/unloader can just set the event and it will immediately unload itself.

_________________

Physco wrote:

Its all the same haha they try to disprove our religion but they cant, they just point out that theirs a lack of evidence and an overwhelming amount of evidence on their side.