mirror of
https://github.com/bb107/MemoryModulePP
synced 2026-06-08 13:15:33 +00:00
Add project files.
This commit is contained in:
@@ -0,0 +1,886 @@
|
||||
#include <windows.h>
|
||||
#include <winnt.h>
|
||||
#include <stddef.h>
|
||||
#include <tchar.h>
|
||||
#include "rtltype.h"
|
||||
#include "ntstatus.h"
|
||||
#include <algorithm>
|
||||
#ifdef DEBUG_OUTPUT
|
||||
#include <stdio.h>
|
||||
#endif
|
||||
|
||||
#if _MSC_VER
|
||||
#pragma warning(disable:4055)
|
||||
#pragma warning(error: 4244)
|
||||
#pragma warning(error: 4267)
|
||||
#pragma warning(disable:4996)
|
||||
#define inline __inline
|
||||
#endif
|
||||
|
||||
#ifndef IMAGE_SIZEOF_BASE_RELOCATION
|
||||
#define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION))
|
||||
#endif
|
||||
|
||||
#ifdef _WIN64
|
||||
#define HOST_MACHINE IMAGE_FILE_MACHINE_AMD64
|
||||
#else
|
||||
#define HOST_MACHINE IMAGE_FILE_MACHINE_I386
|
||||
#endif
|
||||
|
||||
#include "MemoryModule.h"
|
||||
#define GET_HEADER_DICTIONARY(headers, idx) &headers->OptionalHeader.DataDirectory[idx]
|
||||
|
||||
static PIMAGE_NT_HEADERS WINAPI GetImageNtHeaders(PMEMORYMODULE pModule) {
|
||||
if (pModule->Signature != MEMORY_MODULE_SIGNATURE)return nullptr;
|
||||
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)((LPBYTE)pModule - pModule->SizeofHeaders);
|
||||
PIMAGE_NT_HEADERS headers = (PIMAGE_NT_HEADERS)((LPBYTE)dos + dos->e_lfanew);
|
||||
if (headers->OptionalHeader.ImageBase /*+ pModule->headers_align*/ != (ULONG64)pModule->codeBase)return nullptr;
|
||||
return headers;
|
||||
}
|
||||
|
||||
PMEMORYMODULE WINAPI MapMemoryModuleHandle(HMEMORYMODULE hModule) {
|
||||
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)hModule;
|
||||
if (!dos)return nullptr;
|
||||
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((LPBYTE)hModule + dos->e_lfanew);
|
||||
if (!nt)return nullptr;
|
||||
PMEMORYMODULE pModule = (PMEMORYMODULE)((LPBYTE)hModule + nt->OptionalHeader.SizeOfHeaders);
|
||||
if (pModule->Signature != MEMORY_MODULE_SIGNATURE || (size_t)pModule->codeBase != nt->OptionalHeader.ImageBase)return nullptr;
|
||||
return pModule;
|
||||
}
|
||||
|
||||
bool WINAPI IsValidMemoryModuleHandle(HMEMORYMODULE hModule) {
|
||||
return MapMemoryModuleHandle(hModule) != nullptr;
|
||||
}
|
||||
|
||||
static inline uintptr_t AlignValueDown(uintptr_t value, uintptr_t alignment) {
|
||||
return value & ~(alignment - 1);
|
||||
}
|
||||
|
||||
static inline LPVOID AlignAddressDown(LPVOID address, uintptr_t alignment) {
|
||||
return (LPVOID)AlignValueDown((uintptr_t)address, alignment);
|
||||
}
|
||||
|
||||
static inline size_t AlignValueUp(size_t value, size_t alignment) {
|
||||
return (value + alignment - 1) & ~(alignment - 1);
|
||||
}
|
||||
|
||||
static inline void* OffsetPointer(void* data, ptrdiff_t offset) {
|
||||
return (void*)((uintptr_t)data + offset);
|
||||
}
|
||||
|
||||
static inline void OutputLastError(const char* msg) {
|
||||
#ifndef DEBUG_OUTPUT
|
||||
UNREFERENCED_PARAMETER(msg);
|
||||
#else
|
||||
LPVOID tmp;
|
||||
char* tmpmsg;
|
||||
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&tmp, 0, nullptr);
|
||||
tmpmsg = (char*)LocalAlloc(LPTR, strlen(msg) + strlen(tmp) + 3);
|
||||
sprintf(tmpmsg, "%s: %s", msg, tmp);
|
||||
OutputDebugString(tmpmsg);
|
||||
LocalFree(tmpmsg);
|
||||
LocalFree(tmp);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _WIN64
|
||||
static void FreePointerList(POINTER_LIST* head) {
|
||||
POINTER_LIST* node = head;
|
||||
while (node) {
|
||||
POINTER_LIST* next;
|
||||
VirtualFree(node->address, 0, MEM_RELEASE);
|
||||
next = node->next;
|
||||
delete node;
|
||||
node = next;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Protection flags for memory pages (Executable, Readable, Writeable)
|
||||
static int ProtectionFlags[2][2][2] = {
|
||||
{
|
||||
// not executable
|
||||
{PAGE_NOACCESS, PAGE_WRITECOPY},
|
||||
{PAGE_READONLY, PAGE_READWRITE},
|
||||
}, {
|
||||
// executable
|
||||
{PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY},
|
||||
{PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE},
|
||||
},
|
||||
};
|
||||
static SIZE_T GetRealSectionSize(PMEMORYMODULE module, PIMAGE_SECTION_HEADER section);
|
||||
static VOID FinalSectionsProtect(PMEMORYMODULE module) {
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
PIMAGE_SECTION_HEADER sections = IMAGE_FIRST_SECTION(headers);
|
||||
DWORD protect, oldProtect;
|
||||
bool executable, readable, writeable;
|
||||
#ifdef _WIN64
|
||||
uintptr_t imageOffset = ((uintptr_t)headers->OptionalHeader.ImageBase & 0xffffffff00000000);
|
||||
#else
|
||||
static const uintptr_t imageOffset = 0;
|
||||
#endif
|
||||
for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i, ++sections) {
|
||||
executable = (sections->Characteristics & IMAGE_SCN_MEM_EXECUTE);
|
||||
readable = (sections->Characteristics & IMAGE_SCN_MEM_READ);
|
||||
writeable = (sections->Characteristics & IMAGE_SCN_MEM_WRITE);
|
||||
protect = ProtectionFlags[executable][readable][writeable];
|
||||
if (sections->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) protect |= PAGE_NOCACHE;
|
||||
VirtualProtect((LPVOID)((uintptr_t)sections->Misc.PhysicalAddress | imageOffset),
|
||||
GetRealSectionSize(module, sections), protect, &oldProtect);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
static BOOL CheckSize(size_t size, size_t expected) {
|
||||
if (size < expected) {
|
||||
SetLastError(ERROR_INVALID_DATA);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static BOOL CopySections(const unsigned char* data, size_t size, PMEMORYMODULE module) {
|
||||
LPBYTE codeBase = module->codeBase;
|
||||
LPVOID dest;
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(headers);
|
||||
size_t alloc_size = 0;
|
||||
bool cp = false;
|
||||
for (int i = 0; i < headers->FileHeader.NumberOfSections; i++, section++) {
|
||||
alloc_size = headers->OptionalHeader.SectionAlignment;
|
||||
cp = false;
|
||||
if (section->SizeOfRawData) {
|
||||
if (!CheckSize(size, static_cast<size_t>(section->PointerToRawData) + section->SizeOfRawData)) return FALSE;
|
||||
alloc_size = section->SizeOfRawData;
|
||||
cp = true;
|
||||
}
|
||||
if (alloc_size) {
|
||||
if (!(dest = VirtualAlloc(codeBase + section->VirtualAddress, alloc_size, MEM_COMMIT, PAGE_READWRITE))) {
|
||||
//section = IMAGE_FIRST_SECTION(headers);
|
||||
//for (int j = 0; j < i; ++j, ++section)VirtualFree(codeBase + section->VirtualAddress, 0, MEM_RELEASE);
|
||||
return FALSE;
|
||||
}
|
||||
section->Misc.PhysicalAddress = (DWORD)((uintptr_t)dest & 0xffffffff);
|
||||
RtlZeroMemory(dest, alloc_size);
|
||||
if (cp) {
|
||||
//section->VirtualAddress += module->headers_align;
|
||||
RtlCopyMemory(dest, data + section->PointerToRawData, section->SizeOfRawData);
|
||||
}
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static SIZE_T GetRealSectionSize(PMEMORYMODULE module, PIMAGE_SECTION_HEADER section) {
|
||||
DWORD size = section->SizeOfRawData;
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
if (size == 0) {
|
||||
if (section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) {
|
||||
size = headers->OptionalHeader.SizeOfInitializedData;
|
||||
}
|
||||
else if (section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
|
||||
size = headers->OptionalHeader.SizeOfUninitializedData;
|
||||
}
|
||||
}
|
||||
return (SIZE_T)size;
|
||||
}
|
||||
|
||||
static BOOL FinalizeSection(PMEMORYMODULE module, PSECTIONFINALIZEDATA sectionData) {
|
||||
if (!sectionData->size) return TRUE;
|
||||
if (sectionData->characteristics & IMAGE_SCN_MEM_DISCARDABLE) {
|
||||
// section is not needed any more and can safely be freed
|
||||
if (sectionData->address == sectionData->alignedAddress &&
|
||||
(sectionData->last || GetImageNtHeaders(module)->OptionalHeader.SectionAlignment == module->pageSize || !(sectionData->size % module->pageSize))) {
|
||||
#pragma warning (disable:6250)
|
||||
VirtualFree(sectionData->address, sectionData->size, MEM_DECOMMIT);
|
||||
#pragma warning (default:6250)
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static BOOL FinalizeSections(PMEMORYMODULE module) {
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(headers);
|
||||
#ifdef _WIN64
|
||||
uintptr_t imageOffset = ((uintptr_t)headers->OptionalHeader.ImageBase & 0xffffffff00000000);
|
||||
#else
|
||||
static const uintptr_t imageOffset = 0;
|
||||
#endif
|
||||
SECTIONFINALIZEDATA sectionData;
|
||||
sectionData.address = (LPVOID)((uintptr_t)section->Misc.PhysicalAddress | imageOffset);
|
||||
sectionData.alignedAddress = AlignAddressDown(sectionData.address, module->pageSize);
|
||||
sectionData.size = GetRealSectionSize(module, section);
|
||||
sectionData.characteristics = section->Characteristics;
|
||||
sectionData.last = FALSE;
|
||||
section++;
|
||||
|
||||
// loop through all sections and change access flags
|
||||
for (int i = 1; i < headers->FileHeader.NumberOfSections; i++, section++) {
|
||||
LPVOID sectionAddress = (LPVOID)((uintptr_t)section->Misc.PhysicalAddress | imageOffset);
|
||||
LPVOID alignedAddress = AlignAddressDown(sectionAddress, module->pageSize);
|
||||
SIZE_T sectionSize = GetRealSectionSize(module, section);
|
||||
if (sectionData.alignedAddress == alignedAddress || (uintptr_t)sectionData.address + sectionData.size > (uintptr_t) alignedAddress) {
|
||||
if (!(section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) || !(sectionData.characteristics & IMAGE_SCN_MEM_DISCARDABLE))
|
||||
sectionData.characteristics = (sectionData.characteristics | section->Characteristics) & ~IMAGE_SCN_MEM_DISCARDABLE;
|
||||
else
|
||||
sectionData.characteristics |= section->Characteristics;
|
||||
sectionData.size = (((uintptr_t)sectionAddress) + ((uintptr_t)sectionSize)) - (uintptr_t)sectionData.address;
|
||||
continue;
|
||||
}
|
||||
if (!FinalizeSection(module, §ionData)) return FALSE;
|
||||
sectionData.address = sectionAddress;
|
||||
sectionData.alignedAddress = alignedAddress;
|
||||
sectionData.size = sectionSize;
|
||||
sectionData.characteristics = section->Characteristics;
|
||||
}
|
||||
sectionData.last = TRUE;
|
||||
return FinalizeSection(module, §ionData);
|
||||
}
|
||||
|
||||
static BOOL ExecuteTLS(PMEMORYMODULE module) {
|
||||
unsigned char* codeBase = module->codeBase;
|
||||
PIMAGE_TLS_DIRECTORY tls;
|
||||
PIMAGE_TLS_CALLBACK* callback;
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(headers, IMAGE_DIRECTORY_ENTRY_TLS);
|
||||
if (directory->VirtualAddress == 0) return TRUE;
|
||||
|
||||
tls = (PIMAGE_TLS_DIRECTORY)(codeBase + directory->VirtualAddress);
|
||||
callback = (PIMAGE_TLS_CALLBACK*)tls->AddressOfCallBacks;
|
||||
if (callback) {
|
||||
while (*callback) {
|
||||
(*callback)((LPVOID)codeBase, DLL_PROCESS_ATTACH, nullptr);
|
||||
callback++;
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
typedef struct _REBASE_INFO {
|
||||
USHORT Offset : 12;
|
||||
USHORT Type : 4;
|
||||
}REBASE_INFO, * PREBASE_INFO;
|
||||
typedef struct _IMAGE_BASE_RELOCATION_HEADER {
|
||||
DWORD VirtualAddress;
|
||||
DWORD SizeOfBlock;
|
||||
REBASE_INFO TypeOffset[ANYSIZE_ARRAY];
|
||||
|
||||
DWORD TypeOffsetCount()const {
|
||||
return (this->SizeOfBlock - 8) / sizeof(_REBASE_INFO);
|
||||
}
|
||||
}IMAGE_BASE_RELOCATION_HEADER, * PIMAGE_BASE_RELOCATION_HEADER;
|
||||
static BOOL PerformBaseRelocation(PMEMORYMODULE module, ptrdiff_t delta) {
|
||||
unsigned char* codeBase = module->codeBase;
|
||||
auto directory = GET_HEADER_DICTIONARY(GetImageNtHeaders(module), IMAGE_DIRECTORY_ENTRY_BASERELOC);
|
||||
auto relocation = (PIMAGE_BASE_RELOCATION_HEADER)(codeBase + directory->VirtualAddress);
|
||||
if (!directory->Size) return (delta == 0);
|
||||
while (relocation->VirtualAddress > 0) {
|
||||
auto relInfo = (_REBASE_INFO*)&relocation->TypeOffset;
|
||||
for (DWORD i = 0; i < relocation->TypeOffsetCount(); ++i, ++relInfo) {
|
||||
switch (relInfo->Type) {
|
||||
case IMAGE_REL_BASED_HIGHLOW: *(DWORD*)(codeBase + relocation->VirtualAddress + relInfo->Offset) += (DWORD)delta; break;
|
||||
#ifdef _WIN64
|
||||
case IMAGE_REL_BASED_DIR64: *(ULONGLONG*)(codeBase + relocation->VirtualAddress + relInfo->Offset) += (ULONGLONG)delta; break;
|
||||
#endif
|
||||
case IMAGE_REL_BASED_ABSOLUTE:
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
// advance to next relocation block
|
||||
//relocation->VirtualAddress += module->headers_align;
|
||||
relocation = decltype(relocation)(OffsetPointer(relocation, relocation->SizeOfBlock));
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static BOOL BuildImportTable(PMEMORYMODULE module) {
|
||||
unsigned char* codeBase = module->codeBase;
|
||||
PIMAGE_IMPORT_DESCRIPTOR importDesc;
|
||||
BOOL result = TRUE;
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(headers, IMAGE_DIRECTORY_ENTRY_IMPORT);
|
||||
if (directory->Size == 0) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
importDesc = (PIMAGE_IMPORT_DESCRIPTOR)(codeBase + directory->VirtualAddress);
|
||||
for (; !IsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++) {
|
||||
uintptr_t* thunkRef;
|
||||
FARPROC* funcRef;
|
||||
HMODULE* tmp;
|
||||
HMODULE handle = LoadLibraryA((LPCSTR)(codeBase + importDesc->Name));
|
||||
if (!handle) {
|
||||
SetLastError(ERROR_MOD_NOT_FOUND);
|
||||
result = FALSE;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!(tmp = (HMODULE*)realloc(module->hModulesList, (static_cast<size_t>(module->dwModulesCount) + 1)* (sizeof(HMODULE))))) {
|
||||
FreeLibrary(handle);
|
||||
SetLastError(ERROR_OUTOFMEMORY);
|
||||
result = FALSE;
|
||||
break;
|
||||
}
|
||||
module->hModulesList = tmp;
|
||||
|
||||
module->hModulesList[module->dwModulesCount++] = handle;
|
||||
if (importDesc->OriginalFirstThunk) {
|
||||
thunkRef = (uintptr_t*)(codeBase + importDesc->OriginalFirstThunk);
|
||||
funcRef = (FARPROC*)(codeBase + importDesc->FirstThunk);
|
||||
}
|
||||
else {
|
||||
// no hint table
|
||||
thunkRef = (uintptr_t*)(codeBase + importDesc->FirstThunk);
|
||||
funcRef = (FARPROC*)(codeBase + importDesc->FirstThunk);
|
||||
}
|
||||
for (; *thunkRef; thunkRef++, funcRef++) {
|
||||
if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) {
|
||||
*funcRef = GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef));
|
||||
}
|
||||
else {
|
||||
PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME)(codeBase + (*thunkRef));
|
||||
*funcRef = GetProcAddress(handle, (LPCSTR)&thunkData->Name);
|
||||
}
|
||||
if (*funcRef == 0) {
|
||||
result = FALSE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
FreeLibrary(handle);
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
HMEMORYMODULE MemoryLoadLibrary(const void* data, size_t size) {
|
||||
PMEMORYMODULE hMemoryModule = nullptr;
|
||||
PIMAGE_DOS_HEADER dos_header, new_dos_header;
|
||||
PIMAGE_NT_HEADERS old_header, new_header;
|
||||
unsigned char* code;
|
||||
ptrdiff_t locationDelta;
|
||||
SYSTEM_INFO sysInfo;
|
||||
PIMAGE_SECTION_HEADER section;
|
||||
DWORD i;
|
||||
size_t optionalSectionSize;
|
||||
size_t lastSectionEnd = 0;
|
||||
size_t alignedImageSize;
|
||||
DWORD headers_align;
|
||||
#ifdef _WIN64
|
||||
POINTER_LIST* blockedMemory = nullptr;
|
||||
#endif
|
||||
|
||||
if (!CheckSize(size, sizeof(IMAGE_DOS_HEADER))) return nullptr;
|
||||
dos_header = (PIMAGE_DOS_HEADER)data;
|
||||
if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
|
||||
SetLastError(ERROR_BAD_EXE_FORMAT);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (!CheckSize(size, dos_header->e_lfanew + sizeof(IMAGE_NT_HEADERS))) return nullptr;
|
||||
old_header = (PIMAGE_NT_HEADERS) & ((const unsigned char*)(data))[dos_header->e_lfanew];
|
||||
if (old_header->Signature != IMAGE_NT_SIGNATURE) {
|
||||
SetLastError(ERROR_BAD_EXE_FORMAT);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (old_header->FileHeader.Machine != HOST_MACHINE) {
|
||||
SetLastError(ERROR_BAD_EXE_FORMAT);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (old_header->OptionalHeader.SectionAlignment & 1) {
|
||||
// Only support section alignments that are a multiple of 2
|
||||
SetLastError(ERROR_BAD_EXE_FORMAT);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
//only dll image support
|
||||
if (!(old_header->FileHeader.Characteristics & IMAGE_FILE_DLL)) {
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
section = IMAGE_FIRST_SECTION(old_header);
|
||||
optionalSectionSize = old_header->OptionalHeader.SectionAlignment;
|
||||
for (i = 0; i < old_header->FileHeader.NumberOfSections; i++, section++) {
|
||||
size_t endOfSection;
|
||||
if (section->SizeOfRawData == 0) {
|
||||
// Section without data in the DLL
|
||||
endOfSection = section->VirtualAddress + optionalSectionSize;
|
||||
}
|
||||
else {
|
||||
endOfSection = static_cast<size_t>(section->VirtualAddress) + section->SizeOfRawData;
|
||||
}
|
||||
|
||||
if (endOfSection > lastSectionEnd) {
|
||||
lastSectionEnd = endOfSection;
|
||||
}
|
||||
}
|
||||
|
||||
GetNativeSystemInfo(&sysInfo);
|
||||
alignedImageSize = AlignValueUp(old_header->OptionalHeader.SizeOfImage, sysInfo.dwPageSize);
|
||||
if (alignedImageSize != AlignValueUp(lastSectionEnd, sysInfo.dwPageSize)) {
|
||||
SetLastError(ERROR_BAD_EXE_FORMAT);
|
||||
return nullptr;
|
||||
}
|
||||
alignedImageSize += headers_align = (DWORD)AlignValueUp(sizeof(HMEMORYMODULE) + old_header->OptionalHeader.SizeOfHeaders, sysInfo.dwPageSize);
|
||||
|
||||
// reserve memory for image of library
|
||||
// XXX: is it correct to commit the complete memory region at once?
|
||||
// calling DllEntry raises an exception if we don't...
|
||||
if (!(code = (LPBYTE)VirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase), alignedImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))) {
|
||||
if (!(old_header->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)) {
|
||||
SetLastError(ERROR_BAD_EXE_FORMAT);
|
||||
return nullptr;
|
||||
}
|
||||
if (!(code = (LPBYTE)VirtualAlloc(nullptr, alignedImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))) {
|
||||
SetLastError(ERROR_OUTOFMEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _WIN64
|
||||
// Memory block may not span 4 GB boundaries.
|
||||
while ((((uintptr_t)code) >> 32) < (((uintptr_t)(code + alignedImageSize)) >> 32)) {
|
||||
POINTER_LIST* node = new POINTER_LIST;
|
||||
if (!node) {
|
||||
VirtualFree(code, 0, MEM_RELEASE);
|
||||
FreePointerList(blockedMemory);
|
||||
SetLastError(ERROR_OUTOFMEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
node->next = blockedMemory;
|
||||
node->address = code;
|
||||
blockedMemory = node;
|
||||
|
||||
if (!(code = (LPBYTE)VirtualAlloc(nullptr, alignedImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))) {
|
||||
FreePointerList(blockedMemory);
|
||||
SetLastError(ERROR_OUTOFMEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
new_dos_header = (PIMAGE_DOS_HEADER)code;
|
||||
new_header = (PIMAGE_NT_HEADERS)(code + dos_header->e_lfanew);
|
||||
hMemoryModule = (PMEMORYMODULE)(code + old_header->OptionalHeader.SizeOfHeaders);
|
||||
RtlZeroMemory(hMemoryModule, sizeof(MEMORYMODULE));
|
||||
hMemoryModule->codeBase = code;
|
||||
hMemoryModule->pageSize = sysInfo.dwPageSize;
|
||||
hMemoryModule->Signature = MEMORY_MODULE_SIGNATURE;
|
||||
hMemoryModule->SizeofHeaders = old_header->OptionalHeader.SizeOfHeaders;
|
||||
hMemoryModule->headers_align = headers_align;
|
||||
#ifdef _WIN64
|
||||
hMemoryModule->blockedMemory = blockedMemory;
|
||||
#endif
|
||||
|
||||
if (!CheckSize(size, old_header->OptionalHeader.SizeOfHeaders)) {
|
||||
goto error;
|
||||
}
|
||||
|
||||
// copy PE header to code
|
||||
memcpy(new_dos_header, dos_header, old_header->OptionalHeader.SizeOfHeaders);
|
||||
new_header->OptionalHeader.SizeOfImage = (DWORD)(alignedImageSize);
|
||||
new_header->OptionalHeader.ImageBase = (size_t)code;
|
||||
new_header->OptionalHeader.BaseOfCode = headers_align;
|
||||
|
||||
// copy sections from DLL file block to new memory location
|
||||
if (!CopySections((LPBYTE)data, size, hMemoryModule)) goto error;
|
||||
|
||||
// adjust base address of imported data
|
||||
locationDelta = (ptrdiff_t)(hMemoryModule->codeBase - old_header->OptionalHeader.ImageBase);
|
||||
if (locationDelta && !PerformBaseRelocation(hMemoryModule, locationDelta))goto error;
|
||||
|
||||
// load required dlls and adjust function table of imports
|
||||
if (!BuildImportTable(hMemoryModule)) goto error;
|
||||
|
||||
// mark memory pages depending on section headers and release
|
||||
// sections that are marked as "discardable"
|
||||
if (!FinalizeSections(hMemoryModule)) goto error;
|
||||
FinalSectionsProtect(hMemoryModule);
|
||||
|
||||
// TLS callbacks are executed BEFORE the main loading
|
||||
if (!ExecuteTLS(hMemoryModule)) goto error;
|
||||
|
||||
// get entry point of loaded library
|
||||
if (new_header->OptionalHeader.AddressOfEntryPoint) {
|
||||
__try {
|
||||
// notify library about attaching to process
|
||||
if (!((DllEntryProc)(code + new_header->OptionalHeader.AddressOfEntryPoint))((HINSTANCE)code, DLL_PROCESS_ATTACH, 0)) {
|
||||
SetLastError(ERROR_DLL_INIT_FAILED);
|
||||
goto error;
|
||||
}
|
||||
}
|
||||
__except (EXCEPTION_EXECUTE_HANDLER) {
|
||||
SetLastError(ERROR_ACCESS_DENIED);
|
||||
goto error;
|
||||
}
|
||||
hMemoryModule->initialized = TRUE;
|
||||
}
|
||||
|
||||
return code;
|
||||
error:
|
||||
// cleanup
|
||||
MemoryFreeLibrary(hMemoryModule);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static int _compare(const void* a, const void* b) {
|
||||
const struct ExportNameEntry* p1 = (const struct ExportNameEntry*) a;
|
||||
const struct ExportNameEntry* p2 = (const struct ExportNameEntry*) b;
|
||||
return strcmp(p1->name, p2->name);
|
||||
}
|
||||
|
||||
static int _find(const void* a, const void* b) {
|
||||
LPCSTR* name = (LPCSTR*)a;
|
||||
const struct ExportNameEntry* p = (const struct ExportNameEntry*) b;
|
||||
return strcmp(*name, p->name);
|
||||
}
|
||||
|
||||
FARPROC MemoryGetProcAddress(HMEMORYMODULE mod, LPCSTR name) {
|
||||
PMEMORYMODULE module = MapMemoryModuleHandle(mod);
|
||||
unsigned char* codeBase = module->codeBase - module->headers_align;
|
||||
DWORD idx = 0;
|
||||
PIMAGE_EXPORT_DIRECTORY exports;
|
||||
PIMAGE_NT_HEADERS headers = GetImageNtHeaders(module);
|
||||
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(headers, IMAGE_DIRECTORY_ENTRY_EXPORT);
|
||||
if (directory->Size == 0) {
|
||||
// no export table found
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
exports = (PIMAGE_EXPORT_DIRECTORY)(codeBase + directory->VirtualAddress);
|
||||
if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) {
|
||||
// DLL doesn't export anything
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (HIWORD(name) == 0) {
|
||||
// load function by ordinal value
|
||||
if (LOWORD(name) < exports->Base) {
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
idx = LOWORD(name) - exports->Base;
|
||||
}
|
||||
else if (!exports->NumberOfNames) {
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
else {
|
||||
const struct ExportNameEntry* found;
|
||||
|
||||
// Lazily build name table and sort it by names
|
||||
if (!module->nameExportsTable) {
|
||||
DWORD i;
|
||||
DWORD* nameRef = (DWORD*)(codeBase + exports->AddressOfNames);
|
||||
WORD* ordinal = (WORD*)(codeBase + exports->AddressOfNameOrdinals);
|
||||
ExportNameEntry* entry = new ExportNameEntry[exports->NumberOfNames];
|
||||
module->nameExportsTable = entry;
|
||||
if (!entry) {
|
||||
SetLastError(ERROR_OUTOFMEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
for (i = 0; i < exports->NumberOfNames; i++, nameRef++, ordinal++, entry++) {
|
||||
entry->name = (const char*)(codeBase + (*nameRef));
|
||||
entry->idx = *ordinal;
|
||||
}
|
||||
qsort(module->nameExportsTable,
|
||||
exports->NumberOfNames,
|
||||
sizeof(struct ExportNameEntry), _compare);
|
||||
}
|
||||
|
||||
// search function name in list of exported names with binary search
|
||||
found = (const struct ExportNameEntry*) bsearch(&name,
|
||||
module->nameExportsTable,
|
||||
exports->NumberOfNames,
|
||||
sizeof(struct ExportNameEntry), _find);
|
||||
if (!found) {
|
||||
// exported symbol not found
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
idx = found->idx;
|
||||
}
|
||||
|
||||
if (idx > exports->NumberOfFunctions) {
|
||||
// name <-> ordinal number don't match
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// AddressOfFunctions contains the RVAs to the "real" functions
|
||||
return (FARPROC)(LPVOID)(codeBase + (*(DWORD*)(codeBase + exports->AddressOfFunctions + (static_cast<size_t>(idx) * 4))));
|
||||
}
|
||||
|
||||
bool MemoryFreeLibrary(HMEMORYMODULE mod) {
|
||||
PMEMORYMODULE module = MapMemoryModuleHandle(mod);
|
||||
PIMAGE_NT_HEADERS headers = module ? GetImageNtHeaders(module) : nullptr;
|
||||
|
||||
if (!module || module->Signature != MEMORY_MODULE_SIGNATURE || !headers) return false;
|
||||
if (module->initialized) {
|
||||
DllEntryProc DllEntry = (DllEntryProc)(LPVOID)(module->codeBase + headers->OptionalHeader.AddressOfEntryPoint);
|
||||
(*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0);
|
||||
}
|
||||
if (module->nameExportsTable)delete[] module->nameExportsTable;
|
||||
if (module->hModulesList != nullptr) {
|
||||
int i;
|
||||
for (i = 0; i < module->dwModulesCount; i++) {
|
||||
if (module->hModulesList[i]) {
|
||||
FreeLibrary(module->hModulesList[i]);
|
||||
}
|
||||
}
|
||||
free(module->hModulesList);
|
||||
}
|
||||
#ifdef _WIN64
|
||||
FreePointerList(module->blockedMemory);
|
||||
#endif
|
||||
if (module->codeBase != nullptr) VirtualFree(mod, 0, MEM_RELEASE);
|
||||
return true;
|
||||
}
|
||||
|
||||
#define DEFAULT_LANGUAGE MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)
|
||||
|
||||
HMEMORYRSRC MemoryFindResource(HMEMORYMODULE module, LPCTSTR name, LPCTSTR type) {
|
||||
return MemoryFindResourceEx(module, name, type, DEFAULT_LANGUAGE);
|
||||
}
|
||||
|
||||
static PIMAGE_RESOURCE_DIRECTORY_ENTRY _MemorySearchResourceEntry(void* root, PIMAGE_RESOURCE_DIRECTORY resources, LPCTSTR key) {
|
||||
PIMAGE_RESOURCE_DIRECTORY_ENTRY entries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(resources + 1);
|
||||
PIMAGE_RESOURCE_DIRECTORY_ENTRY result = nullptr;
|
||||
DWORD start;
|
||||
DWORD end;
|
||||
DWORD middle;
|
||||
|
||||
if (!IS_INTRESOURCE(key) && key[0] == TEXT('#')) {
|
||||
// special case: resource id given as string
|
||||
TCHAR* endpos = nullptr;
|
||||
long int tmpkey = (WORD)_tcstol((TCHAR*)&key[1], &endpos, 10);
|
||||
if (tmpkey <= 0xffff && lstrlen(endpos) == 0) {
|
||||
key = MAKEINTRESOURCE(tmpkey);
|
||||
}
|
||||
}
|
||||
|
||||
// entries are stored as ordered list of named entries,
|
||||
// followed by an ordered list of id entries - we can do
|
||||
// a binary search to find faster...
|
||||
if (IS_INTRESOURCE(key)) {
|
||||
WORD check = (WORD)(uintptr_t)key;
|
||||
start = resources->NumberOfNamedEntries;
|
||||
end = start + resources->NumberOfIdEntries;
|
||||
|
||||
while (end > start) {
|
||||
WORD entryName;
|
||||
middle = (start + end) >> 1;
|
||||
entryName = (WORD)entries[middle].Name;
|
||||
if (check < entryName) {
|
||||
end = (end != middle ? middle : middle - 1);
|
||||
}
|
||||
else if (check > entryName) {
|
||||
start = (start != middle ? middle : middle + 1);
|
||||
}
|
||||
else {
|
||||
result = &entries[middle];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
LPCWSTR searchKey;
|
||||
size_t searchKeyLen = _tcslen(key);
|
||||
|
||||
#if defined(UNICODE)
|
||||
searchKey = key;
|
||||
#else
|
||||
// Resource names are always stored using 16bit characters, need to
|
||||
// convert string we search for.
|
||||
#define MAX_LOCAL_KEY_LENGTH 2048
|
||||
// In most cases resource names are short, so optimize for that by
|
||||
// using a pre-allocated array.
|
||||
wchar_t _searchKeySpace[MAX_LOCAL_KEY_LENGTH + 1];
|
||||
LPWSTR _searchKey = nullptr;
|
||||
if (searchKeyLen > MAX_LOCAL_KEY_LENGTH) {
|
||||
if (!(_searchKey = new wchar_t[searchKeyLen + 1])) {
|
||||
SetLastError(ERROR_OUTOFMEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
else {
|
||||
_searchKey = &_searchKeySpace[0];
|
||||
}
|
||||
|
||||
mbstowcs(_searchKey, key, searchKeyLen);
|
||||
_searchKey[searchKeyLen] = 0;
|
||||
searchKey = _searchKey;
|
||||
#endif
|
||||
start = 0;
|
||||
end = resources->NumberOfNamedEntries;
|
||||
while (end > start) {
|
||||
int cmp;
|
||||
PIMAGE_RESOURCE_DIR_STRING_U resourceString;
|
||||
middle = (start + end) >> 1;
|
||||
resourceString = (PIMAGE_RESOURCE_DIR_STRING_U)OffsetPointer(root, entries[middle].Name & 0x7FFFFFFF);
|
||||
cmp = _wcsnicmp(searchKey, resourceString->NameString, resourceString->Length);
|
||||
if (cmp == 0) {
|
||||
// Handle partial match
|
||||
if (searchKeyLen > resourceString->Length) {
|
||||
cmp = 1;
|
||||
}
|
||||
else if (searchKeyLen < resourceString->Length) {
|
||||
cmp = -1;
|
||||
}
|
||||
}
|
||||
if (cmp < 0) {
|
||||
end = (middle != end ? middle : middle - 1);
|
||||
}
|
||||
else if (cmp > 0) {
|
||||
start = (middle != start ? middle : middle + 1);
|
||||
}
|
||||
else {
|
||||
result = &entries[middle];
|
||||
break;
|
||||
}
|
||||
}
|
||||
#if !defined(UNICODE)
|
||||
if (searchKeyLen > MAX_LOCAL_KEY_LENGTH) {
|
||||
delete[] _searchKey;
|
||||
}
|
||||
#undef MAX_LOCAL_KEY_LENGTH
|
||||
#endif
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
HMEMORYRSRC MemoryFindResourceEx(HMEMORYMODULE module, LPCTSTR name, LPCTSTR type, WORD language) {
|
||||
PMEMORYMODULE mod = MapMemoryModuleHandle(module);
|
||||
unsigned char* codeBase = mod->codeBase;
|
||||
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(GetImageNtHeaders(mod), IMAGE_DIRECTORY_ENTRY_RESOURCE);
|
||||
PIMAGE_RESOURCE_DIRECTORY rootResources;
|
||||
PIMAGE_RESOURCE_DIRECTORY nameResources;
|
||||
PIMAGE_RESOURCE_DIRECTORY typeResources;
|
||||
PIMAGE_RESOURCE_DIRECTORY_ENTRY foundType;
|
||||
PIMAGE_RESOURCE_DIRECTORY_ENTRY foundName;
|
||||
PIMAGE_RESOURCE_DIRECTORY_ENTRY foundLanguage;
|
||||
if (directory->Size == 0) {
|
||||
// no resource table found
|
||||
SetLastError(ERROR_RESOURCE_DATA_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (language == DEFAULT_LANGUAGE) {
|
||||
// use language from current thread
|
||||
language = LANGIDFROMLCID(GetThreadLocale());
|
||||
}
|
||||
|
||||
// resources are stored as three-level tree
|
||||
// - first node is the type
|
||||
// - second node is the name
|
||||
// - third node is the language
|
||||
rootResources = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + directory->VirtualAddress);
|
||||
foundType = _MemorySearchResourceEntry(rootResources, rootResources, type);
|
||||
if (foundType == nullptr) {
|
||||
SetLastError(ERROR_RESOURCE_TYPE_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
typeResources = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + directory->VirtualAddress + (foundType->OffsetToData & 0x7fffffff));
|
||||
foundName = _MemorySearchResourceEntry(rootResources, typeResources, name);
|
||||
if (foundName == nullptr) {
|
||||
SetLastError(ERROR_RESOURCE_NAME_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
nameResources = (PIMAGE_RESOURCE_DIRECTORY)(codeBase + directory->VirtualAddress + (foundName->OffsetToData & 0x7fffffff));
|
||||
foundLanguage = _MemorySearchResourceEntry(rootResources, nameResources, (LPCTSTR)(uintptr_t)language);
|
||||
if (foundLanguage == nullptr) {
|
||||
// requested language not found, use first available
|
||||
if (nameResources->NumberOfIdEntries == 0) {
|
||||
SetLastError(ERROR_RESOURCE_LANG_NOT_FOUND);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
foundLanguage = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(nameResources + 1);
|
||||
}
|
||||
|
||||
return (codeBase + directory->VirtualAddress + (foundLanguage->OffsetToData & 0x7fffffff));
|
||||
}
|
||||
|
||||
DWORD MemorySizeofResource(HMEMORYMODULE module, HMEMORYRSRC resource) {
|
||||
PIMAGE_RESOURCE_DATA_ENTRY entry;
|
||||
UNREFERENCED_PARAMETER(module);
|
||||
entry = (PIMAGE_RESOURCE_DATA_ENTRY)resource;
|
||||
if (entry == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return entry->Size;
|
||||
}
|
||||
|
||||
LPVOID MemoryLoadResource(HMEMORYMODULE module, HMEMORYRSRC resource) {
|
||||
unsigned char* codeBase = MapMemoryModuleHandle(module)->codeBase;
|
||||
PIMAGE_RESOURCE_DATA_ENTRY entry = (PIMAGE_RESOURCE_DATA_ENTRY)resource;
|
||||
if (entry == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return codeBase + entry->OffsetToData;
|
||||
}
|
||||
|
||||
int MemoryLoadString(HMEMORYMODULE module, UINT id, LPTSTR buffer, int maxsize) {
|
||||
return MemoryLoadStringEx(module, id, buffer, maxsize, DEFAULT_LANGUAGE);
|
||||
}
|
||||
|
||||
int MemoryLoadStringEx(HMEMORYMODULE module, UINT id, LPTSTR buffer, int maxsize, WORD language) {
|
||||
HMEMORYRSRC resource;
|
||||
PIMAGE_RESOURCE_DIR_STRING_U data;
|
||||
DWORD size;
|
||||
if (maxsize == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
resource = MemoryFindResourceEx(module, MAKEINTRESOURCEW((static_cast<size_t>(id) >> 4) + 1), RT_STRING, language);
|
||||
if (resource == nullptr) {
|
||||
buffer[0] = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
data = (PIMAGE_RESOURCE_DIR_STRING_U)MemoryLoadResource(module, resource);
|
||||
id = id & 0x0f;
|
||||
while (id--) {
|
||||
data = (PIMAGE_RESOURCE_DIR_STRING_U)OffsetPointer(data, (static_cast<size_t>(data->Length) + 1) * sizeof(WCHAR));
|
||||
}
|
||||
if (data->Length == 0) {
|
||||
SetLastError(ERROR_RESOURCE_NAME_NOT_FOUND);
|
||||
buffer[0] = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
size = data->Length;
|
||||
if (size >= (DWORD)maxsize) {
|
||||
size = maxsize;
|
||||
}
|
||||
else {
|
||||
buffer[size] = 0;
|
||||
}
|
||||
#if defined(UNICODE)
|
||||
wcsncpy(buffer, data->NameString, size);
|
||||
#else
|
||||
wcstombs(buffer, data->NameString, size);
|
||||
#endif
|
||||
return size;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef __MEMORY_MODULE_HEADER
|
||||
#define __MEMORY_MODULE_HEADER
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#pragma warning(disable:4996)
|
||||
struct ExportNameEntry {
|
||||
LPCSTR name;
|
||||
WORD idx;
|
||||
};
|
||||
typedef struct {
|
||||
LPVOID address;
|
||||
LPVOID alignedAddress;
|
||||
SIZE_T size;
|
||||
DWORD characteristics;
|
||||
BOOL last;
|
||||
} SECTIONFINALIZEDATA, * PSECTIONFINALIZEDATA;
|
||||
typedef BOOL(WINAPI* DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved);
|
||||
#ifdef _WIN64
|
||||
typedef struct POINTER_LIST {
|
||||
struct POINTER_LIST* next;
|
||||
void* address;
|
||||
} POINTER_LIST;
|
||||
#endif
|
||||
typedef void* HMEMORYMODULE;
|
||||
typedef void* HMEMORYRSRC;
|
||||
typedef struct _MEMORYMODULE {
|
||||
/*
|
||||
---------------------------
|
||||
|xxxxxxxx BaseAddress |
|
||||
|... |
|
||||
|... |
|
||||
|... | --> IMAGE_DOS_HEADER
|
||||
|... | --> IMAGE_NT_HEADERS
|
||||
|... |
|
||||
|... |
|
||||
--------------------------
|
||||
struct MEMORYMODULE;
|
||||
... (align)
|
||||
codes
|
||||
*/
|
||||
ULONG64 Signature;
|
||||
__declspec(align(sizeof(size_t))) struct {
|
||||
DWORD SizeofHeaders;
|
||||
|
||||
//Not implemented
|
||||
struct {
|
||||
union {
|
||||
//Status Flags
|
||||
BYTE initialized : 1;
|
||||
BYTE reservedStatusFlags : 7;
|
||||
|
||||
BYTE cbFlagsReserved;
|
||||
|
||||
//Load Flags
|
||||
WORD notMapDll : 1;
|
||||
WORD notInsertLdrEntry : 1;
|
||||
WORD notInsertInvertedFunctionTableEntry : 1;
|
||||
WORD notUseReferenceCount : 1;
|
||||
WORD reservedLoadFlags : 12;
|
||||
};
|
||||
DWORD dwModuleFlags;
|
||||
};
|
||||
};
|
||||
|
||||
LPBYTE codeBase; //codeBase == ImageBase + OptionalHeader.BaseOfCode;
|
||||
__declspec(align(sizeof(size_t))) struct {
|
||||
PVOID lpReserved;
|
||||
};
|
||||
|
||||
HMODULE* hModulesList; //Import module handles
|
||||
__declspec(align(sizeof(size_t))) struct {
|
||||
DWORD dwModulesCount; //number of module handles
|
||||
DWORD dwReserved;
|
||||
};
|
||||
|
||||
ExportNameEntry* nameExportsTable;
|
||||
__declspec(align(sizeof(size_t))) struct {
|
||||
DWORD pageSize; //SYSTEM_INFO::dwPageSize
|
||||
DWORD headers_align; //headers_align == OptionalHeaders.BaseOfCode;
|
||||
};
|
||||
|
||||
#ifdef _WIN64
|
||||
POINTER_LIST* blockedMemory;
|
||||
PVOID lpReserved2;
|
||||
#endif
|
||||
} MEMORYMODULE, * PMEMORYMODULE;
|
||||
|
||||
|
||||
#define MEMORY_MODULE_SIGNATURE 0x00aabbcc11ffee00
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Load DLL from memory location with the given size.
|
||||
*
|
||||
* All dependencies are resolved using default LoadLibrary/GetProcAddress
|
||||
* calls through the Windows API.
|
||||
*/
|
||||
HMEMORYMODULE MemoryLoadLibrary(const void*, size_t);
|
||||
|
||||
/**
|
||||
* Get address of exported method. Supports loading both by name and by
|
||||
* ordinal value.
|
||||
*/
|
||||
FARPROC MemoryGetProcAddress(HMEMORYMODULE, LPCSTR);
|
||||
|
||||
/**
|
||||
* Free previously loaded DLL.
|
||||
*/
|
||||
bool MemoryFreeLibrary(HMEMORYMODULE);
|
||||
|
||||
/**
|
||||
* Find the location of a resource with the specified type and name.
|
||||
*/
|
||||
HMEMORYRSRC MemoryFindResource(HMEMORYMODULE, LPCTSTR, LPCTSTR);
|
||||
|
||||
/**
|
||||
* Find the location of a resource with the specified type, name and language.
|
||||
*/
|
||||
HMEMORYRSRC MemoryFindResourceEx(HMEMORYMODULE, LPCTSTR, LPCTSTR, WORD);
|
||||
|
||||
/**
|
||||
* Get the size of the resource in bytes.
|
||||
*/
|
||||
DWORD MemorySizeofResource(HMEMORYMODULE, HMEMORYRSRC);
|
||||
|
||||
/**
|
||||
* Get a pointer to the contents of the resource.
|
||||
*/
|
||||
LPVOID MemoryLoadResource(HMEMORYMODULE, HMEMORYRSRC);
|
||||
|
||||
/**
|
||||
* Load a string resource.
|
||||
*/
|
||||
int MemoryLoadString(HMEMORYMODULE, UINT, LPTSTR, int);
|
||||
|
||||
/**
|
||||
* Load a string resource with a given language.
|
||||
*/
|
||||
int MemoryLoadStringEx(HMEMORYMODULE, UINT, LPTSTR, int, WORD);
|
||||
|
||||
bool WINAPI IsValidMemoryModuleHandle(HMEMORYMODULE hModule);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // __MEMORY_MODULE_HEADER
|
||||
@@ -0,0 +1,176 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="MemoryModule.cpp" />
|
||||
<ClCompile Include="Native.cpp" />
|
||||
<ClCompile Include="NativeFunctionsInternal.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="MemoryModule.h" />
|
||||
<ClInclude Include="Native.h" />
|
||||
<ClInclude Include="NativeFunctionsInternal.h" />
|
||||
<ClInclude Include="rtltype.h" />
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>16.0</VCProjectVersion>
|
||||
<ProjectGuid>{5B1F46DB-036E-4A50-AF5F-F5D6584D42C6}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<RootNamespace>MemoryModule</RootNamespace>
|
||||
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||
<ProjectName>MemoryModule</ProjectName>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="Shared">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<PrecompiledHeaderFile>
|
||||
</PrecompiledHeaderFile>
|
||||
<PrecompiledHeaderOutputFile />
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<PrecompiledHeaderFile>
|
||||
</PrecompiledHeaderFile>
|
||||
<PrecompiledHeaderOutputFile />
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<PrecompiledHeaderFile>
|
||||
</PrecompiledHeaderFile>
|
||||
<PrecompiledHeaderOutputFile />
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>NotUsing</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<PrecompiledHeaderFile>
|
||||
</PrecompiledHeaderFile>
|
||||
<PrecompiledHeaderOutputFile />
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="Source Files">
|
||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Header Files">
|
||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Resource Files">
|
||||
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
||||
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="MemoryModule.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Native.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="NativeFunctionsInternal.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="MemoryModule.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Native.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="rtltype.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="NativeFunctionsInternal.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,360 @@
|
||||
#include "Native.h"
|
||||
#pragma warning(disable:6387)
|
||||
#pragma warning(disable:26812)
|
||||
#pragma comment(lib,"Secur32.lib")
|
||||
|
||||
FARPROC NTAPI RtlGetNtProcAddress(LPCSTR func_name) {
|
||||
return GetProcAddress(GetModuleHandleA("ntdll.dll"), func_name);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtOpenProcessToken(IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, OUT PHANDLE TokenHandle) {
|
||||
typedef NTSTATUS(NTAPI *NtOpenProcessToken_t)(IN HANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, OUT PHANDLE TokenHandle);
|
||||
return (((NtOpenProcessToken_t)RtlGetNtProcAddress("NtOpenProcessToken"))(ProcessHandle, DesiredAccess, TokenHandle));
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtDuplicateToken(IN HANDLE ExistingToken, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
|
||||
IN SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, IN TOKEN_TYPE TokenType, OUT PHANDLE NewToken) {
|
||||
typedef NTSTATUS(NTAPI *NtDuplicateToken_t)(IN HANDLE, IN ACCESS_MASK, IN POBJECT_ATTRIBUTES OPTIONAL, IN SECURITY_IMPERSONATION_LEVEL, IN TOKEN_TYPE, OUT PHANDLE);
|
||||
return (((NtDuplicateToken_t)RtlGetNtProcAddress("NtDuplicateToken"))(ExistingToken, DesiredAccess, ObjectAttributes, ImpersonationLevel, TokenType, NewToken));
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtAdjustPrivilegesToken(IN HANDLE TokenHandle, IN BOOLEAN DisableAllPrivileges, IN PTOKEN_PRIVILEGES TokenPrivileges,
|
||||
IN ULONG PreviousPrivilegesLength, OUT PTOKEN_PRIVILEGES PreviousPrivileges OPTIONAL, OUT PULONG RequiredLength OPTIONAL) {
|
||||
typedef NTSTATUS(NTAPI *NtAdjustPrivilegesToken_t)(IN HANDLE, IN BOOLEAN, IN PTOKEN_PRIVILEGES, IN ULONG, OUT PTOKEN_PRIVILEGES OPTIONAL, OUT PULONG OPTIONAL);
|
||||
return (((NtAdjustPrivilegesToken_t)RtlGetNtProcAddress("NtAdjustPrivilegesToken"))
|
||||
(TokenHandle, DisableAllPrivileges, TokenPrivileges, PreviousPrivilegesLength, PreviousPrivileges, RequiredLength));
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtAllocateLocallyUniqueId(OUT PLUID LocallyUniqueId) {
|
||||
typedef NTSTATUS(NTAPI *NtAllocateLocallyUniqueId_t)(OUT PLUID LocallyUniqueId);
|
||||
return (((NtAllocateLocallyUniqueId_t)RtlGetNtProcAddress("NtAllocateLocallyUniqueId"))(LocallyUniqueId));
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtQueryObject(
|
||||
IN HANDLE ObjectHandle,
|
||||
IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
|
||||
OUT PVOID ObjectInformation,
|
||||
IN ULONG Length,
|
||||
OUT PULONG ResultLength) {
|
||||
typedef NtQueryInformation_t NtQueryObject_t;
|
||||
return (((NtQueryObject_t)RtlGetNtProcAddress("NtQueryObject")))(ObjectHandle, ObjectInformationClass, ObjectInformation, Length, ResultLength);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtSetInformationObject(
|
||||
IN HANDLE ObjectHandle,
|
||||
IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
|
||||
IN PVOID ObjectInformation,
|
||||
IN ULONG Length) {
|
||||
return (((NTSTATUS(__stdcall*)(HANDLE, OBJECT_INFORMATION_CLASS, PVOID, ULONG))RtlGetNtProcAddress("NtSetInformationObject")))
|
||||
(ObjectHandle, ObjectInformationClass, ObjectInformation, Length);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtOpenThreadToken(
|
||||
IN HANDLE ThreadHandle,
|
||||
IN ACCESS_MASK DesiredAccess,
|
||||
IN BOOLEAN OpenAsSelf,
|
||||
OUT PHANDLE TokenHandle) {
|
||||
typedef NTSTATUS (NTAPI *NtOpenThreadToken_t)(
|
||||
IN HANDLE ThreadHandle,
|
||||
IN ACCESS_MASK DesiredAccess,
|
||||
IN BOOLEAN OpenAsSelf,
|
||||
OUT PHANDLE TokenHandle);
|
||||
return (((NtOpenThreadToken_t)RtlGetNtProcAddress("NtOpenThreadToken")))(ThreadHandle, DesiredAccess, OpenAsSelf, TokenHandle);
|
||||
}
|
||||
|
||||
BOOL RtlFreeHeap(PVOID HeapHandle, ULONG Flags, PVOID BaseAddress) {
|
||||
return ((BOOL(__stdcall*)(PVOID, ULONG, PVOID))RtlGetNtProcAddress("RtlFreeHeap"))(HeapHandle, Flags, BaseAddress);
|
||||
}
|
||||
|
||||
PVOID RtlAllocateHeap(PVOID HeapHandle, ULONG Flags, SIZE_T Size) {
|
||||
return ((PVOID(__stdcall*)(PVOID, ULONG, SIZE_T))RtlGetNtProcAddress("RtlAllocateHeap"))(HeapHandle, Flags, Size);
|
||||
}
|
||||
|
||||
PVOID RtlCreateHeap(ULONG Flags, PVOID HeapBase, SIZE_T ReserveSize, SIZE_T CommitSize, PVOID Lock, PRTL_HEAP_PARAMETERS Parameters) {
|
||||
return ((PVOID(__stdcall*)(ULONG, PVOID, SIZE_T, SIZE_T, PVOID, PRTL_HEAP_PARAMETERS))RtlGetNtProcAddress("RtlCreateHeap"))(
|
||||
Flags, HeapBase, ReserveSize, CommitSize, Lock, Parameters);
|
||||
}
|
||||
|
||||
PVOID BsRtlCreateHeap(ULONG Flags, SIZE_T ReserveSize, SIZE_T CommitSize) {
|
||||
return RtlCreateHeap(Flags | HEAP_GROWABLE, NULL, ReserveSize, CommitSize, NULL, NULL);
|
||||
}
|
||||
|
||||
PVOID RtlDestroyHeap(PVOID HeapHandle) {
|
||||
return ((PVOID(__stdcall*)(PVOID))RtlGetNtProcAddress("RtlDestroyHeap"))(HeapHandle);
|
||||
}
|
||||
|
||||
FARPROC WINAPI GetNtProcAddress(LPCSTR func_name) {
|
||||
return GetProcAddress(GetModuleHandleA("ntdll.dll"), func_name);
|
||||
}
|
||||
|
||||
LPCSTR f_NtCreateToken = "NtCreateToken";
|
||||
LPCSTR f_NtDuplicateObject = "NtDuplicateObject";
|
||||
LPCSTR f_RtlNtStatusToDosError = "RtlNtStatusToDosError";
|
||||
LPCSTR f_NtDuplicateToken = "NtDuplicateToken";
|
||||
|
||||
NTSTATUS NTAPI NtCreateToken(
|
||||
PHANDLE TokenHandle,
|
||||
ACCESS_MASK DesiredAccess,
|
||||
POBJECT_ATTRIBUTES ObjectAttributes,
|
||||
TOKEN_TYPE TokenType,
|
||||
PLUID AuthenticationId,
|
||||
PLARGE_INTEGER ExpirationTime,
|
||||
PTOKEN_USER TokenUser,
|
||||
PTOKEN_GROUPS TokenGroups,
|
||||
PTOKEN_PRIVILEGES TokenPrivileges,
|
||||
PTOKEN_OWNER TokenOwner,
|
||||
PTOKEN_PRIMARY_GROUP TokenPrimaryGroup,
|
||||
PTOKEN_DEFAULT_DACL TokenDefaultDacl,
|
||||
PTOKEN_SOURCE TokenSource) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(PHANDLE, ACCESS_MASK, LPVOID, TOKEN_TYPE, PLUID,
|
||||
PLARGE_INTEGER, PTOKEN_USER, PTOKEN_GROUPS, PTOKEN_PRIVILEGES,
|
||||
PTOKEN_OWNER, PTOKEN_PRIMARY_GROUP, PTOKEN_DEFAULT_DACL, PTOKEN_SOURCE)>(GetNtProcAddress(f_NtCreateToken))(
|
||||
TokenHandle, DesiredAccess, ObjectAttributes, TokenType, AuthenticationId,
|
||||
ExpirationTime, TokenUser, TokenGroups, TokenPrivileges, TokenOwner,
|
||||
TokenPrimaryGroup, TokenDefaultDacl, TokenSource);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtDuplicateObject(
|
||||
IN HANDLE SourceProcessHandle,
|
||||
IN HANDLE SourceHandle,
|
||||
IN HANDLE TargetProcessHandle,
|
||||
OUT PHANDLE TargetHandle,
|
||||
IN ACCESS_MASK DesiredAccess OPTIONAL,
|
||||
IN BOOLEAN InheritHandle,
|
||||
IN ULONG Options) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, HANDLE, HANDLE, PHANDLE, ACCESS_MASK, BOOLEAN, LONG)>(GetNtProcAddress(f_NtDuplicateObject))
|
||||
(SourceProcessHandle, SourceHandle, TargetProcessHandle, TargetHandle, DesiredAccess, InheritHandle, Options);
|
||||
}
|
||||
|
||||
DWORD NTAPI RtlNtStatusToDosError(NTSTATUS status) {
|
||||
return reinterpret_cast<DWORD(NTAPI*)(NTSTATUS)>(GetNtProcAddress(f_RtlNtStatusToDosError))(status);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtDuplicateToken(
|
||||
HANDLE ExistingTokenHandle,
|
||||
ACCESS_MASK DesiredAccess,
|
||||
POBJECT_ATTRIBUTES ObjectAttributes,
|
||||
BOOLEAN EffectiveOnly,
|
||||
TOKEN_TYPE TokenType,
|
||||
PHANDLE NewTokenHandle) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, BOOLEAN, TOKEN_TYPE, PHANDLE)>
|
||||
(GetNtProcAddress(f_NtDuplicateToken))(ExistingTokenHandle, DesiredAccess, ObjectAttributes, EffectiveOnly, TokenType, NewTokenHandle);
|
||||
}
|
||||
|
||||
NTSTATUS NtQuerySystemInformation(IN SYSTEM_INFORMATION_CLASS _class, OUT PVOID buffer, IN ULONG buffer_size, OUT PULONG out_len) {
|
||||
return reinterpret_cast<NtQuerySystemInformation_t>(GetNtProcAddress("NtQuerySystemInformation"))(_class, buffer, buffer_size, out_len);
|
||||
}
|
||||
|
||||
NTSTATUS WINAPI NtQueryInformationProcess(IN HANDLE hProcess, IN LONG _class, OUT PVOID buffer, IN ULONG buffer_size, OUT PULONG out_len) {
|
||||
return reinterpret_cast<NtQueryInformation_t>(GetNtProcAddress("NtQueryInformationProcess"))(hProcess, _class, buffer, buffer_size, out_len);
|
||||
}
|
||||
|
||||
NTSTATUS WINAPI NtQueryInformationThread(IN HANDLE hThread, IN LONG _class, OUT PVOID buffer, IN ULONG buffer_size, OUT PULONG out_len) {
|
||||
return reinterpret_cast<NtQueryInformation_t>(GetNtProcAddress("NtQueryInformationThread"))(hThread, _class, buffer, buffer_size, out_len);
|
||||
}
|
||||
|
||||
LPCSTR module = "kernel32.dll";
|
||||
LPCSTR f_CreateProcessInternalW = "CreateProcessInternalW";
|
||||
BOOL WINAPI CreateProcessInternalW(
|
||||
_In_opt_ HANDLE hUserToken,
|
||||
_In_opt_ LPCWSTR lpApplicationName,
|
||||
_Inout_opt_ LPWSTR lpCommandLine,
|
||||
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
|
||||
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
|
||||
_In_ BOOL bInheritHandles,
|
||||
_In_ DWORD dwCreationFlags,
|
||||
_In_opt_ LPVOID lpEnvironment,
|
||||
_In_opt_ LPCWSTR lpCurrentDirectory,
|
||||
_In_ LPSTARTUPINFOW lpStartupInfo,
|
||||
_Out_ LPPROCESS_INFORMATION lpProcessInformation,
|
||||
_Outptr_opt_ PHANDLE hRestrictedUserToken
|
||||
) {
|
||||
return reinterpret_cast<BOOL(WINAPI*)(HANDLE, LPCWSTR, LPWSTR, LPSECURITY_ATTRIBUTES,
|
||||
LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION, PHANDLE)>
|
||||
(GetProcAddress(GetModuleHandleA(module), f_CreateProcessInternalW))(hUserToken, lpApplicationName,
|
||||
lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment,
|
||||
lpCurrentDirectory, lpStartupInfo, lpProcessInformation, hRestrictedUserToken);
|
||||
}
|
||||
|
||||
LPCSTR f_CreateProcessInternalA = "CreateProcessInternalA";
|
||||
BOOL WINAPI CreateProcessInternalA(
|
||||
_In_opt_ HANDLE hUserToken,
|
||||
_In_opt_ LPCSTR lpApplicationName,
|
||||
_Inout_opt_ LPSTR lpCommandLine,
|
||||
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
|
||||
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
|
||||
_In_ BOOL bInheritHandles,
|
||||
_In_ DWORD dwCreationFlags,
|
||||
_In_opt_ LPVOID lpEnvironment,
|
||||
_In_opt_ LPCSTR lpCurrentDirectory,
|
||||
_In_ LPSTARTUPINFOA lpStartupInfo,
|
||||
_Out_ LPPROCESS_INFORMATION lpProcessInformation,
|
||||
_Outptr_opt_ PHANDLE hRestrictedUserToken
|
||||
) {
|
||||
return reinterpret_cast<BOOL(WINAPI*)(HANDLE, LPCSTR, LPSTR, LPSECURITY_ATTRIBUTES,
|
||||
LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPCSTR, LPSTARTUPINFOA, LPPROCESS_INFORMATION, PHANDLE)>
|
||||
(GetProcAddress(GetModuleHandleA(module), f_CreateProcessInternalA))(hUserToken, lpApplicationName,
|
||||
lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment,
|
||||
lpCurrentDirectory, lpStartupInfo, lpProcessInformation, hRestrictedUserToken);
|
||||
}
|
||||
|
||||
VOID NTAPI RtlInitUnicodeString(PUNICODE_STRING DestinationString, PCWSTR SourceString) {
|
||||
return reinterpret_cast<VOID(NTAPI*)(PUNICODE_STRING, PCWSTR)>
|
||||
(RtlGetNtProcAddress("RtlInitUnicodeString"))(DestinationString, SourceString);
|
||||
}
|
||||
|
||||
BOOL NTAPI RtlCreateUnicodeString(PUNICODE_STRING DestinationString, PCWSTR SourceString) {
|
||||
return reinterpret_cast<BOOL(NTAPI*)(PUNICODE_STRING, PCWSTR)>
|
||||
(RtlGetNtProcAddress("RtlCreateUnicodeString"))(DestinationString, SourceString);
|
||||
}
|
||||
|
||||
VOID NTAPI RtlFreeUnicodeString(PUNICODE_STRING UnicodeString) {
|
||||
return reinterpret_cast<VOID(NTAPI*)(PUNICODE_STRING)>
|
||||
(RtlGetNtProcAddress("RtlFreeUnicodeString"))(UnicodeString);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtClose(IN HANDLE Handle) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE)>(RtlGetNtProcAddress("NtClose"))(Handle);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI RtlCreateUserThread(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL,
|
||||
IN BOOLEAN CreateSuspended,
|
||||
IN ULONG StackZeroBits,
|
||||
IN SIZE_T StackReserved,
|
||||
IN SIZE_T StackCommit,
|
||||
IN PVOID StartAddress,
|
||||
IN PVOID StartParameter OPTIONAL,
|
||||
OUT PHANDLE ThreadHandle,
|
||||
OUT CLIENT_ID* ClientID) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PSECURITY_DESCRIPTOR, BOOLEAN, ULONG, SIZE_T, SIZE_T, PVOID, PVOID, PHANDLE, CLIENT_ID*)>
|
||||
(RtlGetNtProcAddress("RtlCreateUserThread"))(
|
||||
ProcessHandle, SecurityDescriptor, CreateSuspended, StackZeroBits,
|
||||
StackReserved, StackCommit, StartAddress, StartParameter, ThreadHandle, ClientID);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtAllocateVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN OUT PVOID *BaseAddress,
|
||||
IN ULONG ZeroBits,
|
||||
IN OUT PULONG RegionSize,
|
||||
IN ULONG AllocationType,
|
||||
IN ULONG Protect) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, ULONG, PULONG, ULONG, ULONG)>(RtlGetNtProcAddress("NtAllocateVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, ZeroBits, RegionSize, AllocationType, Protect);
|
||||
}
|
||||
NTSTATUS NTAPI NtFreeVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID *BaseAddress,
|
||||
IN OUT PULONG RegionSize,
|
||||
IN ULONG FreeType) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, PULONG, ULONG)>(RtlGetNtProcAddress("NtFreeVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, RegionSize, FreeType);
|
||||
}
|
||||
NTSTATUS NTAPI NtReadVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID BaseAddress,
|
||||
OUT PVOID Buffer,
|
||||
IN ULONG NumberOfBytesToRead,
|
||||
OUT PULONG NumberOfBytesReaded OPTIONAL) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, PVOID, ULONG, PULONG)>(RtlGetNtProcAddress("NtReadVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, Buffer, NumberOfBytesToRead, NumberOfBytesReaded);
|
||||
}
|
||||
NTSTATUS NTAPI NtWriteVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID BaseAddress,
|
||||
IN PVOID Buffer,
|
||||
IN ULONG NumberOfBytesToWrite,
|
||||
OUT PULONG NumberOfBytesWritten OPTIONAL) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, PVOID, ULONG, PULONG)>(RtlGetNtProcAddress("NtWriteVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, Buffer, NumberOfBytesToWrite, NumberOfBytesWritten);
|
||||
}
|
||||
NTSTATUS NTAPI NtProtectVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN OUT PVOID *BaseAddress,
|
||||
IN OUT PSIZE_T NumberOfBytesToProtect,
|
||||
IN SIZE_T NewAccessProtection,
|
||||
OUT PSIZE_T OldAccessProtection) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, PSIZE_T, SIZE_T, PSIZE_T)>(RtlGetNtProcAddress("NtProtectVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, NumberOfBytesToProtect, NewAccessProtection, OldAccessProtection);
|
||||
}
|
||||
NTSTATUS NTAPI NtLockVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID *BaseAddress,
|
||||
IN OUT PULONG NumberOfBytesToLock,
|
||||
IN ULONG LockOption) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, PULONG, ULONG)>(RtlGetNtProcAddress("NtLockVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, NumberOfBytesToLock, LockOption);
|
||||
}
|
||||
NTSTATUS NTAPI NtUnlockVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID *BaseAddress,
|
||||
IN OUT PULONG NumberOfBytesToUnlock,
|
||||
IN ULONG LockType) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, PULONG, ULONG)>(RtlGetNtProcAddress("NtUnlockVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, NumberOfBytesToUnlock, LockType);
|
||||
}
|
||||
NTSTATUS NTAPI NtQueryVirtualMemory(
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID BaseAddress,
|
||||
IN MEMORY_INFORMATION_CLASS MemoryInformationClass,
|
||||
OUT PVOID Buffer,
|
||||
IN SIZE_T Length,
|
||||
OUT PSIZE_T ResultLength OPTIONAL) {
|
||||
return reinterpret_cast<NTSTATUS(NTAPI*)(HANDLE, PVOID, MEMORY_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T)>(RtlGetNtProcAddress("NtQueryVirtualMemory"))
|
||||
(ProcessHandle, BaseAddress, MemoryInformationClass, Buffer, Length, ResultLength);
|
||||
}
|
||||
|
||||
PVOID RtlImageDirectoryEntryToData(PVOID BaseAddress, BOOLEAN MappedAsImage, USHORT Directory, PULONG Size) {
|
||||
return ((decltype(&RtlImageDirectoryEntryToData))RtlGetNtProcAddress("RtlImageDirectoryEntryToData"))(BaseAddress, MappedAsImage, Directory, Size);
|
||||
}
|
||||
|
||||
VOID RtlInitAnsiString(PANSI_STRING DestinationString, LPCSTR SourceString) {
|
||||
return ((decltype(&RtlInitAnsiString))RtlGetNtProcAddress("RtlInitAnsiString"))(DestinationString, SourceString);
|
||||
}
|
||||
|
||||
NTSTATUS RtlAnsiStringToUnicodeString(PUNICODE_STRING DestinationString, PANSI_STRING SourceString, BOOLEAN AllocateDestinationString) {
|
||||
return ((decltype(&RtlAnsiStringToUnicodeString))RtlGetNtProcAddress("RtlAnsiStringToUnicodeString"))(DestinationString, SourceString, AllocateDestinationString);
|
||||
}
|
||||
|
||||
PIMAGE_NT_HEADERS NTAPI RtlImageNtHeader(LPVOID BaseAddress) {
|
||||
#pragma warning(disable:6387)
|
||||
return (decltype(&RtlImageNtHeader)(GetProcAddress(GetModuleHandleA("ntdll.dll"), "RtlImageNtHeader")))(BaseAddress);
|
||||
}
|
||||
|
||||
PPEB NTAPI NtCurrentPeb() {
|
||||
return NtCurrentTeb()->ProcessEnvironmentBlock;
|
||||
}
|
||||
|
||||
WCHAR NTAPI RtlUpcaseUnicodeChar(IN WCHAR Source) {
|
||||
USHORT Offset;
|
||||
if (Source < 'a') return Source;
|
||||
if (Source <= 'z') return (Source - ('a' - 'A'));
|
||||
Offset = 0;
|
||||
return Source + (SHORT)Offset;
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI RtlHashUnicodeString(IN PCUNICODE_STRING String, IN BOOLEAN CaseInSensitive, IN ULONG HashAlgorithm, OUT PULONG HashValue) {
|
||||
return (decltype(&RtlHashUnicodeString)(RtlGetNtProcAddress("RtlHashUnicodeString")))(String, CaseInSensitive, HashAlgorithm, HashValue);
|
||||
}
|
||||
|
||||
VOID RtlGetNtVersionNumbers(OUT DWORD* MajorVersion, OUT DWORD* MinorVersion, OUT DWORD* BuildNumber) {
|
||||
static DWORD Versions[3]{ 0 };
|
||||
static auto _RtlGetNtVersionNumbers = (decltype(&RtlGetNtVersionNumbers))RtlGetNtProcAddress("RtlGetNtVersionNumbers");
|
||||
|
||||
if (Versions[0] || !_RtlGetNtVersionNumbers) goto ret;
|
||||
_RtlGetNtVersionNumbers(Versions, Versions + 1, Versions + 2);
|
||||
if (Versions[2] & 0xf0000000)Versions[2] &= 0xffff;
|
||||
|
||||
ret:
|
||||
if (MajorVersion)*MajorVersion = Versions[0];
|
||||
if (MinorVersion)*MinorVersion = Versions[1];
|
||||
if (BuildNumber)*BuildNumber = Versions[2];
|
||||
return;
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtQuerySystemTime(PLARGE_INTEGER SystemTime) {
|
||||
return (decltype(&NtQuerySystemTime)(RtlGetNtProcAddress("NtQuerySystemTime")))(SystemTime);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,880 @@
|
||||
#include "NativeFunctionsInternal.h"
|
||||
#include <random>
|
||||
#pragma warning(disable:6328)
|
||||
#pragma warning(disable:4267)
|
||||
#pragma warning(disable:26812)
|
||||
|
||||
#define RTL_VERIFY_FLAGS_MAJOR_VERSION 0
|
||||
#define RTL_VERIFY_FLAGS_MINOR_VERSION 1
|
||||
#define RTL_VERIFY_FLAGS_BUILD_NUMBERS 2
|
||||
#define RTL_VERIFY_FLAGS_DEFAULT RTL_VERIFY_FLAGS_MAJOR_VERSION|RTL_VERIFY_FLAGS_MINOR_VERSION|RTL_VERIFY_FLAGS_BUILD_NUMBERS
|
||||
static bool NTAPI RtlVerifyVersion(IN DWORD MajorVersion, IN DWORD MinorVersion OPTIONAL, IN DWORD BuildNumber OPTIONAL, IN BYTE Flags) {
|
||||
DWORD Versions[3];
|
||||
RtlGetNtVersionNumbers(Versions, Versions + 1, Versions + 2);
|
||||
if (Versions[0] == MajorVersion &&
|
||||
((Flags & RTL_VERIFY_FLAGS_MINOR_VERSION) ? Versions[1] == MinorVersion : true) &&
|
||||
((Flags & RTL_VERIFY_FLAGS_BUILD_NUMBERS) ? Versions[2] == BuildNumber : true))return true;
|
||||
return false;
|
||||
}
|
||||
static bool NTAPI RtlIsWindowsVersionOrGreater(IN DWORD MajorVersion, IN DWORD MinorVersion, IN DWORD BuildNumber) {
|
||||
DWORD Versions[3];
|
||||
RtlGetNtVersionNumbers(Versions, Versions + 1, Versions + 2);
|
||||
if (Versions[0] == MajorVersion) {
|
||||
if (Versions[1] == MinorVersion) return Versions[2] >= BuildNumber;
|
||||
else return (Versions[1] > MinorVersion);
|
||||
}
|
||||
else return Versions[0] > MajorVersion;
|
||||
}
|
||||
|
||||
static ULONG NTAPI LdrHashEntry(IN const UNICODE_STRING& str, IN bool _xor = true) {
|
||||
ULONG result = 0;
|
||||
if (RtlIsWindowsVersionOrGreater(6, 2, 0)) {
|
||||
RtlHashUnicodeString(&str, TRUE, HASH_STRING_ALGORITHM_DEFAULT, &result);
|
||||
}
|
||||
else {
|
||||
for (USHORT i = 0; i < (str.Length / sizeof(wchar_t)); ++i)
|
||||
result += 0x1003F * RtlUpcaseUnicodeChar(str.Buffer[i]);
|
||||
}
|
||||
if (_xor)result &= (LDR_HASH_TABLE_ENTRIES - 1);
|
||||
return result;
|
||||
}
|
||||
|
||||
static HANDLE NTAPI RtlFindtLdrpHeap() {
|
||||
PLIST_ENTRY ListHead, ListEntry;
|
||||
PLDR_DATA_TABLE_ENTRY CurEntry;
|
||||
static HANDLE result = nullptr;
|
||||
DWORD dwHeaps = 0;
|
||||
HANDLE* hHeaps = nullptr;
|
||||
|
||||
if (result)return result;
|
||||
dwHeaps = GetProcessHeaps(dwHeaps, hHeaps);
|
||||
hHeaps = new HANDLE[dwHeaps];
|
||||
ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
|
||||
ListEntry = ListHead->Flink;
|
||||
if (ListHead == ListEntry)return nullptr;
|
||||
CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
|
||||
GetProcessHeaps(dwHeaps, hHeaps);
|
||||
for (DWORD i = 0; i < dwHeaps; ++i) {
|
||||
if (HeapValidate(hHeaps[i], 0, CurEntry)) {
|
||||
result = hHeaps[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
delete[]hHeaps;
|
||||
return result;
|
||||
}
|
||||
static PLDR_DATA_TABLE_ENTRY NTAPI RtlFindNtdllLdrEntry() {
|
||||
PLIST_ENTRY ListHead, ListEntry;
|
||||
static PLDR_DATA_TABLE_ENTRY CurEntry = nullptr;
|
||||
if (CurEntry)return CurEntry;
|
||||
|
||||
ListHead = &NtCurrentPeb()->Ldr->InInitializationOrderModuleList;
|
||||
ListEntry = ListHead->Flink;
|
||||
while (ListHead != ListEntry) {
|
||||
CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
|
||||
ListEntry = ListEntry->Flink;
|
||||
if (0 == wcsnicmp(CurEntry->BaseDllName.Buffer, L"ntdll.dll", CurEntry->BaseDllName.Length))
|
||||
return CurEntry;
|
||||
}
|
||||
|
||||
return CurEntry = nullptr;
|
||||
}
|
||||
static PLIST_ENTRY NTAPI RtlFindLdrpHashTable() {
|
||||
static PLIST_ENTRY list = nullptr;
|
||||
if (list) return list;
|
||||
|
||||
PLDR_DATA_TABLE_ENTRY CurEntry = RtlFindNtdllLdrEntry();
|
||||
if (!CurEntry)return list;
|
||||
|
||||
if (CurEntry->HashLinks.Flink == &CurEntry->HashLinks)return list;
|
||||
list = (decltype(list))((size_t)CurEntry->HashLinks.Flink - LdrHashEntry(CurEntry->BaseDllName) * sizeof(_LIST_ENTRY));
|
||||
return list;
|
||||
}
|
||||
|
||||
static PVOID NTAPI NtAllocateLdrpHeap(IN size_t size) {
|
||||
HANDLE heap = RtlFindtLdrpHeap();
|
||||
if (!heap)return nullptr;
|
||||
|
||||
return RtlAllocateHeap(heap, HEAP_ZERO_MEMORY, size);
|
||||
}
|
||||
static BOOL NTAPI NtFreeLdrpHeap(IN PVOID buffer) {
|
||||
HANDLE LdrpHeap = RtlFindtLdrpHeap();
|
||||
if (!LdrpHeap)return FALSE;
|
||||
return RtlFreeHeap(LdrpHeap, 0, buffer);
|
||||
}
|
||||
|
||||
static VOID NTAPI NtInitializeListEntry(OUT PLIST_ENTRY entry) {
|
||||
entry->Blink = entry->Flink = entry;
|
||||
}
|
||||
static VOID NTAPI NtInitializeSingleEntry(OUT PSINGLE_LIST_ENTRY entry) {
|
||||
entry->Next = entry;
|
||||
}
|
||||
FORCEINLINE BOOLEAN NTAPI RemoveEntryList(IN PLIST_ENTRY Entry) {
|
||||
PLIST_ENTRY OldFlink;
|
||||
PLIST_ENTRY OldBlink;
|
||||
|
||||
OldFlink = Entry->Flink;
|
||||
OldBlink = Entry->Blink;
|
||||
|
||||
OldFlink->Blink = OldBlink;
|
||||
OldBlink->Flink = OldFlink;
|
||||
return (BOOLEAN)(OldFlink == OldBlink);
|
||||
}
|
||||
|
||||
static WINDOWS_VERSION NTAPI NtWindowsVersion() {
|
||||
static WINDOWS_VERSION version = null;
|
||||
DWORD versions[3]{};
|
||||
if (version)return version;
|
||||
RtlGetNtVersionNumbers(versions, versions + 1, versions + 2);
|
||||
|
||||
switch (versions[0]) {
|
||||
case 5: {
|
||||
switch (versions[1]) {
|
||||
case 1:return version = versions[2] == 2600 ? xp : invalid;
|
||||
case 2:return version = versions[2] == 3790 ? xp : invalid;
|
||||
default:break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 6: {
|
||||
switch (versions[1]) {
|
||||
case 0: {
|
||||
switch (versions[2]) {
|
||||
case 6000:
|
||||
case 6001:
|
||||
case 6002:
|
||||
return version = vista;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 1: {
|
||||
switch (versions[2]) {
|
||||
case 7600:
|
||||
case 7601:
|
||||
return version = win7;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 2: {
|
||||
if (versions[2] == 9200)return version = win8;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 3: {
|
||||
if (versions[2] == 9600)return version = win8_1;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 10: {
|
||||
if (versions[1])break;
|
||||
switch (versions[2]) {
|
||||
case 10240:
|
||||
case 10586: return version = win10;
|
||||
case 14393: return version = win10_1;
|
||||
case 15063:
|
||||
case 16299:
|
||||
case 17134:
|
||||
case 17763:
|
||||
case 18362:return version = win10_2;
|
||||
default:if (RtlIsWindowsVersionOrGreater(versions[0], versions[1], 15063))return version = win10_2;
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return version = invalid;
|
||||
}
|
||||
static size_t NTAPI NtLdrDataTableEntrySize() {
|
||||
static size_t size = 0;
|
||||
if (size)return size;
|
||||
|
||||
switch (NtWindowsVersion()) {
|
||||
case xp:return size = sizeof(LDR_DATA_TABLE_ENTRY_XP);
|
||||
case vista:return size = sizeof(LDR_DATA_TABLE_ENTRY_VISTA);
|
||||
case win7:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN7);
|
||||
case win8:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN8);
|
||||
case win8_1:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN8_1);
|
||||
case win10:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN10);
|
||||
case win10_1:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN10_1);
|
||||
case win10_2:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN10_2);
|
||||
default:return size = sizeof(LDR_DATA_TABLE_ENTRY_WIN10_2);
|
||||
}
|
||||
}
|
||||
|
||||
static PRTL_BALANCED_NODE NTAPI RtlFindLdrpModuleBaseAddressIndex() {
|
||||
static PRTL_BALANCED_NODE LdrpModuleBaseAddressIndex = nullptr;
|
||||
if (LdrpModuleBaseAddressIndex)return LdrpModuleBaseAddressIndex;
|
||||
|
||||
PLDR_DATA_TABLE_ENTRY ntdll = RtlFindNtdllLdrEntry();
|
||||
PLDR_DATA_TABLE_ENTRY_WIN10 nt10 = decltype(nt10)(ntdll);
|
||||
|
||||
if (!ntdll || !RtlIsWindowsVersionOrGreater(6, 2, 0))return nullptr;
|
||||
LdrpModuleBaseAddressIndex = &nt10->BaseAddressIndexNode;
|
||||
while (LdrpModuleBaseAddressIndex->ParentValue) {
|
||||
LdrpModuleBaseAddressIndex = decltype(LdrpModuleBaseAddressIndex)(LdrpModuleBaseAddressIndex->ParentValue & (~7));
|
||||
}
|
||||
if (LdrpModuleBaseAddressIndex->Red)LdrpModuleBaseAddressIndex = nullptr;
|
||||
return LdrpModuleBaseAddressIndex;
|
||||
}
|
||||
static NTSTATUS NTAPI NtInsertModuleBaseAddressIndexNode(IN PLDR_DATA_TABLE_ENTRY DataTableEntry, IN PVOID BaseAddress) {
|
||||
auto LdrpModuleBaseAddressIndex = RtlFindLdrpModuleBaseAddressIndex();
|
||||
if (!LdrpModuleBaseAddressIndex)return STATUS_UNSUCCESSFUL;
|
||||
|
||||
PLDR_DATA_TABLE_ENTRY_WIN8 LdrNode = decltype(LdrNode)((size_t)LdrpModuleBaseAddressIndex - offsetof(LDR_DATA_TABLE_ENTRY_WIN8, BaseAddressIndexNode));
|
||||
RTL_RB_TREE tree{ LdrpModuleBaseAddressIndex };
|
||||
bool bRight = false;
|
||||
const auto i = offsetof(LDR_DATA_TABLE_ENTRY_WIN8, BaseAddressIndexNode);
|
||||
while (true) {
|
||||
if (BaseAddress < LdrNode->DllBase) {
|
||||
if (!LdrNode->BaseAddressIndexNode.Left)break;
|
||||
LdrNode = decltype(LdrNode)((size_t)LdrNode->BaseAddressIndexNode.Left - offsetof(LDR_DATA_TABLE_ENTRY_WIN8, BaseAddressIndexNode));
|
||||
}
|
||||
else if (BaseAddress > LdrNode->DllBase) {
|
||||
if (!LdrNode->BaseAddressIndexNode.Right) {
|
||||
bRight = true;
|
||||
break;
|
||||
}
|
||||
LdrNode = decltype(LdrNode)((size_t)LdrNode->BaseAddressIndexNode.Right - offsetof(LDR_DATA_TABLE_ENTRY_WIN8, BaseAddressIndexNode));
|
||||
}
|
||||
else {
|
||||
LdrNode->DdagNode->LoadCount++;
|
||||
if (RtlIsWindowsVersionOrGreater(10, 0, 0)) {
|
||||
PLDR_DATA_TABLE_ENTRY_WIN10(LdrNode)->ReferenceCount++;
|
||||
}
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
RtlRbInsertNodeEx(&tree, &LdrNode->BaseAddressIndexNode, bRight, &PLDR_DATA_TABLE_ENTRY_WIN8(DataTableEntry)->BaseAddressIndexNode);
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
static NTSTATUS NTAPI NtRemoveModuleBaseAddressIndexNode(IN PLDR_DATA_TABLE_ENTRY DataTableEntry) {
|
||||
RTL_RB_TREE tree{ RtlFindLdrpModuleBaseAddressIndex() };
|
||||
if (!tree.Root)return STATUS_UNSUCCESSFUL;
|
||||
|
||||
RtlRbRemoveNode(&tree, &PLDR_DATA_TABLE_ENTRY_WIN8(DataTableEntry)->BaseAddressIndexNode);
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
static bool NTAPI NtInitializeLdrDataTableEntry(
|
||||
OUT PLDR_DATA_TABLE_ENTRY LdrEntry,
|
||||
IN PVOID BaseAddress,
|
||||
IN ULONG SizeofImage,
|
||||
IN DWORD TimeDateStamp,
|
||||
IN UNICODE_STRING &DllBaseName,
|
||||
IN UNICODE_STRING &DllFullName,
|
||||
IN PVOID EntryPoint) {
|
||||
|
||||
RtlZeroMemory(LdrEntry, NtLdrDataTableEntrySize());
|
||||
PIMAGE_NT_HEADERS headers = RtlImageNtHeader(BaseAddress);
|
||||
|
||||
switch (NtWindowsVersion()) {
|
||||
case win10:
|
||||
case win10_1:
|
||||
case win10_2: {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_WIN10)LdrEntry;
|
||||
entry->ReferenceCount = 1;
|
||||
}
|
||||
case win8:
|
||||
case win8_1: {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_WIN8)LdrEntry;
|
||||
|
||||
entry->OriginalBase = headers->OptionalHeader.ImageBase;
|
||||
entry->BaseNameHashValue = LdrHashEntry(DllBaseName, false);
|
||||
entry->LoadReason = LoadReasonDynamicLoad;
|
||||
if (!NT_SUCCESS(NtInsertModuleBaseAddressIndexNode(LdrEntry, BaseAddress)))return false;
|
||||
if (!(entry->DdagNode = (decltype(entry->DdagNode))NtAllocateLdrpHeap(sizeof(_LDR_DDAG_NODE))))return false;
|
||||
NtInitializeListEntry(&entry->NodeModuleLink);
|
||||
NtInitializeListEntry(&entry->DdagNode->Modules);
|
||||
NtInitializeSingleEntry(&entry->DdagNode->CondenseLink);
|
||||
entry->DdagNode->State = LdrModulesReadyToRun;
|
||||
entry->DdagNode->LoadCount = 0;
|
||||
}
|
||||
|
||||
case win7: {
|
||||
if (NtLdrDataTableEntrySize() == sizeof(LDR_DATA_TABLE_ENTRY_WIN7)) {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_WIN7)LdrEntry;
|
||||
entry->OriginalBase = headers->OptionalHeader.ImageBase;
|
||||
NtQuerySystemTime(&entry->LoadTime);
|
||||
}
|
||||
}
|
||||
case vista: {
|
||||
if (NtLdrDataTableEntrySize() == sizeof(LDR_DATA_TABLE_ENTRY_VISTA) ||
|
||||
NtLdrDataTableEntrySize() == sizeof(LDR_DATA_TABLE_ENTRY_WIN7)) {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_VISTA)LdrEntry;
|
||||
NtInitializeListEntry(&entry->ForwarderLinks);
|
||||
NtInitializeListEntry(&entry->StaticLinks);
|
||||
NtInitializeListEntry(&entry->ServiceTagLinks);
|
||||
}
|
||||
}
|
||||
case xp: {
|
||||
LdrEntry->DllBase = BaseAddress;
|
||||
LdrEntry->SizeOfImage = SizeofImage;
|
||||
LdrEntry->TimeDateStamp = TimeDateStamp;
|
||||
LdrEntry->BaseDllName = DllBaseName;
|
||||
LdrEntry->FullDllName = DllFullName;
|
||||
LdrEntry->EntryPoint = EntryPoint;
|
||||
if (headers->OptionalHeader.DllCharacteristics & IMAGE_FILE_DLL)LdrEntry->Flags |= LDRP_IMAGE_DLL;
|
||||
return true;
|
||||
}
|
||||
default:return false;
|
||||
}
|
||||
}
|
||||
static bool NTAPI NtFreeLdrDataTableEntry(IN PLDR_DATA_TABLE_ENTRY LdrEntry) {
|
||||
switch (NtWindowsVersion()) {
|
||||
case win10:
|
||||
case win10_1:
|
||||
case win10_2: {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_WIN10)LdrEntry;
|
||||
NtFreeLdrpHeap(entry->DdagNode);
|
||||
}
|
||||
case win8:
|
||||
case win8_1: {
|
||||
NtRemoveModuleBaseAddressIndexNode(LdrEntry);
|
||||
}
|
||||
case win7:
|
||||
case vista:
|
||||
case xp: {
|
||||
NtFreeLdrpHeap(LdrEntry->BaseDllName.Buffer);
|
||||
NtFreeLdrpHeap(LdrEntry->FullDllName.Buffer);
|
||||
RemoveEntryList(&LdrEntry->InLoadOrderLinks);
|
||||
RemoveEntryList(&LdrEntry->InMemoryOrderLinks);
|
||||
RemoveEntryList(&LdrEntry->HashLinks);
|
||||
NtFreeLdrpHeap(LdrEntry);
|
||||
return true;
|
||||
}
|
||||
default:return false;
|
||||
}
|
||||
}
|
||||
|
||||
#define FLAG_REFERENCE 0
|
||||
#define FLAG_DEREFERENCE 1
|
||||
static NTSTATUS NTAPI NtUpdateReferenceCount(IN OUT PLDR_DATA_TABLE_ENTRY LdrEntry, IN DWORD Flags) {
|
||||
if (Flags != FLAG_REFERENCE && Flags != FLAG_DEREFERENCE)return STATUS_INVALID_PARAMETER_2;
|
||||
switch (NtWindowsVersion()) {
|
||||
case xp:
|
||||
case vista:
|
||||
case win7: {
|
||||
if (Flags == FLAG_REFERENCE && LdrEntry->LoadCount != 0xffff)
|
||||
++LdrEntry->LoadCount;
|
||||
if (Flags == FLAG_DEREFERENCE && LdrEntry->LoadCount)
|
||||
--LdrEntry->LoadCount;
|
||||
break;
|
||||
}
|
||||
case win8:
|
||||
case win8_1:
|
||||
case win10:
|
||||
case win10_1:
|
||||
case win10_2: {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_WIN10)LdrEntry;
|
||||
if (Flags == FLAG_REFERENCE) {
|
||||
if (entry->ObsoleteLoadCount != 0xffff)++entry->ObsoleteLoadCount;
|
||||
if (entry->DdagNode->LoadCount != 0xffffffff)++entry->DdagNode->LoadCount;
|
||||
}
|
||||
if (Flags == FLAG_DEREFERENCE) {
|
||||
if (entry->ObsoleteLoadCount)--entry->ObsoleteLoadCount;
|
||||
if (entry->DdagNode->LoadCount)--entry->DdagNode->LoadCount;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:return STATUS_UNSUCCESSFUL;
|
||||
}
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
static NTSTATUS NTAPI NtGetReferenceCount(IN PLDR_DATA_TABLE_ENTRY LdrEntry, OUT PULONG Count) {
|
||||
switch (NtWindowsVersion()) {
|
||||
case xp:
|
||||
case vista:
|
||||
case win7: {
|
||||
*Count = LdrEntry->LoadCount;
|
||||
break;
|
||||
}
|
||||
case win8:
|
||||
case win8_1:
|
||||
case win10:
|
||||
case win10_1:
|
||||
case win10_2: {
|
||||
auto entry = (PLDR_DATA_TABLE_ENTRY_WIN8)LdrEntry;
|
||||
*Count = entry->DdagNode->LoadCount == entry->ObsoleteLoadCount ? entry->ObsoleteLoadCount : entry->DdagNode->LoadCount;
|
||||
break;
|
||||
}
|
||||
default:return STATUS_UNSUCCESSFUL;
|
||||
}
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
static bool NTAPI NtResolveDllNameUnicodeString(
|
||||
IN PCWSTR DllName OPTIONAL, IN PCWSTR DllFullName OPTIONAL,
|
||||
OUT PUNICODE_STRING BaseDllName, OUT PUNICODE_STRING FullDllName) {
|
||||
|
||||
std::random_device random;
|
||||
size_t Length = 0;
|
||||
size_t FullLength = 0;
|
||||
PWSTR _DllName = nullptr, _DllFullName = _DllName;
|
||||
bool result = false;
|
||||
if (DllName) {
|
||||
bool add = false;
|
||||
if ((Length = wcslen(DllName)) <= 4 || wcsnicmp(DllName + Length - 4, L".dll", 4)) {
|
||||
add = true;
|
||||
Length += 4;
|
||||
}
|
||||
_DllName = new wchar_t[++Length];
|
||||
wcscpy(_DllName, DllName);
|
||||
if (add)wcscat(_DllName, L".DLL");
|
||||
}
|
||||
else {
|
||||
Length = 16 + 4 + 1; //hex(ULONG64) + ".dll" + '\0'
|
||||
_DllName = new wchar_t[Length];
|
||||
swprintf(_DllName, L"%016llX.DLL", ((ULONG64)random() << 32) | random());
|
||||
}
|
||||
if (DllFullName) {
|
||||
bool add = false;
|
||||
FullLength = wcslen(DllFullName);
|
||||
if (DllName && !wcsstr(DllFullName, DllName) && wcsnicmp(DllFullName + FullLength - 4, L".dll", 4)) {
|
||||
add = true;
|
||||
FullLength += Length;
|
||||
}
|
||||
wcscpy(_DllFullName = new wchar_t[++FullLength], DllFullName);
|
||||
if (add) wsprintfW(_DllFullName, L"%s\\%s", _DllFullName, _DllName);
|
||||
}
|
||||
else {
|
||||
FullLength = 16 + 1 + Length; //hex(ULONG64) + '\\' + _DllName
|
||||
swprintf(_DllFullName = new wchar_t[FullLength], L"%016llX\\%s", ((ULONG64)random() << 32) | random(), _DllName);
|
||||
}
|
||||
FullLength *= sizeof(wchar_t);
|
||||
Length *= sizeof(wchar_t);
|
||||
|
||||
/* Allocate space for full DLL name */
|
||||
if (!(FullDllName->Buffer = (PWSTR)NtAllocateLdrpHeap(FullLength))) goto end;
|
||||
FullDllName->Length = FullLength - sizeof(wchar_t);
|
||||
FullDllName->MaximumLength = FullLength;
|
||||
wcscpy(FullDllName->Buffer, _DllFullName);
|
||||
|
||||
/* Construct base DLL name */
|
||||
BaseDllName->Length = Length - sizeof(wchar_t);
|
||||
BaseDllName->MaximumLength = Length;
|
||||
BaseDllName->Buffer = (PWSTR)NtAllocateLdrpHeap(Length);
|
||||
if (!BaseDllName->Buffer) {
|
||||
NtFreeLdrpHeap(BaseDllName->Buffer);
|
||||
goto end;
|
||||
}
|
||||
wcscpy(BaseDllName->Buffer, _DllName);
|
||||
result = true;
|
||||
end:
|
||||
delete[]_DllName;
|
||||
delete[]_DllFullName;
|
||||
return result;
|
||||
}
|
||||
|
||||
static PLDR_DATA_TABLE_ENTRY NTAPI NtAllocateDataTableEntry(IN PVOID BaseAddress) {
|
||||
PLDR_DATA_TABLE_ENTRY LdrEntry = nullptr;
|
||||
PIMAGE_NT_HEADERS NtHeader;
|
||||
|
||||
/* Make sure the header is valid */
|
||||
if (NtHeader = RtlImageNtHeader(BaseAddress)) {
|
||||
/* Allocate an entry */
|
||||
LdrEntry = (decltype(LdrEntry))NtAllocateLdrpHeap(NtLdrDataTableEntrySize());
|
||||
}
|
||||
|
||||
/* Return the entry */
|
||||
return LdrEntry;
|
||||
}
|
||||
|
||||
static VOID NTAPI NtInsertMemoryTableEntry(IN PLDR_DATA_TABLE_ENTRY LdrEntry) {
|
||||
PPEB_LDR_DATA PebData = NtCurrentPeb()->Ldr;
|
||||
PLIST_ENTRY LdrpHashTable = RtlFindLdrpHashTable();
|
||||
ULONG i;
|
||||
|
||||
/* Insert into hash table */
|
||||
i = LdrHashEntry(LdrEntry->BaseDllName);
|
||||
InsertTailList(&LdrpHashTable[i], &LdrEntry->HashLinks);
|
||||
|
||||
/* Insert into other lists */
|
||||
InsertTailList(&PebData->InLoadOrderModuleList, &LdrEntry->InLoadOrderLinks);
|
||||
InsertTailList(&PebData->InMemoryOrderModuleList, &LdrEntry->InMemoryOrderLinks);
|
||||
}
|
||||
|
||||
static NTSTATUS NTAPI NtMapDllMemory(IN HMEMORYMODULE ViewBase, IN PCWSTR DllName OPTIONAL,
|
||||
IN PCWSTR lpFullDllName OPTIONAL, OUT PLDR_DATA_TABLE_ENTRY* DataTableEntry OPTIONAL) {
|
||||
|
||||
UNICODE_STRING FullDllName, BaseDllName;
|
||||
PIMAGE_NT_HEADERS NtHeaders;
|
||||
PLDR_DATA_TABLE_ENTRY LdrEntry;
|
||||
|
||||
if (!(NtHeaders = RtlImageNtHeader(ViewBase))) return STATUS_INVALID_IMAGE_FORMAT;
|
||||
|
||||
if (!(LdrEntry = NtAllocateDataTableEntry(ViewBase))) return STATUS_NO_MEMORY;
|
||||
|
||||
if (!NtResolveDllNameUnicodeString(DllName, lpFullDllName, &BaseDllName, &FullDllName)) {
|
||||
NtFreeLdrpHeap(LdrEntry);
|
||||
return STATUS_NO_MEMORY;
|
||||
}
|
||||
|
||||
if (!NtInitializeLdrDataTableEntry(LdrEntry, ViewBase,
|
||||
NtHeaders->OptionalHeader.SizeOfImage,
|
||||
NtHeaders->FileHeader.TimeDateStamp,
|
||||
BaseDllName, FullDllName,
|
||||
(PVOID)(NtHeaders->OptionalHeader.AddressOfEntryPoint + NtHeaders->OptionalHeader.ImageBase))) {
|
||||
NtFreeLdrpHeap(LdrEntry);
|
||||
NtFreeLdrpHeap(BaseDllName.Buffer);
|
||||
NtFreeLdrpHeap(FullDllName.Buffer);
|
||||
return STATUS_UNSUCCESSFUL;
|
||||
}
|
||||
|
||||
NtInsertMemoryTableEntry(LdrEntry);
|
||||
if (DataTableEntry)*DataTableEntry = LdrEntry;
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtLoadDllMemory(OUT HMEMORYMODULE* BaseAddress, IN LPVOID BufferAddress, IN size_t BufferSize) {
|
||||
return NtLoadDllMemoryExW(BaseAddress, nullptr, 0, BufferAddress, BufferSize, nullptr, nullptr);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtLoadDllMemoryExW(
|
||||
OUT HMEMORYMODULE* BaseAddress,
|
||||
OUT PLDR_DATA_TABLE_ENTRY* LdrEntry OPTIONAL,
|
||||
IN DWORD dwFlags,
|
||||
IN LPVOID BufferAddress,
|
||||
IN size_t BufferSize,
|
||||
IN LPCWSTR DllName OPTIONAL,
|
||||
IN LPCWSTR DllFullName OPTIONAL) {
|
||||
if (IsBadReadPtr(BufferAddress, BufferSize) || IsBadWritePtr(BaseAddress, sizeof(HMEMORYMODULE)))return STATUS_ACCESS_VIOLATION;
|
||||
*BaseAddress = nullptr;
|
||||
|
||||
if (DllName) {
|
||||
PLIST_ENTRY ListHead, ListEntry;
|
||||
PLDR_DATA_TABLE_ENTRY CurEntry;
|
||||
PIMAGE_NT_HEADERS h1 = RtlImageNtHeader(BufferAddress), h2 = nullptr;
|
||||
if (!h1)return STATUS_INVALID_IMAGE_FORMAT;
|
||||
ListEntry = (ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList)->Flink;
|
||||
while (ListEntry != ListHead) {
|
||||
CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
|
||||
ListEntry = ListEntry->Flink;
|
||||
/* Check if it's being unloaded */
|
||||
if (!CurEntry->InMemoryOrderLinks.Flink) continue;
|
||||
/* Check if name matches */
|
||||
if (!wcsnicmp(DllName, CurEntry->BaseDllName.Buffer, (CurEntry->BaseDllName.Length / sizeof(wchar_t)) - 4) ||
|
||||
!wcsnicmp(DllName, CurEntry->BaseDllName.Buffer, CurEntry->BaseDllName.Length / sizeof(wchar_t))) {
|
||||
/* Let's compare their headers */
|
||||
if (!(h2 = RtlImageNtHeader(CurEntry->DllBase)))continue;
|
||||
if ((h1->OptionalHeader.SizeOfCode == h2->OptionalHeader.SizeOfCode) &&
|
||||
(h1->OptionalHeader.SizeOfHeaders == h2->OptionalHeader.SizeOfHeaders)) {
|
||||
/* This is our entry!, update load count and return success */
|
||||
NtUpdateReferenceCount(CurEntry, FLAG_REFERENCE);
|
||||
*BaseAddress = CurEntry->DllBase;
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!(*BaseAddress = MemoryLoadLibrary(BufferAddress, BufferSize))) {
|
||||
switch (GetLastError()) {
|
||||
case ERROR_BAD_EXE_FORMAT:
|
||||
return STATUS_INVALID_IMAGE_FORMAT;
|
||||
case ERROR_OUTOFMEMORY:
|
||||
return STATUS_NO_MEMORY;
|
||||
case ERROR_DLL_INIT_FAILED:
|
||||
return STATUS_DLL_INIT_FAILED;
|
||||
default:
|
||||
return STATUS_UNSUCCESSFUL;
|
||||
}
|
||||
}
|
||||
|
||||
NTSTATUS status = NtMapDllMemory(*BaseAddress, DllName, DllFullName, LdrEntry);
|
||||
if (!NT_SUCCESS(status)) MemoryFreeLibrary(*BaseAddress);
|
||||
status = RtlInsertInvertedFunctionTable((PVOID)RtlImageNtHeader(*BaseAddress)->OptionalHeader.ImageBase, RtlImageNtHeader(*BaseAddress)->OptionalHeader.SizeOfImage);
|
||||
if (!NT_SUCCESS(status)) MemoryFreeLibrary(*BaseAddress);
|
||||
return status;
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI NtUnloadDllMemory(IN HMEMORYMODULE BaseAddress) {
|
||||
if (IsBadReadPtr(BaseAddress, sizeof(size_t)))return STATUS_ACCESS_VIOLATION;
|
||||
if (!IsValidMemoryModuleHandle(BaseAddress))return STATUS_INVALID_HANDLE;
|
||||
|
||||
PLIST_ENTRY ListHead, ListEntry;
|
||||
PLDR_DATA_TABLE_ENTRY CurEntry;
|
||||
ULONG count = 0;
|
||||
NTSTATUS status = STATUS_SUCCESS;
|
||||
|
||||
ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
|
||||
ListEntry = ListHead->Flink;
|
||||
while (ListEntry != ListHead) {
|
||||
CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
|
||||
ListEntry = ListEntry->Flink;
|
||||
/* Check if it's being unloaded */
|
||||
if (!CurEntry->InMemoryOrderLinks.Flink) continue;
|
||||
/* Check if name matches */
|
||||
if (CurEntry->DllBase == BaseAddress) {
|
||||
if (RtlImageNtHeader(BaseAddress)->OptionalHeader.SizeOfImage == CurEntry->SizeOfImage) {
|
||||
status = NtGetReferenceCount(CurEntry, &count);
|
||||
if (!NT_SUCCESS(status))return status;
|
||||
if (!count) {
|
||||
status = RtlRemoveInvertedFunctionTable(BaseAddress);
|
||||
if (!NT_SUCCESS(status))__fastfail(status);
|
||||
if (!MemoryFreeLibrary(BaseAddress))__fastfail(STATUS_UNSUCCESSFUL);
|
||||
if (!NtFreeLdrDataTableEntry(CurEntry))__fastfail(STATUS_NOT_SUPPORTED);
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
else {
|
||||
return NtUpdateReferenceCount(CurEntry, FLAG_DEREFERENCE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return STATUS_INVALID_HANDLE;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
NT functions
|
||||
*/
|
||||
VOID NTAPI RtlRbInsertNodeEx(IN PRTL_RB_TREE Tree, IN PRTL_BALANCED_NODE Parent, IN BOOLEAN Right, OUT PRTL_BALANCED_NODE Node) {
|
||||
decltype(&RtlRbInsertNodeEx)_RtlRbInsertNodeEx = decltype(_RtlRbInsertNodeEx)(RtlGetNtProcAddress("RtlRbInsertNodeEx"));
|
||||
if (!_RtlRbInsertNodeEx)return;
|
||||
return _RtlRbInsertNodeEx(Tree, Parent, Right, Node);
|
||||
}
|
||||
VOID NTAPI RtlRbRemoveNode(IN PRTL_RB_TREE Tree, IN PRTL_BALANCED_NODE Node) {
|
||||
decltype(&RtlRbRemoveNode)_RtlRbRemoveNode = decltype(_RtlRbRemoveNode)(RtlGetNtProcAddress("RtlRbRemoveNode"));
|
||||
if (!_RtlRbRemoveNode)return;
|
||||
return _RtlRbRemoveNode(Tree, Node);
|
||||
}
|
||||
|
||||
static VOID NTAPI RtlpInsertInvertedFunctionTable(IN PRTL_INVERTED_FUNCTION_TABLE InvertedTable, IN PVOID ImageBase, IN ULONG SizeOfImage) {
|
||||
ULONG CurrentSize;
|
||||
PRUNTIME_FUNCTION FunctionTable;
|
||||
ULONG Index = 1;
|
||||
ULONG SizeOfTable = 0;
|
||||
PIMAGE_NT_HEADERS headers = RtlImageNtHeader(ImageBase);
|
||||
PIMAGE_DATA_DIRECTORY dir = &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
|
||||
bool need = RtlIsWindowsVersionOrGreater(10, 0, 0);
|
||||
|
||||
Index = (ULONG)need;
|
||||
CurrentSize = InvertedTable->Count;
|
||||
if (CurrentSize != InvertedTable->MaxCount) {
|
||||
if (need)_InterlockedIncrement(&InvertedTable->Epoch);
|
||||
if (CurrentSize != 0) {
|
||||
for (Index = 1; Index < CurrentSize; ++Index) {
|
||||
if (ImageBase < InvertedTable->Entries[Index].ImageBase) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (Index != CurrentSize) {
|
||||
RtlMoveMemory(&InvertedTable->Entries[Index + 1],
|
||||
&InvertedTable->Entries[Index],
|
||||
(CurrentSize - Index) * sizeof(RTL_INVERTED_FUNCTION_TABLE_ENTRY));
|
||||
}
|
||||
}
|
||||
|
||||
FunctionTable = (decltype(FunctionTable))((size_t)ImageBase + dir->VirtualAddress);
|
||||
if (FunctionTable != RtlImageDirectoryEntryToData(ImageBase, TRUE, IMAGE_DIRECTORY_ENTRY_EXCEPTION, &SizeOfTable) || SizeOfTable != dir->Size) {
|
||||
__fastfail(STATUS_BAD_DATA);
|
||||
}
|
||||
//SizeOfTable = dir->Size;
|
||||
|
||||
InvertedTable->Entries[Index].ExceptionDirectory = FunctionTable;
|
||||
InvertedTable->Entries[Index].ImageBase = ImageBase;
|
||||
InvertedTable->Entries[Index].ImageSize = SizeOfImage;
|
||||
InvertedTable->Entries[Index].ExceptionDirectorySize = SizeOfTable;
|
||||
InvertedTable->Count++;
|
||||
if (need)_InterlockedIncrement(&InvertedTable->Epoch);
|
||||
}
|
||||
else {
|
||||
need ? (InvertedTable->Overflow = TRUE) : (InvertedTable->Epoch = TRUE);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
static VOID NTAPI RtlpRemoveInvertedFunctionTable(IN PRTL_INVERTED_FUNCTION_TABLE InvertedTable, IN PVOID ImageBase) {
|
||||
ULONG CurrentSize;
|
||||
ULONG Index;
|
||||
bool need = RtlIsWindowsVersionOrGreater(6, 2, 0);
|
||||
|
||||
CurrentSize = InvertedTable->Count;
|
||||
for (Index = 0; Index < CurrentSize; Index += 1) {
|
||||
if (ImageBase == InvertedTable->Entries[Index].ImageBase) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (Index != CurrentSize) {
|
||||
if (need)_InterlockedIncrement(&InvertedTable->Epoch);
|
||||
if (CurrentSize != 1) {
|
||||
RtlMoveMemory(&InvertedTable->Entries[Index],
|
||||
&InvertedTable->Entries[Index + 1],
|
||||
(CurrentSize - Index - 1) * sizeof(RTL_INVERTED_FUNCTION_TABLE_ENTRY));
|
||||
}
|
||||
InvertedTable->Count -= 1;
|
||||
if (need)_InterlockedIncrement(&InvertedTable->Epoch);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
static PVOID NTAPI RtlFindLdrpInvertedFunctionTable() {
|
||||
static PVOID LdrpInvertedFunctionTable = nullptr;
|
||||
if (LdrpInvertedFunctionTable)return LdrpInvertedFunctionTable;
|
||||
|
||||
// _RTL_INVERTED_FUNCTION_TABLE x64 x86
|
||||
// Count +0x0 +0x0 ????????
|
||||
// MaxCount +0x4 +0x4 0x00000200
|
||||
// Epoch +0x8 +0x8 ????????
|
||||
// OverFlow +0xc +0xc 0x00000000
|
||||
// _RTL_INVERTED_FUNCTION_TABLE_ENTRY[0] +0x10 +0x10 ntdll.dll(win10) or The smallest base module
|
||||
// ExceptionDirectory +0x10 +0x10 ++++++++
|
||||
// ImageBase +0x18 +0x14 ++++++++
|
||||
// ImageSize +0x20 +0x18 ++++++++
|
||||
// ExceptionDirectorySize +0x24 +0x1c ++++++++
|
||||
// _RTL_INVERTED_FUNCTION_TABLE_ENTRY[1] ... ... ...
|
||||
// ......
|
||||
|
||||
HMODULE hModule = nullptr, hNtdll = GetModuleHandleW(L"ntdll.dll");
|
||||
PIMAGE_NT_HEADERS NtdllHeaders = RtlImageNtHeader(hNtdll), ModuleHeaders = nullptr;
|
||||
_RTL_INVERTED_FUNCTION_TABLE_ENTRY entry{};
|
||||
PIMAGE_DATA_DIRECTORY dir = nullptr;
|
||||
LPCSTR lpSectionName = ".data";
|
||||
PIMAGE_SECTION_HEADER section = nullptr;
|
||||
struct _SEARCH_DATA {
|
||||
PVOID BaseAddress;
|
||||
DWORD Size;
|
||||
bool operator!() {
|
||||
return !BaseAddress || !Size;
|
||||
}
|
||||
PVOID operator++() {
|
||||
(*(size_t*)&BaseAddress)++;
|
||||
return BaseAddress;
|
||||
}
|
||||
PVOID operator+=(size_t size) {
|
||||
(*(size_t*)&BaseAddress) += size;
|
||||
return BaseAddress;
|
||||
}
|
||||
}data{};
|
||||
const auto EntrySize = sizeof(entry);
|
||||
|
||||
if (RtlIsWindowsVersionOrGreater(10, 0, 0)) {
|
||||
hModule = hNtdll;
|
||||
ModuleHeaders = NtdllHeaders;
|
||||
lpSectionName = ".mrdata";
|
||||
}
|
||||
else {
|
||||
PLIST_ENTRY ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList,
|
||||
ListEntry = ListHead->Flink;
|
||||
PLDR_DATA_TABLE_ENTRY CurEntry = nullptr;
|
||||
while (ListEntry != ListHead) {
|
||||
CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
|
||||
ListEntry = ListEntry->Flink;
|
||||
hModule = (HMODULE)(hModule ? min(hModule, CurEntry->DllBase) : CurEntry->DllBase);
|
||||
}
|
||||
ModuleHeaders = RtlImageNtHeader(hModule);
|
||||
}
|
||||
|
||||
if (!hModule || !ModuleHeaders || !hNtdll || !NtdllHeaders)return LdrpInvertedFunctionTable;
|
||||
dir = &ModuleHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION];
|
||||
entry = {
|
||||
dir->Size ? decltype(entry.ExceptionDirectory)((size_t)hModule + dir->VirtualAddress) : nullptr ,
|
||||
(PVOID)hModule, ModuleHeaders->OptionalHeader.SizeOfImage,dir->Size
|
||||
};
|
||||
section = IMAGE_FIRST_SECTION(NtdllHeaders);
|
||||
for (WORD i = 0; i < NtdllHeaders->FileHeader.NumberOfSections; ++i) {
|
||||
if (!_stricmp(lpSectionName, (LPCSTR)section->Name)) {
|
||||
data = { (PVOID)((size_t)hNtdll + section->VirtualAddress),section->SizeOfRawData };
|
||||
break;
|
||||
}
|
||||
++section;
|
||||
}
|
||||
if (!data || IsBadReadPtr(data.BaseAddress, data.Size))return LdrpInvertedFunctionTable;
|
||||
|
||||
while (data.Size && (data.Size - EntrySize)) {
|
||||
if (RtlCompareMemory(data.BaseAddress, &entry, EntrySize) == EntrySize) {
|
||||
PRTL_INVERTED_FUNCTION_TABLE tab = decltype(tab)((size_t)data.BaseAddress - 0x10);
|
||||
if (RtlIsWindowsVersionOrGreater(6, 2, 0) && tab->MaxCount == 0x200 && !tab->Overflow) {
|
||||
return LdrpInvertedFunctionTable = tab;
|
||||
}
|
||||
else {
|
||||
if (tab->MaxCount == 0x200 && !tab->Epoch)
|
||||
return LdrpInvertedFunctionTable = tab;
|
||||
}
|
||||
}
|
||||
++data;
|
||||
--data.Size;
|
||||
}
|
||||
|
||||
return LdrpInvertedFunctionTable;
|
||||
}
|
||||
static NTSTATUS NTAPI RtlProtectMrdata(IN SIZE_T Protect) {
|
||||
static PVOID MrdataBase = nullptr;
|
||||
static SIZE_T size = 0;
|
||||
NTSTATUS status;
|
||||
PVOID tmp;
|
||||
SIZE_T tmp_len;
|
||||
SIZE_T old;
|
||||
|
||||
if (!MrdataBase) {
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
status = NtQueryVirtualMemory(GetCurrentProcess(), RtlFindLdrpInvertedFunctionTable(), MemoryBasicInformation, &mbi, sizeof(mbi), nullptr);
|
||||
if (!NT_SUCCESS(status))return status;
|
||||
MrdataBase = mbi.BaseAddress;
|
||||
size = mbi.RegionSize;
|
||||
}
|
||||
|
||||
tmp = MrdataBase;
|
||||
tmp_len = size;
|
||||
return NtProtectVirtualMemory(GetCurrentProcess(), &tmp, &tmp_len, Protect, &old);
|
||||
}
|
||||
|
||||
NTSTATUS NTAPI RtlInsertInvertedFunctionTable(IN PVOID BaseAddress, IN size_t ImageSize) {
|
||||
static auto table = PRTL_INVERTED_FUNCTION_TABLE(RtlFindLdrpInvertedFunctionTable());
|
||||
if (!table)return STATUS_NOT_SUPPORTED;
|
||||
bool need_virtual_protect = RtlIsWindowsVersionOrGreater(10, 0, 0);
|
||||
NTSTATUS status;
|
||||
|
||||
if (need_virtual_protect) {
|
||||
status = RtlProtectMrdata(PAGE_READWRITE);
|
||||
if (!NT_SUCCESS(status))return status;
|
||||
}
|
||||
RtlpInsertInvertedFunctionTable(table, BaseAddress, ImageSize);
|
||||
if (need_virtual_protect) {
|
||||
status = RtlProtectMrdata(PAGE_READONLY);
|
||||
if (!NT_SUCCESS(status))return status;
|
||||
}
|
||||
|
||||
if (RtlIsWindowsVersionOrGreater(6, 2, 0)) return table->Overflow ? STATUS_INVALID_ADDRESS : STATUS_SUCCESS;
|
||||
else return table->Epoch ? STATUS_INVALID_ADDRESS : STATUS_SUCCESS;
|
||||
}
|
||||
NTSTATUS NTAPI RtlRemoveInvertedFunctionTable(IN PVOID ImageBase) {
|
||||
static auto table = PRTL_INVERTED_FUNCTION_TABLE(RtlFindLdrpInvertedFunctionTable());
|
||||
bool need_virtual_protect = RtlIsWindowsVersionOrGreater(10, 0, 0);
|
||||
NTSTATUS status;
|
||||
|
||||
if (need_virtual_protect) {
|
||||
status = RtlProtectMrdata(PAGE_READWRITE);
|
||||
if (!NT_SUCCESS(status))return status;
|
||||
}
|
||||
RtlpRemoveInvertedFunctionTable(table, ImageBase);
|
||||
if (need_virtual_protect) {
|
||||
status = RtlProtectMrdata(PAGE_READONLY);
|
||||
if (!NT_SUCCESS(status))return status;
|
||||
}
|
||||
|
||||
return STATUS_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
#pragma once
|
||||
#include <Windows.h>
|
||||
#include "rtltype.h"
|
||||
#include "ntstatus.h"
|
||||
#include "MemoryModule.h"
|
||||
|
||||
//
|
||||
// Loader Data Table Entry Flags
|
||||
//
|
||||
#define LDRP_STATIC_LINK 0x00000002
|
||||
#define LDRP_IMAGE_DLL 0x00000004
|
||||
#define LDRP_SHIMENG_SUPPRESSED_ENTRY 0x00000008
|
||||
#define LDRP_IMAGE_INTEGRITY_FORCED 0x00000020
|
||||
#define LDRP_LOAD_IN_PROGRESS 0x00001000
|
||||
#define LDRP_UNLOAD_IN_PROGRESS 0x00002000
|
||||
#define LDRP_ENTRY_PROCESSED 0x00004000
|
||||
#define LDRP_ENTRY_INSERTED 0x00008000
|
||||
#define LDRP_CURRENT_LOAD 0x00010000
|
||||
#define LDRP_FAILED_BUILTIN_LOAD 0x00020000
|
||||
#define LDRP_DONT_CALL_FOR_THREADS 0x00040000
|
||||
#define LDRP_PROCESS_ATTACH_CALLED 0x00080000
|
||||
#define LDRP_DEBUG_SYMBOLS_LOADED 0x00100000
|
||||
#define LDRP_IMAGE_NOT_AT_BASE 0x00200000
|
||||
#define LDRP_COR_IMAGE 0x00400000
|
||||
#define LDR_COR_OWNS_UNMAP 0x00800000
|
||||
#define LDRP_SYSTEM_MAPPED 0x01000000
|
||||
#define LDRP_IMAGE_VERIFYING 0x02000000
|
||||
#define LDRP_DRIVER_DEPENDENT_DLL 0x04000000
|
||||
#define LDRP_ENTRY_NATIVE 0x08000000
|
||||
#define LDRP_REDIRECTED 0x10000000
|
||||
#define LDRP_NON_PAGED_DEBUG_INFO 0x20000000
|
||||
#define LDRP_MM_LOADED 0x40000000
|
||||
#define LDRP_COMPAT_DATABASE_PROCESSED 0x80000000
|
||||
|
||||
#define LDR_GET_HASH_ENTRY(x) (RtlUpcaseUnicodeChar((x)) & (LDR_HASH_TABLE_ENTRIES - 1))
|
||||
#define LDR_HASH_TABLE_ENTRIES 32
|
||||
#define InsertTailList(ListHead,Entry) {\
|
||||
PLIST_ENTRY _EX_Blink;\
|
||||
PLIST_ENTRY _EX_ListHead;\
|
||||
_EX_ListHead = (ListHead);\
|
||||
_EX_Blink = _EX_ListHead->Blink;\
|
||||
(Entry)->Flink = _EX_ListHead;\
|
||||
(Entry)->Blink = _EX_Blink;\
|
||||
_EX_Blink->Flink = (Entry);\
|
||||
_EX_ListHead->Blink = (Entry);\
|
||||
}
|
||||
|
||||
//0x18 bytes (sizeof)
|
||||
typedef struct _RTL_BALANCED_NODE {
|
||||
union {
|
||||
_RTL_BALANCED_NODE* Children[2]; //0x0
|
||||
struct {
|
||||
_RTL_BALANCED_NODE* Left; //0x0
|
||||
_RTL_BALANCED_NODE* Right; //0x8
|
||||
};
|
||||
};
|
||||
union {
|
||||
struct {
|
||||
UCHAR Red : 1; //0x10
|
||||
UCHAR Balance : 2; //0x10
|
||||
};
|
||||
ULONGLONG ParentValue; //0x10
|
||||
};
|
||||
}RTL_BALANCED_NODE, * PRTL_BALANCED_NODE;
|
||||
|
||||
enum _LDR_DLL_LOAD_REASON {
|
||||
LoadReasonStaticDependency = 0,
|
||||
LoadReasonStaticForwarderDependency = 1,
|
||||
LoadReasonDynamicForwarderDependency = 2,
|
||||
LoadReasonDelayloadDependency = 3,
|
||||
LoadReasonDynamicLoad = 4,
|
||||
LoadReasonAsImageLoad = 5,
|
||||
LoadReasonAsDataLoad = 6,
|
||||
LoadReasonUnknown = -1
|
||||
};
|
||||
|
||||
//0x10 bytes (sizeof)
|
||||
struct _LDR_SERVICE_TAG_RECORD {
|
||||
_LDR_SERVICE_TAG_RECORD* Next; //0x0
|
||||
ULONG ServiceTag; //0x8
|
||||
};
|
||||
//0x8 bytes (sizeof)
|
||||
struct _LDRP_CSLIST {
|
||||
_SINGLE_LIST_ENTRY* Tail; //0x0
|
||||
};
|
||||
//0x4 bytes (sizeof)
|
||||
enum _LDR_DDAG_STATE {
|
||||
LdrModulesMerged = -5,
|
||||
LdrModulesInitError = -4,
|
||||
LdrModulesSnapError = -3,
|
||||
LdrModulesUnloaded = -2,
|
||||
LdrModulesUnloading = -1,
|
||||
LdrModulesPlaceHolder = 0,
|
||||
LdrModulesMapping = 1,
|
||||
LdrModulesMapped = 2,
|
||||
LdrModulesWaitingForDependencies = 3,
|
||||
LdrModulesSnapping = 4,
|
||||
LdrModulesSnapped = 5,
|
||||
LdrModulesCondensed = 6,
|
||||
LdrModulesReadyToInit = 7,
|
||||
LdrModulesInitializing = 8,
|
||||
LdrModulesReadyToRun = 9
|
||||
};
|
||||
//0x50 bytes (sizeof)
|
||||
struct _LDR_DDAG_NODE {
|
||||
_LIST_ENTRY Modules; //0x0
|
||||
_LDR_SERVICE_TAG_RECORD* ServiceTagList; //0x10
|
||||
ULONG LoadCount; //0x18
|
||||
ULONG LoadWhileUnloadingCount; //0x1c
|
||||
ULONG LowestLink; //0x20
|
||||
_LDRP_CSLIST Dependencies; //0x28
|
||||
_LDRP_CSLIST IncomingDependencies; //0x30
|
||||
_LDR_DDAG_STATE State; //0x38
|
||||
_SINGLE_LIST_ENTRY CondenseLink; //0x40
|
||||
ULONG PreorderNumber; //0x48
|
||||
};
|
||||
|
||||
//5.1.2600 Windows XP SP3
|
||||
//5.2.3790 Windows XP | 2003 SP2
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_XP {
|
||||
_LIST_ENTRY InLoadOrderLinks; //0x0
|
||||
_LIST_ENTRY InMemoryOrderLinks; //0x10
|
||||
_LIST_ENTRY InInitializationOrderLinks; //0x20
|
||||
VOID* DllBase; //0x30
|
||||
VOID* EntryPoint; //0x38
|
||||
ULONG SizeOfImage; //0x40
|
||||
_UNICODE_STRING FullDllName; //0x48
|
||||
_UNICODE_STRING BaseDllName; //0x58
|
||||
ULONG Flags; //0x68
|
||||
USHORT LoadCount; //0x6c
|
||||
USHORT TlsIndex; //0x6e
|
||||
union {
|
||||
_LIST_ENTRY HashLinks; //0x70
|
||||
struct {
|
||||
VOID* SectionPointer; //0x70
|
||||
ULONG CheckSum; //0x78
|
||||
};
|
||||
};
|
||||
union {
|
||||
ULONG TimeDateStamp; //0x80
|
||||
VOID* LoadedImports; //0x80
|
||||
};
|
||||
_ACTIVATION_CONTEXT* EntryPointActivationContext; //0x88
|
||||
VOID* PatchInformation; //0x90
|
||||
}LDR_DATA_TABLE_ENTRY_XP, * PLDR_DATA_TABLE_ENTRY_XP;
|
||||
|
||||
//6.0.6000 Vista | 2008 RTM
|
||||
//6.0.6001 Vista | 2008 SP1
|
||||
//6.0.6002 Vista | 2008 SP2
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_VISTA :public _LDR_DATA_TABLE_ENTRY_XP {
|
||||
_LIST_ENTRY ForwarderLinks; //0x98
|
||||
_LIST_ENTRY ServiceTagLinks; //0xa8
|
||||
_LIST_ENTRY StaticLinks; //0xb8
|
||||
}LDR_DATA_TABLE_ENTRY_VISTA, * PLDR_DATA_TABLE_ENTRY_VISTA;
|
||||
|
||||
//6.1.7600 Windows 7 | 2008R2 SP1
|
||||
//6.1.7601 Windows 7 | 2008R2 RTM
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_WIN7 :public _LDR_DATA_TABLE_ENTRY_VISTA {
|
||||
VOID* ContextInformation; //0xc8
|
||||
ULONGLONG OriginalBase; //0xd0
|
||||
_LARGE_INTEGER LoadTime; //0xd8
|
||||
}LDR_DATA_TABLE_ENTRY_WIN7, * PLDR_DATA_TABLE_ENTRY_WIN7;
|
||||
|
||||
//6.2.9200 Windows 8 | 2012 RTM
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_WIN8 {
|
||||
_LIST_ENTRY InLoadOrderLinks; //0x0
|
||||
_LIST_ENTRY InMemoryOrderLinks; //0x10
|
||||
union {
|
||||
_LIST_ENTRY InInitializationOrderLinks; //0x20
|
||||
_LIST_ENTRY InProgressLinks; //0x20
|
||||
};
|
||||
VOID* DllBase; //0x30
|
||||
VOID* EntryPoint; //0x38
|
||||
ULONG SizeOfImage; //0x40
|
||||
_UNICODE_STRING FullDllName; //0x48
|
||||
_UNICODE_STRING BaseDllName; //0x58
|
||||
union {
|
||||
UCHAR FlagGroup[4]; //0x68
|
||||
ULONG Flags; //0x68
|
||||
struct {
|
||||
ULONG PackagedBinary : 1; //0x68
|
||||
ULONG MarkedForRemoval : 1; //0x68
|
||||
ULONG ImageDll : 1; //0x68
|
||||
ULONG LoadNotificationsSent : 1; //0x68
|
||||
ULONG TelemetryEntryProcessed : 1; //0x68
|
||||
ULONG ProcessStaticImport : 1; //0x68
|
||||
ULONG InLegacyLists : 1; //0x68
|
||||
ULONG InIndexes : 1; //0x68
|
||||
ULONG ShimDll : 1; //0x68
|
||||
ULONG InExceptionTable : 1; //0x68
|
||||
ULONG ReservedFlags1 : 2; //0x68
|
||||
ULONG LoadInProgress : 1; //0x68
|
||||
ULONG ReservedFlags2 : 1; //0x68
|
||||
ULONG EntryProcessed : 1; //0x68
|
||||
ULONG ReservedFlags3 : 3; //0x68
|
||||
ULONG DontCallForThreads : 1; //0x68
|
||||
ULONG ProcessAttachCalled : 1; //0x68
|
||||
ULONG ProcessAttachFailed : 1; //0x68
|
||||
ULONG CorDeferredValidate : 1; //0x68
|
||||
ULONG CorImage : 1; //0x68
|
||||
ULONG DontRelocate : 1; //0x68
|
||||
ULONG CorILOnly : 1; //0x68
|
||||
ULONG ReservedFlags5 : 3; //0x68
|
||||
ULONG Redirected : 1; //0x68
|
||||
ULONG ReservedFlags6 : 2; //0x68
|
||||
ULONG CompatDatabaseProcessed : 1; //0x68
|
||||
};
|
||||
};
|
||||
USHORT ObsoleteLoadCount; //0x6c
|
||||
USHORT TlsIndex; //0x6e
|
||||
_LIST_ENTRY HashLinks; //0x70
|
||||
ULONG TimeDateStamp; //0x80
|
||||
_ACTIVATION_CONTEXT* EntryPointActivationContext; //0x88
|
||||
VOID* PatchInformation; //0x90
|
||||
_LDR_DDAG_NODE* DdagNode; //0x98
|
||||
_LIST_ENTRY NodeModuleLink; //0xa0
|
||||
VOID* SnapContext; //0xb0
|
||||
VOID* ParentDllBase; //0xb8
|
||||
VOID* SwitchBackContext; //0xc0
|
||||
_RTL_BALANCED_NODE BaseAddressIndexNode; //0xc8
|
||||
_RTL_BALANCED_NODE MappingInfoIndexNode; //0xe0
|
||||
ULONGLONG OriginalBase; //0xf8
|
||||
_LARGE_INTEGER LoadTime; //0x100
|
||||
ULONG BaseNameHashValue; //0x108
|
||||
_LDR_DLL_LOAD_REASON LoadReason; //0x10c
|
||||
}LDR_DATA_TABLE_ENTRY_WIN8, * PLDR_DATA_TABLE_ENTRY_WIN8;
|
||||
|
||||
//6.3.9600 Windows 8.1 | 2012R2 RTM | 2012R2 Update 1
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_WIN8_1 :public _LDR_DATA_TABLE_ENTRY_WIN8 {
|
||||
ULONG ImplicitPathOptions;
|
||||
}LDR_DATA_TABLE_ENTRY_WIN8_1, * PLDR_DATA_TABLE_ENTRY_WIN8_1;
|
||||
|
||||
//10.0.10240 Windows 10 | 2016 1507 Threshold 1
|
||||
//10.0.10586 Windows 10 | 2016 1511 Threshold 2
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_WIN10 {
|
||||
_LIST_ENTRY InLoadOrderLinks; //0x0
|
||||
_LIST_ENTRY InMemoryOrderLinks; //0x10
|
||||
_LIST_ENTRY InInitializationOrderLinks; //0x20
|
||||
VOID* DllBase; //0x30
|
||||
VOID* EntryPoint; //0x38
|
||||
ULONG SizeOfImage; //0x40
|
||||
_UNICODE_STRING FullDllName; //0x48
|
||||
_UNICODE_STRING BaseDllName; //0x58
|
||||
union {
|
||||
UCHAR FlagGroup[4]; //0x68
|
||||
ULONG Flags; //0x68
|
||||
struct {
|
||||
ULONG PackagedBinary : 1; //0x68
|
||||
ULONG MarkedForRemoval : 1; //0x68
|
||||
ULONG ImageDll : 1; //0x68
|
||||
ULONG LoadNotificationsSent : 1; //0x68
|
||||
ULONG TelemetryEntryProcessed : 1; //0x68
|
||||
ULONG ProcessStaticImport : 1; //0x68
|
||||
ULONG InLegacyLists : 1; //0x68
|
||||
ULONG InIndexes : 1; //0x68
|
||||
ULONG ShimDll : 1; //0x68
|
||||
ULONG InExceptionTable : 1; //0x68
|
||||
ULONG ReservedFlags1 : 2; //0x68
|
||||
ULONG LoadInProgress : 1; //0x68
|
||||
ULONG LoadConfigProcessed : 1; //0x68
|
||||
ULONG EntryProcessed : 1; //0x68
|
||||
ULONG ProtectDelayLoad : 1; //0x68
|
||||
ULONG ReservedFlags3 : 2; //0x68
|
||||
ULONG DontCallForThreads : 1; //0x68
|
||||
ULONG ProcessAttachCalled : 1; //0x68
|
||||
ULONG ProcessAttachFailed : 1; //0x68
|
||||
ULONG CorDeferredValidate : 1; //0x68
|
||||
ULONG CorImage : 1; //0x68
|
||||
ULONG DontRelocate : 1; //0x68
|
||||
ULONG CorILOnly : 1; //0x68
|
||||
ULONG ReservedFlags5 : 3; //0x68
|
||||
ULONG Redirected : 1; //0x68
|
||||
ULONG ReservedFlags6 : 2; //0x68
|
||||
ULONG CompatDatabaseProcessed : 1; //0x68
|
||||
};
|
||||
};
|
||||
USHORT ObsoleteLoadCount; //0x6c
|
||||
USHORT TlsIndex; //0x6e
|
||||
_LIST_ENTRY HashLinks; //0x70
|
||||
ULONG TimeDateStamp; //0x80
|
||||
_ACTIVATION_CONTEXT* EntryPointActivationContext; //0x88
|
||||
VOID* Lock; //0x90
|
||||
_LDR_DDAG_NODE* DdagNode; //0x98
|
||||
_LIST_ENTRY NodeModuleLink; //0xa0
|
||||
VOID* LoadContext; //0xb0
|
||||
VOID* ParentDllBase; //0xb8
|
||||
VOID* SwitchBackContext; //0xc0
|
||||
_RTL_BALANCED_NODE BaseAddressIndexNode; //0xc8
|
||||
_RTL_BALANCED_NODE MappingInfoIndexNode; //0xe0
|
||||
ULONGLONG OriginalBase; //0xf8
|
||||
_LARGE_INTEGER LoadTime; //0x100
|
||||
ULONG BaseNameHashValue; //0x108
|
||||
_LDR_DLL_LOAD_REASON LoadReason; //0x10c
|
||||
ULONG ImplicitPathOptions; //0x110
|
||||
ULONG ReferenceCount; //0x114
|
||||
}LDR_DATA_TABLE_ENTRY_WIN10, * PLDR_DATA_TABLE_ENTRY_WIN10;
|
||||
|
||||
//10.0.14393 Windows 10 | 2016 1607 Redstone 1 (Anniversary Update)
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_WIN10_1 :public _LDR_DATA_TABLE_ENTRY_WIN10 {
|
||||
ULONG DependentLoadFlags; //0x118
|
||||
}LDR_DATA_TABLE_ENTRY_WIN10_1,*PLDR_DATA_TABLE_ENTRY_WIN10_1;
|
||||
|
||||
//10.0.15063 Windows 10 | 2016 1703 Redstone 2 (Creators Update)
|
||||
//10.0.16299 Windows 10 | 2016 1709 Redstone 3 (Fall Creators Update)
|
||||
//10.0.17134 Windows 10 | 2016 1803 Redstone 4 (Spring Creators Update)
|
||||
//10.0.17763 Windows 10 | 2016 1809 Redstone 5 (October Update)
|
||||
//10.0.18362 Windows 10 | 2016 1903 19H1 (May 2019 Update) | 2016 1909 19H2 (November 2019 Update)
|
||||
typedef struct _LDR_DATA_TABLE_ENTRY_WIN10_2 {
|
||||
_LIST_ENTRY InLoadOrderLinks; //0x0
|
||||
_LIST_ENTRY InMemoryOrderLinks; //0x10
|
||||
_LIST_ENTRY InInitializationOrderLinks; //0x20
|
||||
VOID* DllBase; //0x30
|
||||
VOID* EntryPoint; //0x38
|
||||
ULONG SizeOfImage; //0x40
|
||||
_UNICODE_STRING FullDllName; //0x48
|
||||
_UNICODE_STRING BaseDllName; //0x58
|
||||
union {
|
||||
UCHAR FlagGroup[4]; //0x68
|
||||
ULONG Flags; //0x68
|
||||
struct {
|
||||
ULONG PackagedBinary : 1; //0x68
|
||||
ULONG MarkedForRemoval : 1; //0x68
|
||||
ULONG ImageDll : 1; //0x68
|
||||
ULONG LoadNotificationsSent : 1; //0x68
|
||||
ULONG TelemetryEntryProcessed : 1; //0x68
|
||||
ULONG ProcessStaticImport : 1; //0x68
|
||||
ULONG InLegacyLists : 1; //0x68
|
||||
ULONG InIndexes : 1; //0x68
|
||||
ULONG ShimDll : 1; //0x68
|
||||
ULONG InExceptionTable : 1; //0x68
|
||||
ULONG ReservedFlags1 : 2; //0x68
|
||||
ULONG LoadInProgress : 1; //0x68
|
||||
ULONG LoadConfigProcessed : 1; //0x68
|
||||
ULONG EntryProcessed : 1; //0x68
|
||||
ULONG ProtectDelayLoad : 1; //0x68
|
||||
ULONG ReservedFlags3 : 2; //0x68
|
||||
ULONG DontCallForThreads : 1; //0x68
|
||||
ULONG ProcessAttachCalled : 1; //0x68
|
||||
ULONG ProcessAttachFailed : 1; //0x68
|
||||
ULONG CorDeferredValidate : 1; //0x68
|
||||
ULONG CorImage : 1; //0x68
|
||||
ULONG DontRelocate : 1; //0x68
|
||||
ULONG CorILOnly : 1; //0x68
|
||||
ULONG ReservedFlags5 : 3; //0x68
|
||||
ULONG Redirected : 1; //0x68
|
||||
ULONG ReservedFlags6 : 2; //0x68
|
||||
ULONG CompatDatabaseProcessed : 1; //0x68
|
||||
};
|
||||
};
|
||||
USHORT ObsoleteLoadCount; //0x6c
|
||||
USHORT TlsIndex; //0x6e
|
||||
_LIST_ENTRY HashLinks; //0x70
|
||||
ULONG TimeDateStamp; //0x80
|
||||
_ACTIVATION_CONTEXT* EntryPointActivationContext; //0x88
|
||||
VOID* Lock; //0x90
|
||||
_LDR_DDAG_NODE* DdagNode; //0x98
|
||||
_LIST_ENTRY NodeModuleLink; //0xa0
|
||||
VOID* LoadContext; //0xb0
|
||||
VOID* ParentDllBase; //0xb8
|
||||
VOID* SwitchBackContext; //0xc0
|
||||
_RTL_BALANCED_NODE BaseAddressIndexNode; //0xc8
|
||||
_RTL_BALANCED_NODE MappingInfoIndexNode; //0xe0
|
||||
ULONGLONG OriginalBase; //0xf8
|
||||
_LARGE_INTEGER LoadTime; //0x100
|
||||
ULONG BaseNameHashValue; //0x108
|
||||
_LDR_DLL_LOAD_REASON LoadReason; //0x10c
|
||||
ULONG ImplicitPathOptions; //0x110
|
||||
ULONG ReferenceCount; //0x114
|
||||
ULONG DependentLoadFlags; //0x118
|
||||
UCHAR SigningLevel; //0x11c
|
||||
}LDR_DATA_TABLE_ENTRY_WIN10_2, * PLDR_DATA_TABLE_ENTRY_WIN10_2;
|
||||
|
||||
typedef enum _WINDOWS_VERSION {
|
||||
null,
|
||||
xp,
|
||||
vista,
|
||||
win7,
|
||||
win8,
|
||||
win8_1,
|
||||
win10,
|
||||
win10_1,
|
||||
win10_2,
|
||||
invalid
|
||||
}WINDOWS_VERSION;
|
||||
|
||||
NTSTATUS NTAPI NtLoadDllMemory(
|
||||
OUT HMEMORYMODULE* BaseAddress,
|
||||
IN LPVOID BufferAddress,
|
||||
IN size_t BufferSize
|
||||
);
|
||||
|
||||
#define LOAD_FLAGS_NOT_ADD_LDR_ENTRY
|
||||
#define LOAD_FLAGS_NOT_ADD_INVERTED_FUNCTION
|
||||
|
||||
#define LOAD_FLAGS_NOT_MAP_DLL
|
||||
|
||||
NTSTATUS NTAPI NtLoadDllMemoryExW(
|
||||
OUT HMEMORYMODULE* BaseAddress,
|
||||
OUT PLDR_DATA_TABLE_ENTRY* LdrEntry OPTIONAL,
|
||||
IN DWORD dwFlags,
|
||||
IN LPVOID BufferAddress,
|
||||
IN size_t BufferSize,
|
||||
IN LPCWSTR DllName OPTIONAL,
|
||||
IN LPCWSTR DllFullName OPTIONAL
|
||||
);
|
||||
|
||||
NTSTATUS NTAPI NtUnloadDllMemory(IN HMEMORYMODULE BaseAddress);
|
||||
|
||||
typedef struct _RTL_RB_TREE {
|
||||
PRTL_BALANCED_NODE Root;
|
||||
PRTL_BALANCED_NODE Min;
|
||||
} RTL_RB_TREE, * PRTL_RB_TREE;
|
||||
// RtlRbInsertNodeEx
|
||||
VOID NTAPI RtlRbInsertNodeEx(IN PRTL_RB_TREE Tree, IN PRTL_BALANCED_NODE Parent, IN BOOLEAN Right, OUT PRTL_BALANCED_NODE Node);
|
||||
// RtlRbRemoveNode
|
||||
VOID NTAPI RtlRbRemoveNode(IN PRTL_RB_TREE Tree, IN PRTL_BALANCED_NODE Node);
|
||||
|
||||
typedef struct _RTL_INVERTED_FUNCTION_TABLE_ENTRY {
|
||||
PIMAGE_RUNTIME_FUNCTION_ENTRY ExceptionDirectory;
|
||||
PVOID ImageBase;
|
||||
ULONG ImageSize;
|
||||
ULONG ExceptionDirectorySize;
|
||||
} RTL_INVERTED_FUNCTION_TABLE_ENTRY, * PRTL_INVERTED_FUNCTION_TABLE_ENTRY;
|
||||
typedef struct _RTL_INVERTED_FUNCTION_TABLE {
|
||||
ULONG Count;
|
||||
ULONG MaxCount;
|
||||
ULONG Epoch;
|
||||
ULONG Overflow;
|
||||
RTL_INVERTED_FUNCTION_TABLE_ENTRY Entries[0x200];
|
||||
} RTL_INVERTED_FUNCTION_TABLE, * PRTL_INVERTED_FUNCTION_TABLE;
|
||||
|
||||
NTSTATUS NTAPI RtlInsertInvertedFunctionTable(IN PVOID BaseAddress, IN size_t ImageSize);
|
||||
NTSTATUS NTAPI RtlRemoveInvertedFunctionTable(IN PVOID ImageBase);
|
||||
+23288
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user