SetWindowsHookEx Injection
Malware installs a global Windows message hook via SetWindowsHookEx to force its DLL into target processes, executing code whenever a hooked event fires.
SetWindowsHookEx installs a hook procedure into a hook chain to monitor system events such as keystrokes, mouse clicks, and window messages. When called with a thread ID of 0, the hook is global — the OS loads the DLL containing the hook procedure into every GUI process on the desktop. This provides a convenient, API-sanctioned DLL injection primitive.
Attackers use low-level keyboard hooks (WH_KEYBOARD_LL) for keylogging, and global message hooks (WH_GETMESSAGE, WH_CBT) to inject a malicious DLL into every GUI application.
How it works
// malicious_hook.dll — the hook procedure exported from the injected DLL
__declspec(dllexport) LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0) {
// Malicious action here (e.g., log keystrokes, launch payload)
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
// injector.exe — installs the global hook
int main(void)
{
HMODULE hDll = LoadLibraryW(L"malicious_hook.dll");
HOOKPROC pProc = (HOOKPROC)GetProcAddress(hDll, "HookProc");
// WH_GETMESSAGE (3) → fires for every GetMessage call in any GUI thread
HHOOK hHook = SetWindowsHookExW(WH_GETMESSAGE, pProc, hDll, 0 /* global */);
// Keep alive — DLL stays mapped in remote processes as long as hook is active
MSG msg;
while (GetMessageW(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
UnhookWindowsHookEx(hHook);
return 0;
}The OS maps the DLL into each target process transparently; the hook procedure executes in the context of the target process every time the relevant event occurs there.
Detection & analysis
During analysis:
- Use Process Hacker or x64dbg's module list to detect unexpected DLLs loaded in GUI processes.
- Sysinternals Autoruns shows registered global hooks; look for DLLs in unusual paths under
HKCUsoftware keys orAppData. - API monitor: trace
SetWindowsHookExW/Acalls withhmod != NULLanddwThreadId == 0.
Static / automated detection:
- YARA rule U1227: co-occurrence of
SetWindowsHookExA,UnhookWindowsHookEx, andCallNextHookExin a PE export table. - SIGMA rule: alert on process image loads where a DLL appears in multiple unrelated GUI processes within seconds.
- Defender / EDR: hook injection via
SetWindowsHookExmaps to MITRE T1056.001 (keylogging) or T1546 (event-triggered execution).