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:
Create a malicious DLL that exports one function, which when invoked, executes meterpreter shellcode
Create another program that loads the malicious binary by:
Resolving address of the exported function
Installing a keyboard hook. The hook is then pointed to the exported function
Notepad.exe is launched by the victim and a keypress is registered
Since keyboard events are hooked, notepad.exe loads in our malicious dll and invokes the exported function
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: