DLL Injection Part I - .exe surgery without an incision
=======================================================

by isildur, December 2002


The following article will show you how you can do code injection
without modifying in any way the target application. No patching or
whatsoever. We will inject our own dll in the target address space
and then take complete control of it.


How it's done
=============

There is more than one way to acheive this and the following method is
one of them. It works on all 32 bit Windows platform.

Ok, so how do you do this? With a loader and using a Windows API
function called SetWindowsHooksEx. This function is used to monitor the system
for specific events. We want to monitor the messages sent to our target's
message queue. For that we will use the WH_GETMESSAGE type of hook.

So we will use WH_GETMESSAGE as the first parameter of that function. The second
parameter is a pointer to a callback function that will be called when a message is
posted to our target. For our needs, that function will reside in a separate dll, not directly
inside our loader. That's the key for our trick to work (more on that in a moment).
The third param is our dll's instance handle. The last param is the target's main
thread ID.

So basically, to take control over our target, we need to find it's main window handle first.
Then, using that handle we get the thread ID for that window. With that information, we can
then set the hook and inject our dll. Our hook function will then subclass the target's main
window with our own window procedure. With that, we can then do lots of things like add or modify
menus, modify the behavior of the application etc. The limit is your imagination...

So you say "Yeah but how does the dll get injected?". Windows will do that automatically for you
when you set the hook. Isn't that great? Ok, but we still have to follow some strict rules for
everything to work fine.


In details
==========

Remember when I said that the function pointer has to reside in our dll, not in the loader itself?
Here is what happens:

After setting the hook on our target:

1. A message is about to be dispatched to our target main window.
2. The system verifies if there is a WH_GETMESSAGE hook installed for this thread.
3. It finds our hook, then it checks to see if the dll containing the hook callback function is already
   mapped in the target's address space.
4. It will see that it's not mapped there, so it loads the dll in the target's address space. Bingo!
5. It then calls our callback funtion, and that's where the fun begins...


Implementation
==============

Target: Notepad
Goal:   Alter the way Notepad looks (adding a menu to change text and backgroud color)

Tools needed: MSVC (Other C compilers may work but I had to use some #pragma directives
              that may be different with other compilers.)

Let's have some fun with Notepad!

We will build a little loader and a dll to inject in Notepad. The loader will execute Notepad,
get its main window handle and the window's thread ID. The loader will then set up the hook
that will inject the dll in Notepad's address space. Our dll will add color functionality to
Notepad.

You will need to download the source for the loader and dll to understand the rest of this
article. Get it here (link) or at www.geocities.com/v_d_d (link).


Inside the loader
-----------------

Look at the file notepadLoader.c. This is a very simple dialog based win32 application.
The function that does the job is InitializeApp(). Inside, we call loadNotepad() which just
executes Notepad using CreateProcess. Then we load our dll using LoadLibrary and we get
the pointers of two functions inside the dll, SetHook and UnsetHook. We then get the main
window handle with a call to FindWindow using the class name of that window, which in our case
is "Notepad". (By the way, make sure notepad is not running when you execute the loader
because I did not put any code to update multiple instances of the target.)

I found the class name for Notepad's main window using a utility called Spy++ that comes
with the MSVC compiler. Then we get the thread ID of that window with a call to GetWindowThreadProcessId.
And last but not least, we call our dll function SetHook passing the thread ID and window handle
to it. That's all the loader does. When we close the dialog, we call UnsetHook to clean up, because
it is not recommended to leave unused hooks behind in the system.


Inside our DLL
--------------

The first function we will look at is SetHook. We first check if there is already a hook.
We want to set the hook only once. We save the window handle to a global variable for later
use. We make a call to SetWindowsHookEx with WH_GETMESSAGE. The second parameter we put
is a callback function pointer, in this case called GetMsgProc. This callback function is implemented
in the dll. This is the function that the system will call every time a message
is posted to Notepad. I will describe it in a moment. We pass it the dll
instance handle that we saved when the dll got loaded (in the DLL_PROCESS_ATTACH section).
The last param is the thread ID that the loader passed to SetHook. We save the caller's
thread ID by calling GetCurrentThreadId. It is sometimes usefull if we want to send information back
to the calling thread (not used in this example). Then we do a PostThreadMessage to Notepad's
thread posting WM_NULL just to make it enter our hook callback function for the first time.

The next function we look at is our famous hook callback function called GetMsgProc. In our
case, we want to do something only the first time this function is called, so we set a static
flag to make it do stuff just the first time. This is the place you can call some of your own
functions doing what ever you need to do. This gets executed in the target's process address space.

For our example, we want to subclass Notepad's main window procedure. The way you do this is
by calling SetWindowLong. You pass Notepad's window handle (that we saved earlier in SetHook),
GWL_WNDPROC as second param and last, a pointer to our own window procedure (that we implement in
the dll also). This call returns a pointer to Notepad's original window procedure, so we save it to a global
variable for later use (we need it). What this does is that every time Notepad's window procedure
is called, it will call OUR OWN window procedure and we can filter the messages BEFORE Notepad.
In our window procedure, we return by calling the ORIGINAL window procedure for any message
we want Notepad to process. 

Now that we subclassed Notepad's window proc, we need the window handle
of the edit box (where you type text in Notepad). So we call FindWindowEx which will search for
child windows of the window handle we provide. We give it Notepad's main window handle and we
use the Edit box's class name "Edit" to find its handle. We save the Edit box's handle to a global
variable for later use. Then we call createAndLoadMenuItems which is a function we implemented that will
add new menu items under the "Format" menu. We add a "Set background color" and a "Set text color"
menu item. Look at the source for more details on that one.

We now have to implement the stuff that will happen when a user clicks on those new menu items. We
do that in our window procedure. Look at the source code if you want the details for that. You could
do anything you want at this point, now that you know how to set things up. My point was to show you
how inject the dll, not teach the whole Win32 API ;-)

So if you click on the new menu items, you will be able to change the text and backgroud colors. Neat?


Important Note
==============

If you look at the dll's source, you will see some #pragma directives at the top. This is vital for
our trick to work. What this does is reserve some global variables to be shared between all processes that
loads our dll. That means that a value set to one of those variables by one process will be reflected
in the other processes that also loaded the dll. If we don't do that, each process will have a different
copy of those variables. You have to understand that there is one process that loads the dll (our loader)
and sets up the hook, and a second process (Notepad) that gets our dll loaded in its address space. Our dll
is loaded by 2 different processes. So it is important that some variables be shared between the two processes
for this method to work. Try it without the #pragma directives and you will see what I mean.


Final words
===========

This was just a small example basically to show you how to set things up but with a little bit of imagination,
you will soon find that the possibilities are great. What is cool about this method is that we didn't have
to patch a single byte of the target application. The disadvantage though is that we need a loader to set up
the hook. But depending on what you need to do, you can save loads of time by being able to code your stuff
in C or C++ using the full extent of the Windows API. No messing with import tables and calculating jumps
and addresses in machine opcode. You could even transform Notepad into a full fledged word processor! lol :)

In part II of this series of articles, I will show a similar method without the use of a loader. The byte patching
is minimal though and the implementation gets done in a dll like with this method. I hope you learned something and
that I was clear enough in my explanations.

isildur

v_d_d(a t)yahoo(d o t)com









