Malware Development Trick 46: Dissecting a Simple Windows Keylogger in C for Red and Blue Teams + Video

Listen to this Post

Featured Image

Introduction:

Keyloggers remain a staple in the attacker’s arsenal, capturing every keystroke to harvest credentials, personal messages, and sensitive data. Understanding how these tools are built at a low level is crucial for both Red Teams aiming to simulate realistic threats and Blue Teams striving to detect them. This article dissects a simple Windows keylogger written in C, exploring the mechanics of hooking, the Windows message loop, and provides actionable steps for both offensive execution and defensive mitigation.

Learning Objectives:

  • Understand the Windows API functions used for keyboard input monitoring (SetWindowsHookEx, GetMessage).
  • Analyze the structure and flow of a basic C-based keylogger.
  • Learn how to compile and test the keylogger in a controlled environment.
  • Identify key Indicators of Compromise (IoCs) for detecting such malware.
  • Implement mitigation strategies and detection rules to defend against keyloggers.

You Should Know:

1. Understanding the Core Mechanism: Windows Hooks

The provided keylogger example leverages the Windows hook mechanism, a powerful feature that allows a program to monitor or manipulate message traffic. The specific function used is SetWindowsHookEx, which installs an application-defined hook procedure into a hook chain. For a keylogger, the hook type is WH_KEYBOARD_LL, a low-level keyboard hook that monitors keyboard input events globally, even if the target window is not in focus.

Step‑by‑step guide explaining what this does:

