DLL Injection Part 2 — Hooks

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

Last time we saw how to inject DLL using registry. Today we are going to implement another approach using Hooks.

Hooks

Hooks allow us to execute a piece of code when specified type of message is sent to window. For instance, we might want to implement keylogger which would register all pressed keys without modifying them. Since there is an option to register global hook — e.g., hook which will execute in every process in the system — we can use this approach to inject our custom logic. Of course “every process in the system” means only processes which we can access easily, we will not overcome the UAC or hack system this way.

Code

Let’s assume that we have the following method:

We receive three arguments describing the message, do something with them, and finally call method CallNextHookEx which passes the hook information to the next method in the hook chain. We need to compile this code and output DLL library. Let’s call it KeyboardHook.dll. Now we can inject the routine using the following code:

When we compile the code, put DLL into correct place (see “search order” in previous part), and execute it, we should successfully hook our code. To verify this, try to press any key on the keyboard and our code from DLL should execute. It should work across the processes, so it should execute when you type in notepad as well.

Summary

As we can see, this method is pretty easy. All we need to do is to prepare custom routine for handling Windows messages and execute a piece of code to register the hook. We are also able to inject the code into already started process. However, there are drawbacks: we do not control into which processes we inject our code (because it is injected into every program), we need to rely on windows messages what sometimes might be difficult (e.g., when passing a keyboard message to windows service), also anti-viruses sometimes blocks this method.