
AV Evasion and Payload Obfuscation Techniques
Antivirus evasion covering shellcode encoding, PE manipulation, process hollowing, direct syscalls and sandbox checks.
Introduction
Antivirus detects in three layers: static signature matching against known byte patterns and strings, heuristic analysis of the PE structure, and behavioral monitoring of API call sequences at runtime. Each layer needs its own answer. Encoding defeats static signatures, PE manipulation defeats heuristics, and syscall-based execution defeats behavioral hooks.
Every evasion technique becomes a signature in the end. Plain XOR-encoded shellcode stubs have been signatured for years. Simple process hollowing with WriteProcessMemory + ResumeThread trips AMSI and EDR sensors today. To stay ahead you need to know what each AV layer inspects and write code whose artifacts fall outside it.
Language choice matters more than most operators admit. AV vendors train their ML models mostly on PE files produced by MSVC, Delphi and .NET. A payload compiled with Nim, Go or Rust has PE headers, import tables and section layouts that differ from those, and gets lower detection rates before any obfuscation is applied.
Authorization required
These techniques defeat real endpoint security controls. Only test AV evasion on systems you own or have explicit written authorization to test. Deploying evasive payloads against production systems without authorization is a criminal offense under the CFAA and equivalent statutes elsewhere.
Impact
- A persistent foothold on endpoints with active AV/EDR coverage
- Shellcode execution without triggering signature-based detections
- A way past the userland API hooks that EDR behavioral engines use
- .NET assemblies converted to position-independent shellcode, which removes assembly-load telemetry
- Sandbox analysis defeated by environment fingerprinting before the payload runs
- A legitimate process image hosting the shellcode, which masks network connections and file I/O
Technical details
Static evasion: shellcode encoding
Static AV scans the bytes of a file, computes entropy scores and matches strings. Raw Meterpreter or Cobalt Strike shellcode contains byte sequences that match existing signatures within seconds of upload to VirusTotal.
XOR encoding with a rotating key destroys the byte signature and adds very little stub code. The decoder runs in memory, so the shellcode stays encrypted on disk. AES-128/256 encryption is stronger: no known-plaintext patterns survive and entropy is uniformly high. Some AV engines flag high-entropy blobs as suspicious.
The loader stub has to avoid detection too. Patterns like VirtualAlloc + RtlMoveMemory + CreateThread appear in thousands of malware samples. Using NtAllocateVirtualMemory + NtWriteVirtualMemory + NtCreateThreadEx through direct syscalls removes the high-level API strings from the import table.
PE manipulation
PE metadata leaks information even when the payload bytes are clean. Debug symbols include original source paths. Compile timestamps often match known toolkits. The standard section names are .text, .data and .rdata. Malicious packers often reuse the same randomized alternatives, and those become signatures in turn.
Strip all debug information at compile time. Set the TimeDateStamp field in the COFF header to a plausible historical date. Rename sections to mimic legitimate applications (.ndata for NSIS installers, for example). Remove or modify the Rich Header, which encodes the compiler version and linker metadata.
Language choice: Nim, Go, Rust
These languages compile to native PE files whose structure differs from the MSVC/MFC baseline the AV models were trained on:
- Nim compiles through a C backend and produces clean import tables with few suspicious imports.
nim c --gc:arc --passL:"-static" payload.nimbuilds a statically linked binary with no runtime DLL dependencies. - Go links statically by default. The Go runtime brings its own section layouts and import patterns. Disabling CGO (
CGO_ENABLED=0) removes all C runtime hooks. - Rust produces tight PE files.
#![no_std]with a custom allocator leaves the Rust standard library out of the binary, which keeps the PE and its import table small.
None of these stays safe. Once operators adopt a language widely, vendors train on it. What you get is a detection gap of months to years on the less common variants.
Shellter: injecting into a legitimate PE
Shellter injects shellcode into an existing legitimate 32-bit PE file. It finds execution paths through the original code and inserts a polymorphic loader that passes control to the shellcode before returning to the normal execution flow. The payload inherits the host binary's signature and structural metadata.
Process hollowing
Process hollowing spawns a legitimate process suspended, unmaps its original image, writes a malicious PE or shellcode in its place, points the thread context at the new entry point, and resumes the thread. Task Manager shows the legitimate binary, but it runs attacker code.
What gets detected is the sequence of API calls: CreateProcess with CREATE_SUSPENDED, NtUnmapViewOfSection, VirtualAllocEx, WriteProcessMemory, SetThreadContext, ResumeThread. EDRs hook every one of these. Direct syscalls and delays between operations lower the heuristic score.
Direct syscalls: SysWhispers2 and Hell's Gate
EDR products instrument userland by patching the first bytes of NTAPI functions in ntdll.dll with JMP instructions that point to the EDR's inspection routines. A call to NtAllocateVirtualMemory runs the EDR's hook before it reaches the kernel.
Direct syscalls skip the hook by invoking the kernel directly. Each NTAPI function is a thin wrapper that loads a syscall number into EAX and executes the syscall instruction. Syscall numbers change between Windows versions, so tools resolve them at runtime from the loaded ntdll.dll image. Hell's Gate reads the clean syscall stubs before any hooks are applied. SysWhispers2 sorts the exported function addresses to infer the syscall IDs (SSN sorting).
Donut: .NET to shellcode
Donut converts .NET assemblies, VBScript, JScript and EXEs into position-independent shellcode that can be injected into any process. You no longer need a .NET loader on disk, and you avoid the assembly-load events that AMSI intercepts. The shellcode bootstraps the CLR in the target process, loads the assembly from memory and invokes the specified method.
Sandbox evasion
Automated analysis sandboxes run a payload for a fixed window (typically 30 to 120 seconds) in a virtualized environment. Fingerprint the environment to detect a sandbox before running the payload:
- Sleep: call
Sleep(30000)before execution. Sandboxes often accelerate or skip sleep calls, which aGetTickCountdelta comparison shows. - Processor count: read
dwNumberOfProcessorsfromGetSystemInfo. Sandboxes typically expose 1 or 2 cores. - User interaction: check how far the cursor moves over time. Automated sandboxes show no mouse movement.
- Disk artifacts: check for recently created files, browser history and installed applications. A clean sandbox has none.
Attack tools
#!/usr/bin/env python3
import sys, os
def xor_encode(shellcode: bytes, key: bytes) -> bytes:
return bytes([b ^ key[i % len(key)] for i, b in enumerate(shellcode)])
with open(sys.argv[1], 'rb') as f:
sc = f.read()
key = os.urandom(16)
encoded = xor_encode(sc, key)
print(f"Key: {key.hex()}")
print(f"Shellcode length: {len(encoded)}")
print(f'unsigned char key[] = {{ {", ".join(hex(b) for b in key)} }};')
print(f'unsigned char sc[] = {{ {", ".join(hex(b) for b in encoded)} }};')#include <windows.h>
unsigned char key[] = { /* key bytes */ };
unsigned char sc[] = { /* encoded shellcode */ };
void decode_and_exec() {
for (size_t i = 0; i < sizeof(sc); i++)
sc[i] ^= key[i % sizeof(key)];
LPVOID mem = VirtualAlloc(NULL, sizeof(sc),
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
memcpy(mem, sc, sizeof(sc));
((void(*)())mem)();
}import winim/lean, nimcrypto
proc loadShellcode(encSc: seq[byte], key: seq[byte]) =
var sc = aes256Decrypt(encSc, key) # nimcrypto AES-256
let mem = VirtualAlloc(nil, cast[SIZE_T](sc.len),
MEM_COMMIT or MEM_RESERVE,
PAGE_EXECUTE_READWRITE)
copyMem(mem, addr sc[0], sc.len)
let fn = cast[proc(){.nimcall.}](mem)
fn()Detection
Static analysis signals
| Indicator | Detection method | Notes |
|---|---|---|
| High entropy sections (>7.0) | PE entropy scan | Packed/encrypted payloads |
| No imports or minimal imports | Import table analysis | Syscall-only loaders |
| Missing Rich Header | PE metadata check | Manually stripped headers |
| Mismatched section sizes | SizeOfRawData vs VirtualSize | Hollowed sections |
| Compile timestamp anomalies | COFF TimeDateStamp | Future or epoch-0 dates |
Behavioral and EDR signals
| Event | Source | MITRE |
|---|---|---|
NtAllocateVirtualMemory + PAGE_EXECUTE_READWRITE on self | ETW Microsoft-Windows-Kernel-Memory | T1055 |
CreateProcess with CREATE_SUSPENDED followed by WriteProcessMemory | Sysmon Event ID 8 (CreateRemoteThread) | T1055.012 |
Thread context modification (SetThreadContext) on foreign process | EDR kernel callback | T1055.012 |
Syscall instruction outside ntdll.dll address range | ETW syscall tracing / Kernel patch guard | T1620 |
LoadLibrary / GetProcAddress chains for NTAPI resolution | API monitor, Frida hooks | T1027 |
SIEM queries
index=windows source="XmlWinEventLog:Microsoft-Windows-Sysmon/Operational"
EventCode=8
SourceImage="*\\svchost.exe" OR SourceImage="*\\explorer.exe"
NOT TargetImage IN ("*\\svchost.exe", "*\\explorer.exe")
| stats count by SourceImage, TargetImage, StartAddress, ComputerName
| where count < 3index=windows EventCode=1
| eval entropy_flag=if(like(CommandLine, "%TEMP%") OR like(CommandLine, "%AppData%"), 1, 0)
| where entropy_flag=1 AND NOT match(Image, "(?i)^C:\\\\Program Files")
| table _time, ComputerName, Image, CommandLine, ParentImageDeviceEvents
| where ActionType == "MemoryRemoteProtect"
| where InitiatingProcessFileName !in~ ("svchost.exe", "lsass.exe", "csrss.exe")
| where AdditionalFields contains "PAGE_EXECUTE"
| project Timestamp, DeviceName, InitiatingProcessFileName,
InitiatingProcessCommandLine, RemoteUrl
| order by Timestamp descRemediation
Endpoint controls
- Deploy an EDR that instruments the kernel through ETW and minifilter drivers as well as userland hooks. Direct syscalls skip userland hooks, but the ETW telemetry is still there.
- Enable Windows Defender Credential Guard and Virtualization-Based Security (VBS), which enforces code integrity policies that block the unsigned kernel drivers some evasion techniques use
- Configure Attack Surface Reduction (ASR) rules: block Office macro execution, block Win32 API calls from Office macros, block executable content from email client
- Enable AMSI for PowerShell, JScript and VBA, so in-memory script content goes through AV scanning before execution
- Enforce application allowlisting with Windows Defender Application Control (WDAC), which stops unsigned PE execution whatever the obfuscation
Network controls
- Inspect TLS traffic at the perimeter for Cobalt Strike/Brute Ratel malleable C2 profiles (JA3/JA3S fingerprints, HTTP header anomalies)
- Block outbound connections from processes that should not generate network traffic (
svchost.exeto non-Microsoft IPs,explorer.exedirect C2)
Monitoring
- Collect full Sysmon telemetry: Event IDs 1, 3, 7, 8, 10, 11, 12, 13, 15, 17, 18, 22, 23, 25, 26
- Enable
Microsoft-Windows-Kernel-MemoryETW provider for virtual memory operation auditing - Alert on processes with
PAGE_EXECUTE_READWRITEmemory allocations from userland (not kernel drivers)
References
MITRE ATT&CK techniques
- T1027 - Obfuscated Files or Information
- T1055 - Process Injection
- T1140 - Deobfuscate/Decode Files or Information
- T1620 - Reflective Code Loading
Tools and documentation
- SysWhispers2: direct syscall stub generator
- Donut: .NET/PE to shellcode converter
- Shellter: PE shellcode injector
- Hell's Gate: dynamic syscall number resolution
- Nim for offensive tooling: Nim payload templates
Next steps
Kerberoasting
With a payload that survives on the endpoint, request and crack service tickets.
ACL abuse in Active Directory
Turn the foothold into privilege through misconfigured object permissions.
AS-REP roasting
Crack accounts that do not require Kerberos pre-authentication.
DNSAdmins exploitation
Escalate from DNSAdmins membership to code execution on a domain controller.
AppLocker and WDAC Bypass Techniques
AppLocker and Windows Defender Application Control bypass methods, covering trusted folder abuse, LOLBAS proxy execution and Constrained Language Mode escape.
EDR Evasion Techniques in Modern Red Team Operations
EDR evasion techniques covering direct syscalls, API unhooking, process injection, sleep obfuscation, PPID and command-line spoofing, and ETW and AMSI patching.