The low-level hook does not require a specific DLL to be injected into other processes because it is processed globally. The hook procedure is called every time a keyboard event occurs. The key steps in the code are:
1. Install the Hook: `HHOOK hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookProcedure, GetModuleHandle(NULL), 0);` The `HookProcedure` is the callback function that will process keystrokes. The last parameter `0` makes it a global thread-independent hook.
2. Define the Callback: The `HookProcedure` function intercepts the `WM_KEYDOWN` message. It extracts the virtual-key code (e.g., VK_RETURN for Enter, VK_SHIFT for Shift) and translates it using `MapVirtualKey` or by maintaining a static keymap to log the actual character.
3. Message Loop: The program enters a message loop (while (GetMessage(&msg, NULL, 0, 0))) to keep the hook active and processing events. Without this, the program would exit immediately, and the hook would be removed.
4. Logging: The keystroke is typically written to a file, often hidden in a user directory like `C:\Users\Public\` or `%TEMP%` to avoid immediate suspicion.

2. Compiling and Testing the Keylogger (Offensive Simulation)

To understand the tool’s functionality, it can be compiled in a safe, isolated lab environment. This should never be run on a production system without explicit authorization.

Step‑by‑step guide:

  1. Save the Code: Copy the C source code (typically provided in the original post) into a file, e.g., keylogger.c.

2. Compile with MinGW or Visual Studio:

  • Using MinGW (Command Line): Open a command prompt with developer tools or MinGW configured.
    gcc -o keylogger.exe keylogger.c -luser32
    

    The `-luser32` flag links the User32.lib library, which contains `SetWindowsHookEx` and other GUI functions.

  • Using Visual Studio: Open a Developer Command Prompt and run:
    cl keylogger.c user32.lib
    
  1. Execution (In a VM): Run the executable as a standard user.
    keylogger.exe
    

    The console window may remain open. The logged keystrokes will be written to a specified file (e.g., log.txt). To test, open Notepad and type a test string like “Password123”. Check the log file to see the captured input.

  2. Process Analysis: Use tools like Process Explorer or Task Manager to observe the running `keylogger.exe` process. Note its memory usage and any open file handles pointing to the log file.

3. Detection and Mitigation for Blue Teams

Detecting a low-level keylogger like this relies on monitoring for anomalous API calls and process behavior.

Step‑by‑step guide for detection:

  1. Monitor for SetWindowsHookEx: Use a security information and event management (SIEM) solution or Endpoint Detection and Response (EDR) to log and alert on the use of SetWindowsHookEx, especially with the `WH_KEYBOARD_LL` flag (value 13). This is a strong indicator of keystroke logging attempts.

– PowerShell to search for processes using hooks:

Get-Process | Where-Object { $_.Modules.ModuleName -contains "user32.dll" } | Select-Object Name, Id

(This is a very broad filter; more advanced hunting would require inspecting hook chains directly.)
2. Command-line logging: Enable command-line process auditing in Windows (via Group Policy: Administrative Templates -> System -> Audit Process Creation). This can help identify when `keylogger.exe` is launched.
3. Network Monitoring: While this specific keylogger writes to a file, more advanced variants exfiltrate data. Monitor for unusual outbound connections from non-browser processes.
4. File Integrity Monitoring: Monitor write access to sensitive user profile directories and the creation of hidden or suspicious text files in `%APPDATA%` or %TEMP%.

4. Hardening Against Keyloggers

Prevention and hardening are the best defenses. These steps can significantly reduce the risk of keyloggers successfully capturing data.

Step‑by‑step guide for system hardening:

  1. Enable Windows Defender Credential Guard: This isolates secrets and prevents even kernel-level access from dumping credentials.
  2. Use Application Control: Implement AppLocker or Windows Defender Application Control (WDAC) to block the execution of unauthorized binaries, including custom-compiled tools like this keylogger.
  3. Employ a Virtual Keyboard for Sensitive Input: For highly sensitive data (like banking passwords), using the on-screen keyboard (OSK) can bypass hardware and software keyloggers, as there are no physical keystrokes to intercept. Launch it via:
    osk
    
  4. Keep Software Updated: Ensure all software, especially browsers and the OS, are patched to prevent privilege escalation that could allow a keylogger to run at a higher integrity level.

5. API Security and Keylogger Relevance

While this is a host-based attack, the concept relates to API security in a broader sense. Keyloggers often target credentials that are then used to authenticate to APIs.

Step‑by‑step guide for securing API keys on endpoints:

  1. Avoid Hardcoding: Never store API keys in plaintext in applications or scripts that could be logged by a keylogger as a user types them.
  2. Use Environment Variables or Secure Vaults: Store secrets in secure, encrypted vaults (like Windows Credential Manager) that are accessed programmatically, not typed out by a user.
  3. Implement Multi-Factor Authentication (MFA): Even if a keylogger captures a password, MFA can prevent unauthorized access, as the one-time code cannot be captured by a simple keystroke logger (unless it is also typed).

What Undercode Say:

Key Takeaway 1: Simplicity is Stealthy. This keylogger demonstrates that sophisticated malware doesn’t require thousands of lines of code. By leveraging the built-in, trusted Windows API (user32.dll), it can operate without raising immediate red flags. This reinforces the need for behavior-based detection (EDR) rather than simple signature-based antivirus.

Key Takeaway 2: Defense in Depth is Mandatory. No single tool can prevent a keylogger. A layered approach combining application whitelisting, principle of least privilege, user education (to avoid running untrusted `.exe` files), and continuous monitoring for anomalous hook installations is the only effective strategy. Blue Teams must focus on the “living off the land” aspects of such attacks.

Analysis:

The educational value of this code for cybersecurity professionals is immense. For Red Teams, it’s a foundational building block for more complex credential-harvesting tools. For Blue Teams, analyzing it provides deep insight into how attackers think and operate. The use of low-level hooks is a classic technique that, despite being well-known, remains effective because it operates at a layer many users and basic security tools ignore. The real-world implication is that an attacker who achieves initial code execution on a workstation can silently harvest everything typed—from emails to banking credentials—for days or weeks, emphasizing the critical importance of securing endpoints.

Prediction:

As EDR solutions become more adept at flagging SetWindowsHookEx, we will see a shift in malware development towards more sophisticated techniques. Future keyloggers will likely move away from user-land hooks and increasingly leverage hardware-level attacks (like USB device emulation), direct kernel object manipulation, or use of graphics frameworks (like DirectX) to capture input before it reaches the standard Windows message queue. This will force defenders to look beyond the traditional API and monitor for anomalies in kernel callbacks and hardware behavior.

▶️ Related Video (76% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Florian Hansemann – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky