SetWindowHookEx Code Injection

Windows allow programs to install hooks to monitor various system events such as mouse clicks and keyboard key presses by using SetWindowHookEx.

In this lab SetWindowHookEx is used to inject a malicious DLL into notepad.exe, which then executes meterpreter shellcode.

Overview

The workflow of the technique is as follows:

  1. Create a malicious DLL that exports one function, which when invoked, executes meterpreter shellcode

  2. Create another program that loads the malicious binary by:

    1. Resolving address of the exported function

    2. Installing a keyboard hook. The hook is then pointed to the exported function

  3. Notepad.exe is launched by the victim and a keypress is registered

  4. Since keyboard events are hooked, notepad.exe loads in our malicious dll and invokes the exported function

  5. Metepreter session is established on the attacking system

Execution

Let's create a DLL with an export a function spotlessExport that executes meterpreter shellcode when invoked:

Compile the DLL and check if the export was successful. We can use dumpbin.exe to do this, but first we need to find it (if we have Visual Studio installed):

cmd /c dir /s/b c:\dumpbin*

Then use it like so to dump the exported functions:

dumpbin.exe dllhook.dll /exports

Below shows the output of exported functions for dllhook.dll as presented by CFF Explorer (left) and dumpin:

Demo

Below shows the technique in action:

  • Process Explorer (top right) with notepad (bottom right) selected

  • In the middle - the code that installs the hook to all threads that are in the same desktop as the calling thread

  • Attacking system with multi-handler on the left - ready to catch the meterpreter

  • Once the hook is installed and a key is pressed in when notepad is in focus, dllhook.dll is loaded into notepad.exe process and our malicious exported function exportedSpotless is executed, which in turn results in a meterpreter shell

Code

Both hooks.cpp and dllhook.cpp are provided below:

#include "pch.h"
#include <iostream>
#include <Windows.h>

int main()
{
	HMODULE library = LoadLibraryA("dllhook.dll");
	HOOKPROC hookProc = (HOOKPROC)GetProcAddress(library, "spotlessExport");

	HHOOK hook = SetWindowsHookEx(WH_KEYBOARD, hookProc, library, 0);
	Sleep(10*1000);
	UnhookWindowsHookEx(hook);

	return 0;
}

References

Last updated